From 63c0488ff73a002bef361d6ee28e021f19543e56 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 28 Jun 2026 16:12:50 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E6=89=B9=E9=87=8F?= =?UTF-8?q?=E7=94=9F=E7=A0=81=E3=80=81=E4=BA=8C=E7=BB=B4=E7=A0=81=E5=AF=BC?= =?UTF-8?q?=E5=87=BA=E4=B8=8E=E5=85=AC=E5=BC=80=E6=BA=AF=E6=BA=90=E6=BF=80?= =?UTF-8?q?=E6=B4=BB=E8=AE=A1=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Cursor --- aidocs/project_context.md | 1 + apps/api/src/app.module.ts | 6 + .../public-trace/public-trace.controller.ts | 35 ++++ .../src/public-trace/public-trace.module.ts | 10 + .../src/public-trace/public-trace.service.ts | 189 ++++++++++++++++++ apps/api/src/redis/redis.module.ts | 24 +++ apps/api/src/trace-code/dto/trace-code.dto.ts | 52 +++++ apps/api/src/trace-code/gen-code.processor.ts | 72 +++++++ .../src/trace-code/trace-code.controller.ts | 77 +++++++ apps/api/src/trace-code/trace-code.module.ts | 14 ++ apps/api/src/trace-code/trace-code.service.ts | 172 ++++++++++++++++ 11 files changed, 652 insertions(+) create mode 100644 apps/api/src/public-trace/public-trace.controller.ts create mode 100644 apps/api/src/public-trace/public-trace.module.ts create mode 100644 apps/api/src/public-trace/public-trace.service.ts create mode 100644 apps/api/src/redis/redis.module.ts create mode 100644 apps/api/src/trace-code/dto/trace-code.dto.ts create mode 100644 apps/api/src/trace-code/gen-code.processor.ts create mode 100644 apps/api/src/trace-code/trace-code.controller.ts create mode 100644 apps/api/src/trace-code/trace-code.module.ts create mode 100644 apps/api/src/trace-code/trace-code.service.ts diff --git a/aidocs/project_context.md b/aidocs/project_context.md index 144e659..9098afc 100644 --- a/aidocs/project_context.md +++ b/aidocs/project_context.md @@ -54,4 +54,5 @@ - 阶段 3(平台能力)已完成:StorageService 抽象(LocalDriver 默认 + OssDriver 基于 @aws-sdk/client-s3 S3 兼容,env `STORAGE_DRIVER`/`CDN_BASE_URL` 切换,getUrl 返回绝对地址,支持 read/putKey/derivedKey);`POST /api/upload`(按 image/video/file 校验类型与大小);QueueModule(BullMQ 连 Redis)+ JobsModule(Job 表进度,`GET /api/jobs`、`/jobs/:id`);BlockchainModule(AttestationProvider 接口 + MockProvider 拟真返回 + TianheProvider 占位,`hashData` 摘要);GeoModule(Mock 归属地)+ UA 解析工具。已验证上传→静态访问→jobs 列表。 - 阶段 4(核心业务)已完成:模板(动态字段,增删改查、options、停用软删、在用校验);艺术品建档(模板驱动动态字段、多图、软删、状态,媒体以 key 存储、读取转绝对 URL);溯源节点(时间轴增删改查 + reorder);认证文件(上传原件→入 WATERMARK 队列用 sharp 生成平铺水印图,水印文案取 system_setting/config,原件 key 存 originFileUrl、水印 key 存 watermarkFileUrl,读取转 URL)。已验证模板→作品→节点→证书→水印异步生成→可访问。 - 约定:媒体统一以存储 key 存库,响应时经 StorageService.getUrl 转绝对 URL(便于 CDN/OSS 切换);写操作需 OPERATOR+(SUPER_ADMIN 全通),读操作任意已登录角色。 +- 阶段 5(生码与公开溯源)已完成:批量生码(GEN_CODE 队列异步,nanoid 短码 10 位/追溯码 18 位,url=`BASE_URL/t/{shortCode}`,分块 createMany,回写 batch/job 进度);批次/追溯码列表、二维码 PNG(qrcode)、Excel 导出(exceljs 含二维码 DataURL)、绑定/解绑作品(UNBOUND→INACTIVE);public-trace 公开匿名:短码经 Redis 映射缓存解析→校验→未激活则激活计数=1+首次激活时间、已激活则原子 increment→聚合作品(动态字段映射label)/时间轴/证书(仅水印图)/链上凭证→写查询日志(IP/地区/设备/结果);`/t/:shortCode` 302 跳转 C 端。已验证生码→绑定→首扫激活→复扫+1→无效码 INVALID。 diff --git a/apps/api/src/app.module.ts b/apps/api/src/app.module.ts index 648f4e2..102a7e3 100644 --- a/apps/api/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -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], }) diff --git a/apps/api/src/public-trace/public-trace.controller.ts b/apps/api/src/public-trace/public-trace.controller.ts new file mode 100644 index 0000000..f6721ad --- /dev/null +++ b/apps/api/src/public-trace/public-trace.controller.ts @@ -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, 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('traceUrlTemplate') || + 'http://localhost:5174/#/pages/trace/index?code={code}'; + res.redirect(302, template.replace('{code}', encodeURIComponent(shortCode))); + } +} diff --git a/apps/api/src/public-trace/public-trace.module.ts b/apps/api/src/public-trace/public-trace.module.ts new file mode 100644 index 0000000..83fd88c --- /dev/null +++ b/apps/api/src/public-trace/public-trace.module.ts @@ -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 {} diff --git a/apps/api/src/public-trace/public-trace.service.ts b/apps/api/src/public-trace/public-trace.service.ts new file mode 100644 index 0000000..2cdb7ff --- /dev/null +++ b/apps/api/src/public-trace/public-trace.service.ts @@ -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 { + 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) || {}; + 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 { + 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}`); + } + } +} diff --git a/apps/api/src/redis/redis.module.ts b/apps/api/src/redis/redis.module.ts new file mode 100644 index 0000000..a06bf3b --- /dev/null +++ b/apps/api/src/redis/redis.module.ts @@ -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('redis.host'), + port: config.get('redis.port'), + password: config.get('redis.password') || undefined, + maxRetriesPerRequest: null, + }), + }, + ], + exports: [REDIS_CLIENT], +}) +export class RedisModule {} diff --git a/apps/api/src/trace-code/dto/trace-code.dto.ts b/apps/api/src/trace-code/dto/trace-code.dto.ts new file mode 100644 index 0000000..200f2cd --- /dev/null +++ b/apps/api/src/trace-code/dto/trace-code.dto.ts @@ -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; +} diff --git a/apps/api/src/trace-code/gen-code.processor.ts b/apps/api/src/trace-code/gen-code.processor.ts new file mode 100644 index 0000000..fef49da --- /dev/null +++ b/apps/api/src/trace-code/gen-code.processor.ts @@ -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): Promise { + 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; + } + } +} diff --git a/apps/api/src/trace-code/trace-code.controller.ts b/apps/api/src/trace-code/trace-code.controller.ts new file mode 100644 index 0000000..60aafb0 --- /dev/null +++ b/apps/api/src/trace-code/trace-code.controller.ts @@ -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)); + } +} diff --git a/apps/api/src/trace-code/trace-code.module.ts b/apps/api/src/trace-code/trace-code.module.ts new file mode 100644 index 0000000..9037c7a --- /dev/null +++ b/apps/api/src/trace-code/trace-code.module.ts @@ -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 {} diff --git a/apps/api/src/trace-code/trace-code.service.ts b/apps/api/src/trace-code/trace-code.service.ts new file mode 100644 index 0000000..2ff7926 --- /dev/null +++ b/apps/api/src/trace-code/trace-code.service.ts @@ -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('baseUrl') || 'http://localhost:3000').replace(/\/$/, ''); + const path = this.config.get('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 { + 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 { + 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(); + } +}