import { Injectable } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bullmq'; import { Queue } from 'bullmq'; import { Response } from 'express'; import * as ExcelJS from 'exceljs'; import AdmZip from 'adm-zip'; import sharp from 'sharp'; import { Prisma, RoleType } from '@prisma/client'; import { ErrorCode, JobStatus, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.service'; import { JobsService } from '../jobs/jobs.service'; import { BusinessException } from '../common/exceptions/business.exception'; import { buildPage } from '../common/utils/pagination.util'; import { buildOrderBy } from '../common/utils/sort.util'; import { AuthUser } from '../common/decorators/current-user.decorator'; import { OutboundDto } from './dto/outbound.dto'; import { QueryImportRowsDto } from './dto/import-session.dto'; import { isOutbound } from './outbound.util'; const ZIP_MAX_SIZE = 30 * 1024 * 1024; const SESSION_TTL_DAYS = 2; @Injectable() export class OutboundService { constructor( private readonly prisma: PrismaService, private readonly storage: StorageService, private readonly jobs: JobsService, @InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly importQueue: Queue, @InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW) private readonly previewQueue: Queue, ) {} async updateSingle(traceCodeId: bigint, dto: OutboundDto) { const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, include: { artwork: { select: { templateId: true, archiveNo: true } } }, }); if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404); // 一物一码只能出库一次:已登记出库时间或出库图任一即视为已出库 if (isOutbound(code)) { throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库'); } // 出库时间必填:出库登记必须有出库时间 if (!dto.outTime) { throw new BusinessException(ErrorCode.BAD_REQUEST, '出库时间不能为空'); } const imageKeys = dto.outImageKeys ?? (dto.outImageKey ? [dto.outImageKey] : []); const data: Prisma.TraceCodeUpdateInput = {}; if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null; if ('outImageKeys' in dto || 'outImageKey' in dto) { let imageItems = imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' })); // 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号} if (imageItems.length && code.artwork?.archiveNo) { const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`; imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({ ...item, name: item.key.split('/').pop() || item.name, })); } // 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致 data.outImages = imageItems.length ? imageItems : Prisma.DbNull; } if ('remark' in dto) data.remark = dto.remark || null; return this.prisma.traceCode.update({ where: { id: traceCodeId }, data, }); } async generateTemplate(res: Response): Promise { const wb = new ExcelJS.Workbook(); const ws = wb.addWorksheet('导入模板'); ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: c.key === 'outImages' ? 36 : 22 })); ws.getRow(1).font = { bold: true }; ws.addRow({ shortCode: '请替换为真实追溯码', batchNo: 'B20260704001', outTime: '2026-07-04 10:00', outImages: 'images/out-001.jpg', remark: '单图示例', }); ws.addRow({ shortCode: '请替换为真实追溯码', batchNo: 'B20260704001', outTime: '2026-07-04 11:00', outImages: 'images/out-002.png;images/out-003.jpg', remark: '多图示例', }); const note = wb.addWorksheet('字段说明'); note.columns = [ { header: '列名', key: 'header', width: 18 }, { header: '是否必填', key: 'required', width: 12 }, { header: '说明', key: 'note', width: 70 }, ]; note.getRow(1).font = { bold: true }; OUTBOUND_IMPORT_COLUMNS.forEach((c) => note.addRow({ header: c.header, required: c.required ? '是' : '否', note: c.note }), ); const zip = new AdmZip(); zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer())); zip.addFile( '说明.txt', Buffer.from( [ '出库批量导入说明', '', '1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。', '2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。', '3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。', '4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。', '5. 链上哈希、存证链接和上链时间由天河链接口返回后自动写入,不在导入模板中手工填写。', ].join('\r\n'), 'utf8', ), ); zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8')); zip.addFile('images/out-002.png', await this.sampleImage('#3b82f6', 'png')); zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b')); res.setHeader('Content-Type', 'application/zip'); res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.zip"'); res.end(zip.toBuffer()); } private sampleImage(color: string, format: 'jpeg' | 'png' = 'jpeg') { const img = sharp({ create: { width: 720, height: 480, channels: 3, background: color, }, }); return format === 'png' ? img.png().toBuffer() : img.jpeg({ quality: 86 }).toBuffer(); } async startPreview(file: Express.Multer.File, userId: number) { if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件'); const name = (file.originalname || '').toLowerCase(); if (!name.endsWith('.zip') || file.size > ZIP_MAX_SIZE) { throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 30MB 以内的 ZIP 文件'); } const saved = await this.storage.save(file.buffer, file.originalname || 'outbound-import.zip', 'application/zip'); const session = await this.prisma.outboundImportSession.create({ data: { fileName: file.originalname || 'outbound-import.zip', fileKey: saved.key, createdBy: userId, expiresAt: new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000), }, }); const job = await this.jobs.create(JobType.IMPORT_OUTBOUND_PREVIEW, 0, userId, { sessionId: session.id, fileKey: saved.key, }); await this.previewQueue.add('preview', { jobId: job.id, sessionId: session.id, fileKey: saved.key }); return { sessionId: session.id, jobId: job.id }; } startImport(file: Express.Multer.File, userId: number) { return this.startPreview(file, userId); } async getSession(id: string, user: AuthUser) { const session = await this.prisma.outboundImportSession.findUnique({ where: { id } }); if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入会话不存在', 404); if (user.role !== RoleType.SUPER_ADMIN && session.createdBy !== user.id) { throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该导入会话的权限', 403); } return session; } async listRows(id: string, query: QueryImportRowsDto, user: AuthUser) { await this.getSession(id, user); const where: Prisma.OutboundImportRowWhereInput = { sessionId: id }; if (query.status) where.status = query.status as any; const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['outTime', 'createdAt'] as const, { rowNo: 'asc' }); const [list, total] = await this.prisma.$transaction([ this.prisma.outboundImportRow.findMany({ where, orderBy, skip: query.skip, take: query.take, }), this.prisma.outboundImportRow.count({ where }), ]); return buildPage(list, total, query.page, query.pageSize); } async commitSession(id: string, user: AuthUser) { const session = await this.getSession(id, user); if (session.status !== 'READY') { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话尚未准备完成或已处理'); } if (session.invalidCount > 0) { throw new BusinessException(ErrorCode.BAD_REQUEST, '预览存在错误行,请修正后重新上传'); } const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, session.validCount, user.id, { sessionId: id }); await this.prisma.outboundImportSession.update({ where: { id }, data: { status: 'IMPORTING', committedAt: new Date() }, }); // 入队失败时回退会话状态为 READY,避免卡在 IMPORTING 且无对应队列任务 try { await this.importQueue.add('import', { jobId: job.id, sessionId: id }); } catch (e) { await this.prisma.outboundImportSession.update({ where: { id }, data: { status: 'READY', committedAt: null } }); await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message }); throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入任务入队失败,请稍后重试'); } return { jobId: job.id, sessionId: id }; } }