diff --git a/firstleg/src/main/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceService.java b/firstleg/src/main/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceService.java index cec01a0a7..93daa7d93 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceService.java @@ -24,6 +24,7 @@ import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -46,7 +47,11 @@ public class CabinetLoadingEvidenceService { public EvidenceList upsert(long taskId, String key, UpsertRequest request, long operatorId, String operatorName) { Scope scope = scope(taskId, request.warehouseId(), operatorId, true); requireKey(key); - String requestHash = hash(request); + return persist(scope, taskId, key, request, hash(request), operatorId, operatorName); + } + + private EvidenceList persist(Scope scope, long taskId, String key, UpsertRequest request, + String requestHash, long operatorId, String operatorName) { CabinetLoadingEvidenceEntity replay = mapper.byOperation(taskId, key); if (replay != null) { if (!Objects.equals(requestHash, replay.getRequestHash())) throw conflict("相同幂等键的请求内容不一致"); @@ -87,12 +92,23 @@ public class CabinetLoadingEvidenceService { String evidenceType, String sealNo, String remark, MultipartFile multipart, long operatorId, String operatorName) { Scope scope = scope(taskId, warehouseId, operatorId, true); + requireKey(key); + String type = evidenceType.trim(); + if (!LoadingEvidenceType.VALUES.contains(type)) throw bad("不支持的装柜证据类型"); + String normalizedSealNo = LoadingEvidenceType.SEAL.equals(type) ? normalizedSeal(sealNo) : null; + String requestHash = hash(new UploadHashRequest(warehouseId, expectedVersion, type, + normalizedSealNo, remark, multipartHash(multipart))); + CabinetLoadingEvidenceEntity replay = mapper.byOperation(taskId, key); + if (replay != null) { + if (!Objects.equals(requestHash, replay.getRequestHash())) throw conflict("相同幂等键的请求内容不一致"); + return view(scope); + } try { - var response = files.upload(internalToken, operatorId, scope.containerBookingId(), evidenceType, multipart); + var response = files.upload(internalToken, operatorId, scope.containerBookingId(), type, multipart); var uploaded = response == null ? null : response.data(); if (uploaded == null) throw new BizException(ResultCode.SERVICE_UNAVAILABLE, "装柜证据文件上传失败"); - return upsert(taskId, key, new UpsertRequest(warehouseId, expectedVersion, evidenceType, - uploaded.fileId(), sealNo, remark), operatorId, operatorName); + return persist(scope, taskId, key, new UpsertRequest(warehouseId, expectedVersion, type, + uploaded.fileId(), normalizedSealNo, remark), requestHash, operatorId, operatorName); } catch (FeignException exception) { throw new BizException(ResultCode.SERVICE_UNAVAILABLE, "文件服务暂不可用"); } @@ -181,6 +197,15 @@ public class CabinetLoadingEvidenceService { objectMapper.writeValueAsString(value).getBytes(StandardCharsets.UTF_8))); } catch (JsonProcessingException | NoSuchAlgorithmException exception) { throw new IllegalStateException(exception); } } + private static String multipartHash(MultipartFile file) { + try { + return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(file.getBytes())); + } catch (IOException exception) { + throw bad("装柜证据文件读取失败"); + } catch (NoSuchAlgorithmException exception) { + throw new IllegalStateException(exception); + } + } private static String normalizedSeal(String value) { if (!StringUtils.hasText(value)) throw bad("铅封证据必须填写锁码"); return value.trim(); @@ -189,5 +214,7 @@ public class CabinetLoadingEvidenceService { private static BizException bad(String message) { return new BizException(ResultCode.BAD_REQUEST, message); } private static BizException conflict(String message) { return new BizException(ResultCode.CONFLICT, message); } private static String id(Long value) { return value == null ? null : value.toString(); } + private record UploadHashRequest(long warehouseId, int expectedVersion, String evidenceType, + String sealNo, String remark, String fileHash) {} private record Scope(LoadingPickTaskEntity task, long containerBookingId) {} } diff --git a/firstleg/src/test/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceServiceTest.java index 851d3db56..4b28e2219 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/loading/service/CabinetLoadingEvidenceServiceTest.java @@ -13,12 +13,17 @@ import jakarta.annotation.Resource; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.mock.web.MockMultipartFile; import org.springframework.test.context.junit.jupiter.SpringJUnitConfig; import java.util.List; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.HexFormat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -98,6 +103,38 @@ class CabinetLoadingEvidenceServiceTest { verify(mapper).insert(org.mockito.ArgumentMatchers.any(CabinetLoadingEvidenceEntity.class)); } + @Test + void multipartReplayUsesRequestAndContentHashBeforeUploadingAgain() throws Exception { + when(objectMapper.writeValueAsString(org.mockito.ArgumentMatchers.any())).thenReturn("request"); + CabinetLoadingEvidenceEntity persisted = evidence("PHOTO_STEP_1"); + persisted.setId(401L); persisted.setSourceTaskId(20L); persisted.setFileId(301L); + persisted.setOperationKey("photo-replay"); + persisted.setRequestHash(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256") + .digest("request".getBytes(StandardCharsets.UTF_8)))); + persisted.setVersion(0); + when(mapper.byOperation(20L, "photo-replay")).thenReturn(null, null, persisted); + when(mapper.byContainer(99L)).thenReturn(List.of(persisted)); + var upload = new LoadingEvidenceFileClient.UploadResult(301L, "PLATFORM", 0L, + "LOADING_PHOTO_STEP_1", "99", "photo.png", "image/png", 5L); + when(files.upload(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq(99L), org.mockito.ArgumentMatchers.eq("PHOTO_STEP_1"), + org.mockito.ArgumentMatchers.any())).thenReturn(com.baiyue.common.core.api.ApiResponse.success(upload)); + var metadata = new LoadingEvidenceFileClient.FileMetadata(301L, "PLATFORM", 0L, + "LOADING_PHOTO_STEP_1", "99", "photo.png", "image/png"); + when(files.validate(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(99L), + org.mockito.ArgumentMatchers.eq("PHOTO_STEP_1"), org.mockito.ArgumentMatchers.eq(301L))) + .thenReturn(com.baiyue.common.core.api.ApiResponse.success(metadata)); + var file = new MockMultipartFile("file", "photo.png", "image/png", "photo".getBytes(StandardCharsets.UTF_8)); + + service.upload(20L, 8L, "photo-replay", 0, "PHOTO_STEP_1", null, "remark", file, 9L, "operator"); + service.upload(20L, 8L, "photo-replay", 0, "PHOTO_STEP_1", null, "remark", file, 9L, "operator"); + + verify(files, times(1)).upload(org.mockito.ArgumentMatchers.anyString(), org.mockito.ArgumentMatchers.eq(9L), + org.mockito.ArgumentMatchers.eq(99L), org.mockito.ArgumentMatchers.eq("PHOTO_STEP_1"), + org.mockito.ArgumentMatchers.any()); + verify(mapper, times(1)).insert(org.mockito.ArgumentMatchers.any(CabinetLoadingEvidenceEntity.class)); + } + private static CabinetLoadingEvidenceEntity evidence(String type) { CabinetLoadingEvidenceEntity value = new CabinetLoadingEvidenceEntity(); value.setEvidenceType(type); value.setStatus("ACTIVE"); value.setContainerBookingId(99L); diff --git a/scripts/admin-test-env-modules/phase3-loading-finalize.mjs b/scripts/admin-test-env-modules/phase3-loading-finalize.mjs index 03f7baca0..00128dc99 100644 --- a/scripts/admin-test-env-modules/phase3-loading-finalize.mjs +++ b/scripts/admin-test-env-modules/phase3-loading-finalize.mjs @@ -99,6 +99,21 @@ async function waitForCompletion(context, taskDetailPath, operationsPath, attemp return { taskResponse, task, operationsResponse, operations, attempts } } +async function waitForEvidenceSnapshot(context, evidencePath, expectedTypes, attempts = 30) { + let response = null + for (let attempt = 1; attempt <= attempts; attempt += 1) { + response = await context.request('GET', evidencePath) + const evidences = response?.http === 200 && String(response?.body?.code) === '200' + ? response.body.data?.evidences : null + if (Array.isArray(evidences) && expectedTypes.every((type) => + evidences.some((item) => item?.evidenceType === type && item?.status !== 'VOID'))) { + return { response, attempts: attempt } + } + if (attempt < attempts) await new Promise((resolve) => setTimeout(resolve, 1_000)) + } + return { response, attempts } +} + export async function run(context) { const fixture = context.createdResources?.phase3Loading const tenantId = id(fixture?.tenantId); const inboundId = id(fixture?.inboundId) @@ -302,12 +317,14 @@ export async function run(context) { `orderId=${orderId}, found=${Boolean(unifiedRow)}, mainStatus=${unifiedRow?.mainStatus || 'missing'}`, OPTIONS) const evidencePath = `${base}/loading/evidence?tenantId=${encodeURIComponent(tenantId)}` - const immutableEvidenceResponse = await context.request('GET', evidencePath) + const immutableEvidenceResult = await waitForEvidenceSnapshot( + context, evidencePath, fixture.evidenceTypes || []) + const immutableEvidenceResponse = immutableEvidenceResult.response const immutableEvidence = context.apiSuccess(MODULE, '读取 LOADED 后不可变证据快照', immutableEvidenceResponse, '', OPTIONS) context.assert(MODULE, '统一硬门禁通过后五类有效证据仍完整', immutableEvidenceResponse, fixture.evidenceTypes?.every?.((type) => immutableEvidence?.evidences?.some?.((item) => item.evidenceType === type && item.status !== 'VOID')), - `evidences=${immutableEvidence?.evidences?.length ?? 'missing'}`, OPTIONS) + `evidences=${immutableEvidence?.evidences?.length ?? 'missing'}, attempts=${immutableEvidenceResult.attempts}`, OPTIONS) const immutablePlanResponse = await context.request('GET', planPath) const immutablePlan = context.apiSuccess(MODULE, '读取 LOADED 后装柜计划快照', immutablePlanResponse, '', OPTIONS) const finalVersion = Number(finalData?.summary?.version)