Files
Artveris/apps/api/src/outbound/import.processor.ts
T

136 lines
5.5 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 || '' },
include: { artwork: { select: { templateId: true, archiveNo: true } } },
});
if (!code) throw new Error('追溯码不存在');
// 预览到提交之间可能已被出库:再次校验,避免重复出库
if (isOutbound(code)) throw new Error('该追溯码已登记出库,不可重复出库');
let imageItems = jsonArray<{ key: string; url?: string; name?: string; type?: string }>(row.outImageKeys).map(
(item) => ({ key: item.key, name: item.name, type: item.type || 'image' }),
);
// 出库实况图归位到 {模板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,
}));
}
await this.prisma.traceCode.update({
where: { id: code.id },
data: {
outTime: row.outTime ?? undefined,
outImages: imageItems.length ? imageItems : 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;
}
}