feat: 实现批量生码、二维码导出与公开溯源激活计数

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Nixevol
2026-06-28 16:12:50 +08:00
co-authored by Cursor
parent b4108d7434
commit 63c0488ff7
11 changed files with 652 additions and 0 deletions
@@ -0,0 +1,52 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsEnum, IsInt, IsOptional, IsString, Max, MaxLength, Min } from 'class-validator';
import { TraceCodeStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class GenerateBatchDto {
@ApiProperty({ description: '生成数量', minimum: 1, maximum: 10000 })
@Type(() => Number)
@IsInt()
@Min(1)
@Max(10000)
quantity!: number;
@ApiPropertyOptional({ description: '批次编号(留空自动生成)' })
@IsOptional()
@IsString()
@MaxLength(50)
batchNo?: string;
}
export class QueryTraceCodeDto extends PaginationDto {
@ApiPropertyOptional({ description: '批次 ID' })
@IsOptional()
@Type(() => Number)
@IsInt()
batchId?: number;
@ApiPropertyOptional({ description: '状态', enum: TraceCodeStatus })
@IsOptional()
@IsEnum(TraceCodeStatus)
status?: TraceCodeStatus;
@ApiPropertyOptional({ description: '关键词(短码/追溯码/SKU/档案号)' })
@IsOptional()
@IsString()
keyword?: string;
}
export class BindArtworkDto {
@ApiProperty({ description: '艺术品 ID' })
@Type(() => Number)
@IsInt()
artworkId!: number;
}
export class QueryBatchDto extends PaginationDto {
@ApiPropertyOptional({ description: '关键词(批次编号)' })
@IsOptional()
@IsString()
keyword?: string;
}
@@ -0,0 +1,72 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { customAlphabet } from 'nanoid';
import { BatchStatus, JobStatus, QUEUE_NAMES, SHORT_CODE_LENGTH } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { JobsService } from '../jobs/jobs.service';
import { TraceCodeService } from './trace-code.service';
const ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
const shortId = customAlphabet(ALPHABET, SHORT_CODE_LENGTH);
const codeId = customAlphabet(ALPHABET, 18);
interface GenJobData {
batchId: number;
jobId: string;
quantity: number;
}
@Processor(QUEUE_NAMES.GEN_CODE)
export class GenCodeProcessor extends WorkerHost {
private readonly logger = new Logger(GenCodeProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly jobs: JobsService,
private readonly traceCode: TraceCodeService,
) {
super();
}
async process(job: Job<GenJobData>): Promise<void> {
const { batchId, jobId, quantity } = job.data;
await this.jobs.start(jobId);
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.GENERATING } });
let generated = 0;
const chunkSize = 500;
try {
while (generated < quantity) {
const n = Math.min(chunkSize, quantity - generated);
const rows = Array.from({ length: n }, () => {
const shortCode = shortId();
return {
code: codeId(),
shortCode,
batchId,
url: this.traceCode.buildTraceUrl(shortCode),
};
});
await this.prisma.traceCode.createMany({ data: rows, skipDuplicates: true });
generated += n;
await this.jobs.progress(jobId, generated, 0);
await this.prisma.batch.update({
where: { id: batchId },
data: { generatedCount: generated },
});
}
await this.jobs.finish(jobId, { status: JobStatus.SUCCESS, successCount: generated });
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.DONE } });
this.logger.log(`批次 ${batchId} 生成 ${generated} 个追溯码`);
} catch (e) {
await this.jobs.finish(jobId, {
status: JobStatus.FAILED,
successCount: generated,
error: (e as Error).message,
});
await this.prisma.batch.update({ where: { id: batchId }, data: { status: BatchStatus.FAILED } });
throw e;
}
}
}
@@ -0,0 +1,77 @@
import {
Body,
Controller,
Get,
Param,
Post,
Put,
Query,
Res,
} from '@nestjs/common';
import { ApiBearerAuth, ApiOperation, ApiTags } from '@nestjs/swagger';
import { Response } from 'express';
import { RoleType } from '@artveris/shared';
import { TraceCodeService } from './trace-code.service';
import {
BindArtworkDto,
GenerateBatchDto,
QueryBatchDto,
QueryTraceCodeDto,
} from './dto/trace-code.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@ApiTags('批量生码')
@ApiBearerAuth()
@Controller()
export class TraceCodeController {
constructor(private readonly service: TraceCodeService) {}
@Post('trace-codes/batch')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '按批次异步生成追溯码' })
generate(@Body() dto: GenerateBatchDto, @CurrentUser() user: AuthUser) {
return this.service.generateBatch(dto, user.id);
}
@Get('batches')
@ApiOperation({ summary: '批次列表' })
batches(@Query() query: QueryBatchDto) {
return this.service.listBatches(query);
}
@Get('trace-codes')
@ApiOperation({ summary: '追溯码列表' })
list(@Query() query: QueryTraceCodeDto) {
return this.service.list(query);
}
@Get('trace-codes/export')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '导出追溯码 Excel' })
export(@Query('batchId') batchId: string | undefined, @Res() res: Response) {
return this.service.exportExcel(batchId ? Number(batchId) : undefined, res);
}
@Get('trace-codes/:id/qrcode')
@ApiOperation({ summary: '获取追溯码二维码 PNG' })
async qrcode(@Param('id') id: string, @Res() res: Response) {
const buf = await this.service.getQrPng(BigInt(id));
res.setHeader('Content-Type', 'image/png');
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));
}
}
@@ -0,0 +1,14 @@
import { Module } from '@nestjs/common';
import { BullModule } from '@nestjs/bullmq';
import { QUEUE_NAMES } from '@artveris/shared';
import { TraceCodeService } from './trace-code.service';
import { TraceCodeController } from './trace-code.controller';
import { GenCodeProcessor } from './gen-code.processor';
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.GEN_CODE })],
controllers: [TraceCodeController],
providers: [TraceCodeService, GenCodeProcessor],
exports: [TraceCodeService],
})
export class TraceCodeModule {}
@@ -0,0 +1,172 @@
import { Injectable } from '@nestjs/common';
import { InjectQueue } from '@nestjs/bullmq';
import { ConfigService } from '@nestjs/config';
import { Queue } from 'bullmq';
import { Prisma } from '@prisma/client';
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 { PrismaService } from '../prisma/prisma.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { JobsService } from '../jobs/jobs.service';
import { GenerateBatchDto, QueryBatchDto, QueryTraceCodeDto } from './dto/trace-code.dto';
@Injectable()
export class TraceCodeService {
constructor(
private readonly prisma: PrismaService,
private readonly jobs: JobsService,
private readonly config: ConfigService,
@InjectQueue(QUEUE_NAMES.GEN_CODE) private readonly genQueue: Queue,
) {}
buildTraceUrl(shortCode: string): string {
const base = (this.config.get<string>('baseUrl') || 'http://localhost:3000').replace(/\/$/, '');
const path = this.config.get<string>('publicTracePath') || '/t';
return `${base}${path}/${shortCode}`;
}
async generateBatch(dto: GenerateBatchDto, userId: number) {
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 },
});
const job = await this.jobs.create(JobType.GEN_CODE, dto.quantity, userId, {
batchId: batch.id,
});
await this.genQueue.add('generate', {
batchId: batch.id,
jobId: job.id,
quantity: dto.quantity,
});
return { batchId: batch.id, batchNo, jobId: job.id, quantity: dto.quantity };
}
async listBatches(query: QueryBatchDto) {
const where: Prisma.BatchWhereInput = {};
if (query.keyword) where.batchNo = { contains: query.keyword };
const [list, total] = await this.prisma.$transaction([
this.prisma.batch.findMany({
where,
orderBy: { id: 'desc' },
skip: query.skip,
take: query.take,
}),
this.prisma.batch.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
}
async list(query: QueryTraceCodeDto) {
const where: Prisma.TraceCodeWhereInput = {};
if (query.batchId) where.batchId = query.batchId;
if (query.status) where.status = query.status;
if (query.keyword) {
where.OR = [
{ shortCode: { contains: query.keyword } },
{ code: { contains: query.keyword } },
{ sku: { contains: query.keyword } },
{ archiveNo: { contains: query.keyword } },
];
}
const [list, total] = await this.prisma.$transaction([
this.prisma.traceCode.findMany({
where,
include: { artwork: { select: { id: true, title: true } } },
orderBy: { id: 'desc' },
skip: query.skip,
take: query.take,
}),
this.prisma.traceCode.count({ where }),
]);
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);
return QRCode.toBuffer(code.url || this.buildTraceUrl(code.shortCode), {
type: 'png',
width: 320,
margin: 1,
});
}
async exportExcel(batchId: number | undefined, res: Response): Promise<void> {
const where: Prisma.TraceCodeWhereInput = {};
if (batchId) where.batchId = batchId;
const codes = await this.prisma.traceCode.findMany({
where,
include: { batch: { select: { batchNo: true } } },
orderBy: { id: 'asc' },
});
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('追溯码');
ws.columns = [
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '追溯码', key: 'code', width: 24 },
{ header: '随机短码', key: 'shortCode', width: 16 },
{ header: '短链 URL', key: 'url', width: 40 },
{ header: '二维码数据(DataURL)', key: 'qr', width: 50 },
{ header: '生成时间', key: 'createdAt', width: 22 },
];
ws.getRow(1).font = { bold: true };
for (const c of codes) {
const url = c.url || this.buildTraceUrl(c.shortCode);
const qr = await QRCode.toDataURL(url, { margin: 1, width: 200 });
ws.addRow({
batchNo: c.batch?.batchNo ?? '',
code: c.code,
shortCode: c.shortCode,
url,
qr,
createdAt: dayjs(c.createdAt).format('YYYY-MM-DD HH:mm:ss'),
});
}
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
res.setHeader(
'Content-Disposition',
`attachment; filename="trace-codes-${batchId ?? 'all'}.xlsx"`,
);
await wb.xlsx.write(res);
res.end();
}
}