feat: 实现批量生码、二维码导出与公开溯源激活计数
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -11,10 +11,13 @@ import { QueueModule } from './queue/queue.module';
|
||||
import { JobsModule } from './jobs/jobs.module';
|
||||
import { BlockchainModule } from './blockchain/blockchain.module';
|
||||
import { GeoModule } from './geo/geo.module';
|
||||
import { RedisModule } from './redis/redis.module';
|
||||
import { TemplateModule } from './template/template.module';
|
||||
import { ArtworkModule } from './artwork/artwork.module';
|
||||
import { TraceNodeModule } from './trace-node/trace-node.module';
|
||||
import { CertificateModule } from './certificate/certificate.module';
|
||||
import { TraceCodeModule } from './trace-code/trace-code.module';
|
||||
import { PublicTraceModule } from './public-trace/public-trace.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -24,6 +27,7 @@ import { CertificateModule } from './certificate/certificate.module';
|
||||
envFilePath: ['../../.env', '.env'],
|
||||
}),
|
||||
PrismaModule,
|
||||
RedisModule,
|
||||
StorageModule,
|
||||
QueueModule,
|
||||
JobsModule,
|
||||
@@ -36,6 +40,8 @@ import { CertificateModule } from './certificate/certificate.module';
|
||||
ArtworkModule,
|
||||
TraceNodeModule,
|
||||
CertificateModule,
|
||||
TraceCodeModule,
|
||||
PublicTraceModule,
|
||||
],
|
||||
controllers: [AppController],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Controller, Get, Param, Req, Res } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import { Request, Response } from 'express';
|
||||
import { ApiOperation, ApiTags } from '@nestjs/swagger';
|
||||
import { Public } from '../common/decorators/public.decorator';
|
||||
import { extractIp } from '../common/utils/ua.util';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
|
||||
@ApiTags('公开溯源')
|
||||
@Controller()
|
||||
export class PublicTraceController {
|
||||
constructor(
|
||||
private readonly service: PublicTraceService,
|
||||
private readonly config: ConfigService,
|
||||
) {}
|
||||
|
||||
@Public()
|
||||
@Get('public/trace/:shortCode')
|
||||
@ApiOperation({ summary: 'C 端溯源查询(匿名)' })
|
||||
trace(@Param('shortCode') shortCode: string, @Req() req: Request) {
|
||||
const ip = extractIp(req.headers as Record<string, unknown>, req.ip);
|
||||
const userAgent = req.headers['user-agent'];
|
||||
return this.service.trace(shortCode, { ip, userAgent });
|
||||
}
|
||||
|
||||
// 短链跳转:扫码打开 /t/:shortCode -> 重定向到 C 端溯源页(不在 /api 前缀下)
|
||||
@Public()
|
||||
@Get('t/:shortCode')
|
||||
redirect(@Param('shortCode') shortCode: string, @Res() res: Response) {
|
||||
const template =
|
||||
this.config.get<string>('traceUrlTemplate') ||
|
||||
'http://localhost:5174/#/pages/trace/index?code={code}';
|
||||
res.redirect(302, template.replace('{code}', encodeURIComponent(shortCode)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { PublicTraceService } from './public-trace.service';
|
||||
import { PublicTraceController } from './public-trace.controller';
|
||||
|
||||
@Module({
|
||||
controllers: [PublicTraceController],
|
||||
providers: [PublicTraceService],
|
||||
exports: [PublicTraceService],
|
||||
})
|
||||
export class PublicTraceModule {}
|
||||
@@ -0,0 +1,189 @@
|
||||
import { Inject, Injectable, Logger } from '@nestjs/common';
|
||||
import type Redis from 'ioredis';
|
||||
import { ArtworkStatus, QueryResult, ProofStatus, TraceCodeStatus } from '@artveris/shared';
|
||||
import { PrismaService } from '../prisma/prisma.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { GeoService } from '../geo/geo.service';
|
||||
import { REDIS_CLIENT } from '../redis/redis.module';
|
||||
import { parseUserAgent } from '../common/utils/ua.util';
|
||||
|
||||
export interface TraceContext {
|
||||
ip: string;
|
||||
userAgent?: string;
|
||||
}
|
||||
|
||||
const MAP_TTL = 3600; // 短码→id 映射缓存 1 小时
|
||||
|
||||
@Injectable()
|
||||
export class PublicTraceService {
|
||||
private readonly logger = new Logger(PublicTraceService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly geo: GeoService,
|
||||
@Inject(REDIS_CLIENT) private readonly redis: Redis,
|
||||
) {}
|
||||
|
||||
private mapMedia(items: unknown) {
|
||||
if (!Array.isArray(items)) return [];
|
||||
return (items as Array<{ key: string; name?: string; type?: string }>)
|
||||
.filter((i) => i && i.key)
|
||||
.map((i) => ({ name: i.name, type: i.type, url: this.storage.getUrl(i.key) }));
|
||||
}
|
||||
|
||||
private async resolveId(shortCode: string): Promise<bigint | null> {
|
||||
const cacheKey = `trace:map:${shortCode}`;
|
||||
const cached = await this.redis.get(cacheKey);
|
||||
if (cached) return BigInt(cached);
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode },
|
||||
select: { id: true },
|
||||
});
|
||||
if (!code) return null;
|
||||
await this.redis.set(cacheKey, code.id.toString(), 'EX', MAP_TTL);
|
||||
return code.id;
|
||||
}
|
||||
|
||||
async trace(shortCode: string, ctx: TraceContext) {
|
||||
const id = await this.resolveId(shortCode);
|
||||
if (id === null) {
|
||||
await this.writeLog(null, null, shortCode, QueryResult.INVALID, ctx);
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { id } });
|
||||
if (!code || !code.artworkId || code.status === TraceCodeStatus.UNBOUND) {
|
||||
await this.writeLog(id, null, shortCode, QueryResult.INVALID, ctx);
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
if (code.status === TraceCodeStatus.DISABLED) {
|
||||
await this.writeLog(id, code.artworkId, shortCode, QueryResult.DISABLED, ctx);
|
||||
return { status: 'DISABLED' as const };
|
||||
}
|
||||
if (code.status === TraceCodeStatus.ABNORMAL) {
|
||||
await this.writeLog(id, code.artworkId, shortCode, QueryResult.ABNORMAL, ctx);
|
||||
return { status: 'ABNORMAL' as const };
|
||||
}
|
||||
|
||||
const artwork = await this.prisma.artwork.findFirst({
|
||||
where: { id: code.artworkId, deletedAt: null },
|
||||
include: {
|
||||
template: { include: { fields: { orderBy: { sortOrder: 'asc' } } } },
|
||||
traceNodes: { orderBy: { sortOrder: 'asc' } },
|
||||
certificates: { orderBy: { id: 'asc' } },
|
||||
},
|
||||
});
|
||||
if (!artwork || artwork.status === ArtworkStatus.DISABLED) {
|
||||
await this.writeLog(id, code.artworkId, shortCode, QueryResult.INVALID, ctx);
|
||||
return { status: 'INVALID' as const };
|
||||
}
|
||||
|
||||
// 激活 / 计数
|
||||
const now = new Date();
|
||||
let firstActivate = false;
|
||||
let updated;
|
||||
if (code.status === TraceCodeStatus.INACTIVE) {
|
||||
updated = await this.prisma.traceCode.update({
|
||||
where: { id },
|
||||
data: {
|
||||
status: TraceCodeStatus.ACTIVE,
|
||||
firstActivatedAt: now,
|
||||
queryCount: 1,
|
||||
lastQueriedAt: now,
|
||||
},
|
||||
});
|
||||
firstActivate = true;
|
||||
} else {
|
||||
updated = await this.prisma.traceCode.update({
|
||||
where: { id },
|
||||
data: { queryCount: { increment: 1 }, lastQueriedAt: now },
|
||||
});
|
||||
}
|
||||
|
||||
const proof = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: id, status: ProofStatus.ONCHAIN },
|
||||
orderBy: { id: 'desc' },
|
||||
});
|
||||
|
||||
const result = firstActivate ? QueryResult.FIRST_ACTIVATE : QueryResult.REPEAT;
|
||||
await this.writeLog(id, artwork.id, shortCode, result, ctx);
|
||||
|
||||
return {
|
||||
status: 'OK' as const,
|
||||
antiCounterfeit: {
|
||||
firstQuery: firstActivate,
|
||||
queryCount: updated.queryCount,
|
||||
firstActivatedAt: updated.firstActivatedAt,
|
||||
},
|
||||
artwork: {
|
||||
title: artwork.title,
|
||||
artist: artwork.artist,
|
||||
images: this.mapMedia(artwork.images),
|
||||
fields: this.buildFields(artwork.template.fields, artwork.dynamicFields),
|
||||
},
|
||||
timeline: artwork.traceNodes.map((n) => ({
|
||||
nodeType: n.nodeType,
|
||||
title: n.title,
|
||||
occurredAt: n.occurredAt,
|
||||
location: n.location,
|
||||
description: n.description,
|
||||
media: this.mapMedia(n.mediaFiles),
|
||||
})),
|
||||
certificates: artwork.certificates.map((c) => ({
|
||||
name: c.name,
|
||||
issuer: c.issuer,
|
||||
issuedAt: c.issuedAt,
|
||||
type: c.type,
|
||||
url: c.watermarkFileUrl ? this.storage.getUrl(c.watermarkFileUrl) : null,
|
||||
})),
|
||||
blockchain: proof
|
||||
? {
|
||||
txHash: proof.txHash,
|
||||
dataHash: proof.dataHash,
|
||||
blockHash: proof.blockHash,
|
||||
blockHeight: proof.blockHeight,
|
||||
chainName: proof.chainName,
|
||||
onchainAt: proof.onchainAt,
|
||||
explorerUrl: proof.explorerUrl,
|
||||
}
|
||||
: null,
|
||||
};
|
||||
}
|
||||
|
||||
private buildFields(
|
||||
fields: Array<{ fieldKey: string; label: string; type: string }>,
|
||||
dynamic: unknown,
|
||||
) {
|
||||
const data = (dynamic as Record<string, unknown>) || {};
|
||||
return fields
|
||||
.map((f) => ({ label: f.label, type: f.type, value: data[f.fieldKey] }))
|
||||
.filter((f) => f.value !== undefined && f.value !== null && f.value !== '');
|
||||
}
|
||||
|
||||
private async writeLog(
|
||||
traceCodeId: bigint | null,
|
||||
artworkId: number | null,
|
||||
shortCode: string,
|
||||
result: QueryResult,
|
||||
ctx: TraceContext,
|
||||
): Promise<void> {
|
||||
try {
|
||||
const device = parseUserAgent(ctx.userAgent);
|
||||
await this.prisma.queryLog.create({
|
||||
data: {
|
||||
traceCodeId: traceCodeId ?? undefined,
|
||||
artworkId: artworkId ?? undefined,
|
||||
shortCode,
|
||||
queryResult: result,
|
||||
ip: ctx.ip,
|
||||
region: this.geo.resolveRegion(ctx.ip),
|
||||
userAgent: ctx.userAgent,
|
||||
deviceType: device.deviceType,
|
||||
},
|
||||
});
|
||||
} catch (e) {
|
||||
this.logger.warn(`查询日志写入失败: ${(e as Error).message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import Redis from 'ioredis';
|
||||
|
||||
export const REDIS_CLIENT = 'REDIS_CLIENT';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
providers: [
|
||||
{
|
||||
provide: REDIS_CLIENT,
|
||||
inject: [ConfigService],
|
||||
useFactory: (config: ConfigService) =>
|
||||
new Redis({
|
||||
host: config.get<string>('redis.host'),
|
||||
port: config.get<number>('redis.port'),
|
||||
password: config.get<string>('redis.password') || undefined,
|
||||
maxRetriesPerRequest: null,
|
||||
}),
|
||||
},
|
||||
],
|
||||
exports: [REDIS_CLIENT],
|
||||
})
|
||||
export class RedisModule {}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user