refactor: 按甲方确认重构为一款多码(档案编号标识款、批次码、按款统计)

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-30 12:02:44 +08:00
co-authored by Cursor
parent 67c5887f8f
commit a16e6f1165
34 changed files with 445 additions and 353 deletions
+32 -2
View File
@@ -27,6 +27,11 @@ 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')}`;
}
async create(dto: CreateArtworkDto, userId: number) {
const tpl = await this.prisma.template.findFirst({
where: { id: dto.templateId, deletedAt: null },
@@ -42,6 +47,11 @@ export class ArtworkService {
createdBy: userId,
},
});
// 创建后回填档案编号(需要自增 id)
await this.prisma.artwork.update({
where: { id: artwork.id },
data: { archiveNo: this.buildArchiveNo(artwork.id) },
});
return this.get(artwork.id);
}
@@ -51,6 +61,7 @@ export class ArtworkService {
where.OR = [
{ title: { contains: query.keyword } },
{ artist: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
if (query.status) where.status = query.status;
@@ -62,7 +73,7 @@ export class ArtworkService {
where,
include: {
template: { select: { id: true, name: true } },
traceCode: { select: { id: true, code: true, shortCode: true, status: true } },
_count: { select: { traceCodes: true } },
},
orderBy: { id: 'desc' },
skip: query.skip,
@@ -70,9 +81,21 @@ 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({
by: ['artworkId'],
where: { artworkId: { in: ids } },
_sum: { queryCount: 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,
}));
return buildPage(list, total, query.page, query.pageSize);
}
@@ -84,10 +107,16 @@ export class ArtworkService {
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
traceNodes: { orderBy: { sortOrder: 'asc' } },
certificates: { orderBy: { id: 'asc' } },
traceCode: { include: { proofs: { orderBy: { id: 'desc' } } } },
batches: { orderBy: { id: 'desc' } },
},
});
if (!a) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
// 码统计:总数、已激活数、查询总次数(按款聚合)
const [total, active, agg] = await this.prisma.$transaction([
this.prisma.traceCode.count({ where: { artworkId: id } }),
this.prisma.traceCode.count({ where: { artworkId: id, status: 'ACTIVE' } }),
this.prisma.traceCode.aggregate({ where: { artworkId: id }, _sum: { queryCount: true } }),
]);
return {
...a,
images: this.mapMedia(a.images),
@@ -97,6 +126,7 @@ export class ArtworkService {
originUrl: c.originFileUrl ? this.storage.getUrl(c.originFileUrl) : null,
watermarkUrl: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
})),
codeStats: { total, active, queryTotal: agg._sum.queryCount ?? 0 },
};
}
@@ -31,9 +31,8 @@ export class AttestationService {
code: code.code,
title: code.artwork.title,
artist: code.artwork.artist,
archiveNo: code.artwork.archiveNo,
dynamicFields: code.artwork.dynamicFields,
sku: code.sku,
archiveNo: code.archiveNo,
nodes: code.artwork.traceNodes.map((n) => ({ type: n.nodeType, title: n.title })),
certificates: code.artwork.certificates.map((c) => c.name),
};
+20 -13
View File
@@ -12,14 +12,14 @@ export class DashboardService {
const [
totalArtworks,
boundCodes,
totalCodes,
activatedCodes,
totalQueries,
todayQueries,
abnormalQueries,
] = await this.prisma.$transaction([
this.prisma.artwork.count({ where: { deletedAt: null } }),
this.prisma.traceCode.count({ where: { artworkId: { not: null } } }),
this.prisma.traceCode.count(),
this.prisma.traceCode.count({ where: { status: TraceCodeStatus.ACTIVE } }),
this.prisma.queryLog.count(),
this.prisma.queryLog.count({ where: { queriedAt: { gte: todayStart } } }),
@@ -30,7 +30,7 @@ export class DashboardService {
return {
totalArtworks,
boundCodes,
totalCodes,
activatedCodes,
totalQueries,
todayQueries,
@@ -58,19 +58,26 @@ export class DashboardService {
return Object.entries(buckets).map(([date, count]) => ({ date, count }));
}
// 高频查询作品榜
// 高频查询作品榜:按款聚合(该款所有码查询次数之和)
async topArtworks(limit: number) {
const codes = await this.prisma.traceCode.findMany({
where: { artworkId: { not: null }, queryCount: { gt: 0 } },
orderBy: { queryCount: 'desc' },
const grouped = await this.prisma.traceCode.groupBy({
by: ['artworkId'],
_sum: { queryCount: true },
orderBy: { _sum: { queryCount: 'desc' } },
take: limit,
include: { artwork: { select: { id: true, title: true } } },
});
return codes.map((c) => ({
artworkId: c.artworkId,
title: c.artwork?.title ?? '-',
shortCode: c.shortCode,
queryCount: c.queryCount,
const ids = grouped.map((g) => g.artworkId);
if (!ids.length) return [];
const artworks = await this.prisma.artwork.findMany({
where: { id: { in: ids } },
select: { id: true, title: true, archiveNo: true },
});
const map = new Map(artworks.map((a) => [a.id, a]));
return grouped.map((g) => ({
artworkId: g.artworkId,
title: map.get(g.artworkId)?.title ?? '-',
archiveNo: map.get(g.artworkId)?.archiveNo ?? '',
queryCount: g._sum.queryCount ?? 0,
}));
}
}
-12
View File
@@ -3,18 +3,6 @@ import { Type } from 'class-transformer';
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
export class OutboundDto {
@ApiPropertyOptional({ description: 'SKU' })
@IsOptional()
@IsString()
@MaxLength(80)
sku?: string;
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
@MaxLength(80)
archiveNo?: string;
@ApiPropertyOptional({ description: '出库时间' })
@IsOptional()
@IsDateString()
@@ -136,8 +136,6 @@ export class ImportProcessor extends WorkerHost {
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
sku: row.values.sku || undefined,
archiveNo: row.values.archiveNo || undefined,
outTime: outTime ?? undefined,
outImage: row.values.outImage || undefined,
remark: row.values.remark || undefined,
@@ -38,8 +38,6 @@ export class OutboundService {
const updated = await this.prisma.traceCode.update({
where: { id: traceCodeId },
data: {
sku: dto.sku,
archiveNo: dto.archiveNo,
outTime: dto.outTime ? new Date(dto.outTime) : undefined,
outImage: dto.outImageKey,
remark: dto.remark,
@@ -8,7 +8,7 @@ import { GeoService } from '../geo/geo.service';
import { REDIS_CLIENT } from '../redis/redis.module';
import { parseUserAgent } from '../common/utils/ua.util';
type TraceCodeWithBatch = Prisma.TraceCodeGetPayload<{ include: { batch: true } }>;
type TraceCodeWithRel = Prisma.TraceCodeGetPayload<{ include: { batch: true; artwork: true } }>;
export interface TraceContext {
ip: string;
@@ -55,9 +55,12 @@ export class PublicTraceService {
return { status: 'INVALID' as const };
}
const code = await this.prisma.traceCode.findUnique({ where: { id }, include: { batch: true } });
if (!code || !code.artworkId || code.status === TraceCodeStatus.UNBOUND) {
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx, code ?? undefined);
const code = await this.prisma.traceCode.findUnique({
where: { id },
include: { batch: true, artwork: true },
});
if (!code) {
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx);
return { status: 'INVALID' as const };
}
if (code.status === TraceCodeStatus.DISABLED) {
@@ -129,6 +132,7 @@ export class PublicTraceService {
artwork: {
title: artwork.title,
artist: artwork.artist,
archiveNo: artwork.archiveNo,
images: this.mapMedia(artwork.images),
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
},
@@ -189,7 +193,7 @@ export class PublicTraceService {
shortCode: string,
result: QueryResult,
ctx: TraceContext,
code?: Partial<TraceCodeWithBatch>,
code?: Partial<TraceCodeWithRel>,
): Promise<void> {
try {
const device = parseUserAgent(ctx.userAgent);
@@ -199,8 +203,7 @@ export class PublicTraceService {
artworkId: artworkId ?? undefined,
shortCode,
code: code?.code ?? undefined,
sku: code?.sku ?? undefined,
archiveNo: code?.archiveNo ?? undefined,
archiveNo: code?.artwork?.archiveNo ?? undefined,
batchNo: code?.batch?.batchNo ?? undefined,
queryCount: code?.queryCount ?? undefined,
firstActivatedAt: code?.firstActivatedAt ?? undefined,
@@ -13,10 +13,10 @@ class QueryLogQueryDto extends PaginationDto {
@IsString()
keyword?: string;
@ApiPropertyOptional({ description: 'SKU' })
@ApiPropertyOptional({ description: '档案编号' })
@IsOptional()
@IsString()
sku?: string;
archiveNo?: string;
@ApiPropertyOptional({ description: '批次编号' })
@IsOptional()
@@ -53,11 +53,10 @@ export class QueryLogController {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ sku: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
if (query.sku) where.sku = { contains: query.sku };
if (query.archiveNo) where.archiveNo = { contains: query.archiveNo };
if (query.batchNo) where.batchNo = { contains: query.batchNo };
if (query.result) where.queryResult = query.result;
if (query.startTime || query.endTime) {
+17 -7
View File
@@ -17,6 +17,11 @@ import { TraceCodeStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class GenerateBatchDto {
@ApiProperty({ description: '所属作品(款)ID' })
@Type(() => Number)
@IsInt()
artworkId!: number;
@ApiProperty({ description: '生成数量', minimum: 1, maximum: 10000 })
@Type(() => Number)
@IsInt()
@@ -38,6 +43,12 @@ export class GenerateBatchDto {
}
export class QueryTraceCodeDto extends PaginationDto {
@ApiPropertyOptional({ description: '作品(款)ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
artworkId?: number;
@ApiPropertyOptional({ description: '批次 ID' })
@IsOptional()
@Type(() => Number)
@@ -105,13 +116,6 @@ export class BatchStatusDto {
abnormal?: boolean;
}
export class BindArtworkDto {
@ApiProperty({ description: '艺术品 ID' })
@Type(() => Number)
@IsInt()
artworkId!: number;
}
export class QueryBatchDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(批次编号)' })
@IsOptional()
@@ -125,6 +129,12 @@ export class ExportTraceCodeDto {
@IsIn(['xlsx', 'csv'])
format?: 'xlsx' | 'csv';
@ApiPropertyOptional({ description: '作品(款)ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
artworkId?: number;
@ApiPropertyOptional({ description: '分组 ID' })
@IsOptional()
@Type(() => Number)
@@ -13,6 +13,7 @@ const codeId = customAlphabet(ALPHABET, 18);
interface GenJobData {
batchId: number;
artworkId: number;
jobId: string;
quantity: number;
groupId?: number | null;
@@ -31,7 +32,7 @@ export class GenCodeProcessor extends WorkerHost {
}
async process(job: Job<GenJobData>): Promise<void> {
const { batchId, jobId, quantity, groupId } = job.data;
const { batchId, artworkId, jobId, quantity, groupId } = job.data;
await this.jobs.start(jobId);
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.GENERATING } });
@@ -45,6 +46,7 @@ export class GenCodeProcessor extends WorkerHost {
return {
code: codeId(),
shortCode,
artworkId,
batchId,
groupId: groupId ?? null,
url: this.traceCode.buildTraceUrl(shortCode),
@@ -17,7 +17,6 @@ import { TraceCodeService } from './trace-code.service';
import {
BatchGroupDto,
BatchStatusDto,
BindArtworkDto,
ExportTraceCodeDto,
GenerateBatchDto,
GroupDto,
@@ -110,17 +109,4 @@ export class TraceCodeController {
res.end(buf);
}
@Put('trace-codes/:id/bind')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '绑定艺术品' })
bind(@Param('id') id: string, @Body() dto: BindArtworkDto) {
return this.service.bind(BigInt(id), dto.artworkId);
}
@Put('trace-codes/:id/unbind')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '解绑艺术品' })
unbind(@Param('id') id: string) {
return this.service.unbind(BigInt(id));
}
}
+29 -42
View File
@@ -7,7 +7,7 @@ import { Response } from 'express';
import * as ExcelJS from 'exceljs';
import * as QRCode from 'qrcode';
import dayjs from 'dayjs';
import { ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
import { ArtworkStatus, ErrorCode, JobType, QUEUE_NAMES, TraceCodeStatus } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
@@ -38,20 +38,28 @@ export class TraceCodeService {
}
async generateBatch(dto: GenerateBatchDto, userId: number) {
// 必须指定作品(款):生码即归属该款(一款多码)
const artwork = await this.prisma.artwork.findFirst({
where: { id: dto.artworkId, deletedAt: null },
});
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
const batchNo = dto.batchNo || `B${dayjs().format('YYYYMMDDHHmmss')}`;
const exists = await this.prisma.batch.findUnique({ where: { batchNo } });
if (exists) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '批次编号已存在');
}
const batch = await this.prisma.batch.create({
data: { batchNo, quantity: dto.quantity, createdBy: userId },
data: { batchNo, artworkId: dto.artworkId, quantity: dto.quantity, createdBy: userId },
});
const job = await this.jobs.create(JobType.GEN_CODE, dto.quantity, userId, {
batchId: batch.id,
artworkId: dto.artworkId,
groupId: dto.groupId ?? null,
});
await this.genQueue.add('generate', {
batchId: batch.id,
artworkId: dto.artworkId,
jobId: job.id,
quantity: dto.quantity,
groupId: dto.groupId ?? null,
@@ -113,20 +121,16 @@ export class TraceCodeService {
data: { status: TraceCodeStatus.DISABLED },
});
} else {
// 启用:按是否已激活/已绑定恢复对应状态
// 启用:已激活过的恢复为 ACTIVE,否则恢复为 INACTIVE
await this.prisma.$transaction([
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: { not: null } },
data: { status: TraceCodeStatus.ACTIVE },
}),
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: null, artworkId: { not: null } },
where: { id: { in: ids }, firstActivatedAt: null },
data: { status: TraceCodeStatus.INACTIVE },
}),
this.prisma.traceCode.updateMany({
where: { id: { in: ids }, firstActivatedAt: null, artworkId: null },
data: { status: TraceCodeStatus.UNBOUND },
}),
]);
}
return { success: true, count: ids.length };
@@ -149,6 +153,7 @@ export class TraceCodeService {
async list(query: QueryTraceCodeDto) {
const where: Prisma.TraceCodeWhereInput = {};
if (query.artworkId) where.artworkId = query.artworkId;
if (query.batchId) where.batchId = query.batchId;
if (query.groupId) where.groupId = query.groupId;
if (query.status) where.status = query.status;
@@ -156,15 +161,16 @@ export class TraceCodeService {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ sku: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
{ artwork: { archiveNo: { contains: query.keyword } } },
{ artwork: { title: { contains: query.keyword } } },
];
}
const [list, total] = await this.prisma.$transaction([
this.prisma.traceCode.findMany({
where,
include: {
artwork: { select: { id: true, title: true } },
artwork: { select: { id: true, title: true, archiveNo: true } },
batch: { select: { id: true, batchNo: true } },
group: { select: { id: true, name: true } },
},
orderBy: { id: 'desc' },
@@ -176,34 +182,6 @@ export class TraceCodeService {
return buildPage(list, total, query.page, query.pageSize);
}
async bind(id: bigint, artworkId: number) {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
const artwork = await this.prisma.artwork.findFirst({ where: { id: artworkId, deletedAt: null } });
if (!artwork) throw new BusinessException(ErrorCode.ARTWORK_NOT_FOUND, '艺术品不存在', 404);
const bound = await this.prisma.traceCode.findUnique({ where: { artworkId } });
if (bound && bound.id !== id) {
throw new BusinessException(ErrorCode.TRACE_CODE_ALREADY_BOUND, '该艺术品已绑定其他追溯码');
}
const next =
code.status === TraceCodeStatus.UNBOUND ? TraceCodeStatus.INACTIVE : code.status;
return this.prisma.traceCode.update({
where: { id },
data: { artworkId, status: next },
});
}
async unbind(id: bigint) {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
return this.prisma.traceCode.update({
where: { id },
data: { artworkId: null, status: TraceCodeStatus.UNBOUND },
});
}
async getQrPng(id: bigint): Promise<Buffer> {
const code = await this.prisma.traceCode.findUnique({ where: { id } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
@@ -224,6 +202,7 @@ export class TraceCodeService {
.map((s) => BigInt(s));
where.id = { in: idList };
} else {
if (dto.artworkId) where.artworkId = dto.artworkId;
if (dto.batchId) where.batchId = dto.batchId;
if (dto.groupId) where.groupId = dto.groupId;
if (dto.status) where.status = dto.status;
@@ -231,21 +210,27 @@ export class TraceCodeService {
where.OR = [
{ shortCode: { contains: dto.keyword } },
{ code: { contains: dto.keyword } },
{ sku: { contains: dto.keyword } },
{ archiveNo: { contains: dto.keyword } },
{ artwork: { archiveNo: { contains: dto.keyword } } },
{ artwork: { title: { contains: dto.keyword } } },
];
}
}
const codes = await this.prisma.traceCode.findMany({
where,
include: { batch: { select: { batchNo: true } }, group: { select: { name: true } } },
include: {
batch: { select: { batchNo: true } },
group: { select: { name: true } },
artwork: { select: { title: true, archiveNo: true } },
},
orderBy: { id: 'asc' },
});
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('追溯码');
ws.columns = [
{ header: '档案编号', key: 'archiveNo', width: 18 },
{ header: '作品名称', key: 'title', width: 20 },
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '分组', key: 'group', width: 14 },
{ header: '追溯码', key: 'code', width: 24 },
@@ -260,6 +245,8 @@ export class TraceCodeService {
const url = c.url || this.buildTraceUrl(c.shortCode);
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
ws.addRow({
archiveNo: c.artwork?.archiveNo ?? '',
title: c.artwork?.title ?? '',
batchNo: c.batch?.batchNo ?? '',
group: c.group?.name ?? '',
code: c.code,