fix: 加固批量出库导入流程
This commit is contained in:
@@ -1,15 +1,22 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { Queue } from 'bullmq';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { Response } from 'express';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import AdmZip from 'adm-zip';
|
||||
import sharp from 'sharp';
|
||||
import { Prisma, RoleType } from '@prisma/client';
|
||||
import { ErrorCode, JobStatus, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import {
|
||||
ErrorCode,
|
||||
JobStatus,
|
||||
JobType,
|
||||
MAX_OUTBOUND_IMPORT_SIZE,
|
||||
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';
|
||||
import { BusinessException } from '../common/exceptions/business.exception';
|
||||
import { buildPage } from '../common/utils/pagination.util';
|
||||
import { buildOrderBy } from '../common/utils/sort.util';
|
||||
@@ -18,15 +25,33 @@ import { OutboundDto } from './dto/outbound.dto';
|
||||
import { QueryImportRowsDto } from './dto/import-session.dto';
|
||||
import { isOutbound } from './outbound.util';
|
||||
|
||||
const ZIP_MAX_SIZE = 30 * 1024 * 1024;
|
||||
const SESSION_TTL_DAYS = 2;
|
||||
|
||||
function jsonArray<T>(value: unknown): T[] {
|
||||
return Array.isArray(value) ? (value as T[]) : [];
|
||||
}
|
||||
|
||||
function formatChinaDate(value: Date | null): string {
|
||||
if (!value) return '';
|
||||
return new Intl.DateTimeFormat('sv-SE', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
}).format(value);
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class OutboundService {
|
||||
private readonly logger = new Logger(OutboundService.name);
|
||||
|
||||
constructor(
|
||||
private readonly prisma: PrismaService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly jobs: JobsService,
|
||||
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND) private readonly importQueue: Queue,
|
||||
@InjectQueue(QUEUE_NAMES.IMPORT_OUTBOUND_PREVIEW) private readonly previewQueue: Queue,
|
||||
) {}
|
||||
@@ -46,14 +71,17 @@ export class OutboundService {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '出库时间不能为空');
|
||||
}
|
||||
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;
|
||||
const data: Prisma.TraceCodeUpdateManyMutationInput = {};
|
||||
const relocatedKeys: string[] = [];
|
||||
data.outTime = new Date(dto.outTime);
|
||||
if ('outImageKeys' in dto || 'outImageKey' in dto) {
|
||||
let imageItems = imageKeys.map((key) => ({ key, type: 'image', name: key.split('/').pop() || '出库实况图' }));
|
||||
// 出库实况图归位到 {模板ID}/{档案编号}/{追溯码}/出库实况_{时间戳}_{序号}
|
||||
if (imageItems.length && code.artwork?.archiveNo) {
|
||||
const dir = `${code.artwork.templateId}/${code.artwork.archiveNo}/${code.shortCode}`;
|
||||
imageItems = (await this.storage.relocateMedia(imageItems, dir, '出库实况')).items.map((item) => ({
|
||||
const relocated = await this.storage.relocateMedia(imageItems, dir, '出库实况');
|
||||
relocatedKeys.push(...relocated.keyMap.values());
|
||||
imageItems = relocated.items.map((item) => ({
|
||||
...item,
|
||||
name: item.key.split('/').pop() || item.name,
|
||||
}));
|
||||
@@ -62,10 +90,37 @@ export class OutboundService {
|
||||
data.outImages = imageItems.length ? imageItems : Prisma.DbNull;
|
||||
}
|
||||
if ('remark' in dto) data.remark = dto.remark || null;
|
||||
return this.prisma.traceCode.update({
|
||||
where: { id: traceCodeId },
|
||||
data,
|
||||
});
|
||||
let duplicateDetected = false;
|
||||
try {
|
||||
const updated = await this.prisma.traceCode.updateMany({
|
||||
where: { id: traceCodeId, outTime: null },
|
||||
data,
|
||||
});
|
||||
if (updated.count !== 1) {
|
||||
duplicateDetected = true;
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '该追溯码已登记出库,不可重复出库');
|
||||
}
|
||||
return this.prisma.traceCode.findUniqueOrThrow({ where: { id: traceCodeId } });
|
||||
} catch (error) {
|
||||
let committedWithRelocatedImages = false;
|
||||
let commitStateKnown = false;
|
||||
if (relocatedKeys.length && !duplicateDetected) {
|
||||
try {
|
||||
const current = await this.prisma.traceCode.findUnique({ where: { id: traceCodeId }, select: { outImages: true } });
|
||||
const currentKeys = Array.isArray(current?.outImages)
|
||||
? current.outImages.map((item: any) => String(item?.key || '')).filter(Boolean)
|
||||
: [];
|
||||
committedWithRelocatedImages = relocatedKeys.every((key) => currentKeys.includes(key));
|
||||
commitStateKnown = true;
|
||||
} catch {
|
||||
// 提交结果未知时保留文件,宁可留待清理也不能删除可能已经入库的业务图片。
|
||||
}
|
||||
}
|
||||
if (duplicateDetected || (commitStateKnown && !committedWithRelocatedImages)) {
|
||||
for (const key of relocatedKeys) await this.storage.remove(key).catch(() => undefined);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async generateTemplate(res: Response): Promise<void> {
|
||||
@@ -73,6 +128,7 @@ export class OutboundService {
|
||||
const ws = wb.addWorksheet('导入模板');
|
||||
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 };
|
||||
ws.getColumn('shortCode').numFmt = '@';
|
||||
ws.addRow({
|
||||
shortCode: '请替换为真实追溯码',
|
||||
batchNo: 'B20260704001',
|
||||
@@ -137,34 +193,106 @@ export class OutboundService {
|
||||
return format === 'png' ? img.png().toBuffer() : img.jpeg({ quality: 86 }).toBuffer();
|
||||
}
|
||||
|
||||
async startPreview(file: Express.Multer.File, userId: number) {
|
||||
async startPreview(file: Express.Multer.File, userId: number, requestId?: string) {
|
||||
const normalizedRequestId = (requestId || '').trim();
|
||||
if (normalizedRequestId && !/^[A-Za-z0-9_-]{16,64}$/.test(normalizedRequestId)) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入请求标识格式无效');
|
||||
}
|
||||
if (normalizedRequestId) {
|
||||
const existing = await this.prisma.outboundImportSession.findUnique({ where: { requestId: normalizedRequestId } });
|
||||
if (existing) {
|
||||
if (existing.createdBy !== userId) throw new BusinessException(ErrorCode.FORBIDDEN, '没有访问该导入请求的权限', 403);
|
||||
if (!existing.previewJobId) throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入预览任务记录不完整');
|
||||
return { sessionId: existing.id, jobId: existing.previewJobId };
|
||||
}
|
||||
}
|
||||
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入 ZIP 文件');
|
||||
const name = (file.originalname || '').toLowerCase();
|
||||
if (!name.endsWith('.zip') || file.size > ZIP_MAX_SIZE) {
|
||||
throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 30MB 以内的 ZIP 文件');
|
||||
if (!name.endsWith('.zip')) throw new BusinessException(ErrorCode.FILE_TYPE_NOT_ALLOWED, '仅支持 ZIP 文件');
|
||||
const fileSize = file.size || file.buffer?.length || 0;
|
||||
if (!fileSize) throw new BusinessException(ErrorCode.BAD_REQUEST, '导入 ZIP 文件不能为空');
|
||||
if (fileSize > MAX_OUTBOUND_IMPORT_SIZE) throw new BusinessException(ErrorCode.FILE_TOO_LARGE, 'ZIP 文件不能超过 30MB');
|
||||
const saved = await this.storage.savePrivate(
|
||||
file.buffer,
|
||||
file.originalname || 'outbound-import.zip',
|
||||
'application/zip',
|
||||
);
|
||||
let created: { sessionId: string; jobId: string; fileKey: string };
|
||||
try {
|
||||
created = await this.prisma.$transaction(async (tx) => {
|
||||
const session = await tx.outboundImportSession.create({
|
||||
data: {
|
||||
fileName: (file.originalname || 'outbound-import.zip').slice(0, 191),
|
||||
fileKey: saved.key,
|
||||
requestId: normalizedRequestId || null,
|
||||
createdBy: userId,
|
||||
expiresAt: new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000),
|
||||
},
|
||||
});
|
||||
const previewJob = await tx.job.create({
|
||||
data: {
|
||||
type: JobType.IMPORT_OUTBOUND_PREVIEW,
|
||||
status: JobStatus.PENDING,
|
||||
createdBy: userId,
|
||||
payload: { sessionId: session.id, fileKey: saved.key },
|
||||
},
|
||||
});
|
||||
await tx.outboundImportSession.update({
|
||||
where: { id: session.id },
|
||||
data: { previewJobId: previewJob.id },
|
||||
});
|
||||
return { sessionId: session.id, jobId: previewJob.id, fileKey: saved.key };
|
||||
});
|
||||
} catch (error) {
|
||||
let persistedByFile: Awaited<ReturnType<typeof this.prisma.outboundImportSession.findFirst>> | null | undefined;
|
||||
try {
|
||||
persistedByFile = await this.prisma.outboundImportSession.findFirst({
|
||||
where: { fileKey: saved.key, createdBy: userId },
|
||||
});
|
||||
} catch {
|
||||
persistedByFile = undefined;
|
||||
}
|
||||
if (persistedByFile?.previewJobId && persistedByFile.fileKey) {
|
||||
created = {
|
||||
sessionId: persistedByFile.id,
|
||||
jobId: persistedByFile.previewJobId,
|
||||
fileKey: persistedByFile.fileKey,
|
||||
};
|
||||
} else {
|
||||
const existing = normalizedRequestId
|
||||
? await this.prisma.outboundImportSession
|
||||
.findUnique({ where: { requestId: normalizedRequestId } })
|
||||
.catch(() => undefined)
|
||||
: null;
|
||||
if (persistedByFile !== undefined && existing !== undefined) {
|
||||
await this.storage.remove(saved.key).catch(() => undefined);
|
||||
}
|
||||
if (existing?.createdBy === userId && existing.previewJobId && existing.fileKey) {
|
||||
created = { sessionId: existing.id, jobId: existing.previewJobId, fileKey: existing.fileKey };
|
||||
} else {
|
||||
this.logger.error(`创建出库导入预览记录失败:${(error as Error).message}`);
|
||||
throw new BusinessException(ErrorCode.INTERNAL_ERROR, '导入预览任务创建失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
}
|
||||
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 };
|
||||
|
||||
try {
|
||||
await this.previewQueue.add(
|
||||
'preview',
|
||||
{ jobId: created.jobId, sessionId: created.sessionId, fileKey: created.fileKey },
|
||||
{ jobId: created.jobId },
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(`出库导入预览任务暂未入队,将自动重试:${(error as Error).message}`);
|
||||
}
|
||||
return { sessionId: created.sessionId, jobId: created.jobId };
|
||||
}
|
||||
|
||||
startImport(file: Express.Multer.File, userId: number) {
|
||||
return this.startPreview(file, userId);
|
||||
}
|
||||
|
||||
async getSession(id: string, user: AuthUser) {
|
||||
private async requireSession(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) {
|
||||
@@ -173,44 +301,155 @@ export class OutboundService {
|
||||
return session;
|
||||
}
|
||||
|
||||
async getSession(id: string, user: AuthUser) {
|
||||
const session = await this.requireSession(id, user);
|
||||
return {
|
||||
id: session.id,
|
||||
status: session.status,
|
||||
fileName: session.fileName,
|
||||
requestId: session.requestId,
|
||||
previewJobId: session.previewJobId,
|
||||
importJobId: session.importJobId,
|
||||
total: session.total,
|
||||
validCount: session.validCount,
|
||||
invalidCount: session.invalidCount,
|
||||
error: session.error,
|
||||
committedAt: session.committedAt,
|
||||
expiresAt: session.expiresAt,
|
||||
createdBy: session.createdBy,
|
||||
createdAt: session.createdAt,
|
||||
updatedAt: session.updatedAt,
|
||||
};
|
||||
}
|
||||
|
||||
async getSessionByRequest(requestId: string, user: AuthUser) {
|
||||
const normalizedRequestId = requestId.trim();
|
||||
if (!/^[A-Za-z0-9_-]{16,64}$/.test(normalizedRequestId)) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入请求标识格式无效');
|
||||
}
|
||||
const session = await this.prisma.outboundImportSession.findUnique({ where: { requestId: normalizedRequestId } });
|
||||
if (!session) throw new BusinessException(ErrorCode.NOT_FOUND, '导入请求不存在', 404);
|
||||
return this.getSession(session.id, user);
|
||||
}
|
||||
|
||||
async listRows(id: string, query: QueryImportRowsDto, user: AuthUser) {
|
||||
await this.getSession(id, user);
|
||||
await this.requireSession(id, user);
|
||||
const where: Prisma.OutboundImportRowWhereInput = { sessionId: id };
|
||||
if (query.status) where.status = query.status as any;
|
||||
const orderBy = buildOrderBy(query.sortField, query.sortOrder, ['outTime', 'createdAt'] as const, { rowNo: 'asc' });
|
||||
const pageSize = Math.min(query.pageSize || 20, 200);
|
||||
const [list, total] = await this.prisma.$transaction([
|
||||
this.prisma.outboundImportRow.findMany({
|
||||
where,
|
||||
orderBy,
|
||||
skip: query.skip,
|
||||
take: query.take,
|
||||
skip: (query.page - 1) * pageSize,
|
||||
take: pageSize,
|
||||
}),
|
||||
this.prisma.outboundImportRow.count({ where }),
|
||||
]);
|
||||
return buildPage(list, total, query.page, query.pageSize);
|
||||
return buildPage(list, total, query.page, pageSize);
|
||||
}
|
||||
|
||||
async commitSession(id: string, user: AuthUser) {
|
||||
const session = await this.getSession(id, user);
|
||||
const session = await this.requireSession(id, user);
|
||||
if (session.importJobId) {
|
||||
if (session.status === 'IMPORTING') {
|
||||
await this.importQueue
|
||||
.add('import', { jobId: session.importJobId, sessionId: id }, { jobId: session.importJobId })
|
||||
.catch((error) => this.logger.warn(`出库导入任务暂未重新入队,将自动重试:${(error as Error).message}`));
|
||||
}
|
||||
return { jobId: session.importJobId, sessionId: id };
|
||||
}
|
||||
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() },
|
||||
if (session.validCount <= 0) throw new BusinessException(ErrorCode.BAD_REQUEST, '没有可导入的数据');
|
||||
const committedAt = new Date();
|
||||
const jobId = randomUUID();
|
||||
const job = await this.prisma.$transaction(async (tx) => {
|
||||
const claimed = await tx.outboundImportSession.updateMany({
|
||||
where: {
|
||||
id,
|
||||
status: 'READY',
|
||||
importJobId: null,
|
||||
invalidCount: 0,
|
||||
validCount: { gt: 0 },
|
||||
expiresAt: { gt: committedAt },
|
||||
},
|
||||
data: { status: 'IMPORTING', committedAt, importJobId: jobId },
|
||||
});
|
||||
if (claimed.count !== 1) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入会话已提交、已过期或状态已变化');
|
||||
}
|
||||
return tx.job.create({
|
||||
data: {
|
||||
id: jobId,
|
||||
type: JobType.IMPORT_OUTBOUND,
|
||||
status: JobStatus.PENDING,
|
||||
total: session.validCount,
|
||||
createdBy: user.id,
|
||||
payload: { sessionId: id },
|
||||
},
|
||||
});
|
||||
});
|
||||
// 入队失败时回退会话状态为 READY,避免卡在 IMPORTING 且无对应队列任务
|
||||
try {
|
||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id });
|
||||
await this.importQueue.add('import', { jobId: job.id, sessionId: id }, { jobId: job.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, '导入任务入队失败,请稍后重试');
|
||||
this.logger.warn(`出库导入任务暂未入队,将自动重试:${(e as Error).message}`);
|
||||
}
|
||||
return { jobId: job.id, sessionId: id };
|
||||
}
|
||||
|
||||
async downloadResult(id: string, user: AuthUser, res: Response): Promise<void> {
|
||||
const session = await this.requireSession(id, user);
|
||||
if (!session.importJobId) throw new BusinessException(ErrorCode.NOT_FOUND, '导入结果不存在', 404);
|
||||
const job = await this.prisma.job.findUnique({ where: { id: session.importJobId } });
|
||||
if (!job || job.type !== JobType.IMPORT_OUTBOUND) {
|
||||
throw new BusinessException(ErrorCode.NOT_FOUND, '导入结果不存在', 404);
|
||||
}
|
||||
if (![JobStatus.SUCCESS, JobStatus.PARTIAL, JobStatus.FAILED].includes(job.status as JobStatus)) {
|
||||
throw new BusinessException(ErrorCode.BAD_REQUEST, '导入任务尚未完成');
|
||||
}
|
||||
|
||||
const rows = await this.prisma.outboundImportRow.findMany({
|
||||
where: { sessionId: id },
|
||||
orderBy: { rowNo: 'asc' },
|
||||
});
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const worksheet = workbook.addWorksheet('导入结果');
|
||||
worksheet.columns = [
|
||||
{ header: '行号', key: 'rowNo', width: 10 },
|
||||
{ header: '追溯码', key: 'shortCode', width: 18 },
|
||||
{ header: '批次编号', key: 'batchNo', width: 22 },
|
||||
{ header: '出库时间', key: 'outTime', width: 22 },
|
||||
{ header: '原图片路径', key: 'imagePaths', width: 40 },
|
||||
{ header: '图片数量', key: 'imageCount', width: 10 },
|
||||
{ header: '备注', key: 'remark', width: 28 },
|
||||
{ header: '处理状态', key: 'status', width: 14 },
|
||||
{ header: '原因', key: 'reason', width: 40 },
|
||||
];
|
||||
worksheet.getRow(1).font = { bold: true };
|
||||
worksheet.getColumn('shortCode').numFmt = '@';
|
||||
for (const row of rows) {
|
||||
worksheet.addRow({
|
||||
rowNo: row.rowNo,
|
||||
shortCode: row.shortCode || '',
|
||||
batchNo: row.batchNo || '',
|
||||
outTime: formatChinaDate(row.outTime),
|
||||
imagePaths: jsonArray<string>(row.outImagePaths).join(';'),
|
||||
imageCount: jsonArray(row.outImagePaths).length,
|
||||
remark: row.remark || '',
|
||||
status: row.status,
|
||||
reason: row.reason || '',
|
||||
});
|
||||
}
|
||||
const buffer = Buffer.from(await workbook.xlsx.writeBuffer());
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
||||
res.setHeader('Content-Disposition', `attachment; filename="outbound-import-result-${id}.xlsx"`);
|
||||
res.setHeader('Cache-Control', 'private, no-store');
|
||||
res.end(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user