feat: 重构追溯码及上链出库流程

This commit is contained in:
Nixevol
2026-07-16 11:49:50 +08:00
parent 5f5c158c01
commit ebc2603815
92 changed files with 7089 additions and 1615 deletions
+15 -1
View File
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { Transform, Type } from 'class-transformer';
import {
ArrayNotEmpty,
IsArray,
@@ -15,6 +15,7 @@ import {
} from 'class-validator';
import { TraceCodeStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
import { ONCHAIN_FILTER_STATUSES, OnchainFilterStatus } from '../../common/dto/trace-code-selection.dto';
export class GenerateBatchDto {
@ApiProperty({ description: '所属作品(款)ID' })
@@ -65,6 +66,19 @@ export class QueryTraceCodeDto extends PaginationDto {
@IsIn(['OUTBOUND', 'NOT_OUTBOUND'])
outboundStatus?: 'OUTBOUND' | 'NOT_OUTBOUND';
@ApiPropertyOptional({ description: '上链状态', enum: ONCHAIN_FILTER_STATUSES })
@IsOptional()
@IsIn(ONCHAIN_FILTER_STATUSES)
proofStatus?: OnchainFilterStatus;
@ApiPropertyOptional({ description: '是否已经首次激活' })
@IsOptional()
@Transform(({ value }) =>
value === undefined || value === null || value === '' ? undefined : value === true || value === 'true',
)
@IsBoolean()
activated?: boolean;
@ApiPropertyOptional({ description: '分组 ID' })
@IsOptional()
@Type(() => Number)
@@ -0,0 +1,138 @@
import { BatchStatus, JobStatus } from '@artveris/shared';
import { GenCodeProcessor } from './gen-code.processor';
describe('GenCodeProcessor recovery', () => {
it('continues from the actual batch count after a worker crashes following createMany', async () => {
let actualCount = 500;
const prisma = {
traceCode: {
count: jest.fn().mockImplementation(async () => actualCount),
createMany: jest.fn().mockImplementation(async ({ data }: any) => {
actualCount += data.length;
return { count: data.length };
}),
},
$queryRaw: jest.fn().mockResolvedValue([]),
batch: { update: jest.fn().mockResolvedValue({}) },
$transaction: jest.fn(async (operation: (tx: any) => unknown) => operation(prisma)),
};
const jobs = {
start: jest.fn().mockResolvedValue({}),
progress: jest.fn().mockResolvedValue({ count: 1 }),
finish: jest.fn().mockResolvedValue({ count: 1 }),
};
const generator = {
generate: jest.fn().mockImplementation(async (count: number) =>
Array.from({ length: count }, (_, index) => ({
serialNo: actualCount + index + 1,
shortCode: `${String(index).padStart(6, '0')}${String(actualCount + index + 1).padStart(6, '0')}`,
})),
),
};
const processor = new GenCodeProcessor(prisma as any, jobs as any, generator as any);
jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined);
await processor.process({
data: { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600, groupId: null },
} as any);
expect(generator.generate).toHaveBeenCalledTimes(1);
expect(generator.generate).toHaveBeenCalledWith(100);
expect(prisma.traceCode.createMany).toHaveBeenCalledTimes(1);
expect(actualCount).toBe(600);
expect(jobs.progress).toHaveBeenNthCalledWith(1, 'job-1', 500, 0);
expect(jobs.finish).toHaveBeenCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 });
expect(prisma.batch.update).toHaveBeenLastCalledWith({
where: { id: 1 },
data: { status: BatchStatus.DONE },
});
});
it('does not generate more codes when the recovered batch is already complete', async () => {
const prisma = {
traceCode: { count: jest.fn().mockResolvedValue(600), createMany: jest.fn() },
batch: { update: jest.fn().mockResolvedValue({}) },
};
const jobs = {
start: jest.fn().mockResolvedValue({}),
progress: jest.fn().mockResolvedValue({ count: 1 }),
finish: jest.fn().mockResolvedValue({ count: 1 }),
};
const generator = { generate: jest.fn() };
const processor = new GenCodeProcessor(prisma as any, jobs as any, generator as any);
jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined);
await processor.process({ data: { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600 } } as any);
expect(generator.generate).not.toHaveBeenCalled();
expect(prisma.traceCode.createMany).not.toHaveBeenCalled();
expect(jobs.finish).toHaveBeenCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 });
});
it('serializes duplicate workers and never exceeds the batch target', async () => {
let actualCount = 0;
let serialNo = 0;
let initialReads = 0;
let releaseInitialReads!: () => void;
const bothWorkersStarted = new Promise<void>((resolve) => { releaseInitialReads = resolve; });
let transactionTail = Promise.resolve();
const prisma: any = {
traceCode: {
count: jest.fn(async () => {
initialReads += 1;
if (initialReads <= 2) {
if (initialReads === 2) releaseInitialReads();
await bothWorkersStarted;
return 0;
}
return actualCount;
}),
createMany: jest.fn(async ({ data }: any) => {
actualCount += data.length;
return { count: data.length };
}),
},
$queryRaw: jest.fn().mockResolvedValue([]),
batch: { update: jest.fn().mockResolvedValue({}) },
$transaction: jest.fn(async (operation: (tx: any) => unknown) => {
const previous = transactionTail;
let release!: () => void;
transactionTail = new Promise<void>((resolve) => { release = resolve; });
await previous;
try {
return await operation(prisma);
} finally {
release();
}
}),
};
const jobs = {
start: jest.fn().mockResolvedValue({}),
progress: jest.fn().mockResolvedValue({ count: 1 }),
finish: jest.fn().mockResolvedValue({ count: 1 }),
};
const generator = {
generate: jest.fn(async (count: number) => Array.from({ length: count }, () => {
serialNo += 1;
return {
serialNo,
shortCode: `${String(serialNo % 1_000_000).padStart(6, '0')}${String(serialNo).padStart(6, '0')}`,
};
})),
};
const processor = new GenCodeProcessor(prisma, jobs as any, generator as any);
jest.spyOn((processor as any).logger, 'log').mockImplementation(() => undefined);
const data = { batchId: 1, artworkId: 2, jobId: 'job-1', quantity: 600 };
await Promise.all([
processor.process({ data } as any),
processor.process({ data } as any),
]);
expect(actualCount).toBe(600);
expect(prisma.traceCode.createMany.mock.calls.reduce((sum: number, [call]: any[]) => sum + call.data.length, 0)).toBe(600);
expect(jobs.finish).toHaveBeenCalledTimes(2);
expect(jobs.finish).toHaveBeenLastCalledWith('job-1', { status: JobStatus.SUCCESS, successCount: 600 });
});
});
+31 -10
View File
@@ -1,10 +1,10 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { Job } from 'bullmq';
import { BatchStatus, JobStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { JobsService } from '../jobs/jobs.service';
import { TraceCodeService } from './trace-code.service';
import { TraceCodeGeneratorService } from './trace-code-generator.service';
interface GenJobData {
@@ -22,7 +22,6 @@ export class GenCodeProcessor extends WorkerHost {
constructor(
private readonly prisma: PrismaService,
private readonly jobs: JobsService,
private readonly traceCode: TraceCodeService,
private readonly generator: TraceCodeGeneratorService,
) {
super();
@@ -36,25 +35,47 @@ export class GenCodeProcessor extends WorkerHost {
let generated = 0;
const chunkSize = 500;
try {
generated = await this.prisma.traceCode.count({ where: { batchId } });
if (generated > quantity) throw new Error('批次实际生码数量超过目标数量,请检查批次数据');
await this.jobs.progress(jobId, generated, 0);
await this.prisma.batch.update({ where: { id: batchId }, data: { generatedCount: generated } });
while (generated < quantity) {
const n = Math.min(chunkSize, quantity - generated);
const shortCodes = await this.generator.generate(n);
const rows = shortCodes.map((shortCode) => {
const generatedCodes = await this.generator.generate(n);
const rows = generatedCodes.map(({ shortCode, serialNo }) => {
return {
shortCode,
serialNo,
artworkId,
batchId,
groupId: groupId ?? null,
url: null,
};
});
const result = await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
generated += result.count;
await this.jobs.progress(jobId, generated, 0);
await this.prisma.batch.update({
where: { id: batchId },
data: { generatedCount: generated },
const persisted = await this.prisma.$transaction(async (tx) => {
await tx.$queryRaw(Prisma.sql`SELECT id FROM \`batch\` WHERE id = ${batchId} FOR UPDATE`);
const current = await tx.traceCode.count({ where: { batchId } });
if (current > quantity) throw new Error('批次实际生码数量超过目标数量,请检查批次数据');
const remaining = quantity - current;
if (remaining === 0) {
await tx.batch.update({ where: { id: batchId }, data: { generatedCount: current } });
return { generated: current, inserted: 0 };
}
const result = await tx.traceCode.createMany({
data: rows.slice(0, remaining),
skipDuplicates: true,
});
const nextCount = current + result.count;
await tx.batch.update({ where: { id: batchId }, data: { generatedCount: nextCount } });
return { generated: nextCount, inserted: result.count };
});
generated = persisted.generated;
if (persisted.inserted === 0 && generated < quantity) {
throw new Error('生码写入未产生新记录,请稍后重试');
}
await this.jobs.progress(jobId, generated, 0);
}
await this.jobs.finish(jobId, { status: JobStatus.SUCCESS, successCount: generated });
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.DONE } });
@@ -1,12 +1,9 @@
import { TraceCodeGeneratorService } from './trace-code-generator.service';
describe('TraceCodeGeneratorService', () => {
let nextSeq: number;
const prisma: any = {
systemSetting: {
findUnique: jest.fn(),
create: jest.fn(),
},
traceCodeDailySequence: {
traceCodeSequence: {
upsert: jest.fn(),
update: jest.fn(),
},
@@ -14,27 +11,43 @@ describe('TraceCodeGeneratorService', () => {
};
beforeEach(() => {
jest.useFakeTimers().setSystemTime(new Date('2026-07-06T08:00:00.000Z'));
prisma.systemSetting.findUnique.mockResolvedValue({ value: 'salt-for-test' });
prisma.traceCodeDailySequence.upsert.mockResolvedValue({});
prisma.traceCodeDailySequence.update.mockResolvedValue({ nextSeq: 1000 });
nextSeq = 1;
prisma.traceCodeSequence.upsert.mockResolvedValue({ id: 1, nextSeq });
prisma.traceCodeSequence.update.mockImplementation(async ({ data }: any) => {
nextSeq += data.nextSeq.increment;
return { id: 1, nextSeq };
});
});
afterEach(() => {
jest.useRealTimers();
jest.clearAllMocks();
});
afterEach(() => jest.clearAllMocks());
it('generates unique 12-digit codes with the Shanghai date embedded', async () => {
it('uses a random six-digit prefix and a global six-digit sequence suffix', async () => {
const service = new TraceCodeGeneratorService(prisma);
const codes = await service.generate(1000);
const codes = await service.generate(3);
expect(codes).toHaveLength(1000);
expect(new Set(codes).size).toBe(1000);
for (const code of codes) {
expect(code).toMatch(/^\d{12}$/);
expect(`${code.slice(2, 4)}${code.slice(5, 7)}${code.slice(8, 10)}`).toBe('260706');
}
expect(codes.slice(0, 5)).not.toEqual(['002600700600', '002600700601', '002600700602', '002600700603', '002600700604']);
expect(codes.map((item) => item.serialNo)).toEqual([1, 2, 3]);
expect(codes.map((item) => item.shortCode.slice(6))).toEqual(['000001', '000002', '000003']);
expect(codes.every((item) => /^\d{12}$/.test(item.shortCode))).toBe(true);
});
it('preserves leading zeroes in the random prefix', () => {
const service = new TraceCodeGeneratorService(prisma);
expect((service as any).formatCode(1, 42)).toBe('000042000001');
});
it('allows the final sequence and rejects allocation past 999999', async () => {
nextSeq = 999_999;
const service = new TraceCodeGeneratorService(prisma);
await expect(service.generate(1)).resolves.toEqual([
expect.objectContaining({ serialNo: 999_999, shortCode: expect.stringMatching(/^\d{6}999999$/) }),
]);
await expect(service.generate(1)).rejects.toThrow('trace.code.sequenceExhausted');
});
it('rejects invalid allocation quantities before opening a transaction', async () => {
const service = new TraceCodeGeneratorService(prisma);
await expect(service.generate(0)).rejects.toThrow('trace.code.invalidQuantity');
expect(prisma.$transaction).not.toHaveBeenCalled();
});
});
@@ -1,15 +1,18 @@
import { Injectable } from '@nestjs/common';
import { createHmac, randomBytes } from 'crypto';
import { randomInt } from 'crypto';
import { Prisma } from '@prisma/client';
import { SHORT_CODE_LENGTH } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
const TRACE_CODE_SALT_KEY = 'traceCodeSalt';
const MAX_DAILY_SEQUENCE = 1_000_000;
const FEISTEL_ROUNDS = 4;
const SEQUENCE_ID = 1;
const MAX_SEQUENCE = 999_999;
export interface GeneratedTraceCode {
shortCode: string;
serialNo: number;
}
interface SequenceRange {
dateKey: string;
start: number;
end: number;
}
@@ -18,109 +21,46 @@ interface SequenceRange {
export class TraceCodeGeneratorService {
constructor(private readonly prisma: PrismaService) {}
async ensureSalt(): Promise<string> {
// 溯源码盐优先以 .env 的 TRACE_CODE_SALT 为权威来源(安装向导写入、升级不覆盖);
// DB 中的 systemSetting.traceCodeSalt 仅作兜底缓存,二者以 env 为准,使「勿更改」注释名副其实。
const envSalt = process.env.TRACE_CODE_SALT?.trim();
if (envSalt) {
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
if (!existing?.value) {
await this.prisma.systemSetting.upsert({
where: { key: TRACE_CODE_SALT_KEY },
update: { value: envSalt },
create: { key: TRACE_CODE_SALT_KEY, value: envSalt },
});
}
return envSalt;
async generate(count: number): Promise<GeneratedTraceCode[]> {
if (!Number.isInteger(count) || count < 1 || count > MAX_SEQUENCE) {
throw new Error('trace.code.invalidQuantity');
}
const existing = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
if (existing?.value) return existing.value;
const salt = randomBytes(32).toString('hex');
try {
await this.prisma.systemSetting.create({ data: { key: TRACE_CODE_SALT_KEY, value: salt } });
return salt;
} catch (e) {
if (this.isUniqueError(e)) {
const row = await this.prisma.systemSetting.findUnique({ where: { key: TRACE_CODE_SALT_KEY } });
if (row?.value) return row.value;
}
throw e;
}
}
async generate(count: number): Promise<string[]> {
const salt = await this.ensureSalt();
const range = await this.allocateRange(count);
return Array.from({ length: range.end - range.start + 1 }, (_, index) =>
this.formatCode(this.permute6(range.start + index, salt, range.dateKey), range.dateKey),
);
return Array.from({ length: count }, (_, index) => {
const serialNo = range.start + index;
return { serialNo, shortCode: this.formatCode(serialNo) };
});
}
private async allocateRange(count: number): Promise<SequenceRange> {
const dateKey = this.shanghaiDateKey();
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
return await this.prisma.$transaction(async (tx) => {
await tx.traceCodeDailySequence.upsert({
where: { dateKey },
await tx.traceCodeSequence.upsert({
where: { id: SEQUENCE_ID },
update: {},
create: { dateKey, nextSeq: 0 },
create: { id: SEQUENCE_ID, nextSeq: 1 },
});
const row = await tx.traceCodeDailySequence.update({
where: { dateKey },
const row = await tx.traceCodeSequence.update({
where: { id: SEQUENCE_ID },
data: { nextSeq: { increment: count } },
});
const start = row.nextSeq - count;
const end = row.nextSeq - 1;
if (end >= MAX_DAILY_SEQUENCE) {
throw new Error('trace.code.dailyLimitExceeded');
if (start < 1 || end > MAX_SEQUENCE) {
throw new Error('trace.code.sequenceExhausted');
}
return { dateKey, start, end };
return { start, end };
});
} catch (e) {
if (!this.isUniqueError(e) || attempt === 2) throw e;
} catch (error) {
if (!this.isUniqueError(error) || attempt === 2) throw error;
}
}
throw new Error('trace.code.sequenceAllocationFailed');
}
private shanghaiDateKey(date = new Date()): string {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Shanghai',
year: '2-digit',
month: '2-digit',
day: '2-digit',
}).formatToParts(date);
const get = (type: string) => parts.find((part) => part.type === type)?.value.padStart(2, '0') ?? '00';
return `${get('year')}${get('month')}${get('day')}`;
}
private permute6(seq: number, salt: string, dateKey: string): string {
let left = Math.floor(seq / 1000);
let right = seq % 1000;
const keys = this.roundKeys(salt, dateKey);
for (let round = 0; round < FEISTEL_ROUNDS; round += 1) {
const nextLeft = right;
const f = (right * keys[round].mul + keys[round].add) % 1000;
right = (left + f) % 1000;
left = nextLeft;
}
return `${left.toString().padStart(3, '0')}${right.toString().padStart(3, '0')}`;
}
private roundKeys(salt: string, dateKey: string): Array<{ mul: number; add: number }> {
const digest = createHmac('sha256', salt).update(`trace-code:${dateKey}`).digest();
return Array.from({ length: FEISTEL_ROUNDS }, (_, index) => {
const rawMul = digest.readUInt16BE(index * 4) % 1000;
return {
mul: rawMul % 2 === 0 ? rawMul + 1 : rawMul,
add: digest.readUInt16BE(index * 4 + 2) % 1000,
};
});
}
private formatCode(scrambled: string, dateKey: string): string {
const code = `${scrambled.slice(0, 2)}${dateKey.slice(0, 2)}${scrambled[2]}${dateKey.slice(2, 4)}${scrambled[3]}${dateKey.slice(4, 6)}${scrambled.slice(4)}`;
private formatCode(serialNo: number, randomValue = randomInt(0, 1_000_000)): string {
const code = `${randomValue.toString().padStart(6, '0')}${serialNo.toString().padStart(6, '0')}`;
if (code.length !== SHORT_CODE_LENGTH || !/^\d{12}$/.test(code)) {
throw new Error('trace.code.invalidGeneratedCode');
}
@@ -32,6 +32,7 @@ import {
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
import { parseBigId } from '../common/utils/bigint.util';
import { MatchTraceCodesDto } from '../common/dto/trace-code-selection.dto';
@ApiTags('批量生码')
@ApiBearerAuth()
@@ -124,6 +125,13 @@ export class TraceCodeController {
return this.service.batchDelete(dto);
}
@Post('trace-codes/match')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '按追溯码批量匹配并校验操作资格' })
matchCodes(@Body() dto: MatchTraceCodesDto) {
return this.service.matchCodes(dto);
}
@Put('trace-codes/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '更新单个追溯码' })
@@ -0,0 +1,65 @@
import { TraceCodeService } from './trace-code.service';
function createHarness(codes: any[]) {
const prisma = {
traceCode: {
findMany: jest.fn().mockResolvedValue(codes),
deleteMany: jest.fn().mockResolvedValue({ count: codes.length }),
},
queryLog: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) },
batch: { update: jest.fn().mockResolvedValue({}) },
$transaction: jest.fn().mockImplementation(async (operations: any[]) => Promise.all(operations)),
};
const service = new TraceCodeService(
prisma as any,
{} as any,
{} as any,
{} as any,
{} as any,
);
return { service, prisma };
}
function code(overrides: Record<string, unknown> = {}) {
return {
id: 1n,
shortCode: '482731000001',
batchId: 10,
outbound: null,
proofs: [],
jobItems: [],
...overrides,
};
}
describe('TraceCodeService.batchDelete', () => {
it.each([
[code({ outbound: { id: 2n } }), '已登记出库'],
[code({ proofs: [{ status: 'ONCHAIN' }] }), '已上链'],
[code({ proofs: [{ status: 'UNKNOWN' }] }), '存在上链记录'],
[code({ jobItems: [{ id: 3n }] }), '存在批量操作记录'],
])('explicitly rejects a referenced trace code', async (blocked, message) => {
const harness = createHarness([blocked]);
await expect(harness.service.batchDelete({ ids: ['1'] })).rejects.toThrow(message);
expect(harness.prisma.traceCode.deleteMany).not.toHaveBeenCalled();
});
it('deduplicates ids and updates batch counters in the same transaction', async () => {
const harness = createHarness([code()]);
await expect(harness.service.batchDelete({ ids: ['1', '1'] })).resolves.toEqual({ success: true, count: 1 });
expect(harness.prisma.traceCode.findMany).toHaveBeenCalledWith({
where: { id: { in: [1n] } },
select: expect.objectContaining({ outbound: expect.anything(), proofs: expect.anything(), jobItems: expect.anything() }),
});
expect(harness.prisma.queryLog.updateMany).toHaveBeenCalledWith({
where: { traceCodeId: { in: [1n] } },
data: { traceCodeId: null },
});
expect(harness.prisma.batch.update).toHaveBeenCalledWith({
where: { id: 10 },
data: { quantity: { decrement: 1 }, generatedCount: { decrement: 1 } },
});
});
});
+192 -63
View File
@@ -16,6 +16,8 @@ import { buildOrderBy } from '../common/utils/sort.util';
import { parseBigId } from '../common/utils/bigint.util';
import { JobsService } from '../jobs/jobs.service';
import { SettingsService } from '../settings/settings.service';
import { buildTraceCodeFilterWhere } from '../common/utils/trace-code-selection.util';
import { MatchTraceCodesDto } from '../common/dto/trace-code-selection.dto';
import {
BatchDeleteDto,
BatchGroupDto,
@@ -46,20 +48,28 @@ export class TraceCodeService {
return `${clientBase}/#/trace/${encodeURIComponent(shortCode)}`;
}
private mapOutImages(code: { outImages?: unknown }) {
const keys = Array.isArray(code.outImages)
? (code.outImages as Array<{ key?: string; name?: string; type?: string }>)
.map((item) => (typeof item === 'string' ? { key: item } : item))
.filter((item) => item?.key)
: [];
return keys.map((item) => ({
...item,
url: this.storage.getUrl(item.key as string),
type: item.type || 'image',
name: item.name || (item.key as string).split('/').pop() || '出库实况图',
private mapOutImages(outbound: { images?: Array<{ id: bigint; fileKey: string; fileName: string; mimeType: string; size: bigint; width: number; height: number; sortOrder: number }> } | null) {
return (outbound?.images ?? []).map((item) => ({
id: item.id,
key: item.fileKey,
url: this.storage.getUrl(item.fileKey),
type: 'image',
name: item.fileName,
mimeType: item.mimeType,
size: item.size,
width: item.width,
height: item.height,
sortOrder: item.sortOrder,
}));
}
private hasPrimaryImage(images: unknown): boolean {
if (!Array.isArray(images) || !images.length) return false;
const first = images[0] as string | { key?: unknown } | null;
const key = typeof first === 'string' ? first : first?.key;
return typeof key === 'string' && key.trim().length > 0 && !/^data:/i.test(key.trim());
}
async generateBatch(dto: GenerateBatchDto, userId: number) {
const artwork = await this.prisma.artwork.findFirst({
where: { id: dto.artworkId, deletedAt: null },
@@ -346,31 +356,60 @@ export class TraceCodeService {
}
async batchDelete(dto: BatchDeleteDto) {
const ids = dto.ids.map((item) => parseBigId(item, '追溯码 ID'));
const ids = [...new Set(dto.ids)].map((item) => parseBigId(item, '追溯码 ID'));
const codes = await this.prisma.traceCode.findMany({
where: { id: { in: ids } },
select: { id: true, batchId: true },
select: {
id: true,
batchId: true,
shortCode: true,
outbound: { select: { id: true } },
proofs: { select: { status: true }, take: 1 },
jobItems: { select: { id: true }, take: 1 },
},
});
if (codes.length !== ids.length) {
throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '部分追溯码不存在', 404);
}
const blocked = codes.find((code) => code.outbound || code.proofs.length || code.jobItems.length);
if (blocked) {
const reason = blocked.outbound
? '已登记出库'
: blocked.proofs[0]?.status === 'ONCHAIN'
? '已上链'
: blocked.proofs.length
? '存在上链记录'
: '存在批量操作记录';
throw new BusinessException(
ErrorCode.BAD_REQUEST,
`追溯码 ${blocked.shortCode} ${reason},不可删除`,
409,
);
}
const batchCounts = new Map<number, number>();
for (const code of codes) {
batchCounts.set(code.batchId, (batchCounts.get(code.batchId) ?? 0) + 1);
}
await this.prisma.$transaction([
this.prisma.queryLog.updateMany({
where: { traceCodeId: { in: ids } },
data: { traceCodeId: null },
}),
this.prisma.traceCode.deleteMany({ where: { id: { in: ids } } }),
...[...batchCounts.entries()].map(([batchId, count]) =>
this.prisma.batch.update({
where: { id: batchId },
data: { quantity: { decrement: count }, generatedCount: { decrement: count } },
try {
await this.prisma.$transaction([
this.prisma.queryLog.updateMany({
where: { traceCodeId: { in: ids } },
data: { traceCodeId: null },
}),
),
]);
this.prisma.traceCode.deleteMany({ where: { id: { in: ids } } }),
...[...batchCounts.entries()].map(([batchId, count]) =>
this.prisma.batch.update({
where: { id: batchId },
data: { quantity: { decrement: count }, generatedCount: { decrement: count } },
}),
),
]);
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2003') {
throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码已被出库、上链或批量任务引用,不可删除', 409);
}
throw error;
}
return { success: true, count: ids.length };
}
@@ -391,51 +430,48 @@ export class TraceCodeService {
return buildPage(list, total, query.page, query.pageSize);
}
private buildTraceCodeWhere(
query: Pick<QueryTraceCodeDto | ExportTraceCodeDto, 'artworkId' | 'batchId' | 'groupId' | 'status' | 'outboundStatus' | 'keyword'>,
): Prisma.TraceCodeWhereInput {
const where: Prisma.TraceCodeWhereInput = {};
const and: 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;
if (query.outboundStatus === 'OUTBOUND') {
and.push({ OR: [{ outTime: { not: null } }, { outImages: { not: Prisma.DbNull } }] });
} else if (query.outboundStatus === 'NOT_OUTBOUND') {
and.push({ outTime: null, outImages: { equals: Prisma.DbNull } });
}
if (query.keyword) {
and.push({
OR: [
{ shortCode: { contains: query.keyword } },
{ url: { contains: query.keyword } },
{ remark: { contains: query.keyword } },
{ artwork: { archiveNo: { contains: query.keyword } } },
{ artwork: { title: { contains: query.keyword } } },
{ artwork: { artist: { contains: query.keyword } } },
{ batch: { batchNo: { contains: query.keyword } } },
{ group: { name: { contains: query.keyword } } },
],
});
}
if (and.length) where.AND = and;
return where;
private buildTraceCodeWhere(query: QueryTraceCodeDto | ExportTraceCodeDto): Prisma.TraceCodeWhereInput {
return buildTraceCodeFilterWhere(query);
}
async list(query: QueryTraceCodeDto) {
const where = this.buildTraceCodeWhere(query);
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'outTime', 'firstActivatedAt'] as const, { id: 'desc' });
const [list, total] = await this.prisma.$transaction([
const operation = query.proofStatus ? 'ONCHAIN' : query.outboundStatus ? 'OUTBOUND' : null;
const eligibilityWhere: Prisma.TraceCodeWhereInput = operation === 'ONCHAIN'
? {
status: { in: ['INACTIVE', 'ACTIVE'] },
artwork: {
is: {
deletedAt: null,
status: 'ACTIVE',
auditStatus: 'APPROVED',
images: { not: Prisma.DbNull },
},
},
OR: [{ proofs: { none: {} } }, { proofs: { some: { status: 'FAILED' } } }],
}
: operation === 'OUTBOUND'
? { outbound: { is: null } }
: {};
const orderBy: Prisma.TraceCodeOrderByWithRelationInput = query.sortField === 'outTime'
? { outbound: { outTime: query.sortOrder === 'asc' || query.sortOrder === 'ascend' ? 'asc' : 'desc' } }
: buildOrderBy(query.sortField, query.sortOrder, ['createdAt', 'firstActivatedAt'] as const, { id: 'desc' });
const [list, total, eligibleTotal] = await this.prisma.$transaction([
this.prisma.traceCode.findMany({
where,
include: {
artwork: { select: { id: true, title: true, archiveNo: true } },
artwork: { select: { id: true, title: true, archiveNo: true, status: true, auditStatus: true, images: true } },
batch: { select: { id: true, batchNo: true } },
group: { select: { id: true, name: true } },
outbound: {
include: {
images: { orderBy: [{ sortOrder: 'asc' }, { id: 'asc' }], take: 1 },
_count: { select: { images: true } },
},
},
proofs: {
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
take: 10,
take: 1,
},
},
orderBy,
@@ -443,27 +479,120 @@ export class TraceCodeService {
take: query.take,
}),
this.prisma.traceCode.count({ where }),
this.prisma.traceCode.count({ where: operation ? { AND: [where, eligibilityWhere] } : where }),
]);
// 链接统一动态生成(DB 不固化 url,换客户端地址后列表/导出/二维码自动跟随);base 每页只取一次
const clientBase = await this.settings.getClientBaseUrl();
return buildPage(
const page = buildPage(
list.map((code) => {
const { proofs, ...rest } = code;
const { proofs, outbound, ...rest } = code;
const latestOnchainProof = proofs.find((p) => p.status === 'ONCHAIN') ?? null;
const outImages = this.mapOutImages(code);
const latestAnyProof = proofs[0] ?? null;
const outImages = this.mapOutImages(outbound);
const hasPrimaryImage = this.hasPrimaryImage(code.artwork.images);
const onchainEligible =
['INACTIVE', 'ACTIVE'].includes(code.status) &&
code.artwork.status === 'ACTIVE' &&
code.artwork.auditStatus === 'APPROVED' &&
hasPrimaryImage &&
(!latestAnyProof || latestAnyProof.status === 'FAILED');
const outboundEligible = !outbound;
const eligible = operation === 'ONCHAIN' ? onchainEligible : operation === 'OUTBOUND' ? outboundEligible : true;
let onchainReason: string | null = null;
if (!['INACTIVE', 'ACTIVE'].includes(code.status)) onchainReason = '停用或异常追溯码不可上链';
else if (code.artwork.status !== 'ACTIVE' || code.artwork.auditStatus !== 'APPROVED') onchainReason = '作品未生效或未审核通过';
else if (!hasPrimaryImage) onchainReason = '作品缺少有效主图';
else if (latestAnyProof?.status === 'ONCHAIN') onchainReason = '该追溯码已上链';
else if (latestAnyProof && latestAnyProof.status !== 'FAILED') onchainReason = '该追溯码正在上链处理中';
const outboundReason = outboundEligible ? null : '该追溯码已登记出库';
const reason = operation === 'ONCHAIN' ? onchainReason : operation === 'OUTBOUND' ? outboundReason : null;
const { images: _artworkImages, ...artwork } = code.artwork;
return {
...rest,
artwork,
outbound: outbound
? { id: outbound.id, outTime: outbound.outTime, remark: outbound.remark, createdAt: outbound.createdAt, updatedAt: outbound.updatedAt }
: null,
outTime: outbound?.outTime ?? null,
remark: outbound?.remark ?? null,
url: `${clientBase}/#/trace/${encodeURIComponent(code.shortCode)}`,
outImageUrl: outImages[0]?.url ?? null,
outImages,
outImageCount: outbound?._count.images ?? 0,
latestProof: latestOnchainProof,
latestAnyProof: proofs[0] ?? null,
latestAnyProof,
proofStatus: latestAnyProof?.status ?? 'NONE',
onchainEligible,
onchainReason,
outboundEligible,
outboundReason,
eligible,
reason,
};
}),
total,
query.page,
query.pageSize,
);
return { ...page, eligibleTotal };
}
async matchCodes(dto: MatchTraceCodesDto) {
const normalized = dto.codes.map((code) => code.trim()).filter(Boolean);
const seen = new Set<string>();
const duplicates = [...new Set(normalized.filter((code) => (seen.has(code) ? true : (seen.add(code), false))))];
const uniqueCodes = [...seen];
const codes = await this.prisma.traceCode.findMany({
where: { shortCode: { in: uniqueCodes } },
include: {
artwork: { select: { id: true, title: true, archiveNo: true, status: true, auditStatus: true, images: true } },
batch: { select: { id: true, batchNo: true } },
group: { select: { id: true, name: true } },
outbound: { select: { id: true, outTime: true } },
proofs: { orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], take: 1 },
},
});
const byCode = new Map(codes.map((code) => [code.shortCode, code]));
const missing = uniqueCodes.filter((code) => !byCode.has(code));
const matched = uniqueCodes.flatMap((shortCode) => {
const code = byCode.get(shortCode);
if (!code) return [];
const proof = code.proofs[0] ?? null;
const hasPrimaryImage = this.hasPrimaryImage(code.artwork.images);
let eligible = false;
let reason: string | null = null;
if (dto.operation === 'OUTBOUND') {
eligible = !code.outbound;
if (!eligible) reason = '该追溯码已登记出库';
} else {
eligible =
['INACTIVE', 'ACTIVE'].includes(code.status) &&
code.artwork.status === 'ACTIVE' &&
code.artwork.auditStatus === 'APPROVED' &&
hasPrimaryImage &&
(!proof || proof.status === 'FAILED');
if (!['INACTIVE', 'ACTIVE'].includes(code.status)) reason = '停用或异常追溯码不可上链';
else if (code.artwork.status !== 'ACTIVE' || code.artwork.auditStatus !== 'APPROVED') reason = '作品未生效或未审核通过';
else if (!hasPrimaryImage) reason = '作品缺少有效主图';
else if (proof?.status === 'ONCHAIN') reason = '该追溯码已上链';
else if (proof && proof.status !== 'FAILED') reason = '该追溯码正在上链处理中';
}
const { images: _artworkImages, ...artwork } = code.artwork;
return [{
id: code.id,
shortCode: code.shortCode,
status: code.status,
artwork,
batch: code.batch,
group: code.group,
outbound: code.outbound,
proof,
proofStatus: proof?.status ?? 'NONE',
eligible,
reason,
}];
});
return { matched, missing, duplicates };
}
async getQrPng(id: bigint): Promise<Buffer> {