From bfb139c7c7bcd895c0a0746eb393d51b53b847fe Mon Sep 17 00:00:00 2001 From: liuyihe <2513762445@qq.com> Date: Thu, 3 Sep 2026 21:33:23 +0800 Subject: [PATCH 01/10] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../service/CustomerDimensionWeightingService.java | 2 +- .../firstleg/service/InboundMeasurementService.java | 3 ++- .../firstleg/service/MeasurementBatchService.java | 11 ++++------- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/CustomerDimensionWeightingService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/CustomerDimensionWeightingService.java index 637dd601b..a4c1c73ce 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/CustomerDimensionWeightingService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/CustomerDimensionWeightingService.java @@ -72,7 +72,7 @@ public class CustomerDimensionWeightingService { return rules.stream() .filter(rule -> rule.contains(measured)) .findFirst() - .map(Rule::weighted) + .map(rule -> rule.weightedActualDimensions(lengthCm, widthCm, heightCm)) .orElseGet(() -> actualDimensions(lengthCm, widthCm, heightCm)); } diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/InboundMeasurementService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/InboundMeasurementService.java index 72772cbea..4b08e8a64 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/InboundMeasurementService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/InboundMeasurementService.java @@ -108,7 +108,8 @@ public class InboundMeasurementService { request.items().stream().map(InboundMeasurementRequests.ItemRequest::chargeRuleId) .filter(java.util.Objects::nonNull).distinct().forEach(ruleId -> { var rule = fbaMasterDataService.rule(tenantId, ruleId); - if (!"ACTIVE".equals(rule.getStatus()) || !java.util.Objects.equals(rule.getCustomerId(), inbound.getCustomerId())) { + long inboundCustomerId = inbound.getCustomerId() == null ? tenantId : inbound.getCustomerId(); + if (!"ACTIVE".equals(rule.getStatus()) || !java.util.Objects.equals(rule.getCustomerId(), inboundCustomerId)) { throw new BizException(ResultCode.VALIDATION_FAILED, "测量明细绑定的计费规则不属于当前客户或已停用"); } }); diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/MeasurementBatchService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/MeasurementBatchService.java index ee8bb0032..5cc581196 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/MeasurementBatchService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/MeasurementBatchService.java @@ -263,16 +263,13 @@ public class MeasurementBatchService { } private CustomerChargeRuleEntity requireCoefficientRule(long tenantId, Long customerId, Long ruleId) { - if (customerId == null || customerId <= 0) { - if (ruleId == null) return null; - throw new BizException(ResultCode.VALIDATION_FAILED, "入库单客户无效,不能应用计费系数"); - } + Long effectiveCustomerId = customerId == null || customerId <= 0 ? tenantId : customerId; CustomerChargeRuleEntity rule = ruleId == null - ? pricingRepository.findDefaultRule(tenantId, customerId) + ? pricingRepository.findDefaultRule(tenantId, effectiveCustomerId) : pricingRepository.findRule(tenantId, ruleId); if (rule == null || !"ACTIVE".equals(rule.getStatus()) - || !Boolean.TRUE.equals(rule.getDefaultRule()) || !customerId.equals(rule.getCustomerId())) { - throw new BizException(ResultCode.VALIDATION_FAILED, "计费规则不属于当前客户、未启用或未设置默认规则"); + || !effectiveCustomerId.equals(rule.getCustomerId())) { + throw new BizException(ResultCode.VALIDATION_FAILED, "计费规则不属于当前客户或已停用"); } return rule; } From a5aecf6171b5a37895b82b3e3dea6c80505b5add Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Thu, 3 Sep 2026 21:34:27 +0800 Subject: [PATCH 02/10] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baiyue/firstleg/dto/SmartLoadingDtos.java | 10 +- .../mapper/SmartLoadingCandidateMapper.java | 147 ++++++++----- .../repository/SmartLoadingRepository.java | 6 +- .../firstleg/service/SmartLoadingService.java | 205 ++++++++++++++++-- 4 files changed, 286 insertions(+), 82 deletions(-) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java b/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java index 2be703b5d..920750aed 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java @@ -7,10 +7,13 @@ public final class SmartLoadingDtos { private SmartLoadingDtos(){} public record InboundCandidateQuery( @NotEmpty @Size(max=9) List<@NotBlank String> channelGroupCodes, @Positive Long warehouseId, @Positive Long customerId, @Size(max=40) String inboundCode, - LocalDate createdStart, LocalDate createdEnd, CandidateOrderStatus orderStatus, + LocalDate createdStart, LocalDate createdEnd, + @Size(max=4) List<@NotNull CandidateOrderStatus> orderStatuses, @Min(1) long page, @Min(1) @Max(200) long size) { public InboundCandidateQuery { channelGroupCodes = channelGroupCodes == null ? List.of() : List.copyOf(channelGroupCodes); + orderStatuses = orderStatuses == null ? List.of() + : List.copyOf(new java.util.LinkedHashSet<>(orderStatuses)); if (page == 0) page = 1; if (size == 0) size = 20; } @@ -24,7 +27,8 @@ public final class SmartLoadingDtos { private SmartLoadingDtos(){} Integer availablePackageCount, BigDecimal unitGrossWeightKg, BigDecimal unitNetWeightKg, BigDecimal averageUnitVolumeCbm, BigDecimal availableVolumeCbm, Long coLoadGroupId, String groupNo, Integer memberCount, Integer groupTotalBoxes, - Boolean locked, String blockReason, String orderStatusSnapshot, LocalDateTime expectedArrivalAt, + Boolean locked, Boolean canAssign, String blockReason, + String orderStatusSnapshot, LocalDateTime expectedArrivalAt, List groupMembers) { public InboundCandidate { groupMembers = groupMembers == null ? List.of() : List.copyOf(groupMembers); } public Long customerId() { return accountId; } @@ -32,7 +36,7 @@ public final class SmartLoadingDtos { private SmartLoadingDtos(){} public record WorkbenchContainerQuery( @NotEmpty @Size(max=9) List<@NotBlank String> channelGroupCodes, @Positive Long warehouseId, @Positive Long customerId, @Size(max=40) String inboundCode, - LocalDate createdStart, LocalDate createdEnd, CandidateOrderStatus orderStatus, + LocalDate createdStart, LocalDate createdEnd, @Min(1) long page, @Min(1) @Max(200) long size) { public WorkbenchContainerQuery { channelGroupCodes = channelGroupCodes == null ? List.of() : List.copyOf(channelGroupCodes); diff --git a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java index fbc264aed..07cacb39c 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java @@ -85,36 +85,48 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba CASE WHEN current_group.id IS NULL THEN eligible.inboundId END inboundId, MIN(eligible.expectedArrivalAt) sortArrivalAt,MIN(eligible.inboundId) sortInboundId FROM ( - SELECT detail.accountId,detail.inboundId,detail.inboundCode,detail.expectedArrivalAt,detail.createdAt, - SUM(detail.availablePackageCount) availablePackageCount - FROM ( - SELECT o.tenant_id accountId,o.id inboundId,o.inbound_code inboundCode, - o.expected_arrival_at expectedArrivalAt,o.created_at createdAt,i.inbound_detail_id, - SUM(i.package_count) - -COALESCE((SELECT SUM(li.package_count) FROM fl_loading_plan_item li - WHERE li.account_id=o.tenant_id AND li.inbound_id=o.id - AND li.inbound_detail_id=i.inbound_detail_id AND li.deleted=0),0) - -COALESCE((SELECT SUM(split_item.package_count) FROM fl_inbound_split_item split_item - WHERE o.inbound_role='MASTER' AND split_item.tenant_id=o.tenant_id - AND split_item.parent_inbound_id=o.id - AND split_item.source_inbound_detail_id=i.inbound_detail_id),0) availablePackageCount - FROM fl_inbound_order o - JOIN fl_inbound_measurement m ON m.tenant_id=o.tenant_id AND m.inbound_id=o.id - AND m.status='APPROVED' - AND m.id=(SELECT MAX(m2.id) FROM fl_inbound_measurement m2 - WHERE m2.tenant_id=o.tenant_id AND m2.inbound_id=o.id AND m2.status='APPROVED') - JOIN fl_inbound_measurement_item i ON i.tenant_id=o.tenant_id AND i.measurement_id=m.id - AND i.inbound_detail_id IS NOT NULL AND i.package_count>0 - WHERE (#{query.warehouseId} IS NULL OR o.warehouse_id=#{query.warehouseId}) - AND o.channel_code IN - #{channel} - AND o.process_status='WAIT_SPLIT' - AND o.actual_gross_weight_kg IS NOT NULL AND o.actual_net_weight_kg IS NOT NULL - AND (o.inbound_role='MASTER' OR (o.split_purpose='REMAINDER' AND o.split_status='NOT_SPLIT')) - GROUP BY o.tenant_id,o.id,o.inbound_code,o.expected_arrival_at,o.created_at,i.inbound_detail_id - HAVING availablePackageCount>0 - ) detail - GROUP BY detail.accountId,detail.inboundId,detail.inboundCode,detail.expectedArrivalAt,detail.createdAt + SELECT o.tenant_id accountId,o.id inboundId,o.inbound_code inboundCode, + o.expected_arrival_at expectedArrivalAt,o.created_at createdAt, + CASE WHEN o.process_status='WAIT_SPLIT' THEN + COALESCE((SELECT SUM(mi.package_count) FROM fl_inbound_measurement m + JOIN fl_inbound_measurement_item mi + ON mi.tenant_id=m.tenant_id AND mi.measurement_id=m.id + AND mi.inbound_detail_id IS NOT NULL AND mi.package_count>0 + WHERE m.tenant_id=o.tenant_id AND m.inbound_id=o.id AND m.status='APPROVED' + AND m.id=(SELECT MAX(m2.id) FROM fl_inbound_measurement m2 + WHERE m2.tenant_id=o.tenant_id AND m2.inbound_id=o.id + AND m2.status='APPROVED')),0) + ELSE COALESCE(o.total_package_count,0) END + -COALESCE((SELECT SUM(li.package_count) FROM fl_loading_plan_item li + WHERE li.account_id=o.tenant_id AND li.inbound_id=o.id AND li.deleted=0),0) + -COALESCE((SELECT SUM(split_item.package_count) FROM fl_inbound_split_item split_item + WHERE o.inbound_role='MASTER' AND split_item.tenant_id=o.tenant_id + AND split_item.parent_inbound_id=o.id),0) availablePackageCount + FROM fl_inbound_order o + WHERE (#{query.warehouseId} IS NULL OR o.warehouse_id=#{query.warehouseId}) + AND o.channel_code IN + #{channel} + AND (o.inbound_role='MASTER' OR (o.split_purpose='REMAINDER' AND o.split_status='NOT_SPLIT')) + AND ( + o.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED', + 'WAIT_PRICING','FEE_CONFIRMING','INBOUNDING','WAIT_SPLIT','LOADING') + ) + + AND ( + + + o.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED','WAIT_PRICING','FEE_CONFIRMING','INBOUNDING') + o.process_status='WAIT_SPLIT' + o.process_status='LOADING' + 1=0 + + + ) + + AND o.tenant_id=#{query.customerId} + AND LOWER(o.inbound_code) LIKE CONCAT('%',LOWER(#{query.inboundCode}),'%') + AND o.created_at>=#{query.createdStart} + AND o.created_at<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY) ) eligible LEFT JOIN fl_coload_group_member current_member ON current_member.tenant_id=eligible.accountId AND current_member.inbound_id=eligible.inboundId @@ -125,21 +137,9 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba CASE WHEN current_group.id IS NULL THEN eligible.accountId END, CASE WHEN current_group.id IS NULL THEN eligible.inboundId END HAVING (current_group.id IS NULL OR ( - MIN(current_group.group_status)='ACTIVE' AND MAX(current_group.locked_plan_id) IS NULL - AND COUNT(*)=(SELECT COUNT(*) FROM fl_coload_group_member group_member_count + COUNT(*)=(SELECT COUNT(*) FROM fl_coload_group_member group_member_count WHERE group_member_count.group_id=current_group.id AND group_member_count.active_flag=1) - AND SUM(CASE WHEN eligible.availablePackageCount=current_member.full_package_count THEN 1 ELSE 0 END)=COUNT(*) )) - - AND SUM(CASE WHEN eligible.accountId=#{query.customerId} THEN 1 ELSE 0 END)>0 - - - AND SUM(CASE WHEN LOWER(eligible.inboundCode) LIKE CONCAT('%',LOWER(#{query.inboundCode}),'%') THEN 1 ELSE 0 END)>0 - - - AND DATE(MIN(eligible.createdAt))>=#{query.createdStart} - AND DATE(MIN(eligible.createdAt))<=#{query.createdEnd} - ORDER BY sortArrivalAt IS NULL,sortArrivalAt,sortInboundId """) @@ -169,8 +169,11 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba WHERE member_count.group_id=current_group.id AND member_count.active_flag=1) memberCount, (SELECT SUM(member_boxes.full_package_count) FROM fl_coload_group_member member_boxes WHERE member_boxes.group_id=current_group.id AND member_boxes.active_flag=1) groupTotalBoxes, - CASE WHEN current_group.id IS NULL THEN NULL ELSE FALSE END locked,NULL blockReason, - o.order_status_snapshot orderStatusSnapshot,o.expected_arrival_at expectedArrivalAt + CASE WHEN current_group.locked_plan_id IS NOT NULL OR EXISTS ( + SELECT 1 FROM fl_loading_plan_item occupied + WHERE occupied.account_id=o.tenant_id AND occupied.inbound_id=o.id AND occupied.deleted=0 + ) THEN TRUE ELSE FALSE END locked,NULL blockReason, + 'WAIT_SPLIT' orderStatusSnapshot,o.expected_arrival_at expectedArrivalAt FROM fl_inbound_order o JOIN fl_inbound_measurement m ON m.tenant_id=o.tenant_id AND m.inbound_id=o.id AND m.status='APPROVED' @@ -182,7 +185,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba ON current_member.tenant_id=o.tenant_id AND current_member.inbound_id=o.id AND current_member.active_flag=1 LEFT JOIN fl_coload_group current_group ON current_group.id=current_member.group_id AND current_group.group_status='ACTIVE' - AND current_group.locked_plan_id IS NULL WHERE o.process_status='WAIT_SPLIT' AND o.actual_gross_weight_kg IS NOT NULL AND o.actual_net_weight_kg IS NOT NULL AND (o.inbound_role='MASTER' OR (o.split_purpose='REMAINDER' AND o.split_status='NOT_SPLIT')) @@ -196,7 +198,45 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba ) GROUP BY o.id,m.id,i.inbound_detail_id,current_group.id,current_group.group_no HAVING availablePackageCount>0 - ORDER BY o.inbounded_at ASC,o.id ASC,i.inbound_detail_id ASC + UNION ALL + SELECT o.tenant_id accountId,o.id inboundId,NULL inboundDetailId, + o.order_id orderId,o.order_no orderNo,o.inbound_code inboundCode, + o.warehouse_id warehouseId,o.channel_code channelCode,o.channel_name channelName, + o.destination_warehouse_id destinationWarehouseId,o.destination_code destinationWarehouseCode, + o.destination_name destinationWarehouseName,o.customer_name customerName,NULL goodsName, + GREATEST(COALESCE(o.total_package_count,0)-COALESCE((SELECT SUM(used.package_count) + FROM fl_loading_plan_item used WHERE used.account_id=o.tenant_id + AND used.inbound_id=o.id AND used.deleted=0),0),0) availablePackageCount, + o.actual_gross_weight_kg/NULLIF(o.total_package_count,0) unitGrossWeightKg, + o.actual_net_weight_kg/NULLIF(o.total_package_count,0) unitNetWeightKg, + o.actual_volume_cbm/NULLIF(o.total_package_count,0) unitVolumeCbm, + current_group.id coLoadGroupId,current_group.group_no groupNo, + (SELECT COUNT(*) FROM fl_coload_group_member member_count + WHERE member_count.group_id=current_group.id AND member_count.active_flag=1) memberCount, + (SELECT SUM(member_boxes.full_package_count) FROM fl_coload_group_member member_boxes + WHERE member_boxes.group_id=current_group.id AND member_boxes.active_flag=1) groupTotalBoxes, + CASE WHEN current_group.locked_plan_id IS NOT NULL OR EXISTS ( + SELECT 1 FROM fl_loading_plan_item occupied + WHERE occupied.account_id=o.tenant_id AND occupied.inbound_id=o.id AND occupied.deleted=0 + ) THEN TRUE ELSE FALSE END locked,NULL blockReason, + CASE WHEN o.process_status='LOADING' THEN 'LOADING' ELSE 'WAIT_MEASURE' END orderStatusSnapshot, + o.expected_arrival_at expectedArrivalAt + FROM fl_inbound_order o + LEFT JOIN fl_coload_group_member current_member + ON current_member.tenant_id=o.tenant_id AND current_member.inbound_id=o.id AND current_member.active_flag=1 + LEFT JOIN fl_coload_group current_group + ON current_group.id=current_member.group_id AND current_group.group_status IN ('ACTIVE','LOCKED') + WHERE o.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED', + 'WAIT_PRICING','FEE_CONFIRMING','INBOUNDING','LOADING') + AND ( + + + current_group.id=#{unit.groupId} + (current_group.id IS NULL AND o.tenant_id=#{unit.accountId} AND o.id=#{unit.inboundId}) + + + ) + ORDER BY inboundId ASC,inboundDetailId ASC """) List globalCandidatesByUnits(@Param("units") List units); @@ -216,7 +256,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba AND b.channel_code IN #{channel} AND b.warehouse_id=#{query.warehouseId} - + AND EXISTS ( SELECT 1 FROM fl_loading_plan_item filter_item JOIN fl_inbound_order filter_inbound ON filter_inbound.tenant_id=filter_item.account_id @@ -226,14 +266,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba AND filter_item.inbound_code LIKE CONCAT('%',#{query.inboundCode},'%') AND filter_inbound.created_at >= #{query.createdStart} AND filter_inbound.created_at < DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY) - - - AND filter_inbound.order_status_snapshot IN ('SUBMITTED','PENDING_REVIEW') - AND filter_inbound.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED','WAIT_PRICING','FEE_CONFIRMING','INBOUNDING') - AND filter_inbound.process_status='WAIT_SPLIT' - AND filter_inbound.process_status='LOADING' - - ) ORDER BY b.updated_at DESC,b.id DESC @@ -241,8 +273,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba """) Page workbenchContainers(Page page, @Param("query") WorkbenchContainerQuery query, - @Param("actualChannels") Set actualChannels, - @Param("orderStatus") String orderStatus); + @Param("actualChannels") Set actualChannels); @Select(""" SELECT o.tenant_id accountId,o.id inboundId,i.inbound_detail_id inboundDetailId, diff --git a/firstleg/src/main/java/com/baiyue/firstleg/repository/SmartLoadingRepository.java b/firstleg/src/main/java/com/baiyue/firstleg/repository/SmartLoadingRepository.java index e506de4f4..8cdaf8ba6 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/repository/SmartLoadingRepository.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/repository/SmartLoadingRepository.java @@ -51,8 +51,7 @@ public class SmartLoadingRepository { public PageResult workbenchContainers(WorkbenchContainerQuery query, Set actualChannels) { return PageResult.from(candidates.workbenchContainers( - new Page<>(query.page(), query.size()), query, actualChannels, - query.orderStatus() == null ? null : query.orderStatus().name())); + new Page<>(query.page(), query.size()), query, actualChannels)); } public List channelContainerCounts(long warehouseId) { return candidates.channelContainerCounts(warehouseId); @@ -68,6 +67,9 @@ public class SmartLoadingRepository { .eq(InboundOrderEntity::getTenantId, accountId) .eq(InboundOrderEntity::getId, inboundId)); } + public InboundOrderEntity inbound(long inboundId) { + return inbounds.selectById(inboundId); + } public InboundOrderEntity inboundForUpdate(long accountId, long inboundId) { return inbounds.selectOne(new LambdaQueryWrapper() .eq(InboundOrderEntity::getTenantId, accountId) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java index 7837693b7..5bfc3f196 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java @@ -121,12 +121,34 @@ public class SmartLoadingService { throw validation("创建开始日期不能晚于结束日期"); } Set actualChannels = actualChannels(query.channelGroupCodes()); - if (query.orderStatus() == CandidateOrderStatus.PENDING_REVIEW) { - return pendingReviewCandidates(query, actualChannels); + EnumSet selected = query.orderStatuses().isEmpty() + ? EnumSet.allOf(CandidateOrderStatus.class) + : EnumSet.copyOf(query.orderStatuses()); + boolean includePending = selected.remove(CandidateOrderStatus.PENDING_REVIEW); + InboundCandidateQuery firstlegQuery = withStatuses(query, List.copyOf(selected), 1, 1); + if (!includePending) return firstlegCandidates(withStatuses(query, List.copyOf(selected), + query.page(), query.size()), actualChannels); + if (selected.isEmpty()) return pendingReviewCandidates(query, actualChannels, query.page(), query.size()); + + PageResult pendingCount = pendingReviewCandidates(query, actualChannels, 1, 1); + PageResult firstlegCount = firstlegCandidates(firstlegQuery, actualChannels); + long total = pendingCount.total() + firstlegCount.total(); + long offset = Math.multiplyExact(query.page() - 1, query.size()); + List records = new ArrayList<>(); + if (offset < pendingCount.total()) { + records.addAll(pendingReviewRange(query, actualChannels, offset, query.size())); } - if (query.orderStatus() != null && query.orderStatus() != CandidateOrderStatus.WAIT_SPLIT) { - return new PageResult<>(List.of(), query.page(), query.size(), 0, 0); + long firstlegOffset = Math.max(0, offset - pendingCount.total()); + int remaining = Math.toIntExact(query.size() - records.size()); + if (remaining > 0 && firstlegOffset < firstlegCount.total()) { + records.addAll(firstlegRange(query, actualChannels, List.copyOf(selected), firstlegOffset, remaining)); } + long pages = total == 0 ? 0 : (total + query.size() - 1) / query.size(); + return new PageResult<>(records, query.page(), query.size(), total, pages); + } + + private PageResult firstlegCandidates(InboundCandidateQuery query, + Set actualChannels) { PageResult unitPage = repository.globalCandidateUnits(query, actualChannels); if (unitPage.records().isEmpty()) { return new PageResult<>(List.of(), unitPage.page(), unitPage.size(), unitPage.total(), unitPage.pages()); @@ -156,12 +178,13 @@ public class SmartLoadingService { } private PageResult pendingReviewCandidates(InboundCandidateQuery query, - Set actualChannels) { + Set actualChannels, + long page, long size) { ApiResponse> response; try { response = pendingReviewOrders.page(internalToken, List.copyOf(actualChannels), query.warehouseId(), query.customerId(), query.inboundCode(), query.createdStart(), query.createdEnd(), - query.page(), query.size()); + page, size); } catch (RuntimeException exception) { throw new BizException(ResultCode.SERVICE_UNAVAILABLE, "待审核订单服务暂时不可用"); } @@ -173,11 +196,49 @@ public class SmartLoadingService { new InboundCandidate(row.customerId(), null, row.orderId(), row.orderNo(), row.inboundCode(), row.warehouseId(), row.channelCode(), row.channelName(), null, null, null, row.customerName(), null, row.totalPackageCount(), null, null, null, null, - null, null, null, null, false, null, + null, null, null, null, false, true, null, "PENDING_REVIEW", null, List.of())).toList(); return new PageResult<>(records, source.page(), source.size(), source.total(), source.pages()); } + private List pendingReviewRange(InboundCandidateQuery query, Set channels, + long offset, long limit) { + return pageRange(offset, limit, (page, size) -> pendingReviewCandidates(query, channels, page, size)); + } + + private List firstlegRange(InboundCandidateQuery query, Set channels, + List statuses, + long offset, long limit) { + return pageRange(offset, limit, (page, size) -> firstlegCandidates( + withStatuses(query, statuses, page, size), channels)); + } + + private static List pageRange(long offset, long limit, + java.util.function.BiFunction> source) { + if (limit <= 0) return List.of(); + final long chunk = 200; + long page = offset / chunk + 1; + int skip = Math.toIntExact(offset % chunk); + List result = new ArrayList<>(); + while (result.size() < limit) { + List rows = source.apply(page++, chunk).records(); + if (rows.isEmpty()) break; + int from = Math.min(skip, rows.size()); + int take = Math.min(Math.toIntExact(limit - result.size()), rows.size() - from); + if (take > 0) result.addAll(rows.subList(from, from + take)); + skip = 0; + if (rows.size() < chunk) break; + } + return List.copyOf(result); + } + + private static InboundCandidateQuery withStatuses(InboundCandidateQuery source, + List statuses, + long page, long size) { + return new InboundCandidateQuery(source.channelGroupCodes(), source.warehouseId(), source.customerId(), + source.inboundCode(), source.createdStart(), source.createdEnd(), statuses, page, size); + } + public PageResult containers(WorkbenchContainerQuery query) { if (query.createdStart() != null && query.createdEnd() != null && query.createdStart().isAfter(query.createdEnd())) { @@ -190,11 +251,12 @@ public class SmartLoadingService { Candidate first = details.get(0); int packages = details.stream().map(Candidate::availablePackageCount) .filter(Objects::nonNull).mapToInt(Integer::intValue).sum(); - BigDecimal volume = details.stream() - .map(detail -> unit(detail.unitVolumeCbm()).multiply(BigDecimal.valueOf( + boolean hasVolume = details.stream().anyMatch(detail -> detail.unitVolumeCbm() != null); + BigDecimal volume = hasVolume ? details.stream().filter(detail -> detail.unitVolumeCbm() != null) + .map(detail -> detail.unitVolumeCbm().multiply(BigDecimal.valueOf( Math.max(0, detail.availablePackageCount() == null ? 0 : detail.availablePackageCount())))) - .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP); - BigDecimal averageVolume = packages == 0 ? BigDecimal.ZERO : volume.divide( + .reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP) : null; + BigDecimal averageVolume = packages == 0 || volume == null ? null : volume.divide( BigDecimal.valueOf(packages), 6, RoundingMode.HALF_UP); String goods = details.stream().map(Candidate::goodsName).filter(StringUtils::hasText) .map(String::trim).distinct().collect(java.util.stream.Collectors.joining("、")); @@ -203,7 +265,7 @@ public class SmartLoadingService { first.destinationWarehouseId(), first.destinationWarehouseCode(), first.destinationWarehouseName(), first.customerName(), goods, packages, first.unitGrossWeightKg(), first.unitNetWeightKg(), averageVolume, volume, first.coLoadGroupId(), first.groupNo(), first.memberCount(), - first.groupTotalBoxes(), first.locked(), first.blockReason(), first.orderStatusSnapshot(), + first.groupTotalBoxes(), first.locked(), canAssign(first), capabilityBlock(first), first.orderStatusSnapshot(), first.expectedArrivalAt(), List.of()); } @@ -217,11 +279,12 @@ public class SmartLoadingService { InboundCandidate first = ordered.get(0); int packages = ordered.stream().map(InboundCandidate::availablePackageCount).mapToInt(Integer::intValue).sum(); if (packages != metadata.groupTotalBoxes()) return null; - BigDecimal volume = ordered.stream().map(InboundCandidate::availableVolumeCbm) - .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP); + boolean hasVolume = ordered.stream().anyMatch(candidate -> candidate.availableVolumeCbm() != null); + BigDecimal volume = hasVolume ? ordered.stream().map(InboundCandidate::availableVolumeCbm) + .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP) : null; BigDecimal gross = weightedAverage(ordered, InboundCandidate::unitGrossWeightKg, packages); BigDecimal net = weightedAverage(ordered, InboundCandidate::unitNetWeightKg, packages); - BigDecimal averageVolume = packages == 0 ? BigDecimal.ZERO + BigDecimal averageVolume = packages == 0 || volume == null ? null : volume.divide(BigDecimal.valueOf(packages), 6, RoundingMode.HALF_UP); List groupMembers = ordered.stream().map(member -> new GroupMemberCandidate( member.accountId(), member.inboundId(), member.orderId(), member.orderNo(), member.inboundCode(), @@ -235,11 +298,42 @@ public class SmartLoadingService { first.inboundCode(), first.warehouseId(), first.channelCode(), first.channelName(), first.destinationWarehouseId(), first.destinationWarehouseCode(), first.destinationWarehouseName(), customers, goods, packages, gross, net, averageVolume, volume, metadata.coLoadGroupId(), metadata.groupNo(), - metadata.memberCount(), metadata.groupTotalBoxes(), false, null, first.orderStatusSnapshot(), + metadata.memberCount(), metadata.groupTotalBoxes(), + ordered.stream().anyMatch(candidate -> Boolean.TRUE.equals(candidate.locked())), + ordered.stream().allMatch(candidate -> Boolean.TRUE.equals(candidate.canAssign())), + ordered.stream().map(InboundCandidate::blockReason).filter(StringUtils::hasText).findFirst().orElse(null), + groupStatus(ordered), ordered.stream().map(InboundCandidate::expectedArrivalAt).filter(Objects::nonNull).min(LocalDateTime::compareTo).orElse(null), groupMembers); } + private static boolean canAssign(Candidate candidate) { + return !Boolean.TRUE.equals(candidate.locked()) && !StringUtils.hasText(candidate.blockReason()) + && candidate.availablePackageCount() != null && candidate.availablePackageCount() > 0; + } + + private static String capabilityBlock(Candidate candidate) { + if (StringUtils.hasText(candidate.blockReason())) return candidate.blockReason(); + if (Boolean.TRUE.equals(candidate.locked())) return "该入仓码已被有效柜次占用"; + if (candidate.availablePackageCount() == null || candidate.availablePackageCount() <= 0) return "没有可加入的剩余箱数"; + return null; + } + + private static String groupStatus(List members) { + return members.stream().map(InboundCandidate::orderStatusSnapshot).filter(StringUtils::hasText) + .min(Comparator.comparingInt(SmartLoadingService::statusOrder)).orElse(null); + } + + private static int statusOrder(String status) { + return switch (status) { + case "PENDING_REVIEW" -> 0; + case "WAIT_MEASURE" -> 1; + case "WAIT_SPLIT" -> 2; + case "LOADING" -> 3; + default -> 4; + }; + } + private static String unitKey(Long groupId, Long accountId, Long inboundId) { return groupId == null ? "I|" + accountId + '|' + inboundId : "G|" + groupId; } @@ -247,8 +341,8 @@ public class SmartLoadingService { private static BigDecimal weightedAverage(List members, java.util.function.Function getter, int packages) { - if (packages == 0) return BigDecimal.ZERO; - return members.stream().map(candidate -> unit(getter.apply(candidate)).multiply( + if (packages == 0 || members.stream().map(getter).anyMatch(Objects::isNull)) return null; + return members.stream().map(candidate -> getter.apply(candidate).multiply( BigDecimal.valueOf(candidate.availablePackageCount()))) .reduce(BigDecimal.ZERO, BigDecimal::add) .divide(BigDecimal.valueOf(packages), 6, RoundingMode.HALF_UP); @@ -466,6 +560,13 @@ public class SmartLoadingService { Plan replay = replay(operation, planId, "ADD_INBOUND", null, requestHash); if (replay != null) return replay; + InboundOrderEntity projection = repository.inbound(request.inboundId()); + if (!wholeGroupAssignment && projection != null && Set.of("PREPARING", "WAIT_MEASURE", + "MEASURING", "MEASURE_PENDING", "MEASURE_REJECTED", "WAIT_PRICING", + "FEE_CONFIRMING", "INBOUNDING").contains(projection.getProcessStatus())) { + return assignDeclaredInbound(planId, request, projection, operation, requestHash, + operatorId, operatorName); + } LoadingPlanEntity plan = editing(planId, request.expectedVersion(), operatorId, operatorName); ContainerBookingEntity booking = requireBooking(plan.getContainerBookingId()); List details = candidates(plan.getContainerBookingId(), booking.getWarehouseId()).stream() @@ -497,6 +598,66 @@ public class SmartLoadingService { return view(assigned, booking); } + private Plan assignDeclaredInbound(long planId, AssignInboundRequest request, + InboundOrderEntity projection, String operation, + String requestHash, long operatorId, String operatorName) { + LoadingPlanEntity plan = editing(planId, request.expectedVersion(), operatorId, operatorName); + ContainerBookingEntity booking = requireBooking(plan.getContainerBookingId()); + InboundOrderEntity locked = repository.inboundForUpdate(projection.getTenantId(), projection.getId()); + if (locked == null || !Set.of("PREPARING", "WAIT_MEASURE", "MEASURING", "MEASURE_PENDING", + "MEASURE_REJECTED", "WAIT_PRICING", "FEE_CONFIRMING", "INBOUNDING") + .contains(locked.getProcessStatus())) { + throw conflict("入仓码状态已变化,请刷新后重试"); + } + if (!repository.activeItemsByInbound(locked.getTenantId(), locked.getId()).isEmpty()) { + throw conflict("该入仓码已被有效柜次占用"); + } + var order = loadInboundSnapshot(locked.getTenantId(), locked.getOrderId()); + if (!Objects.equals(order.inboundCode(), locked.getInboundCode()) + || !Objects.equals(order.warehouseId(), locked.getWarehouseId()) + || !Objects.equals(order.channelCode(), locked.getChannelCode())) { + throw conflict("订单履约快照已变化,请刷新后重试"); + } + List declared = loadDeclaredCargo(locked.getTenantId(), locked.getOrderId()); + List candidates = declared.stream().map(value -> declaredCandidate( + order, locked.getId(), value.cargo(), "WAIT_MEASURE")).toList(); + List allocations = proportionalAllocations(candidates, request.packageCount()); + List current = new ArrayList<>(repository.items(planId)); + List created = new ArrayList<>(); + int sequence = current.size(); + for (InboundAllocation allocation : allocations) { + if (allocation.packageCount() == 0) continue; + Candidate candidate = allocation.candidate(); + requireSameChannel(booking, candidate); + requireSameCustomerScope(booking, candidate); + checkRouteAndCapacity(booking, current, candidate, allocation.packageCount(), true); + OrderCargoClient.CargoBinding cargo = declared.stream().map(DeclaredCargo::cargo) + .filter(value -> Objects.equals(value.cargoId(), candidate.inboundDetailId())) + .findFirst().orElseThrow(() -> conflict("订单货物明细已变化,请刷新后重试")); + LoadingPlanItemEntity item = snapshot(planId, candidate, cargo, allocation.packageCount(), + operatorId, operatorName, ++sequence); + current.add(item); + created.add(item); + } + if (created.isEmpty()) throw validation("入仓码没有可加入装柜清单的箱数"); + splitPreloadService.ensurePendingForPreAllocation(locked.getTenantId(), locked.getId(), + operatorId, operatorName); + touch(plan, operatorId, operatorName); + try { + created.forEach(repository::insert); + } catch (DuplicateKeyException exception) { + throw conflict("该入仓码已被并发加入其他柜次"); + } + history(planId, null, "ADD_INBOUND", plan.getPlanStatus(), plan.getPlanStatus(), operation, + json(values("version", request.expectedVersion(), "inboundId", request.inboundId())), + json(values("requestHash", requestHash, "packageCount", request.packageCount(), + "specificationLineCount", created.size(), "provisional", true)), operatorId, operatorName); + loadingModelBridge.bindIncrementalAllocation(planId, locked.getTenantId(), locked.getId(), + operatorId, operatorName, operation); + created.forEach(item -> loadingPickService.sync(planId, item)); + return view(repository.plan(planId), booking); + } + List proportionalAllocations(List details, int selected) { int available = details.stream().map(Candidate::availablePackageCount).filter(Objects::nonNull) .mapToInt(Integer::intValue).sum(); @@ -1075,6 +1236,12 @@ public class SmartLoadingService { private Candidate declaredCandidate(PendingReviewOrderClient.Row pending, com.baiyue.firstleg.dto.OrderApprovedInboundCommand snapshot, long inboundId, OrderCargoClient.CargoBinding cargo) { + return declaredCandidate(snapshot, inboundId, cargo, pending.mainStatus()); + } + + private Candidate declaredCandidate(com.baiyue.firstleg.dto.OrderApprovedInboundCommand snapshot, + long inboundId, OrderCargoClient.CargoBinding cargo, + String candidateStatus) { int boxes = cargo.originalPackageCount() == null ? 0 : cargo.originalPackageCount(); if (boxes <= 0) throw conflict("订单货物箱数不完整,请先修正订单"); BigDecimal divisor = BigDecimal.valueOf(boxes); @@ -1086,7 +1253,7 @@ public class SmartLoadingService { snapshot.channelName(), snapshot.destinationWarehouseId(), snapshot.destinationCode(), snapshot.destinationName(), snapshot.customerName(), cargo.cargoName(), boxes, unitGross, unitNet, unitVolume, null, null, null, null, false, null, - pending.mainStatus(), snapshot.expectedArrivalAt()); + candidateStatus, snapshot.expectedArrivalAt()); } private record DeclaredCargo(OrderCargoClient.CargoBinding cargo) {} From eca2c94aa3a892c744570e8234bbe3409e4c7da9 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Thu, 3 Sep 2026 21:48:40 +0800 Subject: [PATCH 03/10] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- firstleg/AGENTS.md | 2 +- .../mapper/SmartLoadingCandidateMapper.java | 5 +- .../firstleg/service/SmartLoadingService.java | 15 +- .../main/resources/openapi/firstleg-v1.yaml | 40 ++-- ...ormSmartLoadingControllerContractTest.java | 6 + ...artLoadingCandidateMapperContractTest.java | 24 ++- .../service/SmartLoadingServiceTest.java | 179 ++++++++++++++++-- 7 files changed, 222 insertions(+), 49 deletions(-) diff --git a/firstleg/AGENTS.md b/firstleg/AGENTS.md index 0a081f872..3f539cc14 100644 --- a/firstleg/AGENTS.md +++ b/firstleg/AGENTS.md @@ -76,7 +76,7 @@ ## 三期装柜与 PDA 资源结算 -- 智能装柜全局工作台由服务端把业务渠道分组映射为实际渠道,并分别分页查询候选与 `WAIT_LOADING/EDITING/LOADING` 柜次;候选只返回具备实际装柜资格的 `WAIT_SPLIT` 数据,同柜不可拆组必须成员完整、满箱且作为单个分页与分配单元,不能跨页或拆分。分配到柜时继续复核国内中转仓、实际渠道、容量、组锁和版本;推荐顺序按入库时间先进先出。装柜计划状态为 `EDITING -> LOADING -> COMPLETED`,PDA 全部明细处理完成后自动完成。 +- 智能装柜全局工作台由服务端把业务渠道分组映射为实际渠道,并分别分页查询候选与 `WAIT_LOADING/EDITING/LOADING` 柜次;候选状态筛选使用最多四项的 `orderStatuses`,未传表示 `PENDING_REVIEW/WAIT_MEASURE/WAIT_SPLIT/LOADING` 全部未完成状态。状态只用于搜索和展示,能否加入由有效柜次占用、剩余箱数、国内中转仓、实际渠道、容量、组锁和版本等事实决定;容积和重量均允许达到柜型额定值的 150%,超过即拒绝。待审核或待测量可先占位,但确认预装和启动 PDA 前仍必须进入 `WAIT_SPLIT`。同柜不可拆组必须成员完整、满箱且作为单个分页与分配单元,不能跨页或拆分。推荐顺序按入库时间先进先出。装柜计划状态为 `EDITING -> LOADING -> COMPLETED`,PDA 全部明细处理完成后自动完成。 - PDA 拣货以 `fl_inbound_carton_label.box_code` 对应的稳定箱唛箱码为扫描身份;审核建单、重复打印、手工测量和墨家测量复用同一映射,版本字段只用于并发控制,不进入扫码文本。一个有效且未重复的箱码扫描表示拣出一箱,不得以 SKU、商品件数或页面展示字段替代箱码。任务下发与提交契约见 `src/main/resources/openapi/phase3-pda-convergence-v1.yaml`。 - PDA 部分拣货生成二级子入库单时,数量必须守恒:`已拣数量 + 子单数量 = 拣货前主单可用数量`。子单只允许一层,不能继续拆分。 - `releaseMode=AUTO` 时,释放资源数为 `ceil(实际拣货箱数 × 原资源数 / 原可用箱数)`;`MANUAL` 按 `locationIds` 选择,空数组表示明确释放 0 个。当前契约中未传模式且 `locationIds=null` 时按 AUTO 处理。 diff --git a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java index 07cacb39c..964d961f6 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java @@ -87,6 +87,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba FROM ( SELECT o.tenant_id accountId,o.id inboundId,o.inbound_code inboundCode, o.expected_arrival_at expectedArrivalAt,o.created_at createdAt, + CASE WHEN o.process_status='WAIT_SPLIT' THEN 'WAIT_SPLIT' + WHEN o.process_status='LOADING' THEN 'LOADING' ELSE 'WAIT_MEASURE' END candidateStatus, CASE WHEN o.process_status='WAIT_SPLIT' THEN COALESCE((SELECT SUM(mi.package_count) FROM fl_inbound_measurement m JOIN fl_inbound_measurement_item mi @@ -132,7 +134,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba ON current_member.tenant_id=eligible.accountId AND current_member.inbound_id=eligible.inboundId AND current_member.active_flag=1 LEFT JOIN fl_coload_group current_group - ON current_group.id=current_member.group_id AND current_group.group_status IN ('ACTIVE','LOCKED') + ON current_group.id=current_member.group_id AND current_group.group_status IN ('ACTIVE','LOCKED') + WHERE eligible.candidateStatus<>'WAIT_SPLIT' OR eligible.availablePackageCount>0 GROUP BY current_group.id, CASE WHEN current_group.id IS NULL THEN eligible.accountId END, CASE WHEN current_group.id IS NULL THEN eligible.inboundId END diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java index 5bfc3f196..fed94e1cc 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java @@ -41,7 +41,7 @@ import java.util.*; /** 智能装柜的自动计划、候选、推荐、人工分配和删除编排。 */ @Service public class SmartLoadingService { - private static final BigDecimal CAPACITY_LIMIT_RATIO = new BigDecimal("1.10"); + private static final BigDecimal CAPACITY_LIMIT_RATIO = new BigDecimal("1.50"); private static final Map> WORKBENCH_CHANNEL_GROUPS = Map.of( "MATSON_CLX", Set.of("MATSON_CLX_TRUCK", "MATSON_CLX_PARCEL"), "MATSON_MAX", Set.of("MATSON_MAX_TRUCK", "MATSON_MAX_PARCEL"), @@ -278,7 +278,8 @@ public class SmartLoadingService { .sorted(Comparator.comparing(InboundCandidate::inboundId)).toList(); InboundCandidate first = ordered.get(0); int packages = ordered.stream().map(InboundCandidate::availablePackageCount).mapToInt(Integer::intValue).sum(); - if (packages != metadata.groupTotalBoxes()) return null; + boolean occupied = ordered.stream().anyMatch(candidate -> Boolean.TRUE.equals(candidate.locked())); + if (!occupied && packages != metadata.groupTotalBoxes()) return null; boolean hasVolume = ordered.stream().anyMatch(candidate -> candidate.availableVolumeCbm() != null); BigDecimal volume = hasVolume ? ordered.stream().map(InboundCandidate::availableVolumeCbm) .filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add).setScale(4, RoundingMode.HALF_UP) : null; @@ -299,7 +300,7 @@ public class SmartLoadingService { first.destinationWarehouseId(), first.destinationWarehouseCode(), first.destinationWarehouseName(), customers, goods, packages, gross, net, averageVolume, volume, metadata.coLoadGroupId(), metadata.groupNo(), metadata.memberCount(), metadata.groupTotalBoxes(), - ordered.stream().anyMatch(candidate -> Boolean.TRUE.equals(candidate.locked())), + occupied, ordered.stream().allMatch(candidate -> Boolean.TRUE.equals(candidate.canAssign())), ordered.stream().map(InboundCandidate::blockReason).filter(StringUtils::hasText).findFirst().orElse(null), groupStatus(ordered), @@ -1017,7 +1018,7 @@ public class SmartLoadingService { result.put(member.inboundId(), details); } if (!groupFits(booking, planItems, group, available)) { - throw validation("同柜不可拆组整体超过货柜容积或重量的110%上限"); + throw validation("同柜不可拆组整体超过货柜容积或重量的150%上限"); } return result; } @@ -1270,7 +1271,7 @@ public class SmartLoadingService { if (b.getCapacityCbm()==null || b.getMaxWeightKg()==null) throw validation("货柜容量和最大承重未配置"); if (v.compareTo(b.getCapacityCbm().multiply(CAPACITY_LIMIT_RATIO))>0 || w.compareTo(b.getMaxWeightKg().multiply(CAPACITY_LIMIT_RATIO))>0) { - throw validation("超过货柜容积或重量的110%上限"); + throw validation("超过货柜容积或重量的150%上限"); } } private void checkPlanCapacity(ContainerBookingEntity booking, List items) { @@ -1280,12 +1281,12 @@ public class SmartLoadingService { BigDecimal weight = items.stream().map(x -> unit(x.getGrossWeightKg())) .reduce(BigDecimal.ZERO, BigDecimal::add); if (weight.compareTo(booking.getMaxWeightKg().multiply(CAPACITY_LIMIT_RATIO)) > 0) { - throw validation("超过货柜重量的110%上限"); + throw validation("超过货柜重量的150%上限"); } BigDecimal volume = items.stream().map(x -> unit(x.getVolumeCbm())) .reduce(BigDecimal.ZERO, BigDecimal::add); if (volume.compareTo(booking.getCapacityCbm().multiply(CAPACITY_LIMIT_RATIO)) > 0) { - throw validation("超过货柜容积的110%上限"); + throw validation("超过货柜容积的150%上限"); } } private int fittingBoxes(ContainerBookingEntity b,List lines,Candidate c){ diff --git a/firstleg/src/main/resources/openapi/firstleg-v1.yaml b/firstleg/src/main/resources/openapi/firstleg-v1.yaml index 366bc432a..5536a9948 100644 --- a/firstleg/src/main/resources/openapi/firstleg-v1.yaml +++ b/firstleg/src/main/resources/openapi/firstleg-v1.yaml @@ -486,13 +486,16 @@ paths: summary: 全局分页查询智能装柜候选 description: >- 需要 platform:firstleg:smart-loading:list 权限。查询不绑定柜次;渠道、仓库、客户、入仓码、 - 预计到货日期和订单状态共同作用于全局候选。每个普通入库单返回一行;同柜不可拆组作为一个 + 订单创建日期和订单状态共同作用于全局候选。每个普通入库单返回一行;同柜不可拆组作为一个 分页单元返回,groupMembers 包含完整成员,不会跨页或因单个成员命中搜索条件而拆散。 平均单箱毛重、净重按整票实测重量除以总箱数,平均单箱体积按剩余规格数量加权。 - WAIT_SPLIT 返回 Firstleg 可用箱数;PENDING_REVIEW 返回 Order 权威待审核订单并允许先加入装柜清单。 - 订单审核状态只用于筛选和展示,不直接决定能否占位;已被有效柜次占用、LOADED、COMPLETED、 - 已锁定或成员不完整的组永不返回。分配时仍由目标 planId 接口复核真实渠道、仓库、容量、 - 组锁和并发版本;确认预装/PDA 前必须完成审核与测量并进入 WAIT_SPLIT。 + orderStatuses 可重复传参且最多四项;未传或空数组表示 PENDING_REVIEW、WAIT_MEASURE、WAIT_SPLIT、 + LOADING 全部未完成状态,已完成装柜永不返回。状态映射为:Order SUBMITTED=PENDING_REVIEW; + Firstleg WAIT_MEASURE/MEASURING/MEASURE_PENDING/MEASURE_REJECTED/WAIT_PRICING/FEE_CONFIRMING/INBOUNDING + =WAIT_MEASURE;WAIT_SPLIT=WAIT_SPLIT;LOADING=LOADING。状态只用于搜索和展示,canAssign 由有效柜次占用、 + 剩余箱数、同柜组、仓库、渠道和容量等事实决定;容积和重量均允许达到柜型额定值的150%,超过即拒绝。 + 待审核及待测量可以先加入清单;确认预装/PDA 前 + 仍必须完成审核与测量并进入 WAIT_SPLIT。同柜不可拆组仅在全部成员命中当前状态集合时作为一个分页单位返回。 parameters: - name: channelGroupCodes in: query @@ -514,7 +517,15 @@ paths: - {name: inboundCode, in: query, required: false, schema: {type: string, maxLength: 40}} - {name: createdStart, in: query, required: false, schema: {type: string, format: date}} - {name: createdEnd, in: query, required: false, schema: {type: string, format: date}} - - {name: orderStatus, in: query, required: false, schema: {type: string, enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_SPLIT, LOADING]}} + - name: orderStatuses + in: query + required: false + description: 可重复传参,未传或空数组表示全部四种未完成状态 + schema: + type: array + maxItems: 4 + uniqueItems: true + items: {type: string, enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_SPLIT, LOADING]} - {name: page, in: query, required: false, schema: {type: integer, minimum: 1, default: 1}} - {name: size, in: query, required: false, schema: {type: integer, minimum: 1, maximum: 200, default: 20}} responses: @@ -525,8 +536,8 @@ paths: get: summary: 分页查询智能装柜工作台柜次 description: >- - 需要 platform:firstleg:smart-loading:list 权限。与全局候选使用相同的渠道、仓库、客户、入仓码、 - 订单创建日期及订单状态筛选;客户及入仓事实以柜内任一有效装柜明细命中为准,查询不会修改或拆散同柜组。 + 需要 platform:firstleg:smart-loading:list 权限。柜次查询只使用渠道、仓库、客户、入仓码及订单创建日期; + 候选的 orderStatuses 不作用于柜次列表。客户及入仓事实以柜内任一有效装柜明细命中为准。 只返回 WAIT_LOADING、EDITING 或 LOADING 的 ACTIVE 柜次,COMPLETED 永不返回。 parameters: - name: channelGroupCodes @@ -543,7 +554,6 @@ paths: - {name: inboundCode, in: query, required: false, schema: {type: string, maxLength: 40}} - {name: createdStart, in: query, required: false, schema: {type: string, format: date}} - {name: createdEnd, in: query, required: false, schema: {type: string, format: date}} - - {name: orderStatus, in: query, required: false, schema: {type: string, enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_SPLIT, LOADING]}} - {name: page, in: query, required: false, schema: {type: integer, minimum: 1, default: 1}} - {name: size, in: query, required: false, schema: {type: integer, minimum: 1, maximum: 200, default: 20}} responses: @@ -605,7 +615,8 @@ paths: summary: 按入仓码分配计划装柜箱数 description: >- 需要 platform:firstleg:smart-loading:assign 权限。操作员只选择某个入仓码的本次计划箱数; - 服务端在单一事务内按剩余规格箱数比例生成内部规格快照,用于体积估算及兼容 PDA/拆单。 + 服务端在单一事务内按剩余规格箱数比例生成内部规格快照,用于体积估算及兼容 PDA/拆单; + 柜内总容积和总重量分别允许达到柜型额定值的150%,超过即拒绝。 只记录数量计划,具体实装箱号归属为 UNVERIFIED,不得将内部比例分摊宣称为现场箱号事实。 parameters: - {name: planId, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}} @@ -2007,7 +2018,7 @@ components: type: object required: [accountId, customerId, inboundId, orderId, orderNo, inboundCode, warehouseId, channelCode, channelName, customerName, goodsSummary, availablePackageCount, unitGrossWeightKg, - unitNetWeightKg, averageUnitVolumeCbm, availableVolumeCbm, locked, groupMembers] + unitNetWeightKg, averageUnitVolumeCbm, availableVolumeCbm, locked, canAssign, groupMembers] properties: accountId: {type: string, pattern: '^[1-9][0-9]*$'} customerId: {type: string, pattern: '^[1-9][0-9]*$', description: 与 accountId 相同的客户技术关联ID} @@ -2015,7 +2026,7 @@ components: orderId: {type: string, pattern: '^[1-9][0-9]*$'} orderNo: {type: string} inboundCode: {type: string} - orderStatusSnapshot: {type: string, nullable: true} + orderStatusSnapshot: {type: string, enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_SPLIT, LOADING]} expectedArrivalAt: {type: string, format: date-time, nullable: true} warehouseId: {type: string, pattern: '^[1-9][0-9]*$'} channelCode: {type: string} @@ -2025,7 +2036,7 @@ components: destinationWarehouseName: {type: string, nullable: true} customerName: {type: string} goodsSummary: {type: string, nullable: true} - availablePackageCount: {type: integer, minimum: 1, description: 普通行剩余箱数;组行完整成员箱数合计} + availablePackageCount: {type: integer, minimum: 0, description: 普通行剩余箱数;组行完整成员箱数合计} unitGrossWeightKg: {type: number, minimum: 0, nullable: true} unitNetWeightKg: {type: number, minimum: 0, nullable: true} averageUnitVolumeCbm: {type: number, minimum: 0, nullable: true} @@ -2035,6 +2046,7 @@ components: memberCount: {type: integer, minimum: 2, nullable: true} groupTotalBoxes: {type: integer, minimum: 1, nullable: true} locked: {type: boolean} + canAssign: {type: boolean, description: 当前是否可加入柜次;与搜索状态解耦,以占用及业务约束事实计算} blockReason: {type: string, nullable: true} groupMembers: type: array @@ -2049,7 +2061,7 @@ components: orderNo: {type: string} inboundCode: {type: string} customerName: {type: string} - availablePackageCount: {type: integer, minimum: 1} + availablePackageCount: {type: integer, minimum: 0} orderStatusSnapshot: {type: string, nullable: true} expectedArrivalAt: {type: string, format: date-time, nullable: true} SmartLoadingWorkbenchContainerPageEnvelope: diff --git a/firstleg/src/test/java/com/baiyue/firstleg/controller/PlatformSmartLoadingControllerContractTest.java b/firstleg/src/test/java/com/baiyue/firstleg/controller/PlatformSmartLoadingControllerContractTest.java index 810d74ba5..06d574137 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/controller/PlatformSmartLoadingControllerContractTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/controller/PlatformSmartLoadingControllerContractTest.java @@ -34,10 +34,15 @@ class PlatformSmartLoadingControllerContractTest { .contains("name: warehouseId") .contains("name: createdStart") .contains("name: createdEnd") + .contains("name: orderStatuses") + .contains("maxItems: 4") + .contains("PENDING_REVIEW, WAIT_MEASURE, WAIT_SPLIT, LOADING") .contains("SmartLoadingInboundCandidatePageEnvelope") + .doesNotContain("name: orderStatus,") .doesNotContain("name: expectedArrivalStart") .doesNotContain("name: expectedArrivalEnd") .doesNotContain("name: bookingId"); + assertThat(yaml).contains("canAssign: {type: boolean, description: 当前是否可加入柜次"); } @Test void everyMutationDeclaresDedicatedPermission() throws Exception { authority("assign","platform:firstleg:smart-loading:assign",AuthenticatedUser.class,long.class,AssignRequest.class); @@ -75,6 +80,7 @@ class PlatformSmartLoadingControllerContractTest { .contains("成功响应中的 version 是递增后的 planVersion") .contains("items[].version 是递增后的 itemVersion") .contains("数量调整或动态增量不会覆盖已有 warehouseRemark") + .contains("柜内总容积和总重量分别允许达到柜型额定值的150%") .contains("canAssign: {type: boolean}") .contains("canEdit: {type: boolean}") .contains("pickedPackageCount: {type: integer, minimum: 0}") diff --git a/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java b/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java index c43f615d8..a03e09762 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java @@ -71,10 +71,12 @@ class SmartLoadingCandidateMapperContractTest { assertThat(unitSql) .contains("#{query.warehouseId} IS NULL OR o.warehouse_id=#{query.warehouseId}") .contains("o.channel_code IN") - .contains("o.process_status='WAIT_SPLIT'") + .contains("query.orderStatuses") + .contains("status.name() == 'WAIT_MEASURE'") + .contains("status.name() == 'WAIT_SPLIT'") + .contains("status.name() == 'LOADING'") .contains("current_group.id groupId") .contains("group_member_count.group_id=current_group.id") - .contains("availablePackageCount=current_member.full_package_count") .doesNotContain("fl_container_booking") .doesNotContain("bookingId"); assertThat(detailSql) @@ -82,6 +84,8 @@ class SmartLoadingCandidateMapperContractTest { .contains("current_group.id=#{unit.groupId}") .contains("o.tenant_id=#{unit.accountId}") .contains("o.id=#{unit.inboundId}") + .contains("'WAIT_SPLIT' orderStatusSnapshot") + .contains("THEN 'LOADING' ELSE 'WAIT_MEASURE' END orderStatusSnapshot") .doesNotContain("fl_container_booking"); } @@ -93,8 +97,8 @@ class SmartLoadingCandidateMapperContractTest { assertThat(sql) .contains("o.created_at createdAt") - .contains("DATE(MIN(eligible.createdAt))>=#{query.createdStart}") - .contains("DATE(MIN(eligible.createdAt))<=#{query.createdEnd}") + .contains("o.created_at>=#{query.createdStart}") + .contains("o.created_at<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY)") .doesNotContain("query.expectedArrivalStart", "query.expectedArrivalEnd"); } @@ -126,13 +130,15 @@ class SmartLoadingCandidateMapperContractTest { String unitScript = String.join(" ", units.getAnnotation(Select.class).value()); var query = new InboundCandidateQuery(List.of("MATSON_CLX"), 100L, 9L, "IN-", java.time.LocalDate.parse("2026-09-01"), java.time.LocalDate.parse("2026-09-30"), - null, 1, 20); + List.of(com.baiyue.firstleg.dto.SmartLoadingDtos.CandidateOrderStatus.WAIT_MEASURE, + com.baiyue.firstleg.dto.SmartLoadingDtos.CandidateOrderStatus.WAIT_SPLIT), 1, 20); String renderedUnits = driver.createSqlSource(configuration, unitScript, Map.class) .getBoundSql(Map.of("query", query, "actualChannels", Set.of("MATSON_CLX_TRUCK"))).getSql(); assertThat(renderedUnits) .contains("o.channel_code IN") - .contains("DATE(MIN(eligible.createdAt))>=", "DATE(MIN(eligible.createdAt))<=") - .doesNotContain("DATE(MIN(eligible.expectedArrivalAt))"); + .contains("o.created_at>=", "o.created_at(List.of(unit), 1, 20, 1, 1)); @@ -212,12 +216,97 @@ class SmartLoadingServiceTest { verify(repository, never()).booking(anyLong()); } + @Test + void combinesAllUnfinishedStatusesBeforeReturningTheRequestedPage() { + InboundCandidateQuery query = new InboundCandidateQuery( + List.of("EXX"), null, null, null, null, null, List.of(), 1, 20); + var pending = new PendingReviewOrderClient.Row(31L, "O31", "I31", 9L, "客户", + 100L, "EXX_TRUCK", "EXX海卡", 3, LocalDateTime.parse("2026-09-01T09:00:00"), + "PENDING_REVIEW"); + when(pendingReviewOrders.page(anyString(), anyList(), isNull(), isNull(), isNull(), + isNull(), isNull(), anyLong(), anyLong())).thenAnswer(invocation -> { + long page = invocation.getArgument(7); + long size = invocation.getArgument(8); + return ApiResponse.success(new PageResult<>(page == 1 ? List.of(pending) : List.of(), + page, size, 1, 1)); + }); + Candidate measured = withStatus(candidate(9L, 10L, 20L, 30L, 4), "WAIT_SPLIT", false); + CandidateUnit unit = new CandidateUnit(null, 9L, 10L, null, 10L); + when(repository.globalCandidateUnits(any(), anySet())).thenAnswer(invocation -> { + InboundCandidateQuery requested = invocation.getArgument(0); + return new PageResult<>(requested.page() == 1 ? List.of(unit) : List.of(), + requested.page(), requested.size(), 1, 1); + }); + when(repository.globalCandidatesByUnits(List.of(unit))).thenReturn(List.of(measured)); + + var result = service.inboundCandidates(query); + + assertThat(result.total()).isEqualTo(2); + assertThat(result.records()).extracting(InboundCandidate::orderStatusSnapshot) + .containsExactly("PENDING_REVIEW", "WAIT_SPLIT"); + assertThat(result.records()).extracting(InboundCandidate::canAssign) + .containsExactly(true, true); + ArgumentCaptor firstlegQueries = + ArgumentCaptor.forClass(InboundCandidateQuery.class); + verify(repository, atLeastOnce()).globalCandidateUnits(firstlegQueries.capture(), anySet()); + assertThat(firstlegQueries.getAllValues()).allSatisfy(requested -> + assertThat(requested.orderStatuses()).containsExactly( + CandidateOrderStatus.WAIT_MEASURE, CandidateOrderStatus.WAIT_SPLIT, + CandidateOrderStatus.LOADING)); + } + + @Test + void statusDoesNotBlockAssignmentButAnActiveContainerOccupationDoes() { + InboundCandidateQuery query = new InboundCandidateQuery(List.of("EXX"), null, null, null, + null, null, List.of(CandidateOrderStatus.WAIT_MEASURE, CandidateOrderStatus.LOADING), 1, 20); + Candidate waiting = withStatus(candidate(9L, 10L, 20L, 30L, 4), "WAIT_MEASURE", false); + Candidate loading = withStatus(candidate(19L, 11L, 21L, 31L, 0), "LOADING", true); + List units = List.of(new CandidateUnit(null, 9L, 10L, null, 10L), + new CandidateUnit(null, 19L, 11L, null, 11L)); + when(repository.globalCandidateUnits(eq(query), anySet())) + .thenReturn(new PageResult<>(units, 1, 20, 2, 1)); + when(repository.globalCandidatesByUnits(units)).thenReturn(List.of(waiting, loading)); + + var result = service.inboundCandidates(query); + + assertThat(result.records()).filteredOn(candidate -> "WAIT_MEASURE".equals(candidate.orderStatusSnapshot())) + .singleElement().satisfies(candidate -> assertThat(candidate.canAssign()).isTrue()); + assertThat(result.records()).filteredOn(candidate -> "LOADING".equals(candidate.orderStatusSnapshot())) + .singleElement().satisfies(candidate -> { + assertThat(candidate.canAssign()).isFalse(); + assertThat(candidate.blockReason()).isEqualTo("该入仓码已被有效柜次占用"); + }); + } + + @Test + void keepsAnOccupiedLoadingGroupAsOneNonAssignablePagingUnit() { + InboundCandidateQuery query = new InboundCandidateQuery(List.of("EXX"), null, null, null, + null, null, List.of(CandidateOrderStatus.LOADING), 1, 20); + Candidate first = withStatus(withGroup(candidate(9L, 10L, 20L, 30L, 0), 2, 10), + "LOADING", true); + Candidate second = withStatus(withGroup(candidate(19L, 11L, 21L, 31L, 0), 2, 10), + "LOADING", true); + CandidateUnit unit = new CandidateUnit(700L, null, null, null, 10L); + when(repository.globalCandidateUnits(eq(query), anySet())) + .thenReturn(new PageResult<>(List.of(unit), 1, 20, 1, 1)); + when(repository.globalCandidatesByUnits(List.of(unit))).thenReturn(List.of(first, second)); + + var result = service.inboundCandidates(query); + + assertThat(result.records()).singleElement().satisfies(candidate -> { + assertThat(candidate.coLoadGroupId()).isEqualTo(700L); + assertThat(candidate.groupMembers()).hasSize(2); + assertThat(candidate.canAssign()).isFalse(); + assertThat(candidate.orderStatusSnapshot()).isEqualTo("LOADING"); + }); + } + @Test void pagesPendingReviewOrdersFromTheOrderOwnedReadModelAsAssignableRows() { InboundCandidateQuery query = new InboundCandidateQuery( List.of("EXX"), 193000000000200002L, null, "EXXHK2609020361", LocalDate.parse("2026-09-02"), LocalDate.parse("2026-09-02"), - CandidateOrderStatus.PENDING_REVIEW, 1, 20); + List.of(CandidateOrderStatus.PENDING_REVIEW), 1, 20); var row = new PendingReviewOrderClient.Row(2095052002489335810L, "FL-361", "EXXHK2609020361", 2092797167699816450L, "客户", 193000000000200002L, "EXX_TRUCK", "EXX海卡", 100, LocalDateTime.parse("2026-09-02T15:31:36"), @@ -234,6 +323,7 @@ class SmartLoadingServiceTest { assertThat(candidate.inboundId()).isNull(); assertThat(candidate.inboundCode()).isEqualTo("EXXHK2609020361"); assertThat(candidate.orderStatusSnapshot()).isEqualTo("PENDING_REVIEW"); + assertThat(candidate.canAssign()).isTrue(); assertThat(candidate.blockReason()).isNull(); assertThat(candidate.availablePackageCount()).isEqualTo(100); }); @@ -290,11 +380,55 @@ class SmartLoadingServiceTest { verify(loadingModelBridge).bindIncrementalAllocation(1L, customerId, 10L, 7L, "u", "pending-1"); } + @Test + void assignsWaitMeasureInboundUsingDeclaredFactsWithoutTreatingStatusAsAGate() { + long customerId = 9L; + long inboundId = 10L; + long orderId = 30L; + InboundOrderEntity projection = new InboundOrderEntity(); + projection.setId(inboundId); + projection.setTenantId(customerId); + projection.setOrderId(orderId); + projection.setInboundCode("I10"); + projection.setWarehouseId(100L); + projection.setChannelCode("FBA"); + projection.setProcessStatus("WAIT_MEASURE"); + var snapshot = new com.baiyue.firstleg.dto.OrderApprovedInboundCommand( + customerId, orderId, "O30", "I10", customerId, "客户", 100L, "义乌仓", + null, null, null, "FIRST_LEG", "FBA", "FBA渠道", null, null, null, + null, null, false, "FBA", 200L, "FBA1", "FBA仓", null, null, null, 5); + var label = new OrderCargoClient.CargoLabelBinding(20L, orderId, 1, "货物", 5, + null, null, null); + var cargo = new OrderCargoClient.CargoBinding(20L, orderId, 1, "货物", 5, + new BigDecimal("50"), new BigDecimal("2.5")); + when(repository.inbound(inboundId)).thenReturn(projection); + when(repository.inboundForUpdate(customerId, inboundId)).thenReturn(projection); + when(repository.plan(1L)).thenReturn(plan("EDITING", 0), plan("EDITING", 1)); + when(repository.booking(99L)).thenReturn(booking()); + when(repository.items(1L)).thenReturn(List.of()); + when(repository.touch(1L, 0, 7L, "u")).thenReturn(1); + when(cargoClient.inboundSnapshot(anyString(), eq(customerId), eq(orderId))) + .thenReturn(ApiResponse.success(snapshot)); + when(cargoClient.listForCartonLabels(anyString(), eq(customerId), eq(orderId))) + .thenReturn(ApiResponse.success(List.of(label))); + when(cargoClient.detail(anyString(), eq(customerId), eq(orderId), eq(20L))) + .thenReturn(ApiResponse.success(cargo)); + + Plan result = service.assignInbound(1L, + new AssignInboundRequest(inboundId, 5, 0, "wait-measure-1"), 7L, "u"); + + assertThat(result.version()).isEqualTo(1); + verify(repository).insert(any(LoadingPlanItemEntity.class)); + verify(splitPreloadService).ensurePendingForPreAllocation(customerId, inboundId, 7L, "u"); + verify(loadingModelBridge).bindIncrementalAllocation(1L, customerId, inboundId, + 7L, "u", "wait-measure-1"); + } + @Test void failsClosedWhenPendingReviewOrderSourceIsUnavailable() { InboundCandidateQuery query = new InboundCandidateQuery( List.of("EXX"), null, null, null, null, null, - CandidateOrderStatus.PENDING_REVIEW, 1, 20); + List.of(CandidateOrderStatus.PENDING_REVIEW), 1, 20); when(pendingReviewOrders.page(anyString(), anyList(), isNull(), isNull(), isNull(), isNull(), isNull(), eq(1L), eq(20L))).thenThrow(new RuntimeException("offline")); @@ -310,7 +444,7 @@ class SmartLoadingServiceTest { 1L, "LP-1", "EDITING", 2); WorkbenchContainerQuery query = new WorkbenchContainerQuery(List.of("MATSON_CLX"), 100L, 9L, "IN-10", LocalDate.parse("2026-09-01"), LocalDate.parse("2026-09-30"), - CandidateOrderStatus.WAIT_SPLIT, 1, 20); + 1, 20); when(repository.workbenchContainers(eq(query), any())).thenReturn( new com.baiyue.common.core.api.PageResult<>(List.of(container), 1, 20, 1, 1)); @@ -332,7 +466,7 @@ class SmartLoadingServiceTest { "MATSON_CLX_TRUCK", "美森正班海卡"), "2026-09-10T09:00:00"), 2, 10); InboundCandidateQuery query = new InboundCandidateQuery( List.of("MATSON_CLX"), 100L, null, null, LocalDate.parse("2026-09-01"), - LocalDate.parse("2026-09-01"), null, 1, 1); + LocalDate.parse("2026-09-01"), List.of(CandidateOrderStatus.WAIT_SPLIT), 1, 1); CandidateUnit unit = new CandidateUnit(700L, null, null, LocalDateTime.parse("2026-09-01T09:00:00"), 10L); when(repository.globalCandidateUnits(eq(query), anySet())) @@ -353,7 +487,8 @@ class SmartLoadingServiceTest { @Test void excludesIncompleteColoadGroupInsteadOfPublishingPartialMember() { InboundCandidateQuery query = new InboundCandidateQuery( - List.of("MATSON_CLX"), 100L, null, null, null, null, null, 1, 20); + List.of("MATSON_CLX"), 100L, null, null, null, null, + List.of(CandidateOrderStatus.WAIT_SPLIT), 1, 20); when(repository.globalCandidateUnits(eq(query), anySet())) .thenReturn(new PageResult<>(List.of(), 1, 20, 0, 0)); @@ -582,7 +717,7 @@ class SmartLoadingServiceTest { GroupSnapshot group = group("ACTIVE", null, new Member(9L, 31L, 11L, "IN-11", 4), new Member(9L, 32L, 12L, "IN-12", 4)); ContainerBookingEntity small = booking(); - small.setCapacityCbm(new BigDecimal("3")); + small.setCapacityCbm(new BigDecimal("2.6")); when(repository.plan(1L)).thenReturn(plan("EDITING", 0)); when(repository.planByBooking(99L)).thenReturn(plan("EDITING", 0)); when(repository.booking(99L)).thenReturn(small); @@ -597,7 +732,7 @@ class SmartLoadingServiceTest { 11L, 0, "manual-group-too-large"), 7L, "u"), BizException.class); assertThat(error.getResultCode()).isEqualTo(ResultCode.VALIDATION_FAILED); - assertThat(error).hasMessageContaining("110%上限"); + assertThat(error).hasMessageContaining("150%上限"); verify(coloadGroups, never()).lockWholeGroupForAssignment(anyLong(), anyLong(), anyLong(), anyString(), anyLong(), anyString()); } @@ -800,32 +935,32 @@ class SmartLoadingServiceTest { } @Test - void allowsVolumeAndWeightWithinOneHundredTenPercent() { + void allowsVolumeAndWeightWithinOneHundredFiftyPercent() { stubAssignment(); ContainerBookingEntity tolerant = booking(); - tolerant.setCapacityCbm(new BigDecimal("0.91")); - tolerant.setMaxWeightKg(new BigDecimal("3.64")); + tolerant.setCapacityCbm(new BigDecimal("0.6666667")); + tolerant.setMaxWeightKg(new BigDecimal("2.6666667")); when(repository.booking(99L)).thenReturn(tolerant); - service.assign(1, new AssignRequest(10L, 20L, 2, 0, "assign-110-ok"), 7, "u"); + service.assign(1, new AssignRequest(10L, 20L, 2, 0, "assign-150-ok"), 7, "u"); verify(splitPreloadService).ensurePendingForLoadingAllocation(9L, 10L, 7L, "u"); verify(repository).touch(1, 0, 7, "u"); } @Test - void rejectsVolumeOrWeightAboveOneHundredTenPercent() { + void rejectsVolumeOrWeightAboveOneHundredFiftyPercent() { stubAssignment(); ContainerBookingEntity exceeded = booking(); - exceeded.setCapacityCbm(new BigDecimal("0.90")); - exceeded.setMaxWeightKg(new BigDecimal("3.63")); + exceeded.setCapacityCbm(new BigDecimal("0.6666")); + exceeded.setMaxWeightKg(new BigDecimal("2.6666")); when(repository.booking(99L)).thenReturn(exceeded); BizException error = catchThrowableOfType(() -> service.assign(1, - new AssignRequest(10L, 20L, 2, 0, "assign-110-exceeded"), 7, "u"), BizException.class); + new AssignRequest(10L, 20L, 2, 0, "assign-150-exceeded"), 7, "u"), BizException.class); assertThat(error.getResultCode()).isEqualTo(ResultCode.VALIDATION_FAILED); - assertThat(error.getMessage()).contains("110%"); + assertThat(error.getMessage()).contains("150%"); verify(repository, never()).touch(anyLong(), anyInt(), anyLong(), any()); } @@ -1363,6 +1498,16 @@ class SmartLoadingServiceTest { false, null, value.orderStatusSnapshot(), value.expectedArrivalAt()); } + private static Candidate withStatus(Candidate value, String status, boolean locked) { + return new Candidate(value.accountId(), value.inboundId(), value.inboundDetailId(), value.orderId(), + value.orderNo(), value.inboundCode(), value.warehouseId(), value.channelCode(), value.channelName(), + value.destinationWarehouseId(), value.destinationWarehouseCode(), value.destinationWarehouseName(), + value.customerName(), value.goodsName(), value.availablePackageCount(), value.unitGrossWeightKg(), + value.unitNetWeightKg(), value.unitVolumeCbm(), value.coLoadGroupId(), value.groupNo(), + value.memberCount(), value.groupTotalBoxes(), locked, value.blockReason(), status, + value.expectedArrivalAt()); + } + private static ChannelRow channel(String channelCode, String channelName) { ChannelRow value = new ChannelRow(); value.setChannelCode(channelCode); value.setChannelName(channelName); From b8826c3e92f6079aa6bd8704ef6fba953cdd58d3 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Thu, 3 Sep 2026 21:48:46 +0800 Subject: [PATCH 04/10] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../firstleg/service/SmartLoadingServiceTest.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java index 88b94e1bb..b72a94730 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java @@ -938,11 +938,11 @@ class SmartLoadingServiceTest { void allowsVolumeAndWeightWithinOneHundredFiftyPercent() { stubAssignment(); ContainerBookingEntity tolerant = booking(); - tolerant.setCapacityCbm(new BigDecimal("0.6666667")); - tolerant.setMaxWeightKg(new BigDecimal("2.6666667")); + tolerant.setCapacityCbm(new BigDecimal("1")); + tolerant.setMaxWeightKg(new BigDecimal("4")); when(repository.booking(99L)).thenReturn(tolerant); - service.assign(1, new AssignRequest(10L, 20L, 2, 0, "assign-150-ok"), 7, "u"); + service.assign(1, new AssignRequest(10L, 20L, 3, 0, "assign-150-ok"), 7, "u"); verify(splitPreloadService).ensurePendingForLoadingAllocation(9L, 10L, 7L, "u"); verify(repository).touch(1, 0, 7, "u"); @@ -952,12 +952,12 @@ class SmartLoadingServiceTest { void rejectsVolumeOrWeightAboveOneHundredFiftyPercent() { stubAssignment(); ContainerBookingEntity exceeded = booking(); - exceeded.setCapacityCbm(new BigDecimal("0.6666")); - exceeded.setMaxWeightKg(new BigDecimal("2.6666")); + exceeded.setCapacityCbm(new BigDecimal("0.9999")); + exceeded.setMaxWeightKg(new BigDecimal("3.9999")); when(repository.booking(99L)).thenReturn(exceeded); BizException error = catchThrowableOfType(() -> service.assign(1, - new AssignRequest(10L, 20L, 2, 0, "assign-150-exceeded"), 7, "u"), BizException.class); + new AssignRequest(10L, 20L, 3, 0, "assign-150-exceeded"), 7, "u"), BizException.class); assertThat(error.getResultCode()).isEqualTo(ResultCode.VALIDATION_FAILED); assertThat(error.getMessage()).contains("150%"); From d3eaa901f5308abdf0782376386c30d07315c437 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Thu, 3 Sep 2026 21:50:21 +0800 Subject: [PATCH 05/10] =?UTF-8?q?=E4=BC=98=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../com/baiyue/firstleg/service/SmartLoadingServiceTest.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java index b72a94730..7dd9fda2c 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java @@ -639,7 +639,7 @@ class SmartLoadingServiceTest { new Member(9L, 30L, 10L, "IN-10", 5), new Member(19L, 31L, 11L, "IN-11", 5), new Member(29L, 32L, 12L, "IN-12", 5)); ContainerBookingEntity small = booking(); - small.setCapacityCbm(new BigDecimal("5")); + small.setCapacityCbm(new BigDecimal("4.9")); LoadingPlanEntity plan = plan("EDITING", 0); when(repository.plan(1L)).thenReturn(plan); when(repository.planByBooking(99L)).thenReturn(plan); @@ -665,7 +665,7 @@ class SmartLoadingServiceTest { GroupSnapshot group = group("ACTIVE", null, new Member(9L, 31L, 11L, "IN-11", 4), new Member(9L, 32L, 12L, "IN-12", 4)); ContainerBookingEntity small = booking(); - small.setCapacityCbm(new BigDecimal("5")); + small.setCapacityCbm(new BigDecimal("3.9")); AtomicInteger version = new AtomicInteger(); List saved = new ArrayList<>(); when(repository.plan(1L)).thenAnswer(invocation -> plan("EDITING", version.get())); From 65b29adb01e3b54762c61e0e0688fcd072ee2d1c Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Thu, 3 Sep 2026 22:05:27 +0800 Subject: [PATCH 06/10] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E6=99=BA=E8=83=BD?= =?UTF-8?q?=E8=A3=85=E6=9F=9C=E6=97=A5=E6=9C=9F=E7=AD=9B=E9=80=89=E8=B0=83?= =?UTF-8?q?=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../baiyue/firstleg/client/PendingReviewOrderClient.java | 5 ++--- .../com/baiyue/firstleg/service/SmartLoadingService.java | 6 +++++- .../baiyue/firstleg/service/SmartLoadingServiceTest.java | 4 ++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/client/PendingReviewOrderClient.java b/firstleg/src/main/java/com/baiyue/firstleg/client/PendingReviewOrderClient.java index 0a5d4090f..cc453bef8 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/client/PendingReviewOrderClient.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/client/PendingReviewOrderClient.java @@ -7,7 +7,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; -import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List; @@ -22,8 +21,8 @@ public interface PendingReviewOrderClient { @RequestParam(required = false) Long warehouseId, @RequestParam(required = false) Long customerId, @RequestParam(required = false) String inboundCode, - @RequestParam(required = false) LocalDate createdStart, - @RequestParam(required = false) LocalDate createdEnd, + @RequestParam(required = false) String createdStart, + @RequestParam(required = false) String createdEnd, @RequestParam long page, @RequestParam long size); diff --git a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java index fed94e1cc..2323c5a56 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/service/SmartLoadingService.java @@ -183,7 +183,7 @@ public class SmartLoadingService { ApiResponse> response; try { response = pendingReviewOrders.page(internalToken, List.copyOf(actualChannels), query.warehouseId(), - query.customerId(), query.inboundCode(), query.createdStart(), query.createdEnd(), + query.customerId(), query.inboundCode(), isoDate(query.createdStart()), isoDate(query.createdEnd()), page, size); } catch (RuntimeException exception) { throw new BizException(ResultCode.SERVICE_UNAVAILABLE, "待审核订单服务暂时不可用"); @@ -201,6 +201,10 @@ public class SmartLoadingService { return new PageResult<>(records, source.page(), source.size(), source.total(), source.pages()); } + private static String isoDate(java.time.LocalDate value) { + return value == null ? null : value.toString(); + } + private List pendingReviewRange(InboundCandidateQuery query, Set channels, long offset, long limit) { return pageRange(offset, limit, (page, size) -> pendingReviewCandidates(query, channels, page, size)); diff --git a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java index 7dd9fda2c..7646e66ea 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/service/SmartLoadingServiceTest.java @@ -312,8 +312,8 @@ class SmartLoadingServiceTest { "EXX_TRUCK", "EXX海卡", 100, LocalDateTime.parse("2026-09-02T15:31:36"), "PENDING_REVIEW"); when(pendingReviewOrders.page(anyString(), anyList(), eq(193000000000200002L), - isNull(), eq("EXXHK2609020361"), eq(LocalDate.parse("2026-09-02")), - eq(LocalDate.parse("2026-09-02")), eq(1L), eq(20L))) + isNull(), eq("EXXHK2609020361"), eq("2026-09-02"), + eq("2026-09-02"), eq(1L), eq(20L))) .thenReturn(ApiResponse.success(new PageResult<>(List.of(row), 1, 20, 1, 1))); var result = service.inboundCandidates(query); From ce3cd7e80fa9ed0f2e445f97d63c992eb1a32043 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Fri, 4 Sep 2026 00:33:07 +0800 Subject: [PATCH 07/10] fix(firstleg): preserve coload groups in filtered candidates --- .../mapper/SmartLoadingCandidateMapper.java | 36 +++--- ...artLoadingCandidateMapperContractTest.java | 12 +- .../admin-test-env-modules/coload-groups.mjs | 115 ++++++++++++------ .../inbound-measurement.mjs | 33 +++-- 4 files changed, 132 insertions(+), 64 deletions(-) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java index 964d961f6..111cc787b 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java @@ -113,22 +113,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba o.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED', 'WAIT_PRICING','FEE_CONFIRMING','INBOUNDING','WAIT_SPLIT','LOADING') ) - - AND ( - - - o.process_status IN ('WAIT_MEASURE','MEASURING','MEASURE_PENDING','MEASURE_REJECTED','WAIT_PRICING','FEE_CONFIRMING','INBOUNDING') - o.process_status='WAIT_SPLIT' - o.process_status='LOADING' - 1=0 - - - ) - - AND o.tenant_id=#{query.customerId} - AND LOWER(o.inbound_code) LIKE CONCAT('%',LOWER(#{query.inboundCode}),'%') - AND o.created_at>=#{query.createdStart} - AND o.created_at<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY) ) eligible LEFT JOIN fl_coload_group_member current_member ON current_member.tenant_id=eligible.accountId AND current_member.inbound_id=eligible.inboundId @@ -143,6 +127,26 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba COUNT(*)=(SELECT COUNT(*) FROM fl_coload_group_member group_member_count WHERE group_member_count.group_id=current_group.id AND group_member_count.active_flag=1) )) + + AND MAX(CASE WHEN + + + eligible.candidateStatus='WAIT_MEASURE' + eligible.candidateStatus='WAIT_SPLIT' + eligible.candidateStatus='LOADING' + 1=0 + + + THEN 1 ELSE 0 END)=1 + + + AND MAX(CASE WHEN eligible.accountId=#{query.customerId} THEN 1 ELSE 0 END)=1 + + + AND MAX(CASE WHEN LOWER(eligible.inboundCode) LIKE CONCAT('%',LOWER(#{query.inboundCode}),'%') THEN 1 ELSE 0 END)=1 + + AND MIN(eligible.createdAt)>=#{query.createdStart} + AND MIN(eligible.createdAt)<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY) ORDER BY sortArrivalAt IS NULL,sortArrivalAt,sortInboundId """) diff --git a/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java b/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java index a03e09762..447ee11f6 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/repository/SmartLoadingCandidateMapperContractTest.java @@ -97,8 +97,8 @@ class SmartLoadingCandidateMapperContractTest { assertThat(sql) .contains("o.created_at createdAt") - .contains("o.created_at>=#{query.createdStart}") - .contains("o.created_at<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY)") + .contains("MIN(eligible.createdAt)>=#{query.createdStart}") + .contains("MIN(eligible.createdAt)<DATE_ADD(#{query.createdEnd},INTERVAL 1 DAY)") .doesNotContain("query.expectedArrivalStart", "query.expectedArrivalEnd"); } @@ -136,9 +136,11 @@ class SmartLoadingCandidateMapperContractTest { .getBoundSql(Map.of("query", query, "actualChannels", Set.of("MATSON_CLX_TRUCK"))).getSql(); assertThat(renderedUnits) .contains("o.channel_code IN") - .contains("o.created_at>=", "o.created_at=", "MIN(eligible.createdAt) item?.evidenceType === evidenceType + && item?.status !== 'VOID') + if (!evidenceItem?.fileId) return false } return true } @@ -508,15 +535,34 @@ export async function run(context) { let planId = id(plan?.id) if (!planId) return + const candidateStartedAt = Date.now() const candidateResponse = await context.request('GET', - `/api/platform/v1/first-leg/smart-loading/inbound-candidates?bookingId=${encodeURIComponent(bookingId)}&warehouseId=${encodeURIComponent(first.warehouseId)}`) - const candidates = context.apiSuccess(MODULE, '读取整票智能装柜候选', candidateResponse, - evidence(candidateResponse), OPTIONS) || [] - const groupedCandidates = candidates.filter((item) => id(item?.coLoadGroupId) === groupId) - context.assert(MODULE, '每个组成员候选携带相同整组事实', candidateResponse, - groupedCandidates.length === 2 && groupedCandidates.every((item) => Number(item?.memberCount) === 2 - && Number(item?.groupTotalBoxes) === first.packages + second.packages && item?.locked !== true), - `count=${groupedCandidates.length}, groupTotal=${first.packages + second.packages}`, OPTIONS) + `/api/platform/v1/first-leg/smart-loading/inbound-candidates?channelGroupCodes=${encodeURIComponent(channelGroup(first.channelCode))}&warehouseId=${encodeURIComponent(first.warehouseId)}&page=1&size=200`) + const candidateElapsedMs = Date.now() - candidateStartedAt + const candidatePage = context.apiSuccess(MODULE, '读取整票智能装柜候选', candidateResponse, + evidence(candidateResponse), OPTIONS) + const candidates = candidatePage?.records || [] + context.assert(MODULE, '全局候选200条分页查询性能受控', candidateResponse, + candidateElapsedMs < 5000 && Number(candidatePage?.page) === 1 && Number(candidatePage?.size) === 200, + `elapsedMs=${candidateElapsedMs}, total=${candidatePage?.total ?? 'missing'}`, OPTIONS) + + const today = new Date().toISOString().slice(0, 10) + const filteredResponse = await context.request('GET', + `${SMART}/inbound-candidates?channelGroupCodes=${encodeURIComponent(channelGroup(first.channelCode))}` + + `&warehouseId=${encodeURIComponent(first.warehouseId)}&inboundCode=${encodeURIComponent(first.inboundCode)}` + + `&createdStart=${today}&createdEnd=${today}&orderStatuses=PENDING_REVIEW&orderStatuses=WAIT_SPLIT&page=1&size=20`) + const filteredPage = context.apiSuccess(MODULE, '按创建日期和多状态查询同柜组候选', filteredResponse, + evidence(filteredResponse), OPTIONS) + const filteredGroup = (filteredPage?.records || []).find((item) => id(item?.coLoadGroupId) === groupId) + context.assert(MODULE, '同柜组作为一个分页单位携带全部成员事实', filteredResponse, + Number(filteredPage?.records?.length) === 1 && Number(filteredGroup?.memberCount) === 2 + && Number(filteredGroup?.groupTotalBoxes) === first.packages + second.packages + && filteredGroup?.locked !== true && filteredGroup?.groupMembers?.length === 2, + `units=${filteredPage?.records?.length ?? 0}, members=${filteredGroup?.groupMembers?.length ?? 0}, groupTotal=${first.packages + second.packages}`, OPTIONS) + context.assert(MODULE, '多状态仅用于搜索且命中整组不拆页', filteredResponse, + filteredGroup?.orderStatusSnapshot === 'WAIT_SPLIT' && filteredGroup?.groupMembers?.length === 2, + `date=${today}, status=${filteredGroup?.orderStatusSnapshot || 'missing'}, members=${filteredGroup?.groupMembers?.length ?? 0}`, + OPTIONS) let isolatedCandidates = candidates const competing = [...new Set(isolatedCandidates.filter((item) => item?.locked !== true) @@ -524,14 +570,13 @@ export async function run(context) { let isolatedCandidateResponse = candidateResponse if (competing.length > 0) { isolatedCandidateResponse = await context.request('GET', - `${SMART}/inbound-candidates?bookingId=${encodeURIComponent(bookingId)}&warehouseId=${encodeURIComponent(first.warehouseId)}`) - isolatedCandidates = context.apiSuccess(MODULE, '清理后重新隔离读取目标组候选', isolatedCandidateResponse, - evidence(isolatedCandidateResponse), OPTIONS) || [] + `${SMART}/inbound-candidates?channelGroupCodes=${encodeURIComponent(channelGroup(first.channelCode))}&warehouseId=${encodeURIComponent(first.warehouseId)}&page=1&size=200`) + const isolatedCandidatePage = context.apiSuccess(MODULE, '清理后重新隔离读取目标组候选', isolatedCandidateResponse, + evidence(isolatedCandidateResponse), OPTIONS) + isolatedCandidates = isolatedCandidatePage?.records || [] } - const candidateGroupIds = [...new Set(isolatedCandidates.filter((item) => item?.locked !== true) - .map((item) => id(item?.coLoadGroupId)).filter(Boolean))] - const targetCandidateInbounds = isolatedCandidates.filter((item) => id(item?.coLoadGroupId) === groupId) - .map((item) => id(item?.inboundId)).sort() + const candidateGroupIds = filteredGroup ? [id(filteredGroup.coLoadGroupId)] : [] + const targetCandidateInbounds = (filteredGroup?.groupMembers || []).map((item) => id(item?.inboundId)).sort() context.assert(MODULE, '推荐候选包含当前目标同柜组且成员身份精确', isolatedCandidateResponse, candidateGroupIds.includes(groupId) && JSON.stringify(targetCandidateInbounds) === JSON.stringify([first.inboundId, second.inboundId].sort()), @@ -539,8 +584,8 @@ export async function run(context) { const allCandidateVolume = isolatedCandidates .reduce((sum, item) => sum + Number(item?.availableVolumeCbm || 0), 0) context.assert(MODULE, '推荐候选总量形成容量竞争场景', isolatedCandidateResponse, - allCandidateVolume > 33 * 1.1, - `targetGroupId=${groupId}, candidateVolume=${allCandidateVolume}, limit=${33 * 1.1}`, OPTIONS) + allCandidateVolume > 33 * 1.5, + `targetGroupId=${groupId}, candidateVolume=${allCandidateVolume}, limit=${33 * 1.5}`, OPTIONS) const beforeRecommend = plan const recommendResponse = await context.request('POST', `/api/platform/v1/first-leg/smart-loading/plans/${encodeURIComponent(planId)}/recommend`, { @@ -827,7 +872,7 @@ export async function run(context) { fullBatch?.workflowStatus === 'AWAITING_REVIEW' && fullBatch?.items?.every((item) => Number(item?.pickedPackageCount) === Number(item?.plannedPackageCount)), `workflow=${fullBatch?.workflowStatus || 'missing'}, items=${fullBatch?.items?.length ?? 0}`, OPTIONS) - if (!await uploadCompletionEvidence(context, third, 'coload-full')) return + if (!await uploadCompletionEvidence(context, fullPda.taskId, third.warehouseId, 'coload-full')) return const fullCompleteResponse = await context.request('POST', `${PDA}/tasks/${fullPda.taskId}/complete`, { expectedTaskVersion: Number(fullBatch?.version), operationId: `${context.marker}-coload-full-complete`.slice(0, 128), remark: context.marker, @@ -870,7 +915,7 @@ export async function run(context) { }, undefined, { 'Idempotency-Key': `${context.marker}-normal-batch`.slice(0, 128) }) const normalBatch = context.apiSuccess(MODULE, '未成组普通单PDA批量拣货不回归', normalBatchResponse, evidence(normalBatchResponse), OPTIONS) - if (!await uploadCompletionEvidence(context, seventh, 'normal-split')) return + if (!await uploadCompletionEvidence(context, normalPda.taskId, seventh.warehouseId, 'normal-split')) return const normalCompleteResponse = await context.request('POST', `${PDA}/tasks/${normalPda.taskId}/complete`, { expectedTaskVersion: Number(normalBatch?.version), operationId: `${context.marker}-normal-complete`.slice(0, 128), remark: context.marker, diff --git a/scripts/admin-test-env-modules/inbound-measurement.mjs b/scripts/admin-test-env-modules/inbound-measurement.mjs index 856c8594e..db9ca72ab 100644 --- a/scripts/admin-test-env-modules/inbound-measurement.mjs +++ b/scripts/admin-test-env-modules/inbound-measurement.mjs @@ -415,20 +415,31 @@ export async function run(context) { let measuredResponse = await context.request('GET', measurementPath) let measured = context.apiSuccess(MODULE, '回查覆盖后的尺寸与体积结果', measuredResponse, '', OPTIONS) let measuredItem = measured?.items?.find((item) => asId(item.id) === asId(firstScan.itemId)) - const weightedOuter = measurementProfile?.outer || { length: 64, width: 54, height: 54 } - const unitVolume = halfUp( - weightedOuter.length * weightedOuter.width * weightedOuter.height / 1_000_000, 3) + const weightedOuter = { + length: Number(measuredItem?.calculatedOuterLengthCm ?? measuredItem?.outerLengthCm), + width: Number(measuredItem?.calculatedOuterWidthCm ?? measuredItem?.outerWidthCm), + height: Number(measuredItem?.calculatedOuterHeightCm ?? measuredItem?.outerHeightCm), + } + const calculatedVolume = weightedOuter.length * weightedOuter.width * weightedOuter.height / 1_000_000 + const usesMatchedAddRule = String(measuredItem?.calculationRuleVersion || '').startsWith('CUSTOMER_DIMENSION_') + const unitVolume = usesMatchedAddRule ? halfUp(calculatedVolume, 3) : ceiling(calculatedVolume, 4) const totalVolume = unitVolume * originalPackageCount const volumeWeight = ceiling(totalVolume * 167, 3) + // Device scans retain the measured girth while the weighted dimensions are + // used for volume. The subsequent manual draft explicitly keeps ADD so the + // same customer dimension rule remains frozen for review. const girth = ceiling(replacement.length + 2 * (replacement.width + replacement.height), 3) context.assert(MODULE, '覆盖尺寸、箱数和服务端体积公式正确', measuredResponse, measuredItem && closeTo(measuredItem.lengthCm, replacement.length) && closeTo(measuredItem.widthCm, replacement.width) && closeTo(measuredItem.heightCm, replacement.height) && measuredItem.scannedShipmentId === replacementShipmentId && Number(measuredItem.confirmedPackageCount) === originalPackageCount - && closeTo(measuredItem.outerLengthCm, weightedOuter.length) - && closeTo(measuredItem.outerWidthCm, weightedOuter.width) - && closeTo(measuredItem.outerHeightCm, weightedOuter.height) + && closeTo(measuredItem.calculatedOuterLengthCm, weightedOuter.length) + && closeTo(measuredItem.calculatedOuterWidthCm, weightedOuter.width) + && closeTo(measuredItem.calculatedOuterHeightCm, weightedOuter.height) + && (measuredItem.coefficientMode == null + || ['ACTUAL', 'ADD', 'MULTIPLY'].includes(measuredItem.coefficientMode)) + && Boolean(measuredItem.calculationRuleVersion) && closeTo(measuredItem.unitVolumeCbm, unitVolume) && closeTo(measuredItem.totalVolumeCbm, totalVolume) && closeTo(measuredItem.volumeWeightKg, volumeWeight) && closeTo(measuredItem.girthCm, girth) && closeTo(measured.actualVolumeCbm, totalVolume) && closeTo(measured.volumeWeightKg, volumeWeight), @@ -532,7 +543,10 @@ export async function run(context) { intelligentImageFileId: item.intelligentImageFileId, overLimitWarning: item.overLimitWarning ?? null, outerLengthCm: item.outerLengthCm ?? null, outerWidthCm: item.outerWidthCm ?? null, - outerHeightCm: item.outerHeightCm ?? null, remark: context.marker, + outerHeightCm: item.outerHeightCm ?? null, + coefficientMode: String(item.calculationRuleVersion || '').startsWith('CUSTOMER_DIMENSION_') + ? 'ADD' : item.coefficientMode ?? null, + remark: context.marker, })) : [{ inboundDetailId, itemNo: measuredItem.itemNo, @@ -541,7 +555,10 @@ export async function run(context) { intelligentImageFileId: measuredItem.intelligentImageFileId, overLimitWarning: measuredItem.overLimitWarning ?? null, outerLengthCm: measuredItem.outerLengthCm ?? null, outerWidthCm: measuredItem.outerWidthCm ?? null, - outerHeightCm: measuredItem.outerHeightCm ?? null, remark: context.marker, + outerHeightCm: measuredItem.outerHeightCm ?? null, + coefficientMode: String(measuredItem.calculationRuleVersion || '').startsWith('CUSTOMER_DIMENSION_') + ? 'ADD' : measuredItem.coefficientMode ?? null, + remark: context.marker, }] const draftPayload = { measurementId: measured.measurementId, version: Number(measured.version), From b5be60140e86b7b56a2453f6be249dc2f0c63405 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Fri, 4 Sep 2026 00:41:34 +0800 Subject: [PATCH 08/10] test(firstleg): align full acceptance contracts --- .../src/main/resources/openapi/fba-pricing-v1.yaml | 2 ++ .../CustomerDimensionConfigSqlContractTest.java | 2 +- .../firstleg/service/CartonMeasurementServiceTest.java | 10 +++++----- .../service/CustomerDimensionConfigServiceTest.java | 2 +- scripts/admin-test-env-modules/coload-groups.mjs | 7 ++++++- 5 files changed, 15 insertions(+), 8 deletions(-) diff --git a/firstleg/src/main/resources/openapi/fba-pricing-v1.yaml b/firstleg/src/main/resources/openapi/fba-pricing-v1.yaml index dd8dd9044..ef49a6865 100644 --- a/firstleg/src/main/resources/openapi/fba-pricing-v1.yaml +++ b/firstleg/src/main/resources/openapi/fba-pricing-v1.yaml @@ -300,6 +300,8 @@ components: feeStatus: {type: string, enum: [CALCULATED, CONFIRMED, SENT, SUPERSEDED]} inboundId: {type: string, pattern: '^[1-9][0-9]*$'} inboundCode: {type: string, nullable: true} + measurementId: {type: string, nullable: true} + measurementSource: {type: string, nullable: true} chargeRuleId: {type: string, nullable: true} ruleCode: {type: string, nullable: true} chargeRuleVersion: {type: integer, nullable: true} diff --git a/firstleg/src/test/java/com/baiyue/firstleg/repository/CustomerDimensionConfigSqlContractTest.java b/firstleg/src/test/java/com/baiyue/firstleg/repository/CustomerDimensionConfigSqlContractTest.java index 5811575cd..783615014 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/repository/CustomerDimensionConfigSqlContractTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/repository/CustomerDimensionConfigSqlContractTest.java @@ -35,7 +35,7 @@ class CustomerDimensionConfigSqlContractTest { .contains("inner_width_cm DECIMAL(9,3) NOT NULL") .contains("inner_height_cm DECIMAL(9,3) NOT NULL") .contains("edge_addition_cm DECIMAL(6,3) NOT NULL DEFAULT 2.000") - .contains("default_calculation_mode VARCHAR(16) NOT NULL DEFAULT 'ADD'") + .contains("default_calculation_mode VARCHAR(16) NOT NULL DEFAULT 'ACTUAL'") .contains("initialization_key VARCHAR(128) NOT NULL") .contains("created_by BIGINT UNSIGNED NOT NULL") .contains("updated_by BIGINT UNSIGNED NOT NULL") diff --git a/firstleg/src/test/java/com/baiyue/firstleg/service/CartonMeasurementServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/service/CartonMeasurementServiceTest.java index a70eee172..8f2183280 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/service/CartonMeasurementServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/service/CartonMeasurementServiceTest.java @@ -164,7 +164,7 @@ class CartonMeasurementServiceTest { } @Test - void scanOutsideConfiguredWeightingRulesKeepsImageAndUsesLargestTierAddition() { + void scanOutsideConfiguredWeightingRulesKeepsImageAndUsesActualDimensions() { InboundMeasurementEntity measurement = measurement(30001L, "RECEIVED", 0); when(repository.findItemByBoxCode(10001L, "RK-001#5-1")).thenReturn(null); when(repository.findLatestEditableMeasurement(10001L, 70001L)).thenReturn(measurement); @@ -182,11 +182,11 @@ class CartonMeasurementServiceTest { assertThat(result.created()).isTrue(); assertThat(insertedItem.get().getSourceImageFileId()).isEqualTo(99001L); assertThat(insertedItem.get().getLengthCm()).isEqualByComparingTo("60.100"); - assertThat(insertedItem.get().getOuterLengthCm()).isEqualByComparingTo("64.100"); - assertThat(insertedItem.get().getOuterWidthCm()).isEqualByComparingTo("54.100"); - assertThat(insertedItem.get().getOuterHeightCm()).isEqualByComparingTo("54.100"); + assertThat(insertedItem.get().getOuterLengthCm()).isEqualByComparingTo("60.100"); + assertThat(insertedItem.get().getOuterWidthCm()).isEqualByComparingTo("50.100"); + assertThat(insertedItem.get().getOuterHeightCm()).isEqualByComparingTo("50.100"); assertThat(insertedItem.get().getCalculationRuleVersion()) - .isEqualTo("CUSTOMER_DIMENSION_EXTRA_LARGE_V0"); + .isEqualTo("ACTUAL_DIMENSION_V1"); assertThat(insertedItem.get().getOverLimitWarning()).isNull(); verify(images, never()).delete(any(), any(Long.TYPE), any(Long.TYPE), any(Long.TYPE), any(Long.TYPE)); } diff --git a/firstleg/src/test/java/com/baiyue/firstleg/service/CustomerDimensionConfigServiceTest.java b/firstleg/src/test/java/com/baiyue/firstleg/service/CustomerDimensionConfigServiceTest.java index bd6179c64..48c30d1f4 100644 --- a/firstleg/src/test/java/com/baiyue/firstleg/service/CustomerDimensionConfigServiceTest.java +++ b/firstleg/src/test/java/com/baiyue/firstleg/service/CustomerDimensionConfigServiceTest.java @@ -206,7 +206,7 @@ class CustomerDimensionConfigServiceTest { value.setInnerWidthCm(type.defaultWidthCm()); value.setInnerHeightCm(type.defaultHeightCm()); value.setEdgeAdditionCm(new BigDecimal("2.000")); - value.setDefaultCalculationMode("ADD"); + value.setDefaultCalculationMode("ACTUAL"); value.setRemark(type.defaultRemark()); value.setVersion(0); value.setInitializationKey(initializationKey); diff --git a/scripts/admin-test-env-modules/coload-groups.mjs b/scripts/admin-test-env-modules/coload-groups.mjs index f3738ce96..0b06a21d6 100644 --- a/scripts/admin-test-env-modules/coload-groups.mjs +++ b/scripts/admin-test-env-modules/coload-groups.mjs @@ -546,7 +546,12 @@ export async function run(context) { candidateElapsedMs < 5000 && Number(candidatePage?.page) === 1 && Number(candidatePage?.size) === 200, `elapsedMs=${candidateElapsedMs}, total=${candidatePage?.total ?? 'missing'}`, OPTIONS) - const today = new Date().toISOString().slice(0, 10) + const today = new Intl.DateTimeFormat('en-CA', { + timeZone: 'Asia/Shanghai', + year: 'numeric', + month: '2-digit', + day: '2-digit' + }).format(new Date()) const filteredResponse = await context.request('GET', `${SMART}/inbound-candidates?channelGroupCodes=${encodeURIComponent(channelGroup(first.channelCode))}` + `&warehouseId=${encodeURIComponent(first.warehouseId)}&inboundCode=${encodeURIComponent(first.inboundCode)}` From edadca18c63c29d2307011b17d863e2d2a1036c9 Mon Sep 17 00:00:00 2001 From: ouyangxq <775153912@qq.com> Date: Fri, 4 Sep 2026 09:57:39 +0800 Subject: [PATCH 09/10] perf(firstleg): streamline smart loading assignments --- .../baiyue/firstleg/dto/SmartLoadingDtos.java | 1 + .../mapper/SmartLoadingCandidateMapper.java | 3 ++- .../firstleg/service/SmartLoadingService.java | 26 ++++++++++++------- .../main/resources/openapi/firstleg-v1.yaml | 4 ++- ...ormSmartLoadingControllerContractTest.java | 2 ++ .../service/SmartLoadingServiceTest.java | 11 ++++++++ 6 files changed, 36 insertions(+), 11 deletions(-) diff --git a/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java b/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java index 920750aed..39ea213a1 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/dto/SmartLoadingDtos.java @@ -46,6 +46,7 @@ public final class SmartLoadingDtos { private SmartLoadingDtos(){} } public record WorkbenchContainer(Long bookingId, String bookingNo, String cabinetNo, String containerNo, Long warehouseId, String warehouseName, String channelCode, String channelName, String containerType, + BigDecimal capacityCbm, BigDecimal maxWeightKg, Long planId, String planNo, String planStatus, Integer version) {} public record Candidate(Long accountId, Long inboundId, Long inboundDetailId, Long orderId, String orderNo, String inboundCode, Long warehouseId, String channelCode, String channelName, Long destinationWarehouseId, String destinationWarehouseCode, String destinationWarehouseName, String customerName, String goodsName, Integer availablePackageCount, diff --git a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java index 111cc787b..adecf0137 100644 --- a/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java +++ b/firstleg/src/main/java/com/baiyue/firstleg/mapper/SmartLoadingCandidateMapper.java @@ -252,7 +252,8 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.ba