feat: 完善后台导入日志权限与备份恢复
This commit is contained in:
@@ -3,41 +3,18 @@ import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, ProofStatus, QUEUE_NAMES } from '@artveris/shared';
|
||||
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';
|
||||
|
||||
// 将 ExcelJS 单元格值规整为字符串(兼容 Date / 富文本 / 公式结果 / 超链接 / 数字)
|
||||
function cellToString(v: unknown): string {
|
||||
if (v === null || v === undefined) return '';
|
||||
if (v instanceof Date) return v.toISOString();
|
||||
if (typeof v === 'object') {
|
||||
const o = v as Record<string, unknown>;
|
||||
if (typeof o.text === 'string') return o.text.trim();
|
||||
if (o.result !== undefined && o.result !== null) return String(o.result).trim();
|
||||
if (Array.isArray(o.richText)) return o.richText.map((r: any) => r.text).join('').trim();
|
||||
if (o.hyperlink) return String(o.hyperlink).trim();
|
||||
}
|
||||
return String(v).trim();
|
||||
}
|
||||
|
||||
// 校验并解析日期,非法返回 null(区分 undefined=未填)
|
||||
function parseDate(v?: string): Date | undefined | null {
|
||||
if (!v) return undefined;
|
||||
const d = new Date(v);
|
||||
return isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
interface ImportJobData {
|
||||
jobId: string;
|
||||
fileKey: string;
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
interface RowResult {
|
||||
values: Record<string, string>;
|
||||
ok: boolean;
|
||||
reason: string;
|
||||
function jsonArray<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND)
|
||||
@@ -53,158 +30,108 @@ export class ImportProcessor extends WorkerHost {
|
||||
}
|
||||
|
||||
async process(job: Job<ImportJobData>): Promise<void> {
|
||||
const { jobId, fileKey } = job.data;
|
||||
const { jobId, sessionId } = job.data;
|
||||
await this.jobs.start(jobId);
|
||||
try {
|
||||
const buffer = await this.storage.read(fileKey);
|
||||
const wb = new ExcelJS.Workbook();
|
||||
await wb.xlsx.load(buffer as unknown as ArrayBuffer);
|
||||
const ws = wb.worksheets[0];
|
||||
const rows = await this.prisma.outboundImportRow.findMany({
|
||||
where: { sessionId, status: 'VALID' },
|
||||
orderBy: { rowNo: 'asc' },
|
||||
});
|
||||
|
||||
// 建立 表头文本 -> 字段键 映射
|
||||
const headerToKey = new Map<string, string>();
|
||||
OUTBOUND_IMPORT_COLUMNS.forEach((c) => headerToKey.set(c.header, c.key));
|
||||
const colToKey = new Map<number, string>();
|
||||
const headerRow = ws.getRow(1);
|
||||
headerRow.eachCell((cell, col) => {
|
||||
const key = headerToKey.get(String(cell.value ?? '').trim());
|
||||
if (key) colToKey.set(col, key);
|
||||
});
|
||||
|
||||
const rows: RowResult[] = [];
|
||||
for (let r = 2; r <= ws.rowCount; r++) {
|
||||
const row = ws.getRow(r);
|
||||
const values: Record<string, string> = {};
|
||||
let empty = true;
|
||||
colToKey.forEach((key, col) => {
|
||||
const text = cellToString(row.getCell(col).value);
|
||||
if (text) empty = false;
|
||||
values[key] = text;
|
||||
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 (empty) continue;
|
||||
rows.push({ values, ok: false, reason: '' });
|
||||
}
|
||||
|
||||
await this.jobs.progress(jobId, 0, 0);
|
||||
let success = 0;
|
||||
let fail = 0;
|
||||
for (const row of rows) {
|
||||
const shortCode = row.values.shortCode;
|
||||
if (!shortCode) {
|
||||
row.reason = '短码为空';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode },
|
||||
include: { batch: true },
|
||||
});
|
||||
if (!code) {
|
||||
row.reason = '短码不存在';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
// 批次编号核对:填写则必须与该码实际批次一致
|
||||
if (row.values.batchNo && row.values.batchNo !== (code.batch?.batchNo ?? '')) {
|
||||
row.reason = `批次编号与该码实际批次不符(实际:${code.batch?.batchNo ?? '无'})`;
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
// 字段格式校验
|
||||
const outTime = parseDate(row.values.outTime);
|
||||
if (outTime === null) {
|
||||
row.reason = '出库时间格式不正确(应为 YYYY-MM-DD HH:mm)';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
const onchainAt = parseDate(row.values.onchainAt);
|
||||
if (onchainAt === null) {
|
||||
row.reason = '上链时间格式不正确(应为 YYYY-MM-DD HH:mm)';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
let blockHeight: bigint | undefined;
|
||||
if (row.values.blockHeight) {
|
||||
if (!/^\d+$/.test(row.values.blockHeight)) {
|
||||
row.reason = '区块高度应为整数';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
blockHeight = BigInt(row.values.blockHeight);
|
||||
}
|
||||
try {
|
||||
await this.prisma.traceCode.update({
|
||||
where: { id: code.id },
|
||||
data: {
|
||||
outTime: outTime ?? undefined,
|
||||
outImage: row.values.outImage || undefined,
|
||||
remark: row.values.remark || undefined,
|
||||
},
|
||||
if (row.txHash) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: code.id, txHash: row.txHash },
|
||||
});
|
||||
// 录入上链哈希则登记一条已上链存证(同码同哈希去重,避免重复导入污染)
|
||||
if (row.values.txHash) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId: code.id, txHash: row.values.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' },
|
||||
},
|
||||
});
|
||||
if (!dup) {
|
||||
const dataHash =
|
||||
'0x' + createHash('sha256').update(`${code.code}:${row.values.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId: code.id,
|
||||
dataHash,
|
||||
txHash: row.values.txHash,
|
||||
blockHeight: blockHeight ?? null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: onchainAt ?? new Date(),
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'import' },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
row.ok = true;
|
||||
success++;
|
||||
} catch (e) {
|
||||
row.reason = (e as Error).message;
|
||||
fail++;
|
||||
}
|
||||
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(rows);
|
||||
const status =
|
||||
fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
||||
await this.prisma.job.update({
|
||||
where: { id: jobId },
|
||||
data: {
|
||||
total: rows.length,
|
||||
successCount: success,
|
||||
failCount: fail,
|
||||
status,
|
||||
resultFileUrl: resultUrl,
|
||||
},
|
||||
});
|
||||
this.logger.log(`导入完成:成功 ${success},失败 ${fail}`);
|
||||
} catch (e) {
|
||||
await this.jobs.finish(jobId, { status: JobStatus.FAILED, error: (e as Error).message });
|
||||
this.logger.error(`导入失败:${(e as Error).message}`);
|
||||
}
|
||||
|
||||
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(rows: RowResult[]): Promise<string> {
|
||||
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 = [
|
||||
...OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 })),
|
||||
{ header: '处理状态', key: 'status', width: 12 },
|
||||
{ header: '失败原因', key: 'reason', width: 30 },
|
||||
{ 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({ ...row.values, status: row.ok ? '成功' : '失败', reason: row.reason });
|
||||
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');
|
||||
|
||||
Reference in New Issue
Block a user