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(); } }