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

141 lines
5.2 KiB
TypeScript

import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import { createHash } from 'crypto';
import * as ExcelJS from 'exceljs';
import { JobStatus, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
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('短码不存在');
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,
outImage: imageItems[0]?.key || undefined,
outImages: imageItems.length
? imageItems.map((item) => ({ key: item.key, name: item.name, type: item.type || 'image' }))
: undefined,
remark: row.remark || undefined,
},
});
if (row.txHash) {
const dup = await this.prisma.blockchainProof.findFirst({
where: { traceCodeId: code.id, txHash: row.txHash },
});
if (!dup) {
const dataHash = '0x' + createHash('sha256').update(`${code.code}:${row.txHash}`).digest('hex');
await this.prisma.blockchainProof.create({
data: {
traceCodeId: code.id,
dataHash,
txHash: row.txHash,
blockHeight: row.blockHeight ?? null,
chainName: '手工登记',
onchainAt: row.onchainAt ?? new Date(),
status: ProofStatus.ONCHAIN,
rawResponse: { source: 'import' },
},
});
}
}
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;
await this.prisma.$transaction([
this.prisma.outboundImportSession.update({
where: { id: sessionId },
data: { status: fail === 0 ? 'IMPORTED' : 'FAILED' },
}),
this.prisma.job.update({
where: { id: jobId },
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
}),
]);
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: 'txHash', width: 30 },
{ 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,
txHash: row.txHash || '',
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;
}
}