This commit is contained in:
2026-08-08 12:01:45 +08:00
parent 1a2f598c9a
commit a35cd868b9
56 changed files with 7178 additions and 735 deletions
@@ -76,13 +76,21 @@ class LoadingListControllerContractTest {
.getContentAsString(StandardCharsets.UTF_8);
Map<String, Object> document = stringMap(new Yaml().load(yaml));
assertThat(document.get("openapi")).isEqualTo("3.0.3");
assertThat((Map<?, ?>) document.get("paths")).hasSize(6);
Map<String, Object> paths = stringMap(document.get("paths"));
assertThat(paths).containsOnlyKeys(
"/api/platform/v1/first-leg/loading-plans",
"/api/platform/v1/first-leg/loading-plans/{planId}",
"/api/platform/v1/first-leg/loading-plans/{planId}/transport",
"/api/platform/v1/first-leg/loading-lists",
"/api/platform/v1/first-leg/loading-lists/{planId}");
Map<String, Object> components = stringMap(document.get("components"));
Map<String, Object> schemas = stringMap(components.get("schemas"));
assertThat(schemas).containsKeys(
"LongId", "PreloadPage", "ConfirmedPage", "Customer", "PreloadSummary",
"ConfirmedSummary", "LoadingItem", "OperationHistory", "PreloadDetail",
"ConfirmedDetail", "TransportUpdateRequest", "AdvanceRequest");
"ConfirmedDetail", "TransportUpdateRequest");
assertThat(paths)
.doesNotContainKey("/api/platform/v1/first-leg/loading-plans/{planId}/complete");
assertThat(stringMap(schemas.get("LongId"))).containsEntry("type", "string");
assertThat(properties(schemas, "PreloadPage")).containsKeys("records", "page", "size", "total", "pages");
assertThat(properties(schemas, "PreloadSummary")).containsKeys("planId", "customers", "skuCount");
@@ -0,0 +1,64 @@
package com.baiyue.firstleg.loading.controller;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.firstleg.loading.dto.LoadingRequests.CompleteDeliveryRequest;
import com.baiyue.firstleg.loading.dto.LoadingRequests.CompleteLoadingRequest;
import com.baiyue.firstleg.loading.dto.LoadingRequests.PickingRequest;
import com.baiyue.firstleg.loading.dto.LoadingRequests.UpsertEvidenceRequest;
import org.junit.jupiter.api.Test;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.lang.reflect.Method;
import static org.assertj.core.api.Assertions.assertThat;
class PlatformLoadingDeliveryControllerContractTest {
@Test
void keepsInboundScopedPathsAndPermissions() throws Exception {
assertThat(PlatformLoadingDeliveryController.class.getAnnotation(RequestMapping.class).value())
.containsExactly("/api/platform/v1/inbounds");
post("evidence", "/{inboundId}/loading/evidence",
"platform:firstleg:inbound:loading:edit", UpsertEvidenceRequest.class);
get("evidence", "/{inboundId}/loading/evidence",
"platform:firstleg:inbound:loading:view");
post("completeLoading", "/{inboundId}/loading/complete",
"platform:firstleg:inbound:loading:complete", CompleteLoadingRequest.class);
post("completeDelivery", "/{inboundId}/delivery/complete",
"platform:firstleg:inbound:delivery:complete", CompleteDeliveryRequest.class);
post("startPicking", "/{inboundId}/loading/picking/start",
"platform:firstleg:inbound:picking:edit", PickingRequest.class);
post("completePicking", "/{inboundId}/loading/picking/complete",
"platform:firstleg:inbound:picking:edit", PickingRequest.class);
get("picking", "/{inboundId}/loading/picking",
"platform:firstleg:inbound:picking:view");
}
private static void post(String name, String path, String authority, Class<?> requestType) throws Exception {
Method method = PlatformLoadingDeliveryController.class.getDeclaredMethod(name,
AuthenticatedUser.class, long.class, long.class, String.class, requestType);
assertThat(method.getAnnotation(PostMapping.class).value()).containsExactly(path);
assertAuthority(method, authority);
assertThat(method.getParameters()[1].getAnnotation(RequestParam.class)).isNotNull();
assertThat(method.getParameters()[3].getAnnotation(RequestHeader.class).value())
.isEqualTo("Idempotency-Key");
}
private static void get(String name, String path, String authority) throws Exception {
Method method = PlatformLoadingDeliveryController.class.getDeclaredMethod(name,
AuthenticatedUser.class, long.class, long.class);
assertThat(method.getAnnotation(GetMapping.class).value()).containsExactly(path);
assertAuthority(method, authority);
assertThat(method.getParameters()[1].getAnnotation(RequestParam.class)).isNotNull();
}
private static void assertAuthority(Method method, String authority) {
assertThat(method.getAnnotation(PreAuthorize.class).value())
.isEqualTo("hasAuthority('" + authority + "')");
}
}
@@ -11,14 +11,21 @@ import static org.assertj.core.api.Assertions.assertThat;
class InboundStatusUnificationSqlContractTest {
@Test
void syncsStatusUnificationMigrationToUnifiedDeploymentScript() throws Exception {
void preservesWaitSplitWithoutDataRewrite() throws Exception {
String module = normalize(new ClassPathResource("db/phase3-inbounded-status-unification.sql")
.getContentAsString(StandardCharsets.UTF_8)).trim();
String unified = normalize(Files.readString(unifiedPath(), StandardCharsets.UTF_8));
assertThat(module)
.contains("CREATE PROCEDURE assert_wait_split_compatibility()")
.contains("WAIT_SPLIT 是二期当前有效终点")
.doesNotContain("UPDATE fl_inbound_order")
.doesNotContain("UPDATE fl_inbound_status_history");
assertThat(unified)
.contains("-- 来源:firstleg/src/main/resources/db/phase3-inbounded-status-unification.sql")
.contains(module);
.contains("WAIT_SPLIT 是二期当前有效终点;统一迁移不得改写主表或历史状态")
.doesNotContain("SET process_status = 'INBOUNDED'")
.doesNotContain("SET from_status = 'INBOUNDED'")
.doesNotContain("SET to_status = 'INBOUNDED'");
}
private static Path unifiedPath() {
@@ -0,0 +1,34 @@
package com.baiyue.firstleg.repository;
import org.junit.jupiter.api.Test;
import org.springframework.core.io.ClassPathResource;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.assertj.core.api.Assertions.assertThat;
class MojiaMeasurementReceiptSqlContractTest {
@Test
void schemaAndUnifiedMigrationKeepUnmatchedMeasurementsWithImageReferences() throws Exception {
String schema = new ClassPathResource("db/phase2-inbound-schema.sql")
.getContentAsString(StandardCharsets.UTF_8);
String unified = Files.readString(
Path.of("..", "deploy", "sql", "头程数据库统一增量-MySQL8.sql"),
StandardCharsets.UTF_8);
for (String sql : new String[]{schema, unified}) {
assertThat(sql)
.contains("CREATE TABLE IF NOT EXISTS fl_mojia_measurement_receipt")
.contains("box_code VARCHAR(128) NOT NULL")
.contains("image_file_id BIGINT UNSIGNED NOT NULL")
.contains("status VARCHAR(24) NOT NULL DEFAULT 'UNMATCHED'")
.contains("idx_mojia_receipt_status_time")
.doesNotContain("picture_base64");
}
assertThat(unified)
.contains("墨家未匹配测量收件箱字段未完整创建")
.contains("测量计算规则版本字段长度不是64");
}
}
@@ -91,7 +91,11 @@ class SmartLoadingSqlContractTest {
void shouldAssertCompletePermissionGrants() throws Exception {
assertPermissionContract(migration());
assertPermissionContract(unifiedMigration());
assertThat(unifiedMigration()).contains(migration().trim());
assertThat(unifiedMigration())
.contains("CALL migrate_legacy_loading_pick_task()")
.contains("CREATE TABLE IF NOT EXISTS fl_inbound_loading_pick_task")
.contains("5102121, 0, 'PLATFORM'")
.contains("5102129, 0, 'PLATFORM'");
}
@Test
@@ -126,6 +130,8 @@ class SmartLoadingSqlContractTest {
void shouldProvidePdaContract() throws Exception {
assertThat(migration())
.contains("CREATE TABLE IF NOT EXISTS fl_loading_pick_task")
.contains("CALL migrate_legacy_loading_pick_task()")
.contains("RENAME TABLE fl_loading_pick_task TO fl_inbound_loading_pick_task")
.contains("CREATE TABLE IF NOT EXISTS fl_loading_pick_item")
.contains("CREATE TABLE IF NOT EXISTS fl_loading_pick_history")
.contains("UNIQUE KEY uk_loading_pick_task_plan (loading_plan_id)")
@@ -142,6 +148,38 @@ class SmartLoadingSqlContractTest {
.contains(")) <> 16 THEN");
}
@Test
@DisplayName("统一脚本只定义并调用一次智能装柜断言")
void shouldDefineSmartLoadingAssertionOnce() throws Exception {
String unified = unifiedMigration();
assertThat(count(unified, "CREATE PROCEDURE assert_phase3_smart_loading_schema()"))
.isEqualTo(1);
assertThat(count(unified, "CALL assert_phase3_smart_loading_schema();"))
.isEqualTo(1);
assertThat(count(unified, "SELECT 'PASS' AS migration_status"))
.isEqualTo(1);
}
@Test
@DisplayName("详细拣货和入库汇总拣货使用独立完整表型")
void shouldKeepDetailedAndInboundPickTaskShapesSeparate() throws Exception {
String unified = unifiedMigration();
assertThat(unified)
.contains("CREATE TABLE IF NOT EXISTS fl_loading_pick_task (")
.contains("loading_plan_id BIGINT UNSIGNED NOT NULL")
.contains("container_no VARCHAR(64) NOT NULL")
.contains("task_status VARCHAR(16) NOT NULL DEFAULT 'LOADING'")
.contains("UNIQUE KEY uk_loading_pick_task_plan (loading_plan_id)")
.contains("KEY idx_loading_pick_container (container_no, task_status, started_at)")
.contains("CREATE TABLE IF NOT EXISTS fl_inbound_loading_pick_task (")
.contains("tenant_id BIGINT UNSIGNED NOT NULL")
.contains("inbound_id BIGINT UNSIGNED NOT NULL")
.contains("expected_count INT UNSIGNED NULL")
.contains("picked_count INT UNSIGNED NULL")
.contains("UNIQUE KEY uk_loading_pick_tenant_inbound (tenant_id, inbound_id)")
.contains("KEY idx_loading_pick_status (tenant_id, status, updated_at)");
}
private static String migration() throws Exception {
return new ClassPathResource("db/phase3-smart-loading-schema.sql")
.getContentAsString(StandardCharsets.UTF_8);
@@ -174,4 +212,8 @@ class SmartLoadingSqlContractTest {
Matcher matcher = PERMISSION_PATTERN.matcher(sql);
return matcher.results().map(result -> result.group(1)).collect(Collectors.toSet());
}
private static int count(String value, String token) {
return (value.length() - value.replace(token, "").length()) / token.length();
}
}
@@ -56,7 +56,7 @@ class CustomerDimensionWeightingServiceTest {
}
@Test
void dimensionsBeyondTheLargestRuleAreRecordedUsingActualDimensions() {
void dimensionsOutsideConfiguredWeightingRulesUseActualDimensions() {
var weighted = service.load(10001L).resolve(
new BigDecimal("60.001"), new BigDecimal("50"), new BigDecimal("50"));
@@ -64,8 +64,7 @@ class CustomerDimensionWeightingServiceTest {
assertThat(weighted.outerLengthCm()).isEqualByComparingTo("60.001");
assertThat(weighted.outerWidthCm()).isEqualByComparingTo("50");
assertThat(weighted.outerHeightCm()).isEqualByComparingTo("50");
assertThat(weighted.calculationRuleVersion()).isEqualTo("ACTUAL_DIMENSION_OVERSIZE_V1");
assertThat(weighted.warning()).contains("已按实测尺寸记录").contains("人工复核");
assertThat(weighted.calculationRuleVersion()).isEqualTo("ACTUAL_DIMENSION_V1");
}
@Test
@@ -1,7 +1,14 @@
package com.baiyue.firstleg.service;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.core.api.ResultCode;
import com.baiyue.common.core.exception.BizException;
import com.baiyue.firstleg.client.MeasurementImageClient;
import com.baiyue.firstleg.dto.CartonMeasurementCommand;
import com.baiyue.firstleg.dto.CartonMeasurementResult;
import com.baiyue.firstleg.dto.MojiaMeasurementDtos.UploadResponse;
import com.baiyue.firstleg.entity.MojiaMeasurementReceiptEntity;
import com.baiyue.firstleg.repository.MojiaMeasurementReceiptRepository;
import com.baiyue.firstleg.security.AuthenticatedMeasurementApp;
import com.baiyue.firstleg.security.MeasurementRequestAuthenticator;
import com.baiyue.firstleg.security.MeasurementRequestHeaders;
@@ -9,6 +16,7 @@ import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.Validation;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.springframework.test.util.ReflectionTestUtils;
import java.math.BigDecimal;
import java.time.LocalDateTime;
@@ -26,8 +34,11 @@ class MojiaMeasurementOpenApiServiceTest {
void fixedAppKeyJsonIsConvertedToTheExistingCartonMeasurementFlow() throws Exception {
MeasurementRequestAuthenticator authenticator = mock(MeasurementRequestAuthenticator.class);
CartonMeasurementService cartons = mock(CartonMeasurementService.class);
MeasurementImageClient images = mock(MeasurementImageClient.class);
MojiaMeasurementReceiptRepository receipts = mock(MojiaMeasurementReceiptRepository.class);
var service = new MojiaMeasurementOpenApiService(authenticator, cartons,
new ObjectMapper().findAndRegisterModules(), Validation.buildDefaultValidatorFactory().getValidator());
new ObjectMapper().findAndRegisterModules(), Validation.buildDefaultValidatorFactory().getValidator(),
images, receipts);
MeasurementRequestHeaders headers = new MeasurementRequestHeaders("mojia", null, null, null, null);
when(authenticator.authenticate("POST", MojiaMeasurementOpenApiService.CALLBACK_PATH,
headers, json(), false)).thenReturn(new AuthenticatedMeasurementApp("mojia", 10001L, 90001L, Map.of()));
@@ -35,8 +46,9 @@ class MojiaMeasurementOpenApiServiceTest {
1L, 1, 2L, "RK-001#4-1", 1, new BigDecimal("60.1"), new BigDecimal("40.2"),
new BigDecimal("30.3"), new BigDecimal("12.5"), 3L, "MJ-01", LocalDateTime.now(), true));
CartonMeasurementResult result = service.receive(headers, json());
UploadResponse result = service.receive(headers, json());
assertThat(result.matched()).isTrue();
assertThat(result.boxCode()).isEqualTo("RK-001#4-1");
ArgumentCaptor<CartonMeasurementCommand> command = ArgumentCaptor.forClass(CartonMeasurementCommand.class);
verify(cartons).upsert(eq(10001L), eq(90001L), command.capture());
@@ -46,6 +58,40 @@ class MojiaMeasurementOpenApiServiceTest {
assertThat(command.getValue().image().getBytes()).containsExactly(0xff, 0xd8, 0xff, 0xd9);
}
@Test
void unmatchedSimulationIsAcceptedWithFieldsAndImageSavedForInvestigation() {
MeasurementRequestAuthenticator authenticator = mock(MeasurementRequestAuthenticator.class);
CartonMeasurementService cartons = mock(CartonMeasurementService.class);
MeasurementImageClient images = mock(MeasurementImageClient.class);
MojiaMeasurementReceiptRepository receipts = mock(MojiaMeasurementReceiptRepository.class);
var service = new MojiaMeasurementOpenApiService(authenticator, cartons,
new ObjectMapper().findAndRegisterModules(), Validation.buildDefaultValidatorFactory().getValidator(),
images, receipts);
ReflectionTestUtils.setField(service, "internalToken", "internal-token");
MeasurementRequestHeaders headers = new MeasurementRequestHeaders("mojia", null, null, null, null);
when(authenticator.authenticate("POST", MojiaMeasurementOpenApiService.CALLBACK_PATH,
headers, json(), false)).thenReturn(new AuthenticatedMeasurementApp("mojia", 10001L, 90001L, Map.of()));
when(cartons.upsert(eq(10001L), eq(90001L), any()))
.thenThrow(new BizException(ResultCode.NOT_FOUND, "箱号不存在或不属于当前客户"));
when(images.uploadReceipt(eq("internal-token"), eq(90001L), eq(10001L), any(Long.TYPE), any()))
.thenReturn(ApiResponse.success(new MeasurementImageClient.UploadResult(
3L, "mojia.jpg", "image/jpeg", 4L, "NOT_REQUIRED", null, null, null, null)));
UploadResponse result = service.receive(headers, json());
assertThat(result.accepted()).isTrue();
assertThat(result.matched()).isFalse();
assertThat(result.receiptId()).isNotNull();
assertThat(result.imageFileId()).isEqualTo(3L);
ArgumentCaptor<MojiaMeasurementReceiptEntity> receipt =
ArgumentCaptor.forClass(MojiaMeasurementReceiptEntity.class);
verify(receipts).insert(receipt.capture());
assertThat(receipt.getValue().getBoxCode()).isEqualTo("RK-001#4-1");
assertThat(receipt.getValue().getLengthCm()).isEqualByComparingTo("60.1");
assertThat(receipt.getValue().getImageFileId()).isEqualTo(3L);
assertThat(receipt.getValue().getStatus()).isEqualTo("UNMATCHED");
}
private String json() {
return """
{"boxCode":"RK-001#4-1","length":60.1,"width":40.2,"height":30.3,
@@ -17,7 +17,7 @@ class UnifiedInboundQueryServiceTest {
assertThat(UnifiedInboundQueryService.mainStatus("WAIT_PRICING")).isEqualTo("INBOUNDED");
assertThat(UnifiedInboundQueryService.mainStatus("FEE_CONFIRMING")).isEqualTo("INBOUNDED");
assertThat(UnifiedInboundQueryService.mainStatus("INBOUNDING")).isEqualTo("INBOUNDED");
assertThat(UnifiedInboundQueryService.mainStatus("WAIT_SPLIT")).isEqualTo("INBOUNDED");
assertThat(UnifiedInboundQueryService.mainStatus("WAIT_SPLIT")).isEqualTo("WAIT_SPLIT");
assertThat(UnifiedInboundQueryService.mainStatus("INBOUNDED")).isEqualTo("INBOUNDED");
assertThat(UnifiedInboundQueryService.mainStatus("LOADING")).isEqualTo("LOADING");
assertThat(UnifiedInboundQueryService.mainStatus("LOADED")).isEqualTo("LOADED");
@@ -37,12 +37,34 @@ class UnifiedInboundQueryServiceTest {
assertThat(UnifiedInboundQueryService.nextAction("INBOUNDED", "INBOUNDING", null)).isNull();
assertThat(UnifiedInboundQueryService.nextAction("INBOUNDED", "INBOUNDED", "CONFIRMED")).isNull();
assertThat(UnifiedInboundQueryService.nextAction("INBOUNDED", "WAIT_SPLIT", null))
.isEqualTo("SMART_SPLIT");
.isNull();
assertThat(UnifiedInboundQueryService.nextAction("WAIT_SPLIT", "WAIT_SPLIT", null)).isNull();
assertThat(UnifiedInboundQueryService.nextAction("LOADED", "LOADED", null))
.isEqualTo("COMPLETE_DELIVERY");
assertThat(UnifiedInboundQueryService.nextAction("DELIVERED", "DELIVERED", null)).isNull();
}
@Test
void waitSplitFilterRemainsSeparateFromInbounded() throws Exception {
var method = UnifiedInboundQueryService.class.getDeclaredMethod("internalStatuses", String.class);
method.setAccessible(true);
assertThat(method.invoke(new UnifiedInboundQueryService(), "WAIT_SPLIT"))
.isEqualTo(java.util.List.of("WAIT_SPLIT"));
assertThat(method.invoke(new UnifiedInboundQueryService(), "INBOUNDED"))
.isEqualTo(java.util.List.of("WAIT_PRICING", "FEE_CONFIRMING", "INBOUNDING", "INBOUNDED"));
}
@Test
void phaseTwoMeasurementStatusesDoNotRequireUndeployedPhaseThreeTables() {
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("WAIT_MEASURE")).isFalse();
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("INBOUNDED")).isFalse();
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("WAIT_SPLIT")).isFalse();
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("LOADING")).isTrue();
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("LOADED")).isTrue();
assertThat(UnifiedInboundQueryService.requiresPhaseThreeSummary("DELIVERED")).isTrue();
}
@Test
void rejectsUnknownReviewStatusBeforeRepositoryQuery() {
UnifiedInboundQuery query = new UnifiedInboundQuery(