fix: 修复后端竞态/安全/数据处理问题并移除冗余 outImage 列
首次激活改条件更新消除并发竞态;备份恢复补模型全集与版本校验防清库; 审核列表分页总数、操作日志未捕获 Promise、出库导入重复码、加密密钥可编辑、 溯源码盐以 env 为准、证书按 originKey reconcile、env 加载去重等修复; 新增 parseBigId 防非法入参 500、全局安全响应头、去除 SVG 上传、接入 throttler 限流、 入队失败补偿、hashData 稳定序列化、无效码负缓存、看板已激活口径调整; 移除冗余 TraceCode.outImage 列统一 outImages(迁移 drop_trace_code_out_image)。
This commit is contained in:
@@ -34,6 +34,13 @@ function parseDate(v?: string): Date | undefined | null {
|
||||
return Number.isNaN(d.getTime()) ? null : d;
|
||||
}
|
||||
|
||||
function mimeOf(path: string): string {
|
||||
const ext = path.slice(path.lastIndexOf('.')).toLowerCase();
|
||||
if (ext === '.png') return 'image/png';
|
||||
if (ext === '.webp') return 'image/webp';
|
||||
return 'image/jpeg';
|
||||
}
|
||||
|
||||
function normalizeImagePath(raw: string): string {
|
||||
const p = raw.trim().replace(/^image\//i, 'images/');
|
||||
if (!p) return '';
|
||||
@@ -94,6 +101,7 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
});
|
||||
|
||||
const storedImages = new Map<string, { key: string; url: string; name: string; type: string }>();
|
||||
const seenShortCodes = new Map<string, number>(); // shortCode -> 首次出现行号,用于包内去重
|
||||
const rows: any[] = [];
|
||||
let valid = 0;
|
||||
let invalid = 0;
|
||||
@@ -122,6 +130,11 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
|
||||
try {
|
||||
if (!values.shortCode) throw new Error('追溯码为空');
|
||||
const firstRow = seenShortCodes.get(values.shortCode);
|
||||
if (firstRow) {
|
||||
throw new Error(`追溯码在本次导入中重复(首次出现于第 ${firstRow} 行)`);
|
||||
}
|
||||
seenShortCodes.set(values.shortCode, r);
|
||||
const code = await this.prisma.traceCode.findUnique({
|
||||
where: { shortCode: values.shortCode },
|
||||
include: { batch: true },
|
||||
@@ -144,7 +157,7 @@ export class ImportPreviewProcessor extends WorkerHost {
|
||||
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'}`);
|
||||
const saved = await this.storage.save(img, p.split('/').pop() || 'outbound.jpg', mimeOf(p));
|
||||
storedImages.set(p, { key: saved.key, url: saved.url, name: saved.name, type: 'image' });
|
||||
}
|
||||
imageItems.push(storedImages.get(p)!);
|
||||
|
||||
@@ -47,7 +47,6 @@ export class ImportProcessor extends WorkerHost {
|
||||
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,
|
||||
@@ -68,16 +67,22 @@ export class ImportProcessor extends WorkerHost {
|
||||
|
||||
const resultUrl = await this.buildResultFile(sessionId);
|
||||
const status = fail === 0 ? JobStatus.SUCCESS : success === 0 ? JobStatus.FAILED : JobStatus.PARTIAL;
|
||||
const imported = fail === 0;
|
||||
const session = await this.prisma.outboundImportSession.findUnique({ where: { id: sessionId }, select: { fileKey: true } });
|
||||
await this.prisma.$transaction([
|
||||
this.prisma.outboundImportSession.update({
|
||||
where: { id: sessionId },
|
||||
data: { status: fail === 0 ? 'IMPORTED' : 'FAILED' },
|
||||
data: { status: imported ? 'IMPORTED' : 'FAILED', fileKey: imported ? null : undefined },
|
||||
}),
|
||||
this.prisma.job.update({
|
||||
where: { id: jobId },
|
||||
data: { total: rows.length, successCount: success, failCount: fail, status, resultFileUrl: resultUrl },
|
||||
}),
|
||||
]);
|
||||
// 导入成功后删除原始上传 ZIP,避免长期占用存储(预览图片已成为业务数据,保留)
|
||||
if (imported && session?.fileKey) {
|
||||
await this.storage.remove(session.fileKey).catch((e) => this.logger.warn(`删除导入 ZIP 失败:${(e as Error).message}`));
|
||||
}
|
||||
this.logger.log(`出库导入完成:成功 ${success},失败 ${fail}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -19,6 +19,7 @@ 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';
|
||||
import { parseBigId } from '../common/utils/bigint.util';
|
||||
|
||||
@ApiTags('出库与上链')
|
||||
@ApiBearerAuth()
|
||||
@@ -30,7 +31,7 @@ export class OutboundController {
|
||||
@Roles(RoleType.OPERATOR)
|
||||
@ApiOperation({ summary: '单条登记出库 / 上链信息' })
|
||||
updateSingle(@Param('id') id: string, @Body() dto: OutboundDto) {
|
||||
return this.outboundService.updateSingle(BigInt(id), dto);
|
||||
return this.outboundService.updateSingle(parseBigId(id, '追溯码 ID'), dto);
|
||||
}
|
||||
|
||||
@Get('import/template')
|
||||
|
||||
@@ -6,7 +6,7 @@ import * as ExcelJS from 'exceljs';
|
||||
import AdmZip from 'adm-zip';
|
||||
import sharp from 'sharp';
|
||||
import { Prisma, RoleType } from '@prisma/client';
|
||||
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { ErrorCode, JobStatus, JobType, 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';
|
||||
@@ -37,10 +37,10 @@ export class OutboundService {
|
||||
const data: Prisma.TraceCodeUpdateInput = {};
|
||||
if ('outTime' in dto) data.outTime = dto.outTime ? new Date(dto.outTime) : null;
|
||||
if ('outImageKeys' in dto || 'outImageKey' in dto) {
|
||||
data.outImage = imageKeys[0] || null;
|
||||
// 无图时写 DB NULL(而非 JSON null),保证出库状态筛选一致
|
||||
data.outImages = imageKeys.length
|
||||
? imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }))
|
||||
: Prisma.JsonNull;
|
||||
: Prisma.DbNull;
|
||||
}
|
||||
if ('remark' in dto) data.remark = dto.remark || null;
|
||||
return this.prisma.traceCode.update({
|
||||
@@ -184,7 +184,14 @@ export class OutboundService {
|
||||
where: { id },
|
||||
data: { status: 'IMPORTING', committedAt: new Date() },
|
||||
});
|
||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
||||
// 入队失败时回退会话状态为 READY,避免卡在 IMPORTING 且无对应队列任务
|
||||
try {
|
||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
||||
} catch (e) {
|
||||
await this.prisma.outboundImportSession.update({ where: { id }, data: { status: 'READY', committedAt: null } });
|
||||
await this.jobs.finish(job.id, { status: JobStatus.FAILED, error: (e as Error).message });
|
||||
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入任务入队失败,请稍后重试');
|
||||
}
|
||||
return { jobId: job.id, sessionId: id };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user