feat: 完成 PRD 差距与修复,新增审核流与日志清理功能,支持出库信息与动态字段,优化 C 端用户体验
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
import { ApiPropertyOptional } from '@nestjs/swagger';
|
||||
import { IsDateString, IsOptional, IsString, MaxLength } from 'class-validator';
|
||||
import { Type } from 'class-transformer';
|
||||
import { IsDateString, IsInt, IsOptional, IsString, MaxLength, Min } from 'class-validator';
|
||||
|
||||
export class OutboundDto {
|
||||
@ApiPropertyOptional({ description: 'SKU' })
|
||||
@@ -24,6 +25,24 @@ export class OutboundDto {
|
||||
@IsString()
|
||||
outImageKey?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '上链哈希值(填写则记录上链结果)' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(255)
|
||||
txHash?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '上链时间' })
|
||||
@IsOptional()
|
||||
@IsDateString()
|
||||
onchainAt?: string;
|
||||
|
||||
@ApiPropertyOptional({ description: '区块高度' })
|
||||
@IsOptional()
|
||||
@Type(() => Number)
|
||||
@IsInt()
|
||||
@Min(0)
|
||||
blockHeight?: number;
|
||||
|
||||
@ApiPropertyOptional({ description: '备注' })
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
|
||||
@@ -1,12 +1,34 @@
|
||||
import { Processor, WorkerHost } from '@nestjs/bullmq';
|
||||
import { Logger } from '@nestjs/common';
|
||||
import { Job } from 'bullmq';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import { JobStatus, OUTBOUND_IMPORT_COLUMNS, 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;
|
||||
@@ -55,8 +77,7 @@ export class ImportProcessor extends WorkerHost {
|
||||
const values: Record<string, string> = {};
|
||||
let empty = true;
|
||||
colToKey.forEach((key, col) => {
|
||||
const v = row.getCell(col).value;
|
||||
const text = v === null || v === undefined ? '' : String(v).trim();
|
||||
const text = cellToString(row.getCell(col).value);
|
||||
if (text) empty = false;
|
||||
values[key] = text;
|
||||
});
|
||||
@@ -74,22 +95,76 @@ export class ImportProcessor extends WorkerHost {
|
||||
fail++;
|
||||
continue;
|
||||
}
|
||||
const code = await this.prisma.traceCode.findUnique({ where: { shortCode } });
|
||||
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: {
|
||||
sku: row.values.sku || undefined,
|
||||
archiveNo: row.values.archiveNo || undefined,
|
||||
outTime: row.values.outTime ? new Date(row.values.outTime) : undefined,
|
||||
outTime: outTime ?? undefined,
|
||||
outImage: row.values.outImage || undefined,
|
||||
remark: row.values.remark || undefined,
|
||||
},
|
||||
});
|
||||
// 录入上链哈希则登记一条已上链存证(同码同哈希去重,避免重复导入污染)
|
||||
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.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) {
|
||||
|
||||
@@ -2,14 +2,27 @@ import { Injectable } from '@nestjs/common';
|
||||
import { InjectQueue } from '@nestjs/bullmq';
|
||||
import { Queue } from 'bullmq';
|
||||
import { Response } from 'express';
|
||||
import { createHash } from 'crypto';
|
||||
import * as ExcelJS from 'exceljs';
|
||||
import { ErrorCode, JobType, OUTBOUND_IMPORT_COLUMNS, QUEUE_NAMES } from '@artveris/shared';
|
||||
import {
|
||||
ErrorCode,
|
||||
JobType,
|
||||
OUTBOUND_IMPORT_COLUMNS,
|
||||
ProofStatus,
|
||||
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 { OutboundDto } from './dto/outbound.dto';
|
||||
|
||||
const XLSX_MIME_TYPES = [
|
||||
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
||||
'application/vnd.ms-excel',
|
||||
'application/octet-stream', // 某些浏览器对 .xlsx 的兜底类型
|
||||
];
|
||||
|
||||
@Injectable()
|
||||
export class OutboundService {
|
||||
constructor(
|
||||
@@ -22,7 +35,7 @@ export class OutboundService {
|
||||
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);
|
||||
return this.prisma.traceCode.update({
|
||||
const updated = await this.prisma.traceCode.update({
|
||||
where: { id: traceCodeId },
|
||||
data: {
|
||||
sku: dto.sku,
|
||||
@@ -32,6 +45,42 @@ export class OutboundService {
|
||||
remark: dto.remark,
|
||||
},
|
||||
});
|
||||
// 录入了上链哈希则记录一条已上链存证(手工登记,不触发 Mock 链)
|
||||
if (dto.txHash) {
|
||||
await this.recordProof(traceCodeId, code.code, {
|
||||
txHash: dto.txHash,
|
||||
onchainAt: dto.onchainAt ? new Date(dto.onchainAt) : new Date(),
|
||||
blockHeight: dto.blockHeight,
|
||||
});
|
||||
}
|
||||
return updated;
|
||||
}
|
||||
|
||||
// 手工登记上链结果:写入一条 ONCHAIN 存证(数据哈希由 code+txHash 派生)
|
||||
// 同码同哈希去重:重复保存不会产生多条存证
|
||||
private async recordProof(
|
||||
traceCodeId: bigint,
|
||||
code: string,
|
||||
p: { txHash: string; onchainAt: Date; blockHeight?: number },
|
||||
) {
|
||||
const dup = await this.prisma.blockchainProof.findFirst({
|
||||
where: { traceCodeId, txHash: p.txHash },
|
||||
});
|
||||
if (dup) return;
|
||||
const dataHash =
|
||||
'0x' + createHash('sha256').update(`${code}:${p.txHash}`).digest('hex');
|
||||
await this.prisma.blockchainProof.create({
|
||||
data: {
|
||||
traceCodeId,
|
||||
dataHash,
|
||||
txHash: p.txHash,
|
||||
blockHeight: p.blockHeight !== undefined ? BigInt(p.blockHeight) : null,
|
||||
chainName: '手工登记',
|
||||
onchainAt: p.onchainAt,
|
||||
status: ProofStatus.ONCHAIN,
|
||||
rawResponse: { source: 'manual' },
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async generateTemplate(res: Response): Promise<void> {
|
||||
@@ -65,6 +114,11 @@ export class OutboundService {
|
||||
|
||||
async startImport(file: Express.Multer.File, userId: number) {
|
||||
if (!file) throw new BusinessException(ErrorCode.BAD_REQUEST, '请上传导入文件');
|
||||
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)文件导入');
|
||||
}
|
||||
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 });
|
||||
|
||||
Reference in New Issue
Block a user