import { Injectable, Logger } from '@nestjs/common'; import { InjectQueue } from '@nestjs/bullmq'; import { Queue } from 'bullmq'; import { randomUUID } from 'crypto'; import { readFile, rm } from 'fs/promises'; import { resolve } from 'path'; import { Response } from 'express'; import * as ExcelJS from 'exceljs'; import { Prisma, RoleType } from '@prisma/client'; import { ErrorCode, JobStatus, JobType, QUEUE_NAMES, } from '@artveris/shared'; import { PrismaService } from '../prisma/prisma.service'; import { StorageService } from '../storage/storage.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'; import { OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS } from './outbound-import.util'; const SESSION_TTL_DAYS = 2; const OUTBOUND_IMPORT_TEMPLATE_PATH = resolve(__dirname, '..', 'assets', 'templates', 'outbound-import-template.zip'); function jsonArray(value: unknown): T[] { return Array.isArray(value) ? (value as T[]) : []; } function formatChinaDate(value: Date | null): string { if (!value) return ''; return new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Shanghai', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false, }).format(value); } @Injectable() export class OutboundService { private readonly logger = new Logger(OutboundService.name); constructor( private readonly prisma: PrismaService, private readonly storage: StorageService, @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.TraceCodeUpdateManyMutationInput = {}; const relocatedKeys: string[] = []; data.outTime = new Date(dto.outTime); 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}`; const relocated = await this.storage.relocateMedia(imageItems, dir, '出库实况'); relocatedKeys.push(...relocated.keyMap.values()); imageItems = relocated.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; let duplicateDetected = false; try { const updated = await this.prisma.traceCode.updateMany({ where: { id: traceCodeId, outTime: null }, data, }); if (updated.count !== 1) { duplicateDetected = true; throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库'); } return this.prisma.traceCode.findUniqueOrThrow({ where: { id: traceCodeId } }); } catch (error) { let committedWithRelocatedImages = false; let commitStateKnown = false; if (relocatedKeys.length && !duplicateDetected) { try { const current = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, select: { outImages: true } }); const currentKeys = Array.isArray(current?.outImages) ? current.outImages.map((item: any) => String(item?.key || '')).filter(Boolean) : []; committedWithRelocatedImages = relocatedKeys.every((key) => currentKeys.includes(key)); commitStateKnown = true; } catch { // 提交结果未知时保留文件,宁可留待清理也不能删除可能已经入库的业务图片。 } } if (duplicateDetected || (commitStateKnown && !committedWithRelocatedImages)) { for (const key of relocatedKeys) await this.storage.remove(key).catch(() => undefined); } throw error; } } async generateTemplate(res: Response): Promise { let archive: Buffer; try { archive = await readFile(OUTBOUND_IMPORT_TEMPLATE_PATH); } catch (error) { this.logger.error(`读取出库导入模板失败:${(error as Error).message}`); throw new BusinessException(ErrorCode.INTERNAL_ERROR, '出库导入模板暂不可用'); } res.setHeader('Content-Type', 'application/zip'); res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.zip"'); res.setHeader('Content-Length', String(archive.length)); res.setHeader('Cache-Control', 'no-cache'); res.end(archive); } async startPreview(file: Express.Multer.File, userId: number, requestId?: string) { try { return await this.startPreviewFromUpload(file, userId, requestId); } finally { if (file?.path) { await rm(file.path, { force: true }).catch((error) => this.logger.warn(`清理出库导入上传临时文件失败:${file.path} ${(error as Error).message}`), ); } } } private async startPreviewFromUpload(file: Express.Multer.File, userId: number, requestId?: string) { const normalizedRequestId = (requestId || '').trim(); if (normalizedRequestId && !/^[A-Za-z0-9_-]{16,64}$/.test(normalizedRequestId)) { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入请求标识格式无效'); } if (normalizedRequestId) { const existing = await this.prisma.outboundImportSession.findUnique({ where: { requestId: normalizedRequestId } }); if (existing) { if (existing.createdBy !== userId) throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该导入请求的权限', 403); if (!existing.previewJobId) throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入预览任务记录不完整'); return { sessionId: existing.id, jobId: existing.previewJobId }; } } if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件'); const name = (file.originalname || '').toLowerCase(); if (!name.endsWith('.zip')) throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 ZIP 文件'); const fileSize = file.size || 0; if (!fileSize) throw new BusinessException(ErrorCode.BAD_REQUEST, '导入 ZIP 文件不能为空'); if (!file.path) throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入 ZIP 临时文件不存在'); const saved = await this.storage.savePrivateFile( file.path, file.originalname || 'outbound-import.zip', 'application/zip', { requestTimeoutMs: OUTBOUND_IMPORT_STORAGE_TIMEOUT_MS }, ); let created: { sessionId: string; jobId: string; fileKey: string }; try { created = await this.prisma.$transaction(async (tx) => { const session = await tx.outboundImportSession.create({ data: { fileName: (file.originalname || 'outbound-import.zip').slice(0, 191), fileKey: saved.key, requestId: normalizedRequestId || null, createdBy: userId, expiresAt: new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000), }, }); const previewJob = await tx.job.create({ data: { type: JobType.IMPORT_OUTBOUND_PREVIEW, status: JobStatus.PENDING, createdBy: userId, payload: { sessionId: session.id, fileKey: saved.key }, }, }); await tx.outboundImportSession.update({ where: { id: session.id }, data: { previewJobId: previewJob.id }, }); return { sessionId: session.id, jobId: previewJob.id, fileKey: saved.key }; }); } catch (error) { let persistedByFile: Awaited> | null | undefined; try { persistedByFile = await this.prisma.outboundImportSession.findFirst({ where: { fileKey: saved.key, createdBy: userId }, }); } catch { persistedByFile = undefined; } if (persistedByFile?.previewJobId && persistedByFile.fileKey) { created = { sessionId: persistedByFile.id, jobId: persistedByFile.previewJobId, fileKey: persistedByFile.fileKey, }; } else { const existing = normalizedRequestId ? await this.prisma.outboundImportSession .findUnique({ where: { requestId: normalizedRequestId } }) .catch(() => undefined) : null; if (persistedByFile !== undefined && existing !== undefined) { await this.storage.remove(saved.key).catch(() => undefined); } if (existing?.createdBy === userId && existing.previewJobId && existing.fileKey) { created = { sessionId: existing.id, jobId: existing.previewJobId, fileKey: existing.fileKey }; } else { this.logger.error(`创建出库导入预览记录失败:${(error as Error).message}`); throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入预览任务创建失败,请稍后重试'); } } } try { await this.previewQueue.add( 'preview', { jobId: created.jobId, sessionId: created.sessionId, fileKey: created.fileKey }, { jobId: created.jobId }, ); } catch (error) { this.logger.warn(`出库导入预览任务暂未入队,将自动重试:${(error as Error).message}`); } return { sessionId: created.sessionId, jobId: created.jobId }; } startImport(file: Express.Multer.File, userId: number) { return this.startPreview(file, userId); } private async requireSession(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 getSession(id: string, user: AuthUser) { const session = await this.requireSession(id, user); return { id: session.id, status: session.status, fileName: session.fileName, requestId: session.requestId, previewJobId: session.previewJobId, importJobId: session.importJobId, total: session.total, validCount: session.validCount, invalidCount: session.invalidCount, error: session.error, committedAt: session.committedAt, expiresAt: session.expiresAt, createdBy: session.createdBy, createdAt: session.createdAt, updatedAt: session.updatedAt, }; } async getSessionByRequest(requestId: string, user: AuthUser) { const normalizedRequestId = requestId.trim(); if (!/^[A-Za-z0-9_-]{16,64}$/.test(normalizedRequestId)) { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入请求标识格式无效'); } const session = await this.prisma.outboundImportSession.findUnique({ where: { requestId: normalizedRequestId } }); if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入请求不存在', 404); return this.getSession(session.id, user); } async listRows(id: string, query: QueryImportRowsDto, user: AuthUser) { await this.requireSession(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 pageSize = Math.min(query.pageSize || 20, 200); const [list, total] = await this.prisma.$transaction([ this.prisma.outboundImportRow.findMany({ where, orderBy, skip: (query.page - 1) * pageSize, take: pageSize, }), this.prisma.outboundImportRow.count({ where }), ]); return buildPage(list, total, query.page, pageSize); } async commitSession(id: string, user: AuthUser) { const session = await this.requireSession(id, user); if (session.importJobId) { if (session.status === 'IMPORTING') { await this.importQueue .add('import', { jobId: session.importJobId, sessionId: id }, { jobId: session.importJobId }) .catch((error) => this.logger.warn(`出库导入任务暂未重新入队,将自动重试:${(error as Error).message}`)); } return { jobId: session.importJobId, sessionId: id }; } if (session.status !== 'READY') { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话尚未准备完成或已处理'); } if (session.invalidCount > 0) { throw new BusinessException(ErrorCode.BAD_REQUEST, '预览存在错误行,请修正后重新上传'); } if (session.validCount <= 0) throw new BusinessException(ErrorCode.BAD_REQUEST, '没有可导入的数据'); const committedAt = new Date(); const jobId = randomUUID(); const job = await this.prisma.$transaction(async (tx) => { const claimed = await tx.outboundImportSession.updateMany({ where: { id, status: 'READY', importJobId: null, invalidCount: 0, validCount: { gt: 0 }, expiresAt: { gt: committedAt }, }, data: { status: 'IMPORTING', committedAt, importJobId: jobId }, }); if (claimed.count !== 1) { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话已提交、已过期或状态已变化'); } return tx.job.create({ data: { id: jobId, type: JobType.IMPORT_OUTBOUND, status: JobStatus.PENDING, total: session.validCount, createdBy: user.id, payload: { sessionId: id }, }, }); }); try { await this.importQueue.add('import', { jobId: job.id, sessionId: id }, { jobId: job.id }); } catch (e) { this.logger.warn(`出库导入任务暂未入队,将自动重试:${(e as Error).message}`); } return { jobId: job.id, sessionId: id }; } async downloadResult(id: string, user: AuthUser, res: Response): Promise { const session = await this.requireSession(id, user); if (!session.importJobId) throw new BusinessException(ErrorCode.NOT_FOUND, '导入结果不存在', 404); const job = await this.prisma.job.findUnique({ where: { id: session.importJobId } }); if (!job || job.type !== JobType.IMPORT_OUTBOUND) { throw new BusinessException(ErrorCode.NOT_FOUND, '导入结果不存在', 404); } if (![JobStatus.SUCCESS, JobStatus.PARTIAL, JobStatus.FAILED].includes(job.status as JobStatus)) { throw new BusinessException(ErrorCode.BAD_REQUEST, '导入任务尚未完成'); } const rows = await this.prisma.outboundImportRow.findMany({ where: { sessionId: id }, orderBy: { rowNo: 'asc' }, }); const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('导入结果'); worksheet.columns = [ { header: '行号', key: 'rowNo', width: 10 }, { header: '追溯码', key: 'shortCode', width: 18 }, { header: '批次编号', key: 'batchNo', width: 22 }, { header: '出库时间', key: 'outTime', width: 22 }, { header: '原图片路径', key: 'imagePaths', width: 40 }, { header: '图片数量', key: 'imageCount', width: 10 }, { header: '备注', key: 'remark', width: 28 }, { header: '处理状态', key: 'status', width: 14 }, { header: '原因', key: 'reason', width: 40 }, ]; worksheet.getRow(1).font = { bold: true }; worksheet.getColumn('shortCode').numFmt = '@'; for (const row of rows) { worksheet.addRow({ rowNo: row.rowNo, shortCode: row.shortCode || '', batchNo: row.batchNo || '', outTime: formatChinaDate(row.outTime), imagePaths: jsonArray(row.outImagePaths).join(';'), imageCount: jsonArray(row.outImagePaths).length, remark: row.remark || '', status: row.status, reason: row.reason || '', }); } const buffer = Buffer.from(await workbook.xlsx.writeBuffer()); res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); res.setHeader('Content-Disposition', `attachment; filename="outbound-import-result-${id}.xlsx"`); res.setHeader('Cache-Control', 'private, no-store'); res.end(buffer); } }