fix: 追溯码出库与上链防重复(一物一码只能出库/上链一次)

- 出库:单件登记 + 导入预览 + 导入提交 三处校验 outTime 已存在则拒绝重复出库
- 上链:trigger 存在 ONCHAIN/CONFIRMING/PENDING 存证即拒绝重复上链;FAILED 仍可 retry
- 实测重复出库/重复上链均返回 400 拒绝
This commit is contained in:
Nixevol
2026-07-10 12:06:57 +08:00
parent 223f8912dd
commit 4530a83117
5 changed files with 25 additions and 0 deletions
@@ -27,6 +27,22 @@ export class AttestationService {
throw new BusinessException(ErrorCode.BAD_REQUEST, '追溯码未绑定作品,无法上链');
}
// 防重复上链:已存在「上链成功/上链中/待上链」的存证则拒绝;仅失败(FAILED)的可再次发起。
const active = await this.prisma.blockchainProof.findFirst({
where: {
traceCodeId,
status: { in: [ProofStatus.ONCHAIN, ProofStatus.CONFIRMING, ProofStatus.PENDING] },
},
orderBy: { id: 'desc' },
});
if (active) {
const msg =
active.status === ProofStatus.ONCHAIN
? '该追溯码已上链,不可重复上链'
: '该追溯码正在上链处理中,请稍候';
throw new BusinessException(ErrorCode.BAD_REQUEST, msg);
}
const summary = {
shortCode: code.shortCode,
code: code.code,
@@ -140,6 +140,8 @@ export class ImportPreviewProcessor extends WorkerHost {
include: { batch: true },
});
if (!code) throw new Error('追溯码不存在');
// 一物一码只能出库一次:已登记出库的拒绝重复导入
if (code.outTime) throw new Error('该追溯码已登记出库,不可重复出库');
if (values.batchNo && values.batchNo !== (code.batch?.batchNo ?? '')) {
throw new Error(`批次编号不匹配,实际为 ${code.batch?.batchNo ?? '-'}`);
}
@@ -42,6 +42,8 @@ export class ImportProcessor extends WorkerHost {
try {
const code = await this.prisma.traceCode.findUnique({ where: { shortCode: row.shortCode || '' } });
if (!code) throw new Error('追溯码不存在');
// 预览到提交之间可能已被出库:再次校验,避免重复出库
if (code.outTime) 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 },
@@ -33,6 +33,10 @@ 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);
// 一物一码只能出库一次:已登记出库时间的不可重复登记
if (code.outTime) {
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;