Files
Artveris/apps/api/src/outbound/import.processor.ts
T
Nixevol 18bdfd7e46 fix: 出库批量导入审查加固(统一已出库判定 + 空登记校验)
- 抽 outbound.util.isOutbound(outTime 或 outImages 任一即已出库),单件/预览/提交统一判重复
- 预览新增「出库时间与出库图至少填一项」校验,杜绝导入成功但未出库的空登记
- 端到端实测全链路(正常/已出库/不存在/空行/含错误拒提交/成功/重复拒绝)通过
2026-07-10 12:15:32 +08:00

125 lines
4.9 KiB
TypeScript

import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import * as ExcelJS from 'exceljs';
import { JobStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
import { isOutbound } from './outbound.util';
interface ImportJobData {
jobId: string;
sessionId: string;
}
function jsonArray<T>(value: unknown): T[] {
return Array.isArray(value) ? (value as T[]) : [];
}
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND)
export class ImportProcessor extends WorkerHost {
private readonly logger = new Logger(ImportProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
) {
super();
}
async process(job: Job<ImportJobData>): Promise<void> {
const { jobId, sessionId } = job.data;
await this.jobs.start(jobId);
const rows = await this.prisma.outboundImportRow.findMany({
where: { sessionId, status: 'VALID' },
orderBy: { rowNo: 'asc' },
});
let success = 0;
let fail = 0;
for (const row of rows) {
try {
const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } });
if (!code) throw new Error('追溯码不存在');
// 预览到提交之间可能已被出库:再次校验,避免重复出库
if (isOutbound(code)) throw new Error('该追溯码已登记出库,不可重复出库');
const imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys);
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
outTime: row.outTime ?? undefined,
outImages: imageItems.length
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
: undefined,
remark: row.remark || undefined,
},
});
await this.prisma.outboundImportRow.update({ where: { id: row.id }, data: { status: 'IMPORTED', reason: null } });
success++;
} catch (e) {
await this.prisma.outboundImportRow.update({
where: { id: row.id },
data: { status: 'FAILED', reason: (e as Error).message },
});
fail++;
}
await this.jobs.progress(jobId, success, fail);
}
const resultUrl = await this.buildResultFile(sessionId);
const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
const imported = fail === 0;
const session = await this.prisma.outboundImportSession.findUnique({ where: { id: sessionId }, select: { fileKey: true } });
await this.prisma.$transaction([
this.prisma.outboundImportSession.update({
where: { id: sessionId },
data: { status: imported ? 'IMPORTED' : 'FAILED', fileKey: imported ? null : undefined },
}),
this.prisma.job.update({
where: { id: jobId },
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
}),
]);
// 导入成功后删除原始上传 ZIP,避免长期占用存储(预览图片已成为业务数据,保留)
if (imported && session?.fileKey) {
await this.storage.remove(session.fileKey).catch((e) => this.logger.warn(`删除导入 ZIP 失败:${(e as Error).message}`));
}
this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`);
}
private async buildResultFile(sessionId: string): Promise<string> {
const rows = await this.prisma.outboundImportRow.findMany({
where: { sessionId },
orderBy: { rowNo: 'asc' },
});
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('导入结果');
ws.columns = [
{ header: '行号', key: 'rowNo', width: 10 },
{ header: '追溯码', key: 'shortCode', width: 18 },
{ header: '批次编号', key: 'batchNo', width: 22 },
{ header: '出库时间', key: 'outTime', width: 22 },
{ header: '图片数量', key: 'imageCount', width: 10 },
{ header: '处理状态', key: 'status', width: 14 },
{ header: '原因', key: 'reason', width: 40 },
];
ws.getRow(1).font = { bold: true };
for (const row of rows) {
ws.addRow({
rowNo: row.rowNo,
shortCode: row.shortCode || '',
batchNo: row.batchNo || '',
outTime: row.outTime?.toISOString() || '',
imageCount: jsonArray(row.outImageKeys).length,
status: row.status,
reason: row.reason || '',
});
}
const buf = Buffer.from(await wb.xlsx.writeBuffer());
const saved = await this.storage.save(buf, 'import-result.xlsx', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
return saved.url;
}
}