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
+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 };
}
}