feat: 完善后台导入日志权限与备份恢复

This commit is contained in:
Nixevol
2026-07-04 09:06:35 +08:00
parent 5ae3b12fff
commit d484da3862
61 changed files with 2743 additions and 436 deletions
@@ -0,0 +1,201 @@
import { Processor, WorkerHost } from '@nestjs/bullmq';
import { Logger } from '@nestjs/common';
import { Job } from 'bullmq';
import AdmZip from 'adm-zip';
import * as ExcelJS from 'exceljs';
import sharp from 'sharp';
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 PreviewJobData {
jobId: string;
sessionId: string;
fileKey: string;
}
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();
}
function parseDate(v?: string): Date | undefined | null {
if (!v) return undefined;
const d = new Date(v);
return Number.isNaN(d.getTime()) ? null : d;
}
function normalizeImagePath(raw: string): string {
const p = raw.trim().replace(/^image\//i, 'images/');
if (!p) return '';
if (p.includes('\\') || p.includes('..') || p.startsWith('/') || /^[a-z]:/i.test(p)) {
throw new Error(`图片路径不安全:${raw}`);
}
if (!/^images\/[^/][\w.\- /()\u4e00-\u9fa5]+$/i.test(p)) {
throw new Error(`图片必须位于 images 目录:${raw}`);
}
const ext = p.slice(p.lastIndexOf('.')).toLowerCase();
if (!['.jpg', '.jpeg', '.png', '.webp'].includes(ext)) {
throw new Error(`不支持的图片格式:${raw}`);
}
return p;
}
@Processor(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW)
export class ImportPreviewProcessor extends WorkerHost {
private readonly logger = new Logger(ImportPreviewProcessor.name);
constructor(
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
) {
super();
}
async process(job: Job<PreviewJobData>): Promise<void> {
const { jobId, sessionId, fileKey } = job.data;
await this.jobs.start(jobId);
try {
const buffer = await this.storage.read(fileKey);
const zip = new AdmZip(buffer);
const entries = zip.getEntries().filter((e) => !e.isDirectory);
const xlsxEntries = entries.filter((e) => e.entryName.toLowerCase().endsWith('.xlsx'));
if (xlsxEntries.length !== 1) throw new Error('ZIP 中必须且只能包含一个 xlsx 文件');
const imageEntries = new Map<string, Buffer>();
for (const entry of entries) {
const name = entry.entryName.replace(/\\/g, '/');
if (name === xlsxEntries[0].entryName || name.endsWith('说明.txt')) continue;
const normalized = normalizeImagePath(name);
const data = entry.getData();
if (data.length > 10 * 1024 * 1024) throw new Error(`图片超过 10MB:${name}`);
imageEntries.set(normalized, data);
}
const wb = new ExcelJS.Workbook();
await wb.xlsx.load(xlsxEntries[0].getData() 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>();
ws.getRow(1).eachCell((cell, col) => {
const key = headerToKey.get(String(cell.value ?? '').trim());
if (key) colToKey.set(col, key);
});
const storedImages = new Map<string, { key: string; url: string; name: string; type: string }>();
const rows: any[] = [];
let valid = 0;
let invalid = 0;
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;
});
if (empty) continue;
const result: any = {
sessionId,
rowNo: r,
status: 'INVALID',
shortCode: values.shortCode || null,
batchNo: values.batchNo || null,
txHash: values.txHash || null,
remark: values.remark || null,
reason: '',
preview: values,
};
try {
if (!values.shortCode) throw new Error('短码为空');
const code = await this.prisma.traceCode.findUnique({
where: { shortCode: values.shortCode },
include: { batch: true },
});
if (!code) throw new Error('短码不存在');
if (values.batchNo && values.batchNo !== (code.batch?.batchNo ?? '')) {
throw new Error(`批次编号不匹配,实际为 ${code.batch?.batchNo ?? '-'}`);
}
const outTime = parseDate(values.outTime);
if (outTime === null) throw new Error('出库时间格式不正确');
const onchainAt = parseDate(values.onchainAt);
if (onchainAt === null) throw new Error('上链时间格式不正确');
let blockHeight: bigint | null = null;
if (values.blockHeight) {
if (!/^\d+$/.test(values.blockHeight)) throw new Error('区块高度应为整数');
blockHeight = BigInt(values.blockHeight);
}
const imagePaths = (values.outImages || '')
.split(';')
.map((p) => p.trim())
.filter(Boolean)
.map(normalizeImagePath);
const imageItems: Array<{ key: string; url: string; name: string; type: string }> = [];
for (const p of imagePaths) {
const img = imageEntries.get(p);
if (!img) throw new Error(`图片不存在:${p}`);
if (!storedImages.has(p)) {
await sharp(img).metadata();
const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', `image/${p.endsWith('.png') ? 'png' : 'jpeg'}`);
storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' });
}
imageItems.push(storedImages.get(p)!);
}
Object.assign(result, {
status: 'VALID',
outTime,
onchainAt,
blockHeight,
outImagePaths: imagePaths,
outImageKeys: imageItems,
preview: { ...values, images: imageItems },
});
valid++;
} catch (e) {
result.reason = (e as Error).message;
invalid++;
}
rows.push(result);
}
await this.prisma.$transaction([
this.prisma.outboundImportRow.deleteMany({ where: { sessionId } }),
...rows.map((row) => this.prisma.outboundImportRow.create({ data: row })),
this.prisma.outboundImportSession.update({
where: { id: sessionId },
data: { status: invalid ? 'FAILED' : 'READY', total: rows.length, validCount: valid, invalidCount: invalid },
}),
]);
await this.jobs.finish(jobId, {
status: invalid ? JobStatus.FAILED : JobStatus.SUCCESS,
successCount: valid,
failCount: invalid,
});
} catch (e) {
const message = (e as Error).message;
await this.prisma.outboundImportSession.update({
where: { id: sessionId },
data: { status: 'FAILED', error: message },
});
await this.jobs.finish(jobId, { status: JobStatus.FAILED, error: message });
this.logger.error(`导入预览失败:${message}`);
}
}
}