feat: 完善艺术品审核变更流程
This commit is contained in:
@@ -0,0 +1,31 @@
|
||||
CREATE TABLE `artwork_revision` (
|
||||
`id` VARCHAR(191) NOT NULL,
|
||||
`artwork_id` INTEGER NOT NULL,
|
||||
`title` VARCHAR(191) NOT NULL,
|
||||
`reason` TEXT NULL,
|
||||
`before_snapshot` JSON NOT NULL,
|
||||
`after_snapshot` JSON NOT NULL,
|
||||
`status` ENUM('PENDING', 'APPROVED', 'REJECTED') NOT NULL DEFAULT 'PENDING',
|
||||
`audit_remark` TEXT NULL,
|
||||
`submitted_by` INTEGER NULL,
|
||||
`submitted_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
|
||||
`reviewed_by` INTEGER NULL,
|
||||
`reviewed_at` DATETIME(3) NULL,
|
||||
|
||||
INDEX `artwork_revision_artwork_id_idx`(`artwork_id`),
|
||||
INDEX `artwork_revision_status_idx`(`status`),
|
||||
INDEX `artwork_revision_submitted_at_idx`(`submitted_at`),
|
||||
PRIMARY KEY (`id`)
|
||||
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||
|
||||
ALTER TABLE `artwork_revision`
|
||||
ADD CONSTRAINT `artwork_revision_artwork_id_fkey`
|
||||
FOREIGN KEY (`artwork_id`) REFERENCES `artwork`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `artwork_revision`
|
||||
ADD CONSTRAINT `artwork_revision_submitted_by_fkey`
|
||||
FOREIGN KEY (`submitted_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
ALTER TABLE `artwork_revision`
|
||||
ADD CONSTRAINT `artwork_revision_reviewed_by_fkey`
|
||||
FOREIGN KEY (`reviewed_by`) REFERENCES `sys_user`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -46,6 +46,12 @@ enum AuditStatus {
|
||||
REJECTED
|
||||
}
|
||||
|
||||
enum ArtworkRevisionStatus {
|
||||
PENDING
|
||||
APPROVED
|
||||
REJECTED
|
||||
}
|
||||
|
||||
enum NodeType {
|
||||
CREATE
|
||||
PRODUCE
|
||||
@@ -144,6 +150,8 @@ model SysUser {
|
||||
operationLogs OperationLog[]
|
||||
outboundImportSessions OutboundImportSession[]
|
||||
backupRecords BackupRecord[]
|
||||
submittedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionSubmitter")
|
||||
reviewedArtworkRevisions ArtworkRevision[] @relation("ArtworkRevisionReviewer")
|
||||
|
||||
@@map("sys_user")
|
||||
}
|
||||
@@ -202,6 +210,7 @@ model Artwork {
|
||||
certificates Certificate[]
|
||||
batches Batch[]
|
||||
traceCodes TraceCode[]
|
||||
revisions ArtworkRevision[]
|
||||
|
||||
@@index([templateId])
|
||||
@@index([status])
|
||||
@@ -209,6 +218,30 @@ model Artwork {
|
||||
@@map("artwork")
|
||||
}
|
||||
|
||||
model ArtworkRevision {
|
||||
id String @id @default(cuid())
|
||||
artworkId Int @map("artwork_id")
|
||||
title String
|
||||
reason String? @db.Text
|
||||
beforeSnapshot Json @map("before_snapshot")
|
||||
afterSnapshot Json @map("after_snapshot")
|
||||
status ArtworkRevisionStatus @default(PENDING)
|
||||
auditRemark String? @db.Text @map("audit_remark")
|
||||
submittedBy Int? @map("submitted_by")
|
||||
submittedAt DateTime @default(now()) @map("submitted_at")
|
||||
reviewedBy Int? @map("reviewed_by")
|
||||
reviewedAt DateTime? @map("reviewed_at")
|
||||
|
||||
artwork Artwork @relation(fields: [artworkId], references: [id], onDelete: Cascade)
|
||||
submitter SysUser? @relation("ArtworkRevisionSubmitter", fields: [submittedBy], references: [id])
|
||||
reviewer SysUser? @relation("ArtworkRevisionReviewer", fields: [reviewedBy], references: [id])
|
||||
|
||||
@@index([artworkId])
|
||||
@@index([status])
|
||||
@@index([submittedAt])
|
||||
@@map("artwork_revision")
|
||||
}
|
||||
|
||||
model TraceNode {
|
||||
id Int @id @default(autoincrement())
|
||||
artworkId Int @map("artwork_id")
|
||||
|
||||
@@ -2,7 +2,13 @@ import { Body, Controller, Delete, Get, Param, ParseIntPipe, Post, Put, Query }
|
||||
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { RoleType } from '@artveris/shared';
|
||||
import { ArtworkService } from './artwork.service';
|
||||
import { AuditArtworkDto, CreateArtworkDto, QueryArtworkDto, UpdateArtworkDto } from './dto/artwork.dto';
|
||||
import {
|
||||
AuditArtworkDto,
|
||||
CreateArtworkDto,
|
||||
QueryArtworkDto,
|
||||
QueryArtworkRevisionDto,
|
||||
UpdateArtworkDto,
|
||||
} from './dto/artwork.dto';
|
||||
import { Roles } from '../common/decorators/roles.decorator';
|
||||
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
|
||||
|
||||
@@ -18,12 +24,30 @@ export class ArtworkController {
|
||||
return this.artworkService.list(query);
|
||||
}
|
||||
|
||||
@Get('audit-list')
|
||||
@ApiOperation({ summary: '内容审核列表' })
|
||||
auditList(@Query() query: QueryArtworkRevisionDto) {
|
||||
return this.artworkService.auditList(query);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: '艺术品详情' })
|
||||
get(@Param('id', ParseIntPipe) id: number) {
|
||||
return this.artworkService.get(id);
|
||||
}
|
||||
|
||||
@Get(':id/revisions')
|
||||
@ApiOperation({ summary: '作品审核变更记录' })
|
||||
revisions(@Param('id', ParseIntPipe) id: number, @Query() query: QueryArtworkRevisionDto) {
|
||||
return this.artworkService.listRevisions(id, query);
|
||||
}
|
||||
|
||||
@Get(':id/revisions/:revisionId')
|
||||
@ApiOperation({ summary: '作品审核变更详情' })
|
||||
revision(@Param('id', ParseIntPipe) id: number, @Param('revisionId') revisionId: string) {
|
||||
return this.artworkService.getRevision(id, revisionId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '创建艺术品档案' })
|
||||
@@ -34,8 +58,8 @@ export class ArtworkController {
|
||||
@Put(':id')
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '更新艺术品档案' })
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateArtworkDto) {
|
||||
return this.artworkService.update(id, dto);
|
||||
update(@Param('id', ParseIntPipe) id: number, @Body() dto: UpdateArtworkDto, @CurrentUser() user: AuthUser) {
|
||||
return this.artworkService.update(id, dto, user.id);
|
||||
}
|
||||
|
||||
@Post(':id/audit')
|
||||
|
||||
@@ -2,13 +2,21 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { Prisma } from '@prisma/client';
|
||||
import { Queue } from 'bullmq';
|
||||
import { AuditStatus, ErrorCode, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { ArtworkRevisionStatus, ArtworkStatus, AuditStatus, ErrorCode, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { buildOrderBy } from '../common/utils/sort.util';
|
||||
import { AuditArtworkDto, CreateArtworkDto, QueryArtworkDto, UpdateArtworkDto } from './dto/artwork.dto';
|
||||
import {
|
||||
AuditArtworkDto,
|
||||
CreateArtworkCertificateDto,
|
||||
CreateArtworkDto,
|
||||
CreateArtworkTraceNodeDto,
|
||||
QueryArtworkDto,
|
||||
QueryArtworkRevisionDto,
|
||||
UpdateArtworkDto,
|
||||
} from './dto/artwork.dto';
|
||||
|
||||
interface MediaItem {
|
||||
key: string;
|
||||
@@ -16,6 +24,38 @@ interface MediaItem {
|
||||
type?: string;
|
||||
}
|
||||
|
||||
interface TraceNodeSnapshot {
|
||||
nodeType: string;
|
||||
title: string;
|
||||
occurredAt?: string | null;
|
||||
location?: string | null;
|
||||
description?: string | null;
|
||||
mediaFiles?: MediaItem[];
|
||||
sortOrder: number;
|
||||
}
|
||||
|
||||
interface CertificateSnapshot {
|
||||
name: string;
|
||||
issuer?: string | null;
|
||||
issuedAt?: string | null;
|
||||
type: string;
|
||||
originKey: string;
|
||||
watermarkKey?: string | null;
|
||||
}
|
||||
|
||||
interface ArtworkSnapshot {
|
||||
artwork: {
|
||||
templateId: number;
|
||||
title: string;
|
||||
artist?: string | null;
|
||||
status: ArtworkStatus;
|
||||
dynamicFields: Record<string, unknown>;
|
||||
images: MediaItem[];
|
||||
};
|
||||
traceNodes: TraceNodeSnapshot[];
|
||||
certificates: CertificateSnapshot[];
|
||||
}
|
||||
|
||||
const DEFAULT_TRACE_NODES: Prisma.TraceNodeCreateWithoutArtworkInput[] = [
|
||||
{ nodeType: 'CREATE', title: '创作 / 选胚', sortOrder: 0 },
|
||||
{ nodeType: 'PRODUCE', title: '制作过程', sortOrder: 1 },
|
||||
@@ -38,7 +78,6 @@ export class ArtworkService {
|
||||
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
|
||||
}
|
||||
|
||||
// 档案编号:款级唯一标识,按作品 id 生成,如 ARTVERIS-000001
|
||||
private buildArchiveNo(id: number): string {
|
||||
return `ARTVERIS-${String(id).padStart(6, '0')}`;
|
||||
}
|
||||
@@ -49,25 +88,10 @@ export class ArtworkService {
|
||||
});
|
||||
if (!tpl) throw new BusinessException(ErrorCode.TEMPLATE_NOT_FOUND, '模板不存在', 404);
|
||||
|
||||
const status = dto.status ?? ArtworkStatus.ACTIVE;
|
||||
const traceNodes =
|
||||
dto.traceNodes === undefined
|
||||
? DEFAULT_TRACE_NODES
|
||||
: dto.traceNodes.map((node, index) => ({
|
||||
nodeType: node.nodeType,
|
||||
title: node.title,
|
||||
occurredAt: node.occurredAt ? new Date(node.occurredAt) : null,
|
||||
location: node.location,
|
||||
description: node.description,
|
||||
mediaFiles: (node.mediaFiles ?? []) as unknown as Prisma.InputJsonValue,
|
||||
sortOrder: node.sortOrder ?? index,
|
||||
}));
|
||||
const certificates = (dto.certificates ?? []).map((cert) => ({
|
||||
name: cert.name,
|
||||
issuer: cert.issuer,
|
||||
issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null,
|
||||
type: cert.type,
|
||||
originFileUrl: cert.originKey,
|
||||
}));
|
||||
dto.traceNodes === undefined ? DEFAULT_TRACE_NODES : this.normalizeTraceNodeDto(dto.traceNodes);
|
||||
const certificates = this.normalizeCertificateDto(dto.certificates ?? []);
|
||||
|
||||
const artwork = await this.prisma.$transaction(async (tx) => {
|
||||
const created = await tx.artwork.create({
|
||||
@@ -75,27 +99,57 @@ export class ArtworkService {
|
||||
templateId: dto.templateId,
|
||||
title: dto.title,
|
||||
artist: dto.artist,
|
||||
status: dto.status,
|
||||
status,
|
||||
auditStatus: AuditStatus.PENDING,
|
||||
dynamicFields: (dto.dynamicFields ?? {}) as Prisma.InputJsonValue,
|
||||
images: (dto.images ?? []) as unknown as Prisma.InputJsonValue,
|
||||
createdBy: userId,
|
||||
traceNodes: traceNodes.length ? { create: traceNodes } : undefined,
|
||||
certificates: certificates.length ? { create: certificates } : undefined,
|
||||
traceNodes: traceNodes.length
|
||||
? {
|
||||
create: traceNodes.map((node) => ({
|
||||
nodeType: node.nodeType as any,
|
||||
title: node.title,
|
||||
occurredAt: node.occurredAt ? new Date(node.occurredAt) : null,
|
||||
location: node.location,
|
||||
description: node.description,
|
||||
mediaFiles: (node.mediaFiles ?? []) as unknown as Prisma.InputJsonValue,
|
||||
sortOrder: node.sortOrder,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
certificates: certificates.length
|
||||
? {
|
||||
create: certificates.map((cert) => ({
|
||||
name: cert.name,
|
||||
issuer: cert.issuer,
|
||||
issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null,
|
||||
type: cert.type as any,
|
||||
originFileUrl: cert.originKey,
|
||||
watermarkFileUrl: cert.watermarkKey ?? null,
|
||||
})),
|
||||
}
|
||||
: undefined,
|
||||
},
|
||||
include: { certificates: true },
|
||||
include: { traceNodes: true, certificates: true },
|
||||
});
|
||||
await tx.artwork.update({
|
||||
where: { id: created.id },
|
||||
data: { archiveNo: this.buildArchiveNo(created.id) },
|
||||
const archiveNo = this.buildArchiveNo(created.id);
|
||||
await tx.artwork.update({ where: { id: created.id }, data: { archiveNo } });
|
||||
const snapshot = this.snapshotFromRecord(created);
|
||||
await tx.artworkRevision.create({
|
||||
data: {
|
||||
artworkId: created.id,
|
||||
title: status === ArtworkStatus.DRAFT ? '创建草稿' : '提交初次审核',
|
||||
reason: status === ArtworkStatus.DRAFT ? '新建作品保存为草稿' : '新建作品提交审核',
|
||||
beforeSnapshot: {} as Prisma.InputJsonObject,
|
||||
afterSnapshot: snapshot as unknown as Prisma.InputJsonObject,
|
||||
status: status === ArtworkStatus.DRAFT ? ArtworkRevisionStatus.APPROVED : ArtworkRevisionStatus.PENDING,
|
||||
submittedBy: userId,
|
||||
},
|
||||
});
|
||||
return created;
|
||||
});
|
||||
|
||||
await Promise.all(
|
||||
artwork.certificates.map((cert) =>
|
||||
this.watermarkQueue.add('generate', { certificateId: cert.id, originKey: cert.originFileUrl }),
|
||||
),
|
||||
);
|
||||
await this.enqueuePendingCertificateWatermarks(artwork.id);
|
||||
return this.get(artwork.id);
|
||||
}
|
||||
|
||||
@@ -126,7 +180,7 @@ export class ArtworkService {
|
||||
}),
|
||||
this.prisma.artwork.count({ where }),
|
||||
]);
|
||||
// 每款查询总次数 = 该款所有码 queryCount 之和(PRD 6.5:按款统计)
|
||||
|
||||
const ids = rows.map((r) => r.id);
|
||||
const sums = ids.length
|
||||
? await this.prisma.traceCode.groupBy({
|
||||
@@ -135,13 +189,33 @@ export class ArtworkService {
|
||||
_sum: { queryCount: true },
|
||||
})
|
||||
: [];
|
||||
const revisions = ids.length
|
||||
? await this.prisma.artworkRevision.findMany({
|
||||
where: { artworkId: { in: ids } },
|
||||
orderBy: { submittedAt: 'desc' },
|
||||
select: { id: true, artworkId: true, title: true, status: true, auditRemark: true, submittedAt: true },
|
||||
})
|
||||
: [];
|
||||
const sumMap = new Map(sums.map((s) => [s.artworkId, s._sum.queryCount ?? 0]));
|
||||
const list = rows.map((a) => ({
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
codeCount: a._count.traceCodes,
|
||||
queryTotal: sumMap.get(a.id) ?? 0,
|
||||
}));
|
||||
const revisionMap = new Map<number, (typeof revisions)[number]>();
|
||||
for (const revision of revisions) {
|
||||
const current = revisionMap.get(revision.artworkId);
|
||||
if (!current || revision.status === ArtworkRevisionStatus.PENDING) {
|
||||
revisionMap.set(revision.artworkId, revision);
|
||||
}
|
||||
}
|
||||
const list = rows.map((a) => {
|
||||
const revision = revisionMap.get(a.id) ?? null;
|
||||
return {
|
||||
...a,
|
||||
images: this.mapMedia(a.images),
|
||||
codeCount: a._count.traceCodes,
|
||||
queryTotal: sumMap.get(a.id) ?? 0,
|
||||
latestRevision: revision,
|
||||
effectiveAuditStatus: revision?.status ?? a.auditStatus,
|
||||
effectiveAuditRemark: revision?.auditRemark ?? a.auditRemark,
|
||||
};
|
||||
});
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
@@ -156,12 +230,19 @@ export class ArtworkService {
|
||||
},
|
||||
});
|
||||
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
// 码统计:总数、已激活数、查询总次数(按款聚合)
|
||||
const [total, active, batchTotal, agg] = await this.prisma.$transaction([
|
||||
const [total, active, batchTotal, agg, latestRevision] = await this.prisma.$transaction([
|
||||
this.prisma.traceCode.count({ where: { artworkId: id } }),
|
||||
this.prisma.traceCode.count({ where: { artworkId: id, status: 'ACTIVE' } }),
|
||||
this.prisma.batch.count({ where: { artworkId: id } }),
|
||||
this.prisma.traceCode.aggregate({ where: { artworkId: id }, _sum: { queryCount: true } }),
|
||||
this.prisma.artworkRevision.findFirst({
|
||||
where: { artworkId: id },
|
||||
orderBy: { submittedAt: 'desc' },
|
||||
include: {
|
||||
submitter: { select: { id: true, username: true, realName: true } },
|
||||
reviewer: { select: { id: true, username: true, realName: true } },
|
||||
},
|
||||
}),
|
||||
]);
|
||||
return {
|
||||
...a,
|
||||
@@ -172,35 +253,174 @@ export class ArtworkService {
|
||||
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
|
||||
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
|
||||
})),
|
||||
latestRevision,
|
||||
effectiveAuditStatus: latestRevision?.status ?? a.auditStatus,
|
||||
effectiveAuditRemark: latestRevision?.auditRemark ?? a.auditRemark,
|
||||
codeStats: { total, active, batchTotal, queryTotal: agg._sum.queryCount ?? 0 },
|
||||
};
|
||||
}
|
||||
|
||||
async update(id: number, dto: UpdateArtworkDto) {
|
||||
await this.ensureExists(id);
|
||||
const data: Prisma.ArtworkUpdateInput = {
|
||||
title: dto.title,
|
||||
artist: dto.artist,
|
||||
status: dto.status,
|
||||
// 内容变更需重新审核:编辑后回到待审核
|
||||
auditStatus: AuditStatus.PENDING,
|
||||
auditRemark: null,
|
||||
auditedBy: null,
|
||||
auditedAt: null,
|
||||
async update(id: number, dto: UpdateArtworkDto, userId: number) {
|
||||
const current = await this.getSnapshot(id);
|
||||
const nextStatus = dto.status === ArtworkStatus.DRAFT ? ArtworkStatus.ACTIVE : dto.status ?? current.artwork.status;
|
||||
const afterSnapshot: ArtworkSnapshot = {
|
||||
artwork: {
|
||||
templateId: current.artwork.templateId,
|
||||
title: dto.title ?? current.artwork.title,
|
||||
artist: dto.artist ?? current.artwork.artist,
|
||||
status: nextStatus,
|
||||
dynamicFields: dto.dynamicFields ?? current.artwork.dynamicFields,
|
||||
images: (dto.images ?? current.artwork.images) as MediaItem[],
|
||||
},
|
||||
traceNodes: dto.traceNodes ? this.normalizeTraceNodeDto(dto.traceNodes) : current.traceNodes,
|
||||
certificates: dto.certificates ? this.normalizeCertificateDto(dto.certificates) : current.certificates,
|
||||
};
|
||||
if (dto.dynamicFields !== undefined) {
|
||||
data.dynamicFields = dto.dynamicFields as Prisma.InputJsonValue;
|
||||
}
|
||||
if (dto.images !== undefined) {
|
||||
data.images = dto.images as unknown as Prisma.InputJsonValue;
|
||||
}
|
||||
await this.prisma.artwork.update({ where: { id }, data });
|
||||
|
||||
const artwork = await this.ensureExists(id);
|
||||
const shouldApplyDirectly = artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED;
|
||||
const revisionTitle = dto.revisionTitle || '作品内容修改';
|
||||
const revisionReason = dto.revisionReason || null;
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await this.supersedePendingRevisions(tx, id);
|
||||
const revision = await tx.artworkRevision.create({
|
||||
data: {
|
||||
artworkId: id,
|
||||
title: revisionTitle,
|
||||
reason: revisionReason,
|
||||
beforeSnapshot: current as unknown as Prisma.InputJsonObject,
|
||||
afterSnapshot: afterSnapshot as unknown as Prisma.InputJsonObject,
|
||||
status: ArtworkRevisionStatus.PENDING,
|
||||
submittedBy: userId,
|
||||
},
|
||||
});
|
||||
|
||||
if (shouldApplyDirectly) {
|
||||
await this.applySnapshot(tx, id, afterSnapshot, {
|
||||
auditStatus: AuditStatus.PENDING,
|
||||
auditRemark: null,
|
||||
auditedBy: null,
|
||||
auditedAt: null,
|
||||
});
|
||||
await tx.artworkRevision.update({ where: { id: revision.id }, data: { afterSnapshot: afterSnapshot as unknown as Prisma.InputJsonObject } });
|
||||
}
|
||||
});
|
||||
|
||||
await this.enqueuePendingCertificateWatermarks(id);
|
||||
return this.get(id);
|
||||
}
|
||||
|
||||
// 审核:通过 / 驳回(审核员或超管)
|
||||
async auditList(query: QueryArtworkRevisionDto) {
|
||||
const where: Prisma.ArtworkRevisionWhereInput = {};
|
||||
if (query.status) where.status = query.status;
|
||||
else where.status = ArtworkRevisionStatus.PENDING;
|
||||
if (query.keyword) {
|
||||
where.OR = [
|
||||
{ title: { contains: query.keyword } },
|
||||
{ artwork: { title: { contains: query.keyword } } },
|
||||
{ artwork: { archiveNo: { contains: query.keyword } } },
|
||||
];
|
||||
}
|
||||
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['submittedAt', 'reviewedAt'] as const, {
|
||||
submittedAt: 'desc',
|
||||
});
|
||||
const [rows, total] = await this.prisma.$transaction([
|
||||
this.prisma.artworkRevision.findMany({
|
||||
where,
|
||||
include: {
|
||||
artwork: {
|
||||
include: {
|
||||
template: { select: { id: true, name: true } },
|
||||
_count: { select: { traceCodes: true } },
|
||||
},
|
||||
},
|
||||
submitter: { select: { id: true, username: true, realName: true } },
|
||||
reviewer: { select: { id: true, username: true, realName: true } },
|
||||
},
|
||||
orderBy,
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.artworkRevision.count({ where }),
|
||||
]);
|
||||
const list = rows
|
||||
.filter((r) => !r.artwork.deletedAt && r.artwork.status !== ArtworkStatus.DRAFT)
|
||||
.map((r) => {
|
||||
const after = this.snapshotWithUrls(r.afterSnapshot) as ArtworkSnapshot & {
|
||||
artwork?: { images?: Array<MediaItem & { url: string }> };
|
||||
};
|
||||
return {
|
||||
...r.artwork,
|
||||
title: after.artwork?.title ?? r.artwork.title,
|
||||
artist: after.artwork?.artist ?? r.artwork.artist,
|
||||
revisionId: r.id,
|
||||
revisionTitle: r.title,
|
||||
revisionReason: r.reason,
|
||||
submittedAt: r.submittedAt,
|
||||
submittedBy: r.submitter,
|
||||
reviewedAt: r.reviewedAt,
|
||||
reviewedBy: r.reviewer,
|
||||
auditStatus: r.status,
|
||||
auditRemark: r.auditRemark,
|
||||
images: after.artwork?.images ?? this.mapMedia(r.artwork.images),
|
||||
codeCount: r.artwork._count.traceCodes,
|
||||
isRevision: true,
|
||||
};
|
||||
});
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async listRevisions(id: number, query: QueryArtworkRevisionDto) {
|
||||
await this.ensureExists(id);
|
||||
const where: Prisma.ArtworkRevisionWhereInput = { artworkId: id };
|
||||
if (query.status) where.status = query.status;
|
||||
const [rows, total] = await this.prisma.$transaction([
|
||||
this.prisma.artworkRevision.findMany({
|
||||
where,
|
||||
include: {
|
||||
submitter: { select: { id: true, username: true, realName: true } },
|
||||
reviewer: { select: { id: true, username: true, realName: true } },
|
||||
},
|
||||
orderBy: { submittedAt: 'desc' },
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
}),
|
||||
this.prisma.artworkRevision.count({ where }),
|
||||
]);
|
||||
return buildPage(rows, total, query.page, query.pageSize);
|
||||
}
|
||||
|
||||
async getRevision(id: number, revisionId: string) {
|
||||
const revision = await this.prisma.artworkRevision.findFirst({
|
||||
where: { id: revisionId, artworkId: id },
|
||||
include: {
|
||||
artwork: { select: { id: true, title: true, archiveNo: true } },
|
||||
submitter: { select: { id: true, username: true, realName: true } },
|
||||
reviewer: { select: { id: true, username: true, realName: true } },
|
||||
},
|
||||
});
|
||||
if (!revision) throw new BusinessException(ErrorCode.NOT_FOUND, '修改记录不存在', 404);
|
||||
return {
|
||||
...revision,
|
||||
beforeSnapshot: this.snapshotWithUrls(revision.beforeSnapshot),
|
||||
afterSnapshot: this.snapshotWithUrls(revision.afterSnapshot),
|
||||
};
|
||||
}
|
||||
|
||||
async audit(id: number, dto: AuditArtworkDto, auditorId: number) {
|
||||
await this.ensureExists(id);
|
||||
const revision = dto.revisionId
|
||||
? await this.prisma.artworkRevision.findFirst({ where: { id: dto.revisionId, artworkId: id } })
|
||||
: await this.prisma.artworkRevision.findFirst({
|
||||
where: { artworkId: id, status: ArtworkRevisionStatus.PENDING },
|
||||
orderBy: { submittedAt: 'desc' },
|
||||
});
|
||||
|
||||
if (revision) {
|
||||
await this.auditRevision(id, revision.id, dto, auditorId);
|
||||
return this.get(id);
|
||||
}
|
||||
|
||||
await this.prisma.artwork.update({
|
||||
where: { id },
|
||||
data: {
|
||||
@@ -222,7 +442,7 @@ export class ArtworkService {
|
||||
if (traceCodeCount > 0 || queryLogCount > 0) {
|
||||
throw new BusinessException(
|
||||
ErrorCode.ARTWORK_IN_USE,
|
||||
'该档案已生成追溯码或存在查询记录,不能删除;请改为停用或归档',
|
||||
'该档案已生成追溯码或存在查询记录,不能删除;请改为停用或归档。',
|
||||
400,
|
||||
);
|
||||
}
|
||||
@@ -230,6 +450,242 @@ export class ArtworkService {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
private normalizeTraceNodeDto(nodes: CreateArtworkTraceNodeDto[]): TraceNodeSnapshot[] {
|
||||
return nodes.map((node, index) => ({
|
||||
nodeType: node.nodeType,
|
||||
title: node.title,
|
||||
occurredAt: node.occurredAt ?? null,
|
||||
location: node.location ?? null,
|
||||
description: node.description ?? null,
|
||||
mediaFiles: (node.mediaFiles ?? []) as MediaItem[],
|
||||
sortOrder: node.sortOrder ?? index,
|
||||
}));
|
||||
}
|
||||
|
||||
private normalizeCertificateDto(certs: CreateArtworkCertificateDto[]): CertificateSnapshot[] {
|
||||
return certs.map((cert) => ({
|
||||
name: cert.name,
|
||||
issuer: cert.issuer ?? null,
|
||||
issuedAt: cert.issuedAt ?? null,
|
||||
type: cert.type,
|
||||
originKey: cert.originKey,
|
||||
watermarkKey: cert.watermarkKey ?? null,
|
||||
}));
|
||||
}
|
||||
|
||||
private snapshotFromRecord(record: {
|
||||
templateId: number;
|
||||
title: string;
|
||||
artist: string | null;
|
||||
status: string;
|
||||
dynamicFields: Prisma.JsonValue | null;
|
||||
images: Prisma.JsonValue | null;
|
||||
traceNodes: Array<{
|
||||
nodeType: string;
|
||||
title: string;
|
||||
occurredAt: Date | null;
|
||||
location: string | null;
|
||||
description: string | null;
|
||||
mediaFiles: Prisma.JsonValue | null;
|
||||
sortOrder: number;
|
||||
}>;
|
||||
certificates: Array<{
|
||||
name: string;
|
||||
issuer: string | null;
|
||||
issuedAt: Date | null;
|
||||
type: string;
|
||||
originFileUrl: string;
|
||||
watermarkFileUrl: string | null;
|
||||
}>;
|
||||
}): ArtworkSnapshot {
|
||||
return {
|
||||
artwork: {
|
||||
templateId: record.templateId,
|
||||
title: record.title,
|
||||
artist: record.artist,
|
||||
status: record.status as ArtworkStatus,
|
||||
dynamicFields: (record.dynamicFields as Record<string, unknown>) ?? {},
|
||||
images: (Array.isArray(record.images) ? record.images : []) as unknown as MediaItem[],
|
||||
},
|
||||
traceNodes: record.traceNodes
|
||||
.sort((a, b) => a.sortOrder - b.sortOrder)
|
||||
.map((node) => ({
|
||||
nodeType: node.nodeType,
|
||||
title: node.title,
|
||||
occurredAt: node.occurredAt ? node.occurredAt.toISOString() : null,
|
||||
location: node.location,
|
||||
description: node.description,
|
||||
mediaFiles: (Array.isArray(node.mediaFiles) ? node.mediaFiles : []) as unknown as MediaItem[],
|
||||
sortOrder: node.sortOrder,
|
||||
})),
|
||||
certificates: record.certificates.map((cert) => ({
|
||||
name: cert.name,
|
||||
issuer: cert.issuer,
|
||||
issuedAt: cert.issuedAt ? cert.issuedAt.toISOString() : null,
|
||||
type: cert.type,
|
||||
originKey: cert.originFileUrl,
|
||||
watermarkKey: cert.watermarkFileUrl,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private snapshotWithUrls(input: unknown) {
|
||||
const snapshot = input as ArtworkSnapshot | Record<string, never>;
|
||||
if (!('artwork' in snapshot)) return snapshot;
|
||||
return {
|
||||
...snapshot,
|
||||
artwork: {
|
||||
...snapshot.artwork,
|
||||
images: this.mapMedia(snapshot.artwork.images),
|
||||
},
|
||||
traceNodes: snapshot.traceNodes.map((node) => ({
|
||||
...node,
|
||||
mediaFiles: this.mapMedia(node.mediaFiles),
|
||||
})),
|
||||
certificates: snapshot.certificates.map((cert) => ({
|
||||
...cert,
|
||||
originUrl: cert.originKey ? this.storage.getUrl(cert.originKey) : null,
|
||||
watermarkUrl: cert.watermarkKey ? this.storage.getUrl(cert.watermarkKey) : null,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
private async getSnapshot(id: number): Promise<ArtworkSnapshot> {
|
||||
const artwork = await this.prisma.artwork.findFirst({
|
||||
where: { id, deletedAt: null },
|
||||
include: {
|
||||
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
||||
certificates: { orderBy: { id: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
return this.snapshotFromRecord(artwork);
|
||||
}
|
||||
|
||||
private async applySnapshot(
|
||||
tx: Prisma.TransactionClient,
|
||||
id: number,
|
||||
snapshot: ArtworkSnapshot,
|
||||
auditData: Pick<Prisma.ArtworkUpdateInput, 'auditStatus' | 'auditRemark' | 'auditedBy' | 'auditedAt'>,
|
||||
) {
|
||||
await tx.artwork.update({
|
||||
where: { id },
|
||||
data: {
|
||||
templateId: snapshot.artwork.templateId,
|
||||
title: snapshot.artwork.title,
|
||||
artist: snapshot.artwork.artist,
|
||||
status: snapshot.artwork.status,
|
||||
dynamicFields: snapshot.artwork.dynamicFields as Prisma.InputJsonObject,
|
||||
images: snapshot.artwork.images as unknown as Prisma.InputJsonValue,
|
||||
...auditData,
|
||||
},
|
||||
});
|
||||
await tx.traceNode.deleteMany({ where: { artworkId: id } });
|
||||
if (snapshot.traceNodes.length) {
|
||||
await tx.traceNode.createMany({
|
||||
data: snapshot.traceNodes.map((node, index) => ({
|
||||
artworkId: id,
|
||||
nodeType: node.nodeType as any,
|
||||
title: node.title,
|
||||
occurredAt: node.occurredAt ? new Date(node.occurredAt) : null,
|
||||
location: node.location,
|
||||
description: node.description,
|
||||
mediaFiles: (node.mediaFiles ?? []) as unknown as Prisma.InputJsonValue,
|
||||
sortOrder: index,
|
||||
})),
|
||||
});
|
||||
}
|
||||
await tx.certificate.deleteMany({ where: { artworkId: id } });
|
||||
if (snapshot.certificates.length) {
|
||||
await tx.certificate.createMany({
|
||||
data: snapshot.certificates.map((cert) => ({
|
||||
artworkId: id,
|
||||
name: cert.name,
|
||||
issuer: cert.issuer,
|
||||
issuedAt: cert.issuedAt ? new Date(cert.issuedAt) : null,
|
||||
type: cert.type as any,
|
||||
originFileUrl: cert.originKey,
|
||||
watermarkFileUrl: cert.watermarkKey ?? null,
|
||||
})),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private async supersedePendingRevisions(tx: Prisma.TransactionClient, artworkId: number) {
|
||||
await tx.artworkRevision.updateMany({
|
||||
where: { artworkId, status: ArtworkRevisionStatus.PENDING },
|
||||
data: {
|
||||
status: ArtworkRevisionStatus.REJECTED,
|
||||
auditRemark: '已被新的修改提交替代',
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private async auditRevision(id: number, revisionId: string, dto: AuditArtworkDto, auditorId: number) {
|
||||
const artwork = await this.ensureExists(id);
|
||||
const revision = await this.prisma.artworkRevision.findFirst({ where: { id: revisionId, artworkId: id } });
|
||||
if (!revision) throw new BusinessException(ErrorCode.NOT_FOUND, '修改记录不存在', 404);
|
||||
if (revision.status !== ArtworkRevisionStatus.PENDING) {
|
||||
throw new BusinessException(ErrorCode.VALIDATION_FAILED, '该修改记录已审核,不能重复操作', 400);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
if (dto.approved) {
|
||||
await this.applySnapshot(tx, id, revision.afterSnapshot as unknown as ArtworkSnapshot, {
|
||||
auditStatus: AuditStatus.APPROVED,
|
||||
auditRemark: dto.remark ?? null,
|
||||
auditedBy: auditorId,
|
||||
auditedAt: new Date(),
|
||||
});
|
||||
await tx.artworkRevision.update({
|
||||
where: { id: revisionId },
|
||||
data: {
|
||||
status: ArtworkRevisionStatus.APPROVED,
|
||||
auditRemark: dto.remark ?? null,
|
||||
reviewedBy: auditorId,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
});
|
||||
} else {
|
||||
await tx.artworkRevision.update({
|
||||
where: { id: revisionId },
|
||||
data: {
|
||||
status: ArtworkRevisionStatus.REJECTED,
|
||||
auditRemark: dto.remark ?? null,
|
||||
reviewedBy: auditorId,
|
||||
reviewedAt: new Date(),
|
||||
},
|
||||
});
|
||||
if (artwork.auditStatus !== AuditStatus.APPROVED) {
|
||||
await tx.artwork.update({
|
||||
where: { id },
|
||||
data: {
|
||||
auditStatus: AuditStatus.REJECTED,
|
||||
auditRemark: dto.remark ?? null,
|
||||
auditedBy: auditorId,
|
||||
auditedAt: new Date(),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (dto.approved) await this.enqueuePendingCertificateWatermarks(id);
|
||||
}
|
||||
|
||||
private async enqueuePendingCertificateWatermarks(artworkId: number) {
|
||||
const certs = await this.prisma.certificate.findMany({
|
||||
where: { artworkId, watermarkFileUrl: null },
|
||||
select: { id: true, originFileUrl: true },
|
||||
});
|
||||
await Promise.all(
|
||||
certs.map((cert) =>
|
||||
this.watermarkQueue.add('generate', { certificateId: cert.id, originKey: cert.originFileUrl }),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private async ensureExists(id: number) {
|
||||
const a = await this.prisma.artwork.findFirst({ where: { id, deletedAt: null } });
|
||||
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
ValidateNested,
|
||||
} from 'class-validator';
|
||||
import { IsBoolean } from 'class-validator';
|
||||
import { ArtworkStatus, AuditStatus, CertType, NodeType } from '@artveris/shared';
|
||||
import { ArtworkRevisionStatus, ArtworkStatus, AuditStatus, CertType, NodeType } from '@artveris/shared';
|
||||
import { PaginationDto } from '../../common/dto/pagination.dto';
|
||||
|
||||
export class MediaItemDto {
|
||||
@@ -150,6 +150,11 @@ export class CreateArtworkCertificateDto {
|
||||
@IsString()
|
||||
@IsNotEmpty()
|
||||
originKey!: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '已有水印文件 key' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
watermarkKey?: string;
|
||||
}
|
||||
|
||||
export class UpdateArtworkDto {
|
||||
@@ -181,6 +186,32 @@ export class UpdateArtworkDto {
|
||||
@IsOptional()
|
||||
@IsEnum(ArtworkStatus)
|
||||
status?: ArtworkStatus;
|
||||
|
||||
@ApiPropertyOptional({ description: '变更标题' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(120)
|
||||
revisionTitle?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '变更原因 / 修改说明' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(1000)
|
||||
revisionReason?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '保存时一并提交的溯源时间轴', type: () => [CreateArtworkTraceNodeDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateArtworkTraceNodeDto)
|
||||
traceNodes?: CreateArtworkTraceNodeDto[];
|
||||
|
||||
@ApiPropertyOptional({ description: '保存时一并提交的认证文件', type: () => [CreateArtworkCertificateDto] })
|
||||
@IsOptional()
|
||||
@IsArray()
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => CreateArtworkCertificateDto)
|
||||
certificates?: CreateArtworkCertificateDto[];
|
||||
}
|
||||
|
||||
export class QueryArtworkDto extends PaginationDto {
|
||||
@@ -216,4 +247,21 @@ export class AuditArtworkDto {
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
remark?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '审核变更稿 ID;为空时审核作品当前版本' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
revisionId?: string;
|
||||
}
|
||||
|
||||
export class QueryArtworkRevisionDto extends PaginationDto {
|
||||
@ApiPropertyOptional({ description: '关键词(作品名称 / 档案编号 / 变更标题)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
keyword?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '审核状态', enum: ArtworkRevisionStatus })
|
||||
@IsOptional()
|
||||
@IsEnum(ArtworkRevisionStatus)
|
||||
status?: ArtworkRevisionStatus;
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ const MODELS = [
|
||||
'template',
|
||||
'templateField',
|
||||
'artwork',
|
||||
'artworkRevision',
|
||||
'traceNode',
|
||||
'certificate',
|
||||
'traceCodeGroup',
|
||||
@@ -41,6 +42,7 @@ const PRISMA_MODEL_BY_DELEGATE: Record<(typeof MODELS)[number], string> = {
|
||||
template: 'Template',
|
||||
templateField: 'TemplateField',
|
||||
artwork: 'Artwork',
|
||||
artworkRevision: 'ArtworkRevision',
|
||||
traceNode: 'TraceNode',
|
||||
certificate: 'Certificate',
|
||||
traceCodeGroup: 'TraceCodeGroup',
|
||||
@@ -60,6 +62,8 @@ const DATE_KEYS = new Set([
|
||||
'updatedAt',
|
||||
'deletedAt',
|
||||
'auditedAt',
|
||||
'submittedAt',
|
||||
'reviewedAt',
|
||||
'occurredAt',
|
||||
'issuedAt',
|
||||
'outTime',
|
||||
|
||||
Reference in New Issue
Block a user