feat: 实现出库导入、区块链存证、查询日志、看板与系统设置
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -0,0 +1,140 @@
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, 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;
|
||||
fileKey: string;
|
||||
}
|
||||
|
||||
interface RowResult {
|
||||
values: Record<string, string>;
|
||||
ok: boolean;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
@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, fileKey } = 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 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 v = row.getCell(col).value;
|
||||
const text = v === null || v === undefined ? '' : String(v).trim();
|
||||
if (text) empty = false;
|
||||
values[key] = text;
|
||||
});
|
||||
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 } });
|
||||
if (!code) {
|
||||
row.reason = '短码不存在';
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await this.prisma.traceCode.update({
|
||||
where: { id: code.id },
|
||||
data: {
|
||||
sku: row.values.sku || undefined,
|
||||
archiveNo: row.values.archiveNo || undefined,
|
||||
outTime: row.values.outTime ? new Date(row.values.outTime) : undefined,
|
||||
remark: row.values.remark || undefined,
|
||||
},
|
||||
});
|
||||
row.ok = true;
|
||||
success++;
|
||||
} catch (e) {
|
||||
row.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}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async buildResultFile(rows: RowResult[]): Promise<string> {
|
||||
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 },
|
||||
];
|
||||
ws.getRow(1).font = { bold: true };
|
||||
for (const row of rows) {
|
||||
ws.addRow({ ...row.values, status: row.ok ? '成功' : '失败', 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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user