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,11 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { IsOptional, IsString } from 'class-validator';
import { OutboundImportRowStatus } from '@artveris/shared';
import { PaginationDto } from '../../common/dto/pagination.dto';
export class QueryImportRowsDto extends PaginationDto {
@ApiPropertyOptional({ description: '行状态', enum: OutboundImportRowStatus })
@IsOptional()
@IsString()
status?: OutboundImportRowStatus;
}
+7 -1
View File
@@ -1,6 +1,6 @@
import { ApiPropertyOptional } from '@nestjs/swagger';
import { Type } from 'class-transformer';
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
import { IsArray, IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
export class OutboundDto {
@ApiPropertyOptional({ description: '出库时间' })
@@ -13,6 +13,12 @@ export class OutboundDto {
@IsString()
outImageKey?: string | null;
@ApiPropertyOptional({ description: '出库实况图存储 key 列表' })
@IsOptional()
@IsArray()
@IsString({ each: true })
outImageKeys?: string[];
@ApiPropertyOptional({ description: '上链哈希值(填写则记录上链结果)' })
@IsOptional()
@IsString()
@@ -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}`);
}
}
}
+87 -160
View File
@@ -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');
+34 -4
View File
@@ -5,6 +5,7 @@ import {
Param,
Post,
Put,
Query,
Res,
UploadedFile,
UseInterceptors,
@@ -15,6 +16,7 @@ import { Response } from 'express';
import { MAX_FILE_SIZE, RoleType } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundDto } from './dto/outbound.dto';
import { QueryImportRowsDto } from './dto/import-session.dto';
import { Roles } from '../common/decorators/roles.decorator';
import { CurrentUser, AuthUser } from '../common/decorators/current-user.decorator';
@@ -26,22 +28,50 @@ export class OutboundController {
@Put('trace-codes/:id')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '单条录入出库信息' })
@ApiOperation({ summary: '单条登记出库 / 上链信息' })
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
return this.outboundService.updateSingle(BigInt(id), dto);
}
@Get('import/template')
@ApiOperation({ summary: '下载出库导入模板(xlsx)' })
@ApiOperation({ summary: '下载出库导入 ZIP 模板' })
template(@Res() res: Response) {
return this.outboundService.generateTemplate(res);
}
@Post('import/preview')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '上传 ZIP 并异步解析预览' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 2 } }))
preview(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
return this.outboundService.startPreview(file, user.id);
}
@Get('import-sessions/:id')
@ApiOperation({ summary: '导入会话详情' })
getSession(@Param('id') id: string, @CurrentUser() user: AuthUser) {
return this.outboundService.getSession(id, user);
}
@Get('import-sessions/:id/rows')
@ApiOperation({ summary: '导入预览行列表' })
rows(@Param('id') id: string, @Query() query: QueryImportRowsDto, @CurrentUser() user: AuthUser) {
return this.outboundService.listRows(id, query, user);
}
@Post('import-sessions/:id/commit')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '确认导入预览数据' })
commit(@Param('id') id: string, @CurrentUser() user: AuthUser) {
return this.outboundService.commitSession(id, user);
}
@Post('import')
@Roles(RoleType.OPERATOR)
@ApiOperation({ summary: '批量导入出库信息(异步)' })
@ApiOperation({ summary: '兼容旧入口:上传 ZIP 并异步解析预览' })
@ApiConsumes('multipart/form-data')
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE } }))
@UseInterceptors(FileInterceptor('file', { limits: { fileSize: MAX_FILE_SIZE * 2 } }))
import(@UploadedFile() file: Express.Multer.File, @CurrentUser() user: AuthUser) {
return this.outboundService.startImport(file, user.id);
}
+8 -2
View File
@@ -4,11 +4,17 @@ import { QUEUE_NAMES } from '@artveris/shared';
import { OutboundService } from './outbound.service';
import { OutboundController } from './outbound.controller';
import { ImportProcessor } from './import.processor';
import { ImportPreviewProcessor } from './import-preview.processor';
@Module({
imports: [BullModule.registerQueue({ name: QUEUE_NAMES.IMPORT_OUTBOUND })],
imports: [
BullModule.registerQueue(
{ name: QUEUE_NAMES.IMPORT_OUTBOUND },
{ name: QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW },
),
],
controllers: [OutboundController],
providers: [OutboundService, ImportProcessor],
providers: [OutboundService, ImportProcessor, ImportPreviewProcessor],
exports: [OutboundService],
})
export class OutboundModule {}
+140 -34
View File
@@ -4,7 +4,9 @@ import { Queue } from 'bullmq';
import { Response } from 'express';
import { createHash } from 'crypto';
import * as ExcelJS from 'exceljs';
import { Prisma } from '@prisma/client';
import AdmZip from 'adm-zip';
import sharp from 'sharp';
import { Prisma, RoleType } from '@prisma/client';
import {
ErrorCode,
JobType,
@@ -16,13 +18,15 @@ import { PrismaService } from '../prisma/prisma.service';
import { StorageService } from '../storage/storage.service';
import { JobsService } from '../jobs/jobs.service';
import { BusinessException } from '../common/exceptions/business.exception';
import { buildPage } from '../common/utils/pagination.util';
import { AuthUser } from '../common/decorators/current-user.decorator';
import { OutboundDto } from './dto/outbound.dto';
import { QueryImportRowsDto } from './dto/import-session.dto';
const XLSX_MIME_TYPES = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel',
'application/octet-stream', // 某些浏览器对 .xlsx 的兜底类型
];
const ZIP_MAX_SIZE = 30 * 1024 * 1024;
const IMAGE_MAX_SIZE = 10 * 1024 * 1024;
const SESSION_TTL_DAYS = 2;
const ALLOWED_IMAGE_EXT = new Set(['.jpg', '.jpeg', '.png', '.webp']);
@Injectable()
export class OutboundService {
@@ -30,21 +34,27 @@ export class OutboundService {
private readonly prisma: PrismaService,
private readonly storage: StorageService,
private readonly jobs: JobsService,
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly queue: Queue,
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly importQueue: Queue,
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW) private readonly previewQueue: Queue,
) {}
async updateSingle(traceCodeId: bigint, dto: OutboundDto) {
const code = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId } });
if (!code) throw new BusinessException(ErrorCode.TRACE_CODE_NOT_FOUND, '追溯码不存在', 404);
const imageKeys = dto.outImageKeys ?? (dto.outImageKey ? [dto.outImageKey] : []);
const data: Prisma.TraceCodeUpdateInput = {};
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
if ('outImageKey' in dto) data.outImage = dto.outImageKey || null;
if ('outImageKeys' in dto || 'outImageKey' in dto) {
data.outImage = imageKeys[0] || null;
data.outImages = imageKeys.length
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
: Prisma.JsonNull;
}
if ('remark' in dto) data.remark = dto.remark || null;
const updated = await this.prisma.traceCode.update({
where: { id: traceCodeId },
data,
});
// 录入了上链哈希则记录一条已上链存证(手工登记,不触发 Mock 链)
if (dto.txHash) {
await this.recordProof(traceCodeId, code.code, {
txHash: dto.txHash,
@@ -55,8 +65,6 @@ export class OutboundService {
return updated;
}
// 手工登记上链结果:写入一条 ONCHAIN 存证(数据哈希由 code+txHash 派生)
// 同码同哈希去重:重复保存不会产生多条存证
private async recordProof(
traceCodeId: bigint,
code: string,
@@ -66,8 +74,7 @@ export class OutboundService {
where: { traceCodeId, txHash: p.txHash },
});
if (dup) return;
const dataHash =
'0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
const dataHash = '0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
await this.prisma.blockchainProof.create({
data: {
traceCodeId,
@@ -85,42 +92,141 @@ export class OutboundService {
async generateTemplate(res: Response): Promise<void> {
const wb = new ExcelJS.Workbook();
const ws = wb.addWorksheet('导入模板');
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: 22 }));
ws.columns = OUTBOUND_IMPORT_COLUMNS.map((c) => ({ header: c.header, key: c.key, width: c.key === 'outImages' ? 36 : 22 }));
ws.getRow(1).font = { bold: true };
const example: Record<string, string> = {};
OUTBOUND_IMPORT_COLUMNS.forEach((c) => (example[c.key] = c.example));
ws.addRow(example);
ws.addRow({
shortCode: '请替换为真实短码1',
batchNo: 'B20260704001',
outTime: '2026-07-04 10:00',
outImages: 'images/out-001.jpg',
txHash: '0xabc123',
onchainAt: '2026-07-04 10:30',
blockHeight: '8500001',
remark: '单图示例',
});
ws.addRow({
shortCode: '请替换为真实短码2',
batchNo: 'B20260704001',
outTime: '2026-07-04 11:00',
outImages: 'images/out-002.png;images/out-003.jpg',
txHash: '',
onchainAt: '',
blockHeight: '',
remark: '多图示例',
});
const note = wb.addWorksheet('字段说明');
note.columns = [
{ header: '列名', key: 'header', width: 18 },
{ header: '是否必填', key: 'required', width: 12 },
{ header: '说明', key: 'note', width: 50 },
{ header: '说明', key: 'note', width: 70 },
];
note.getRow(1).font = { bold: true };
OUTBOUND_IMPORT_COLUMNS.forEach((c) =>
note.addRow({ header: c.header, required: c.required ? '是' : '否', note: c.note }),
);
res.setHeader(
'Content-Type',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
);
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.xlsx"');
await wb.xlsx.write(res);
res.end();
const zip = new AdmZip();
zip.addFile('outbound-import-template.xlsx', Buffer.from(await wb.xlsx.writeBuffer()));
zip.addFile('说明.txt', Buffer.from(
[
'出库批量导入说明',
'',
'1. ZIP 根目录必须包含一个 xlsx 文件和 images 文件夹。',
'2. 出库实况图路径填写 images/xxx.jpg,多张图片使用英文分号 ; 分隔。',
'3. 不允许使用绝对路径、..、反斜杠或 images 目录之外的路径。',
'4. 上传 ZIP 后系统会先预览校验,确认无误后才正式导入。',
].join('\r\n'),
'utf8',
));
zip.addFile('images/out-001.jpg', await this.sampleImage('#13a8a8'));
zip.addFile('images/out-002.png', await this.sampleImage('#3b82f6', 'png'));
zip.addFile('images/out-003.jpg', await this.sampleImage('#f59e0b'));
res.setHeader('Content-Type', 'application/zip');
res.setHeader('Content-Disposition', 'attachment; filename="outbound-import-template.zip"');
res.end(zip.toBuffer());
}
async startImport(file: Express.Multer.File, userId: number) {
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入文件');
private sampleImage(color: string, format: 'jpeg' | 'png' = 'jpeg') {
const img = sharp({
create: {
width: 720,
height: 480,
channels: 3,
background: color,
},
});
return format === 'png' ? img.png().toBuffer() : img.jpeg({ quality: 86 }).toBuffer();
}
async startPreview(file: Express.Multer.File, userId: number) {
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件');
const name = (file.originalname || '').toLowerCase();
const okType = XLSX_MIME_TYPES.includes(file.mimetype) || name.endsWith('.xlsx') || name.endsWith('.xls');
if (!okType) {
throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 Excel(.xlsx/.xls)文件导入');
if (!name.endsWith('.zip') || file.size > ZIP_MAX_SIZE) {
throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 30MB 以内的 ZIP 文件');
}
const saved = await this.storage.save(file.buffer, file.originalname || 'import.xlsx', file.mimetype);
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, 0, userId, { fileKey: saved.key });
await this.queue.add('import', { jobId: job.id, fileKey: saved.key });
return { jobId: job.id };
const saved = await this.storage.save(file.buffer, file.originalname || 'outbound-import.zip', 'application/zip');
const session = await this.prisma.outboundImportSession.create({
data: {
fileName: file.originalname || 'outbound-import.zip',
fileKey: saved.key,
createdBy: userId,
expiresAt: new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000),
},
});
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND_PREVIEW, 0, userId, {
sessionId: session.id,
fileKey: saved.key,
});
await this.previewQueue.add('preview', { jobId: job.id, sessionId: session.id, fileKey: saved.key });
return { sessionId: session.id, jobId: job.id };
}
// 兼容旧入口:上传后只做预览,不直接入库。
startImport(file: Express.Multer.File, userId: number) {
return this.startPreview(file, userId);
}
async getSession(id: string, user: AuthUser) {
const session = await this.prisma.outboundImportSession.findUnique({ where: { id } });
if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入会话不存在', 404);
if (user.role !== RoleType.SUPER_ADMIN && session.createdBy !== user.id) {
throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该导入会话的权限', 403);
}
return session;
}
async listRows(id: string, query: QueryImportRowsDto, user: AuthUser) {
await this.getSession(id, user);
const where: Prisma.OutboundImportRowWhereInput = { sessionId: id };
if (query.status) where.status = query.status as any;
const [list, total] = await this.prisma.$transaction([
this.prisma.outboundImportRow.findMany({
where,
orderBy: { rowNo: 'asc' },
skip: query.skip,
take: query.take,
}),
this.prisma.outboundImportRow.count({ where }),
]);
return buildPage(list, total, query.page, query.pageSize);
}
async commitSession(id: string, user: AuthUser) {
const session = await this.getSession(id, user);
if (session.status !== 'READY') {
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话尚未准备完成或已处理');
}
if (session.invalidCount > 0) {
throw new BusinessException(ErrorCode.BAD_REQUEST, '预览存在错误行,请修正后重新上传');
}
const job = await this.jobs.create(JobType.IMPORT_OUTBOUND, session.validCount, user.id, { sessionId: id });
await this.prisma.outboundImportSession.update({
where: { id },
data: { status: 'IMPORTING', committedAt: new Date() },
});
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
return { jobId: job.id, sessionId: id };
}
}