780 lines
29 KiB
TypeScript
780 lines
29 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { InjectQueue } from '@nestjs/bullmq';
|
|
import { Prisma } from '@prisma/client';
|
|
import { Queue } from 'bullmq';
|
|
import { ArtworkRevisionStatus, ArtworkStatus, AuditStatus, ErrorCode, QUEUE_NAMES, RoleType } 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,
|
|
CreateArtworkCertificateDto,
|
|
CreateArtworkDto,
|
|
CreateArtworkTraceNodeDto,
|
|
QueryArtworkDto,
|
|
QueryArtworkRevisionDto,
|
|
UpdateArtworkDto,
|
|
} from './dto/artwork.dto';
|
|
import type { AuthUser } from '../common/decorators/current-user.decorator';
|
|
|
|
interface MediaItem {
|
|
key: string;
|
|
name?: string;
|
|
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 },
|
|
{ nodeType: 'STORAGE', title: '仓储 / 托管', sortOrder: 2 },
|
|
{ nodeType: 'OUTBOUND', title: '出库 / 流转', sortOrder: 3 },
|
|
];
|
|
|
|
@Injectable()
|
|
export class ArtworkService {
|
|
constructor(
|
|
private readonly prisma: PrismaService,
|
|
private readonly storage: StorageService,
|
|
@InjectQueue(QUEUE_NAMES.WATERMARK) private readonly watermarkQueue: Queue,
|
|
) {}
|
|
|
|
private mapMedia(items: unknown): Array<MediaItem & { url: string }> {
|
|
if (!Array.isArray(items)) return [];
|
|
return (items as MediaItem[])
|
|
.filter((i) => i && i.key)
|
|
.map((i) => ({ ...i, url: this.storage.getUrl(i.key) }));
|
|
}
|
|
|
|
private buildArchiveNo(id: number): string {
|
|
return `ARTVERIS-${String(id).padStart(6, '0')}`;
|
|
}
|
|
|
|
async create(dto: CreateArtworkDto, userId: number) {
|
|
const tpl = await this.prisma.template.findFirst({
|
|
where: { id: dto.templateId, deletedAt: null },
|
|
});
|
|
if (!tpl) throw new BusinessException(ErrorCode.TEMPLATE_NOT_FOUND, '模板不存在', 404);
|
|
|
|
const status = dto.status ?? ArtworkStatus.ACTIVE;
|
|
const traceNodes =
|
|
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({
|
|
data: {
|
|
templateId: dto.templateId,
|
|
title: dto.title,
|
|
artist: dto.artist,
|
|
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.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: { traceNodes: true, certificates: true },
|
|
});
|
|
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 this.enqueuePendingCertificateWatermarks(artwork.id);
|
|
return this.get(artwork.id);
|
|
}
|
|
|
|
async list(query: QueryArtworkDto) {
|
|
const where: Prisma.ArtworkWhereInput = { deletedAt: null };
|
|
if (query.keyword) {
|
|
where.OR = [
|
|
{ title: { contains: query.keyword } },
|
|
{ artist: { contains: query.keyword } },
|
|
{ archiveNo: { contains: query.keyword } },
|
|
];
|
|
}
|
|
if (query.status) where.status = query.status;
|
|
if (query.templateId) where.templateId = query.templateId;
|
|
|
|
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'updatedAt'] as const, { id: 'desc' });
|
|
const shouldFilterEffectiveAuditStatus = Boolean(query.auditStatus);
|
|
const [rows, total] = await this.prisma.$transaction([
|
|
this.prisma.artwork.findMany({
|
|
where,
|
|
include: {
|
|
template: { select: { id: true, name: true } },
|
|
_count: { select: { traceCodes: true } },
|
|
},
|
|
orderBy,
|
|
skip: shouldFilterEffectiveAuditStatus ? undefined : query.skip,
|
|
take: shouldFilterEffectiveAuditStatus ? undefined : query.take,
|
|
}),
|
|
this.prisma.artwork.count({ where }),
|
|
]);
|
|
|
|
const ids = rows.map((r) => r.id);
|
|
const sums = ids.length
|
|
? await this.prisma.traceCode.groupBy({
|
|
by: ['artworkId'],
|
|
where: { artworkId: { in: ids } },
|
|
_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 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;
|
|
const effectiveAuditStatus = this.getEffectiveArtworkAuditStatus(a.auditStatus, revision?.status);
|
|
return {
|
|
...a,
|
|
images: this.mapMedia(a.images),
|
|
codeCount: a._count.traceCodes,
|
|
queryTotal: sumMap.get(a.id) ?? 0,
|
|
latestRevision: revision,
|
|
effectiveAuditStatus,
|
|
effectiveAuditRemark: revision?.auditRemark ?? a.auditRemark,
|
|
};
|
|
});
|
|
if (query.auditStatus) {
|
|
const filtered = list.filter((item) => item.effectiveAuditStatus === query.auditStatus);
|
|
const paged = query.pageSize === 0 ? filtered : filtered.slice(query.skip, query.skip + query.pageSize);
|
|
return buildPage(paged, filtered.length, query.page, query.pageSize);
|
|
}
|
|
return buildPage(list, total, query.page, query.pageSize);
|
|
}
|
|
|
|
async get(id: number) {
|
|
const a = await this.prisma.artwork.findFirst({
|
|
where: { id, deletedAt: null },
|
|
include: {
|
|
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
|
|
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
|
certificates: { orderBy: { id: 'asc' } },
|
|
batches: { orderBy: { id: 'desc' } },
|
|
},
|
|
});
|
|
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
|
|
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,
|
|
images: this.mapMedia(a.images),
|
|
traceNodes: a.traceNodes.map((n) => ({ ...n, mediaFiles: this.mapMedia(n.mediaFiles) })),
|
|
certificates: a.certificates.map((c) => ({
|
|
...c,
|
|
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, user: AuthUser) {
|
|
const userId = user.id;
|
|
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,
|
|
};
|
|
|
|
const artwork = await this.ensureExists(id);
|
|
const shouldApplyDirectly = artwork.status !== ArtworkStatus.ACTIVE || artwork.auditStatus !== AuditStatus.APPROVED;
|
|
const shouldAutoApprove = user.role === RoleType.SUPER_ADMIN;
|
|
if (!this.hasSnapshotChanged(current, afterSnapshot)) {
|
|
throw new BusinessException(ErrorCode.VALIDATION_FAILED, '作品内容未发生变化,无需提交审核', 400);
|
|
}
|
|
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: shouldAutoApprove ? ArtworkRevisionStatus.APPROVED : ArtworkRevisionStatus.PENDING,
|
|
auditRemark: null,
|
|
submittedBy: userId,
|
|
reviewedBy: shouldAutoApprove ? userId : null,
|
|
reviewedAt: shouldAutoApprove ? new Date() : null,
|
|
},
|
|
});
|
|
|
|
if (shouldAutoApprove || shouldApplyDirectly) {
|
|
await this.applySnapshot(tx, id, afterSnapshot, {
|
|
auditStatus: shouldAutoApprove ? AuditStatus.APPROVED : AuditStatus.PENDING,
|
|
auditRemark: null,
|
|
auditedBy: shouldAutoApprove ? userId : null,
|
|
auditedAt: shouldAutoApprove ? new Date() : 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: {
|
|
auditStatus: dto.approved ? AuditStatus.APPROVED : AuditStatus.REJECTED,
|
|
auditRemark: dto.remark ?? null,
|
|
auditedBy: auditorId,
|
|
auditedAt: new Date(),
|
|
},
|
|
});
|
|
return this.get(id);
|
|
}
|
|
|
|
async remove(id: number) {
|
|
await this.ensureExists(id);
|
|
const [traceCodeCount, queryLogCount] = await this.prisma.$transaction([
|
|
this.prisma.traceCode.count({ where: { artworkId: id } }),
|
|
this.prisma.queryLog.count({ where: { artworkId: id } }),
|
|
]);
|
|
if (traceCodeCount > 0 || queryLogCount > 0) {
|
|
throw new BusinessException(
|
|
ErrorCode.ARTWORK_IN_USE,
|
|
'该档案已生成追溯码或存在查询记录,不能删除;请改为停用或归档。',
|
|
400,
|
|
);
|
|
}
|
|
await this.prisma.artwork.update({ where: { id }, data: { deletedAt: new Date() } });
|
|
return { success: true };
|
|
}
|
|
|
|
private normalizeTraceNodeDto(nodes: CreateArtworkTraceNodeDto[]): TraceNodeSnapshot[] {
|
|
return nodes.map((node, index) => ({
|
|
nodeType: node.nodeType,
|
|
title: node.title,
|
|
occurredAt: this.normalizeDateOnly(node.occurredAt),
|
|
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: this.normalizeDateOnly(cert.issuedAt),
|
|
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: this.normalizeDateOnly(node.occurredAt),
|
|
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: this.normalizeDateOnly(cert.issuedAt),
|
|
type: cert.type,
|
|
originKey: cert.originFileUrl,
|
|
watermarkKey: cert.watermarkFileUrl,
|
|
})),
|
|
};
|
|
}
|
|
|
|
private hasSnapshotChanged(before: ArtworkSnapshot, after: ArtworkSnapshot): boolean {
|
|
return JSON.stringify(this.normalizeSnapshotForCompare(before)) !== JSON.stringify(this.normalizeSnapshotForCompare(after));
|
|
}
|
|
|
|
private getEffectiveArtworkAuditStatus(auditStatus: string, revisionStatus?: string | null): AuditStatus {
|
|
if (revisionStatus === ArtworkRevisionStatus.PENDING) return AuditStatus.PENDING;
|
|
if (revisionStatus === ArtworkRevisionStatus.REJECTED) return AuditStatus.REJECTED;
|
|
return auditStatus as AuditStatus;
|
|
}
|
|
|
|
private normalizeSnapshotForCompare(snapshot: ArtworkSnapshot) {
|
|
return {
|
|
artwork: {
|
|
templateId: Number(snapshot.artwork.templateId),
|
|
title: snapshot.artwork.title ?? '',
|
|
artist: snapshot.artwork.artist ?? '',
|
|
status: snapshot.artwork.status,
|
|
dynamicFields: this.normalizeJson(snapshot.artwork.dynamicFields ?? {}),
|
|
images: this.normalizeMedia(snapshot.artwork.images),
|
|
},
|
|
traceNodes: snapshot.traceNodes.map((node, index) => ({
|
|
nodeType: node.nodeType,
|
|
title: node.title ?? '',
|
|
occurredAt: this.normalizeDateOnly(node.occurredAt),
|
|
location: node.location ?? '',
|
|
description: node.description ?? '',
|
|
mediaFiles: this.normalizeMedia(node.mediaFiles),
|
|
sortOrder: index,
|
|
})),
|
|
certificates: snapshot.certificates.map((cert) => ({
|
|
name: cert.name ?? '',
|
|
issuer: cert.issuer ?? '',
|
|
issuedAt: this.normalizeDateOnly(cert.issuedAt),
|
|
type: cert.type,
|
|
originKey: cert.originKey,
|
|
watermarkKey: cert.watermarkKey ?? '',
|
|
})),
|
|
};
|
|
}
|
|
|
|
private normalizeMedia(items?: MediaItem[]) {
|
|
return (items ?? []).map((item) => ({
|
|
key: item.key,
|
|
name: item.name ?? '',
|
|
type: item.type ?? '',
|
|
}));
|
|
}
|
|
|
|
private normalizeJson(value: unknown): unknown {
|
|
if (Array.isArray(value)) return value.map((item) => this.normalizeJson(item));
|
|
if (value && typeof value === 'object') {
|
|
return Object.keys(value as Record<string, unknown>)
|
|
.sort()
|
|
.reduce<Record<string, unknown>>((acc, key) => {
|
|
const item = (value as Record<string, unknown>)[key];
|
|
if (item !== undefined) acc[key] = this.normalizeJson(item);
|
|
return acc;
|
|
}, {});
|
|
}
|
|
return value ?? null;
|
|
}
|
|
|
|
private normalizeDateOnly(value?: string | Date | null): string | null {
|
|
if (!value) return null;
|
|
if (value instanceof Date) return value.toISOString().slice(0, 10);
|
|
const date = new Date(value);
|
|
if (!Number.isNaN(date.getTime())) return date.toISOString().slice(0, 10);
|
|
return value.slice(0, 10);
|
|
}
|
|
|
|
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);
|
|
return a;
|
|
}
|
|
}
|