Compare commits

...
Author SHA1 Message Date
ouyangxq 7c6a3af473 Add owned dispatch operations and validated pallet candidate guards 2026-10-20 17:36:19 +08:00
ouyangxq 03a7e66fab test(appointments): require canonical dispatch calendar permission 2026-10-20 17:02:20 +08:00
ouyangxq 6f31fa2131 fix(appointments): open canonical dispatch details from calendar 2026-10-20 16:36:22 +08:00
liuyihe da6b4685d7 Merge remote-tracking branch 'origin/test' into test
# Conflicts:
#	lastleg-service/src/main/java/com/baiyue/lastleg/dispatch/mapper/DispatchBolMapper.java
2026-10-20 14:35:19 +08:00
liuyihe a870b920fe 提交 2026-10-20 14:22:31 +08:00
139 changed files with 5680 additions and 313 deletions
+1 -1
View File
@@ -10,7 +10,7 @@
| warehouse-overseas-service | `baiyue_lastlag_warehouse` | 仅业务代码变化,无新增表或字段,无需 SQL;数据库名称保留正式的 lastlag 拼写 |
| 其他服务 | 各服务原数据库 | 本次比较范围内无 SQL 结构新增,无需 SQL |
已有尾程库使用:[V28 可重复执行 SQL](migrations/overseas/baiyue_lastleg/V28__merge_transfer_measurement_and_compact_numbers.sql)。文件显式指定 `USE baiyue_lastleg`,不访问其他服务数据库。
已有尾程库使用:[V28 可重复执行 SQL](migrations/overseas/baiyue_lastleg/V28__merge_transfer_measurement_and_compact_numbers.sql)。由单 schema 执行器选定 `baiyue_lastleg`,文件内不切库,不访问其他服务数据库。2026-10-20 按尚未执行候选的边界移除内部切库语句,其余结构内容不变;本次未执行此候选。
## 新表与字段
@@ -1,5 +1,5 @@
-- 仅为已初始化的头程库新增独立确认历史;不回填费用确认,不修改订单事实。
USE baiyue_firstleg;
-- 由单 schema 执行器选择 baiyue_firstleg,不在迁移内部切库。
-- 客户独立确认计费重,不回填既有费用确认。
CREATE TABLE IF NOT EXISTS fl_chargeable_weight_confirmation (
id BIGINT NOT NULL COMMENT '确认记录ID',
@@ -2,7 +2,7 @@
-- 目标:lastleg-service / baiyue_lastleg;前置:已有业务表及此前迁移。
-- 只调整结构,不回填、删除或重算业务数据;执行失败应停止,修复后可重跑。
SET NAMES utf8mb4;
USE baiyue_lastleg;
-- 由单 schema 执行器选择 baiyue_lastleg,不在迁移内部切库。
CREATE TABLE IF NOT EXISTS ll_compact_number_clock (
number_key VARCHAR(16) NOT NULL COMMENT '业务前缀和客户名称缩写',
@@ -11,7 +11,6 @@ CREATE TABLE IF NOT EXISTS ll_compact_number_clock (
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='海外业务短单号分配时钟';
-- 仓储转运逐箱测量与清点;仅增加字段,不修改业务数据。
USE baiyue_lastleg;
SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_warehouse_transfer_carton' AND column_name='length_cm'), 'SELECT 1', 'ALTER TABLE ll_warehouse_transfer_carton ADD COLUMN length_cm DECIMAL(12,2) NULL COMMENT ''箱子实测长度厘米'''));
PREPARE transfer_count_stmt FROM @ddl; EXECUTE transfer_count_stmt; DEALLOCATE PREPARE transfer_count_stmt;
SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_warehouse_transfer_carton' AND column_name='width_cm'), 'SELECT 1', 'ALTER TABLE ll_warehouse_transfer_carton ADD COLUMN width_cm DECIMAL(12,2) NULL COMMENT ''箱子实测宽度厘米'''));
@@ -42,7 +41,6 @@ SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE tab
PREPARE transfer_quantity_stmt FROM @ddl; EXECUTE transfer_quantity_stmt; DEALLOCATE PREPARE transfer_quantity_stmt;
-- 仓储转运一箱多SKU清点;仅增加结构,不回填历史业务数据。
USE baiyue_lastleg;
SET @ddl = (SELECT IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_warehouse_transfer_carton' AND column_name='sku_items_json'), 'SELECT 1', 'ALTER TABLE ll_warehouse_transfer_carton ADD COLUMN sku_items_json JSON NULL COMMENT ''实收箱内SKU及逐项件数明细'''));
PREPARE transfer_sku_stmt FROM @ddl; EXECUTE transfer_sku_stmt; DEALLOCATE PREPARE transfer_sku_stmt;
@@ -0,0 +1,49 @@
-- Region: OVERSEAS
-- Schema: baiyue_lastleg
-- Purpose: 排车物理托盘串行点、物理占用及逻辑占用关联结构补齐。
-- Preconditions: MySQL 8;已选中目标schema;ll_dispatch_pallet_lock已有业务基线存在。
-- Postconditions: 两张实托表和physical_lock_id列/idx_dispatch_logical_physical索引存在。
-- 只增加缺失结构,不删除/回填/重算历史数据。重复执行已存在对象时跳过。
-- 与当前lastleg.sql最终定义一致;已有异构对象须人工核对,不能以跳过证明一致。
CREATE TABLE IF NOT EXISTS ll_physical_pallet_guard (
warehouse_pallet_id BIGINT NOT NULL COMMENT '真实全局物理托盘ID',
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '首次建立串行点时间',
PRIMARY KEY (warehouse_pallet_id)
) ENGINE=InnoDB COMMENT='排车冻结与仓内实托组成修改的共同串行点';
CREATE TABLE IF NOT EXISTS ll_dispatch_physical_pallet_lock (
id BIGINT NOT NULL COMMENT '物理实托占用主键',
warehouse_id VARCHAR(128) NOT NULL COMMENT '真实起运仓ID',
warehouse_pallet_id BIGINT NOT NULL COMMENT '全局真实物理托盘ID',
active_warehouse_pallet_id BIGINT NULL COMMENT '活动物理排他键,释放后为空',
dispatch_order_id BIGINT NULL COMMENT '正式排车主单ID,与草稿归属互斥',
draft_token VARCHAR(64) NULL COMMENT '草稿拥有者令牌,与正式排车归属互斥',
draft_container_id BIGINT NULL COMMENT '草稿内唯一占用该实托的容器ID',
operator_id VARCHAR(128) NULL COMMENT '占用操作人ID',
status VARCHAR(32) NOT NULL DEFAULT 'ACTIVE' COMMENT '物理占用状态',
expires_at DATETIME(3) NULL COMMENT '草稿失效时间,正式占用为空',
locked_at DATETIME(3) NOT NULL COMMENT '锁定时间',
released_at DATETIME(3) NULL COMMENT '释放时间',
created_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) COMMENT '创建时间',
updated_at DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '更新时间',
PRIMARY KEY (id),
UNIQUE KEY uk_dispatch_physical_active_pallet (active_warehouse_pallet_id),
KEY idx_dispatch_physical_order (dispatch_order_id,status),
KEY idx_dispatch_physical_draft (draft_token,draft_container_id,status),
CONSTRAINT chk_dispatch_physical_active_key CHECK((status='ACTIVE' AND active_warehouse_pallet_id IS NOT NULL AND active_warehouse_pallet_id=warehouse_pallet_id) OR (status<>'ACTIVE' AND active_warehouse_pallet_id IS NULL)),
CONSTRAINT chk_dispatch_physical_owner CHECK((dispatch_order_id IS NOT NULL AND draft_token IS NULL AND draft_container_id IS NULL) OR (dispatch_order_id IS NULL AND draft_token IS NOT NULL AND draft_container_id IS NOT NULL))
) ENGINE=InnoDB COMMENT='同车共享且跨车排他的物理实托占用';
-- 已只读确认本地缺失:客户逻辑锁到物理锁的可空关联列及查询索引。
-- 仅补结构,不根据历史单据推测或回填关联。
SET @overseas_dimension_ddl = IF(EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='ll_dispatch_pallet_lock' AND column_name='physical_lock_id'), 'SELECT 1', 'ALTER TABLE ll_dispatch_pallet_lock ADD COLUMN physical_lock_id BIGINT NULL COMMENT ''实际物理实托占用ID,非物理来源为空''');
PREPARE overseas_dimension_stmt FROM @overseas_dimension_ddl;
EXECUTE overseas_dimension_stmt;
DEALLOCATE PREPARE overseas_dimension_stmt;
SET @overseas_dimension_ddl = IF(EXISTS (SELECT 1 FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='ll_dispatch_pallet_lock' AND index_name='idx_dispatch_logical_physical'), 'SELECT 1', 'ALTER TABLE ll_dispatch_pallet_lock ADD KEY idx_dispatch_logical_physical (physical_lock_id,status)');
PREPARE overseas_dimension_stmt FROM @overseas_dimension_ddl;
EXECUTE overseas_dimension_stmt;
DEALLOCATE PREPARE overseas_dimension_stmt;
SET @overseas_dimension_ddl = NULL;
+80 -1
View File
@@ -4882,4 +4882,83 @@ CREATE TABLE ll_fleet_pickup_history (
KEY idx_pickup_history_trip(trip_no,id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='取货不可变操作历史';
SELECT 'PASS' AS initialization_status, 'OVERSEAS' AS region, 228 AS initialized_tables;
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_ownership (
dispatch_id BIGINT NOT NULL COMMENT '原排车内部主键',
resource_mode VARCHAR(16) NOT NULL COMMENT '原排车资源模式MASTER或EXTERNAL',
vehicle_id BIGINT NULL COMMENT '真实车辆档案主键,临时外配为空',
vehicle_ownership VARCHAR(16) NOT NULL COMMENT '装车完成时车辆归属OWNED或DISPATCHED',
vehicle_record_version BIGINT NULL COMMENT '捕获归属时真实车辆档案版本',
ownership_captured_at DATETIME(3) NOT NULL COMMENT '归属捕获UTC时间',
loading_completion_hash VARCHAR(128) NOT NULL COMMENT '原排车装车确认事实摘要',
loading_completed_at DATETIME(3) NOT NULL COMMENT '原排车实际装车完成UTC时间',
PRIMARY KEY (dispatch_id),
KEY idx_owned_business_vehicle (vehicle_ownership,vehicle_id),
CONSTRAINT fk_owned_business_ownership_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_ownership CHECK (vehicle_ownership IN ('OWNED','DISPATCHED')),
CONSTRAINT ck_owned_business_resource_mode CHECK (
(resource_mode='MASTER' AND vehicle_id IS NOT NULL AND vehicle_record_version IS NOT NULL AND vehicle_record_version>=0)
OR (resource_mode='EXTERNAL' AND vehicle_id IS NULL AND vehicle_record_version IS NULL AND vehicle_ownership='DISPATCHED'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车装车完成时的车辆归属证据';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_record (
id BIGINT NOT NULL COMMENT '附加运营记录内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
record_version BIGINT NOT NULL COMMENT '附加运营记录并发版本,独立于原排车版本',
currency VARCHAR(3) NULL COMMENT '整车运营金额币种CNY或USD,未登记为空',
total_amount DECIMAL(18,2) NULL COMMENT '人工登记整车总金额,不自动形成账务费用',
actual_distance_miles DECIMAL(12,3) NULL COMMENT '实际行驶英里数,未登记为空',
fuel_consumption_litres_per_100km DECIMAL(12,3) NULL COMMENT '人工登记油耗率,单位升每百公里',
arrivals_json JSON NOT NULL COMMENT '按原目的地键记录的实际到达UTC时间',
photos_json JSON NOT NULL COMMENT '七个照片框当前已绑定文件的分类快照',
created_by VARCHAR(64) NOT NULL COMMENT '首次登记操作人标识',
updated_by VARCHAR(64) NOT NULL COMMENT '最近登记操作人标识',
created_at DATETIME(3) NOT NULL COMMENT '首次登记UTC时间',
updated_at DATETIME(3) NOT NULL COMMENT '最近登记UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_record_dispatch (dispatch_id),
CONSTRAINT fk_owned_business_record_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_record_version CHECK (record_version>=0),
CONSTRAINT ck_owned_business_money CHECK (
(currency IS NULL AND total_amount IS NULL)
OR (currency IS NOT NULL AND currency IN ('CNY','USD') AND total_amount IS NOT NULL AND total_amount>=0)),
CONSTRAINT ck_owned_business_distance CHECK (actual_distance_miles IS NULL OR actual_distance_miles>=0),
CONSTRAINT ck_owned_business_fuel CHECK (fuel_consumption_litres_per_100km IS NULL OR fuel_consumption_litres_per_100km>=0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车自有业务附加运营信息';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_command (
id BIGINT NOT NULL COMMENT '附加运营命令内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
operator_id VARCHAR(64) NOT NULL COMMENT '原命令操作人标识',
idempotency_key VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT '同一原排车内唯一请求键,不按操作者分组',
action VARCHAR(32) NOT NULL COMMENT '运营登记或照片上传绑定动作',
expected_version BIGINT NULL COMMENT '原请求附加版本,纯文件上传可为空',
request_hash CHAR(64) NOT NULL COMMENT '原操作者动作版本与完整请求摘要',
request_json JSON NOT NULL COMMENT '不含文件内容或凭据的完整原请求',
status VARCHAR(24) NOT NULL COMMENT 'PENDING或SUCCEEDED或REJECTED或UNKNOWN_RESULT',
result_json JSON NULL COMMENT '原命令已知成功结果或明确拒绝事实',
error_code VARCHAR(64) NULL COMMENT '明确拒绝或未知结果诊断码',
created_at DATETIME(3) NOT NULL COMMENT '命令意图创建UTC时间',
updated_at DATETIME(3) NOT NULL COMMENT '命令结果更新UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_command_key (dispatch_id,idempotency_key),
CONSTRAINT fk_owned_business_command_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_command_version CHECK (expected_version IS NULL OR expected_version>=0),
CONSTRAINT ck_owned_business_command_status CHECK (status IN ('PENDING','SUCCEEDED','REJECTED','UNKNOWN_RESULT'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车附加运营写命令及可恢复结果';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_history (
id BIGINT NOT NULL COMMENT '附加运营历史内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
record_version BIGINT NOT NULL COMMENT '成功写入后的附加记录版本',
action VARCHAR(32) NOT NULL COMMENT '运营登记或照片绑定动作',
operator_id VARCHAR(64) NOT NULL COMMENT '真实操作人标识',
reason VARCHAR(1000) NULL COMMENT '人工填写的登记或更正说明',
snapshot_json JSON NOT NULL COMMENT '操作后附加运营信息与分类照片不可变快照',
occurred_at DATETIME(3) NOT NULL COMMENT '操作UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_history_version (dispatch_id,record_version),
CONSTRAINT fk_owned_business_history_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_history_version CHECK (record_version>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车自有业务附加运营不可变历史';
SELECT 'PASS' AS initialization_status, 'OVERSEAS' AS region, 232 AS initialized_tables;
@@ -91,6 +91,15 @@ public class LastlegOrderController {
return ApiResponse.success(orderService.page(platformScope(user, customerId), query, relabelNo));
}
/** 按主列表完整筛选读取仓储转运数量,保持同一平台客户边界和列表权限。 */
@GetMapping("/api/platform/v1/last-leg/orders/warehouse-transfer-quantities")
@PreAuthorize("hasAuthority('" + OverseasPermissions.LAST_MILE_ORDER_LIST + "')")
public ApiResponse<com.baiyue.lastleg.transfer.dto.TransferQuantityTotals> transferQuantities(
@AuthenticationPrincipal AuthenticatedUser user, @RequestParam(required=false) String customerId,
@RequestParam(required=false) String relabelNo, @Valid LastlegOrderRequests.Query query) {
return ApiResponse.success(orderService.transferQuantityTotals(platformScope(user,customerId),query,relabelNo));
}
/** Compatibility overload used by non-Spring callers and existing contract tests. */
public ApiResponse<PageResult<LastlegOrderSummary>> list(
AuthenticatedUser user, String customerId, LastlegOrderRequests.Query query) {
@@ -597,12 +597,19 @@ public class DeliveryTransferService {
if (application == null || !RelabelApplicationService.READY_FOR_OUTBOUND.equals(application.getStatus())) {
throw conflict("换标单尚未完成客户确认或已不可出库");
}
if (relabelSnapshotMarks(item, selectedPosition.getId(), application.getRelabelNo()).isEmpty())
throw conflict("换标出库指定位置或箱唛快照不完整,请核对原申请");
List<RelabelItem> sourceItems = relabelItems.selectList(new LambdaQueryWrapper<RelabelItem>()
.eq(RelabelItem::getApplicationId, application.getId())
.eq(RelabelItem::getCustomerId, customerId)
.eq(RelabelItem::getSourceInventoryPositionId, request.inventoryPositionId()));
long sourcePackages = sourceItems.stream().mapToLong(source -> value(source.getNotifiedPackageCount())).sum();
if (sourcePackages != request.packages()) throw conflict("换标出库来源库存快照与任务箱数不一致");
List<String> sourceMarks = sourceItems.stream().map(RelabelItem::getCartonMark)
.filter(StringUtils::hasText).distinct().sorted().toList();
Set<String> sourceIds = sourceItems.stream().map(source -> String.valueOf(source.getId())).collect(Collectors.toSet());
if (sourcePackages != request.packages() || !sourceMarks.equals(expectedMarks)
|| !sourceIds.equals(relabelSnapshotItemIds(item)))
throw conflict("换标出库来源库存快照与任务箱数或箱唛不一致");
int releaseIndex = 0;
for (RelabelItem source : sourceItems) {
inventoryCommands.release(customerId, operatorId, new InventoryCommandRequests.Move(
@@ -720,6 +727,7 @@ public class DeliveryTransferService {
return taskResult(outbound, task);
}
/** 扫描整托前核平全部指定来源,任一不足时不执行部分拣货。 */
@Transactional
public DeliveryResponses.PdaTask pdaPickPallet(String warehouseId, String operatorId, String taskNo,
String palletNo, DeliveryRequests.PdaPalletPick request) {
@@ -769,7 +777,7 @@ public class DeliveryTransferService {
long remaining = value(item.getPackageCount()) - value(item.getPickedPackageCount());
if (remaining <= 0) continue;
Map<Long, List<DeliveryResponses.PdaPickPosition>> positionsById = pdaPickPositions(
task.getCustomerId(), boundWarehouseId, item).stream().collect(Collectors.groupingBy(
task.getCustomerId(), boundWarehouseId, item, outbound.getOutboundType()).stream().collect(Collectors.groupingBy(
DeliveryResponses.PdaPickPosition::inventoryPositionId, LinkedHashMap::new, Collectors.toList()));
for (Map.Entry<Long, List<DeliveryResponses.PdaPickPosition>> entry : positionsById.entrySet()) {
if (remaining <= 0) break;
@@ -1049,6 +1057,7 @@ public class DeliveryTransferService {
.map(task -> taskResult(requireOutboundInWarehouse(task, boundWarehouseId), task)).toList();
}
/** PDA明细展示与整托拣货使用相同的客户、仓库及来源投影。 */
public DeliveryResponses.PdaTaskDetail pdaTaskDetail(String warehouseId, String taskNo) {
String boundWarehouseId = required(warehouseId, "PDA warehouse binding is required");
OutboundPdaTask task = pdaTasks.findByNoAndWarehouse(required(taskNo, "PDA task number is required"),
@@ -1061,7 +1070,7 @@ public class DeliveryTransferService {
value(item.getPickedPackageCount()), item.getStatus(),
("RETURN_OUTBOUND".equals(outbound.getOutboundType())
|| ("RELABEL_OUTBOUND".equals(outbound.getOutboundType()) && item.getWarehousePalletId() == null)) ? returnPickPositions(outbound, task, item)
: pdaPickPositions(task.getCustomerId(), boundWarehouseId, item), item.getReturnSkuQuantity())).toList();
: pdaPickPositions(task.getCustomerId(), boundWarehouseId, item, outbound.getOutboundType()), item.getReturnSkuQuantity())).toList();
return new DeliveryResponses.PdaTaskDetail(taskResult(outbound, task), items);
}
@@ -1119,13 +1128,28 @@ public class DeliveryTransferService {
&& value(item.getPickedPackageCount()) == 0 && "OUTBOUND_PENDING".equals(carton.getStatus()) ? 1 : 0, value(item.getPickedPackageCount())));
}
/** 换标使用指定实物箱及仍归本单的冻结库存;普通出库继续按可用库存和SKU匹配。 */
private List<DeliveryResponses.PdaPickPosition> pdaPickPositions(String customerId, String warehouseId,
OutboundPalletItem item) {
OutboundPalletItem item, String outboundType) {
if (item.getWarehousePalletId() == null) return List.of();
List<DeliveryResponses.PdaPickPosition> result = new ArrayList<>();
Set<String> frozenMarks = new HashSet<>(Arrays.asList(
Optional.ofNullable(item.getCartonMarks()).orElse("").split(",")));
for (InventoryPosition position : inventoryPositions.listPallet(customerId, item.getWarehousePalletId())) {
if ("RELABEL_OUTBOUND".equals(outboundType)) {
List<String> marks = relabelSnapshotMarks(item, position.getId(), null);
InventoryBalance balance = inventoryBalances.selectById(position.getBalanceId());
if (marks.isEmpty() || !customerId.equals(position.getCustomerId())
|| !warehouseId.equals(position.getOverseasWarehouseId())
|| !Objects.equals(item.getWarehousePalletId(), position.getPalletId())
|| balance == null || !customerId.equals(balance.getCustomerId())
|| !warehouseId.equals(balance.getOverseasWarehouseId())
|| !Objects.equals(item.getInboundCode(), balance.getInboundCode())
|| value(position.getHoldPackages()) < marks.size()) continue;
// 本单冻结箱先在写路径校验原申请和来源任务,再释放、分配、拣货、出库;不把其他可用箱混入。
for (String mark : marks) result.add(pdaPosition(position, item, balance, mark, 1, 0));
continue;
}
long available = value(position.getAvailablePackages());
if (available <= 0 || !warehouseId.equals(position.getOverseasWarehouseId())) continue;
InventoryBalance balance = inventoryBalances.selectById(position.getBalanceId());
@@ -1147,6 +1171,37 @@ public class DeliveryTransferService {
return result;
}
/** 仅接受完整的换标出库快照;空SKU不是通配符,必须精确匹配返工后冻结的位置和全部箱唛。 */
private List<String> relabelSnapshotMarks(OutboundPalletItem item, Long positionId, String expectedRelabelNo) {
try {
var refs = objectMapper.readTree(item.getOrderRefs());
if (!"RELABEL_ORDER".equals(refs.path("sourceType").asText())
|| !StringUtils.hasText(refs.path("relabelNo").asText())
|| expectedRelabelNo != null && !expectedRelabelNo.equals(refs.path("relabelNo").asText())
|| positionId == null || !String.valueOf(positionId).equals(refs.path("sourceInventoryPositionId").asText())
|| !refs.path("items").isArray()) return List.of();
var marks = new TreeSet<String>(); var ids = new HashSet<String>(); long packages = 0;
for (var line : refs.path("items")) {
String mark = line.path("cartonMark").asText().trim(), id = line.path("itemId").asText();
long count = line.path("packages").asLong();
if (!StringUtils.hasText(mark) || !StringUtils.hasText(id) || !ids.add(id) || !marks.add(mark) || count != 1) return List.of();
packages += count;
}
var frozen = Arrays.stream(Objects.toString(item.getCartonMarks(), "").split(","))
.map(String::trim).filter(StringUtils::hasText).collect(Collectors.toCollection(TreeSet::new));
return packages == value(item.getPackageCount()) && marks.equals(frozen) ? List.copyOf(marks) : List.of();
} catch (Exception ignored) { return List.of(); }
}
/** 释放冻结前核对快照任务主键与本申请当前位置的真实任务集合完全相同。 */
private Set<String> relabelSnapshotItemIds(OutboundPalletItem item) {
try {
var ids = new HashSet<String>();
for (var line : objectMapper.readTree(item.getOrderRefs()).path("items")) ids.add(line.path("itemId").asText());
return ids;
} catch (Exception ignored) { return Set.of(); }
}
private DeliveryResponses.PdaPickPosition pdaPosition(InventoryPosition position, OutboundPalletItem item,
InventoryBalance balance, String cartonMark,
long available, long picked) {
@@ -29,12 +29,16 @@ public final class CargoDiscardResponses {
}
}
public record Box(Long cartonId, String cartonMark, String palletNo, List<CandidateSku> skus) {}
public record CandidateSku(String skuCode, String productName, long availablePackages) {}
public record CandidateSku(String skuCode, String productName, long availablePackages, Long availablePieces) {
/** 无件数事实时保留未知,不按箱规推算。 */
public CandidateSku(String skuCode, String productName, long availablePackages) { this(skuCode, productName, availablePackages, null); }
}
public record Summary(Long id, String customerId, String discardNo, String inboundCodes,
String overseasWarehouseId, String overseasWarehouseName,
int totalPackages, BigDecimal totalFee, String currency, String status,
String createdBy, LocalDateTime createdAt, LocalDateTime reviewedAt, String outboundNo, LocalDateTime customerConfirmedAt) {}
String createdBy, LocalDateTime createdAt, LocalDateTime reviewedAt, String outboundNo, LocalDateTime customerConfirmedAt,
List<String> skuCodes, int skuCount, int requestedPackages, Integer actualPackages) {}
public record Item(Long id, Long orderId, String inboundCode, String skuCode,
String productName, int availablePackagesSnapshot, int discardPackages, List<String> cartonMarks,
@@ -19,4 +19,15 @@ public interface CargoDiscardDimensionMapper {
WHERE i.customer_id=#{customerId} AND i.application_id=#{applicationId}
""")
List<String> palletNos(@Param("customerId") String customerId, @Param("applicationId") Long applicationId);
/** 仅读取所选转运实收箱的真实件数,其他来源保留未知。 */
@Select("""
SELECT CASE WHEN l.source_type='TRANSFER' THEN c.sku_items_json ELSE NULL END
FROM ll_cargo_discard_item i
JOIN ll_cargo_discard_carton l ON l.customer_id=i.customer_id AND l.application_id=i.application_id
AND (l.item_id=i.id OR (i.source_type='INVENTORY' AND JSON_CONTAINS(i.carton_marks_json,JSON_QUOTE(l.carton_mark))))
LEFT JOIN ll_warehouse_transfer_carton c ON c.id=l.carton_id AND c.customer_id=l.customer_id
WHERE i.customer_id=#{customerId} AND i.id=#{itemId}
""")
List<String> selectedCartonPieces(@Param("customerId") String customerId, @Param("itemId") Long itemId);
}
@@ -25,16 +25,16 @@ public interface CargoDiscardInventoryMapper {
@Select("SELECT p.* FROM ll_inventory_position p WHERE p.customer_id=#{customerId} AND p.id=#{positionId} FOR UPDATE")
com.baiyue.lastleg.inventory.entity.InventoryPosition lockGenericPosition(@Param("customerId") String customerId, @Param("positionId") Long positionId);
/** 按实收托盘及 SKU 关联已清点箱,避免漏箱或混入其他托盘的箱号。 */
/** 按实收托盘关联已清点箱;混装物理余额允许箱内不同 SKU,仍严格限定客户、批次、仓和托盘。 */
@Select("""
SELECT c.id,c.carton_mark,c.sku_code,'INBOUND' source_type
SELECT c.id,c.carton_mark,c.sku_code,'INBOUND' source_type,NULL sku_items_json
FROM ll_inbound_plan_carton c
JOIN ll_inventory_balance b ON b.customer_id=c.customer_id AND b.inbound_order_id=c.order_id
JOIN ll_inventory_position p ON p.customer_id=b.customer_id AND p.balance_id=b.id AND p.pallet_id=c.warehouse_pallet_id
WHERE p.customer_id=#{customerId} AND p.id=#{positionId} AND c.status='AVAILABLE' AND c.received_at IS NOT NULL
AND COALESCE(b.destination_warehouse_code,'')=COALESCE(c.destination_warehouse_code,'')
UNION ALL
SELECT c.id,c.carton_mark,i.sku_code,'TRANSFER' source_type
SELECT c.id,c.carton_mark,i.sku_code,'TRANSFER' source_type,c.sku_items_json
FROM ll_inventory_position p
JOIN ll_inventory_balance b ON b.customer_id=p.customer_id AND b.id=p.balance_id
JOIN ll_warehouse_transfer_order t ON t.customer_id=p.customer_id AND t.inbound_order_id=b.inbound_order_id
@@ -44,7 +44,7 @@ public interface CargoDiscardInventoryMapper {
JOIN ll_warehouse_transfer_carton c ON c.customer_id=t.customer_id AND c.transfer_order_id=t.id
AND c.transfer_pallet_id=tp.id AND c.status='COUNTED'
JOIN ll_warehouse_transfer_item i ON i.customer_id=c.customer_id AND i.id=c.transfer_item_id
AND i.transfer_order_id=t.id AND COALESCE(i.sku_code,'')=COALESCE(b.sku_code,'')
AND i.transfer_order_id=t.id AND (b.sku_code='MIXED' OR COALESCE(i.sku_code,'')=COALESCE(b.sku_code,''))
WHERE p.customer_id=#{customerId} AND p.id=#{positionId}
ORDER BY id
""")
@@ -12,15 +12,22 @@ public final class CargoDiscardQuantities {
/** 退货混装箱按箱 ID 去重,其余来源累加已选择的物理箱数。 */
public static int boxes(List<CargoDiscardItem> lines, boolean actual) {
var returnBoxes = new HashSet<Long>();
var inventoryBoxes = new HashSet<String>();
int total = 0;
for (var line : lines) {
int quantity = actual ? java.util.Objects.requireNonNullElse(line.getActualDiscardPackages(), 0) : line.getDiscardPackages();
if (line.getReturnCartonId() != null) {
if (quantity > 0) returnBoxes.add(line.getReturnCartonId());
} else if ("INVENTORY".equals(line.getSourceType()) && line.getCartonMarksJson() != null && quantity > 0) {
try {
var marks = new com.fasterxml.jackson.databind.ObjectMapper().readTree(line.getCartonMarksJson());
if (!marks.isArray() || marks.size() != quantity) throw new IllegalStateException("废弃箱唛快照与数量不一致");
for (var mark : marks) inventoryBoxes.add(line.getInboundCode() + ":" + mark.asText());
} catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw new IllegalStateException("废弃箱唛快照无法读取", e); }
} else {
total = Math.addExact(total, quantity);
}
}
return Math.addExact(total, returnBoxes.size());
return Math.addExact(Math.addExact(total, returnBoxes.size()), inventoryBoxes.size());
}
}
@@ -9,4 +9,5 @@ public class CargoDiscardStockCartonRow {
private String cartonMark;
private String skuCode;
private String sourceType;
private String skuItemsJson;
}
@@ -21,7 +21,8 @@ public final class PdaCargoDiscardDtos {
}
/** 明细数量按来源标识单位:退货库存为件,其余箱级库存为箱。 */
public record Sku(Long itemId, String skuCode, String productName, int plannedPackages,
Integer actualPackages, String status, String quantityUnit) { }
Integer actualPackages, String status, String quantityUnit,
boolean actualQuantityEditable) { }
public record PalletTask(String discardNo, String customerId, String overseasWarehouseId,
String palletNo, Long profileId, String status, List<Sku> skus, String outboundNo,
String scanMode, List<String> cartonMarks) { }
@@ -1,17 +1,11 @@
package com.baiyue.lastleg.discard.pda.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baiyue.lastleg.discard.dto.CargoDiscardResponses;
import com.baiyue.lastleg.discard.entity.*;
import com.baiyue.lastleg.discard.mapper.*;
import com.baiyue.lastleg.discard.pda.dto.PdaCargoDiscardDtos;
import com.baiyue.lastleg.discard.service.CargoDiscardInventoryAdjustmentService;
import com.baiyue.lastleg.discard.service.CargoDiscardService;
import com.baiyue.lastleg.dropship.entity.DropshipOrderProfile;
import com.baiyue.lastleg.dropship.mapper.DropshipOrderProfileMapper;
import com.baiyue.lastleg.pda.security.PdaWarehouseIdentity;
import com.baiyue.lastleg.returnreceipt.entity.ReturnInventoryCarton;
import com.baiyue.lastleg.returnreceipt.mapper.ReturnInventoryCartonMapper;
import jakarta.annotation.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
@@ -24,28 +18,24 @@ import java.util.stream.Collectors;
@Service
public class PdaCargoDiscardService {
@Resource private com.baiyue.lastleg.discard.service.CargoDiscardPhotoService photoService;
@Resource private CargoDiscardApplicationMapper applications;
@Resource private com.baiyue.lastleg.discard.repository.CargoDiscardPdaRepository repository;
@Resource private com.baiyue.lastleg.discard.service.CargoDiscardOutboundService outboundService;
@Resource private CargoDiscardItemMapper items;
@Resource private CargoDiscardCartonMapper cartons;
@Resource private DropshipOrderProfileMapper profiles;
@Resource private CargoDiscardInventoryAdjustmentService adjustments;
@Resource private CargoDiscardService discardService;
@Resource private ReturnInventoryCartonMapper returnCartons;
@Resource private com.baiyue.lastleg.discard.service.CargoDiscardStockService stockService;
/** 只读取绑定仓已审核申请的实际托盘任务。 */
public List<PdaCargoDiscardDtos.PalletTask> tasks(PdaWarehouseIdentity identity) {
return applications.selectList(new LambdaQueryWrapper<CargoDiscardApplication>()
.eq(CargoDiscardApplication::getOverseasWarehouseId, String.valueOf(identity.overseasWarehouseId()))
.eq(CargoDiscardApplication::getStatus, CargoDiscardService.APPROVED)
.orderByAsc(CargoDiscardApplication::getCreatedAt))
return repository.approved(String.valueOf(identity.overseasWarehouseId()))
.stream().flatMap(a -> palletTasks(a).stream()).toList();
}
/** 扫码读取当前仓库唯一可操作任务。 */
public PdaCargoDiscardDtos.PalletTask resolve(PdaWarehouseIdentity identity, String palletNo) {
return resolve(identity, palletNo, null);
}
/** 扫码时限定已选择申请,防止同托盘多任务误操作。 */
public PdaCargoDiscardDtos.PalletTask resolve(PdaWarehouseIdentity identity, String palletNo, String discardNo) {
var matches = tasks(identity).stream().filter(t -> t.palletNo().equals(palletNo.trim()) || t.cartonMarks().contains(palletNo.trim()))
.filter(t -> discardNo == null || discardNo.isBlank() || t.discardNo().equals(discardNo.trim())).toList();
@@ -54,10 +44,11 @@ public class PdaCargoDiscardService {
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "该仓库没有此托盘的待废弃任务"));
}
/** 仓库按无箱唛对应任务的实点数结算,其余任务继续核平所选箱。 */
@Transactional
public PdaCargoDiscardDtos.PalletTask confirm(PdaWarehouseIdentity identity, String discardNo,
String palletNo, PdaCargoDiscardDtos.Confirm request) {
CargoDiscardApplication application = applications.findNoByWarehouse(discardNo,
CargoDiscardApplication application = repository.lockApplication(discardNo,
String.valueOf(identity.overseasWarehouseId()));
if (application == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "废弃任务不存在或不属于当前仓库");
boolean terminal = CargoDiscardService.PDA_COMPLETED.equals(application.getStatus())
@@ -71,8 +62,12 @@ public class PdaCargoDiscardService {
if (!actuals.keySet().equals(task.skus().stream().map(PdaCargoDiscardDtos.Sku::itemId).collect(Collectors.toSet()))) {
throw conflict("必须提交该托盘全部 SKU 的实际废弃数量");
}
if (task.skus().stream().anyMatch(line -> !Objects.equals(actuals.get(line.itemId()), line.plannedPackages())))
throw conflict("必须完成本次废弃单所选全部箱子,不能漏出");
for (var line : task.skus()) {
int actual = actuals.get(line.itemId());
if (actual < 0 || actual > line.plannedPackages()) throw conflict("实际废弃数量不能超过申请预留数量");
if (!line.actualQuantityEditable() && actual != line.plannedPackages())
throw conflict("必须完成本次废弃单所选全部箱子,不能漏出");
}
if ("CARTON".equals(task.scanMode()) && !Boolean.TRUE.equals(request.confirmAllCartons())) {
var scanned = request.scannedCartonMarks() == null ? List.<String>of() : request.scannedCartonMarks();
if (scanned.size() != task.cartonMarks().size() || !new HashSet<>(scanned).equals(new HashSet<>(task.cartonMarks())))
@@ -80,7 +75,7 @@ public class PdaCargoDiscardService {
}
List<CargoDiscardItem> palletItems = new ArrayList<>();
for (PdaCargoDiscardDtos.Sku line : task.skus()) {
CargoDiscardItem item = items.selectById(line.itemId());
CargoDiscardItem item = repository.item(line.itemId());
if (item == null || !application.getCustomerId().equals(item.getCustomerId())
|| !Objects.equals(application.getId(), item.getApplicationId())
|| !physicalCode(application, item).equals(task.palletNo()))
@@ -90,14 +85,14 @@ public class PdaCargoDiscardService {
throw conflict("已完成托盘的实际数量不能修改");
palletItems.add(item);
}
if (terminal && items.listApplication(application.getCustomerId(), application.getId()).stream()
if (terminal && repository.items(application.getCustomerId(), application.getId()).stream()
.anyMatch(item -> !"COMPLETED".equals(item.getPdaStatus())
|| !application.getCustomerId().equals(item.getCustomerId())
|| !Objects.equals(application.getId(), item.getApplicationId())))
throw conflict("废弃申请终态存在未完成明细,不能恢复作业结果");
photoService.confirm(application, task.palletNo(), request.photoFileIds(),
palletItems.stream().allMatch(item -> "COMPLETED".equals(item.getPdaStatus())));
// A completed pallet is an immutable result, including the final pallet after application completion.
// 已完成托盘保持原始实点结果,终态重放不得再次扣减或释放库存。
if (palletItems.stream().allMatch(item -> "COMPLETED".equals(item.getPdaStatus()))) return task;
if (terminal) throw conflict("废弃终态不能执行未完成托盘");
LocalDateTime now = LocalDateTime.now();
@@ -105,20 +100,25 @@ public class PdaCargoDiscardService {
if ("COMPLETED".equals(item.getPdaStatus())) {
continue;
}
List<CargoDiscardCarton> links = cartons.listApplication(application.getCustomerId(), application.getId()).stream()
List<CargoDiscardCarton> links = repository.cartons(application.getCustomerId(), application.getId()).stream()
.filter(c -> c.getItemId().equals(item.getId())).toList();
adjustments.discardPalletItem(application.getCustomerId(), application, item, links,
actuals.get(item.getId()), identity.operatorKey(), now);
// 未知箱唛对应关系时只按当前仓位冻结桶结算,不猜测被废弃的具体箱唛。
if ("INVENTORY".equals(item.getSourceType()) && stockService.actualQuantityEditable(item)) {
stockService.discard(application.getCustomerId(), identity.operatorKey(), application, item, actuals.get(item.getId()));
} else {
adjustments.discardPalletItem(application.getCustomerId(), application, item, links,
actuals.get(item.getId()), identity.operatorKey(), now);
}
item.setActualDiscardPackages(actuals.get(item.getId())); item.setPdaStatus("COMPLETED");
item.setPdaOperatorId(identity.operatorKey()); item.setPdaCompletedAt(now); items.updateById(item);
item.setPdaOperatorId(identity.operatorKey()); item.setPdaCompletedAt(now); repository.saveItem(item);
}
task.skus().stream().map(PdaCargoDiscardDtos.Sku::itemId).map(items::selectById)
task.skus().stream().map(PdaCargoDiscardDtos.Sku::itemId).map(repository::item)
.filter(this::isReturnItem).map(CargoDiscardItem::getReturnCartonId).filter(Objects::nonNull).distinct()
.forEach(cartonId -> adjustments.finishReturnCarton(application.getCustomerId(), cartonId));
if (items.listApplication(application.getCustomerId(), application.getId()).stream()
if (repository.items(application.getCustomerId(), application.getId()).stream()
.allMatch(i -> "COMPLETED".equals(i.getPdaStatus()))) {
int actualTotal = com.baiyue.lastleg.discard.model.CargoDiscardQuantities.boxes(
items.listApplication(application.getCustomerId(), application.getId()), true);
repository.items(application.getCustomerId(), application.getId()), true);
application.setTotalPackages(actualTotal);
application.setTotalFee(application.getFeePerPackage().multiply(java.math.BigDecimal.valueOf(actualTotal)));
discardService.updateLinkedStatus(application.getCustomerId(), application, CargoDiscardService.APPROVED,
@@ -130,6 +130,7 @@ public class PdaCargoDiscardService {
}
@Transactional
/** 当前申请行锁内保存现场照片,已完成托盘禁止补写。 */
public CargoDiscardResponses.Photo uploadPhoto(PdaWarehouseIdentity identity, String discardNo, String palletNo,
long operatorUserId, org.springframework.web.multipart.MultipartFile file) {
CargoDiscardApplication application = photoApplication(identity, discardNo, palletNo, true);
@@ -140,19 +141,22 @@ public class PdaCargoDiscardService {
}
@Transactional(readOnly = true)
/** 读取绑定仓当前托盘的照片。 */
public List<CargoDiscardResponses.Photo> photos(PdaWarehouseIdentity identity, String discardNo, String palletNo) {
return photoService.list(photoApplication(identity, discardNo, palletNo, false), palletNo.trim(), false);
}
@Transactional(readOnly = true)
/** 下载当前申请和托盘拥有的照片。 */
public com.baiyue.lastleg.discard.gateway.CargoDiscardPhotoFileGateway.DownloadedFile downloadPhoto(
PdaWarehouseIdentity identity, String discardNo, String palletNo, long fileId) {
return photoService.download(photoApplication(identity, discardNo, palletNo, false), palletNo.trim(), fileId, false);
}
/** 照片访问必须同时满足绑定仓和申请托盘范围。 */
private CargoDiscardApplication photoApplication(PdaWarehouseIdentity identity, String discardNo, String palletNo, boolean lock) {
var warehouseId = String.valueOf(identity.overseasWarehouseId());
var application = lock ? applications.findNoByWarehouse(discardNo, warehouseId) : applications.readNoByWarehouse(discardNo, warehouseId);
var application = lock ? repository.lockApplication(discardNo, warehouseId) : repository.readApplication(discardNo, warehouseId);
if (application == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "废弃任务不存在或不属于当前仓库");
if (palletTasks(application).stream().noneMatch(t -> t.palletNo().equals(palletNo.trim())))
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "托盘不属于该废弃单");
@@ -162,13 +166,13 @@ public class PdaCargoDiscardService {
private static final String LOOSE = "散箱";
/** 按实托汇总本单所选箱唛,退货件数与物理箱数分别呈现。 */
private List<PdaCargoDiscardDtos.PalletTask> palletTasks(CargoDiscardApplication application) {
var allItems = items.listApplication(application.getCustomerId(), application.getId());
var allItems = repository.items(application.getCustomerId(), application.getId());
var grouped = allItems.stream().collect(Collectors.groupingBy(i -> physicalCode(application, i), LinkedHashMap::new, Collectors.toList()));
return grouped.entrySet().stream().map(entry -> {
CargoDiscardItem first = entry.getValue().get(0);
var skus = entry.getValue().stream().map(i -> new PdaCargoDiscardDtos.Sku(i.getId(), i.getSkuCode(), i.getProductName(),
i.getDiscardPackages(), i.getActualDiscardPackages(), i.getPdaStatus() == null ? "PENDING" : i.getPdaStatus(),
isReturnItem(i) ? "件" : "箱")).toList();
isReturnItem(i) ? "件" : "箱", "INVENTORY".equals(i.getSourceType()) && stockService.actualQuantityEditable(i))).toList();
String status = skus.stream().allMatch(i -> "COMPLETED".equals(i.status())) ? "COMPLETED" : "PENDING";
var marks = entry.getValue().stream().flatMap(i -> cartonMarks(application, i).stream()).distinct().sorted().toList();
// 退货箱只代表本单选择的箱子,不能因为有托盘号就当成整托废弃。
@@ -180,6 +184,7 @@ public class PdaCargoDiscardService {
status, skus, outboundService.outboundNo(application), cartonScan ? "CARTON" : "PALLET", marks);
}).toList();
}
/** 相关托盘只从客户库存事实读取,不从请求推断。 */
private String physicalCode(CargoDiscardApplication application, CargoDiscardItem item) {
String code;
if ("INVENTORY".equals(item.getSourceType())) {
@@ -187,31 +192,35 @@ public class PdaCargoDiscardService {
if (!application.getOverseasWarehouseId().equals(position.getOverseasWarehouseId())) throw conflict("废弃库存不属于当前仓库");
code = position.getPalletNo();
} else if (isReturnItem(item)) {
var carton = returnCartons.selectById(item.getReturnCartonId());
var carton = repository.returnCarton(item.getReturnCartonId());
if (carton == null || !application.getCustomerId().equals(carton.getCustomerId())) throw conflict("废弃明细关联退货箱不存在");
code = carton.getPalletCode();
} else {
var profile = profiles.selectById(item.getProfileId());
var profile = repository.profile(item.getProfileId());
if (profile == null || !application.getCustomerId().equals(profile.getCustomerId())) throw conflict("废弃明细关联托盘不存在");
code = profile.getPalletNo();
}
return code == null || code.isBlank() ? LOOSE : code.trim();
}
/** 仅返回保存的真实箱唛,未知对应关系不补造箱码。 */
private List<String> cartonMarks(CargoDiscardApplication application, CargoDiscardItem item) {
if ("INVENTORY".equals(item.getSourceType())) return stockService.cartonMarks(item);
if (isReturnItem(item)) {
var carton = returnCartons.selectById(item.getReturnCartonId());
var carton = repository.returnCarton(item.getReturnCartonId());
String mark = com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton);
return mark == null ? List.of() : List.of(mark);
}
return cartons.listApplication(application.getCustomerId(), application.getId()).stream()
return repository.cartons(application.getCustomerId(), application.getId()).stream()
.filter(c -> Objects.equals(c.getItemId(), item.getId())).map(CargoDiscardCarton::getCartonMark).filter(Objects::nonNull).toList();
}
/** 退货库存沿用独立按件结算规则。 */
private boolean isReturnItem(CargoDiscardItem item) {
return "RETURN_CARTON".equals(item.getSourceType()) || item.getReturnCartonId() != null;
}
/** 取首个有效业务展示值。 */
private static String firstNonBlank(String first, String second) {
return first != null && !first.isBlank() ? first : second;
}
/** 返回可恢复业务冲突。 */
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -12,8 +12,29 @@ import java.util.List;
public class CargoDiscardDimensionRepository {
@Resource private CargoDiscardItemMapper items;
@Resource private CargoDiscardDimensionMapper dimensions;
@Resource private com.fasterxml.jackson.databind.ObjectMapper objectMapper;
/** 读取一票客户隔离明细。 */
public List<CargoDiscardItem> items(String customer, Long application) { return items.listApplication(customer, application); }
/** 读取一票托盘身份,保留无事实行。 */
public List<String> pallets(String customer, Long application) { return dimensions.palletNos(customer, application); }
/** 完整箱级事实才可提供件数,缺箱或未知件数不得固定换算。 */
public Long pieces(String customer, CargoDiscardItem item) {
var values = dimensions.selectedCartonPieces(customer, item.getId());
if (values.isEmpty() || values.size() != item.getDiscardPackages()) return null;
long total = 0;
for (var value : values) {
if (value == null || value.isBlank()) return null;
try {
var contents = objectMapper.readTree(value);
if (!contents.isArray()) return null;
long selected = 0;
for (var content : contents) {
if (item.getSkuCode().equals(content.path("skuCode").asText())) selected += content.path("quantity").asLong();
}
if (selected <= 0) return null;
total += selected;
} catch (com.fasterxml.jackson.core.JsonProcessingException e) { return null; }
}
return total;
}
}
@@ -0,0 +1,46 @@
package com.baiyue.lastleg.discard.repository;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baiyue.lastleg.discard.entity.*;
import com.baiyue.lastleg.discard.mapper.*;
import com.baiyue.lastleg.dropship.entity.DropshipOrderProfile;
import com.baiyue.lastleg.dropship.mapper.DropshipOrderProfileMapper;
import com.baiyue.lastleg.returnreceipt.entity.ReturnInventoryCarton;
import com.baiyue.lastleg.returnreceipt.mapper.ReturnInventoryCartonMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import java.util.List;
/** 封装 PDA 废弃任务读取和作业快照持久化,保留绑定仓与申请行锁。 */
@Repository
public class CargoDiscardPdaRepository {
@Resource private CargoDiscardApplicationMapper applications;
@Resource private CargoDiscardItemMapper items;
@Resource private CargoDiscardCartonMapper cartons;
@Resource private DropshipOrderProfileMapper profiles;
@Resource private ReturnInventoryCartonMapper returnCartons;
/** 按已验证绑定仓读取已审核作业,客户归属由申请事实保留。 */
public List<CargoDiscardApplication> approved(String warehouseId) {
return applications.selectList(new LambdaQueryWrapper<CargoDiscardApplication>()
.eq(CargoDiscardApplication::getOverseasWarehouseId, warehouseId)
.eq(CargoDiscardApplication::getStatus, "APPROVED")
.orderByAsc(CargoDiscardApplication::getCreatedAt));
}
/** 写操作按申请串行,保证扣减、释放、实点结果及终态同事务。 */
public CargoDiscardApplication lockApplication(String no, String warehouse) { return applications.findNoByWarehouse(no, warehouse); }
/** 照片只读入口仍限制绑定仓。 */
public CargoDiscardApplication readApplication(String no, String warehouse) { return applications.readNoByWarehouse(no, warehouse); }
/** 按申请所属客户读取全部明细。 */
public List<CargoDiscardItem> items(String customer, Long application) { return items.listApplication(customer, application); }
/** 读取明细后由服务复验客户与申请。 */
public CargoDiscardItem item(Long id) { return items.selectById(id); }
/** 保存一次实际作业结果。 */
public void saveItem(CargoDiscardItem item) { items.updateById(item); }
/** 按客户和申请读取已选箱快照。 */
public List<CargoDiscardCarton> cartons(String customer, Long application) { return cartons.listApplication(customer, application); }
/** 读取原托盘档案供服务核验归属。 */
public DropshipOrderProfile profile(Long id) { return profiles.selectById(id); }
/** 读取退货箱档案供服务核验归属。 */
public ReturnInventoryCarton returnCarton(Long id) { return returnCartons.selectById(id); }
}
@@ -11,9 +11,10 @@ import org.springframework.stereotype.Repository;
public class CargoDiscardQuantityRepository {
@Resource private CargoDiscardItemMapper items;
/** 列表和详情均按所选实物箱展示;空明细保留申请自身快照。 */
/** 完工后列表和详情按实际箱数展示,作业前保留申请预留数量。 */
public int boxes(CargoDiscardApplication application) {
var lines = items.listApplication(application.getCustomerId(), application.getId());
return lines.isEmpty() ? application.getTotalPackages() : CargoDiscardQuantities.boxes(lines, false);
boolean completed = "PDA_COMPLETED".equals(application.getStatus()) || "COMPLETED".equals(application.getStatus());
return lines.isEmpty() ? application.getTotalPackages() : CargoDiscardQuantities.boxes(lines, completed);
}
}
@@ -0,0 +1,47 @@
package com.baiyue.lastleg.discard.repository;
import com.baiyue.lastleg.discard.entity.*;
import com.baiyue.lastleg.discard.mapper.*;
import com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow;
import com.baiyue.lastleg.inventory.entity.*;
import com.baiyue.lastleg.inventory.mapper.*;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import java.util.List;
/** 封装普通库存废弃的客户隔离读取、锁箱和申请快照保存。 */
@Repository
public class CargoDiscardStockRepository {
@Resource private CargoDiscardInventoryMapper stock;
@Resource private InventoryPositionMapper positions;
@Resource private InventoryBalanceMapper balances;
@Resource private CargoDiscardItemMapper items;
@Resource private CargoDiscardCartonMapper links;
/** 读取客户当前可用且没有转运占用的库存仓位。 */
public List<InventoryPosition> candidates(String customer, String keyword) { return stock.genericPositions(customer, keyword); }
/** 读取余额,服务继续校验其客户与仓库归属。 */
public InventoryBalance balance(Long id) { return balances.selectById(id); }
/** 读取客户指定仓位。 */
public InventoryPosition position(String customer, Long id) { return positions.findTenantPosition(customer, id); }
/** 锁定源仓位以串行创建预留。 */
public InventoryPosition lockPosition(String customer, Long id) { return stock.lockGenericPosition(customer, id); }
/** 读取已有的真实箱唛与托盘对应事实。 */
public List<CargoDiscardStockCartonRow> cartons(String customer, Long position) { return stock.genericCartons(customer, position); }
/** 排除须走一件代发逐箱预留的仓位。 */
public boolean dropshipPosition(String customer, Long position) { return stock.isDropshipPosition(customer, position) > 0; }
/** 读取散箱实收流水中的箱码快照。 */
public List<String> looseMarks(String customer, Long position) { return stock.looseCartonMarks(customer, position); }
/** 保存废弃申请的库存来源明细。 */
public void saveItem(CargoDiscardItem item) { items.insert(item); }
/** 保存申请所选实物箱快照。 */
public void saveCarton(CargoDiscardCarton carton) { links.insert(carton); }
/** 读取申请全部所选箱,服务按当前明细筛选。 */
public List<CargoDiscardCarton> selectedCartons(String customer, Long application) { return links.listApplication(customer, application); }
/** 读取同申请各 SKU 的仓位和箱唛快照,用于按物理仓位消除重复库存命令。 */
public List<CargoDiscardItem> applicationItems(String customer, Long application) { return items.listApplication(customer, application); }
/** 普通实收箱用原状态条件更新,防止并发占用。 */
public int changeInboundCarton(String customer, Long id, String from, String to) { return stock.changeGenericCartonStatus(customer, id, from, to); }
/** 转运实收箱保留已清点状态语义。 */
public int changeTransferCarton(String customer, Long id, String from, String to) { return stock.changeTransferCartonStatus(customer, id, from, to); }
}
@@ -58,6 +58,7 @@ public class CargoDiscardOutboundService {
var snapshots = new java.util.ArrayList<OutboundPalletItem>();
var palletCodes = new java.util.HashSet<String>();
var returnBoxIds = new java.util.HashSet<Long>();
var inventoryBoxMarks = new java.util.HashSet<String>();
for (var line : lines) {
boolean returned = line.getReturnCartonId() != null || "RETURN_CARTON".equals(line.getSourceType());
String palletNo;
@@ -88,7 +89,7 @@ public class CargoDiscardOutboundService {
snapshot.setId(line.getId()); snapshot.setCustomerId(application.getCustomerId()); snapshot.setOutboundOrderId(outbound.getId());
snapshot.setPalletNo(palletNo); snapshot.setSkuCode(line.getSkuCode()); snapshot.setInboundCode(line.getInboundCode());
snapshot.setOrderRefs(application.getDiscardNo()); snapshot.setCartonMarks(cartonMarks);
snapshot.setPackageCount(returned ? (returnBoxIds.add(line.getReturnCartonId()) ? 1 : 0) : line.getDiscardPackages());
snapshot.setPackageCount(returned ? (returnBoxIds.add(line.getReturnCartonId()) ? 1 : 0) : physicalBoxes(line, inventoryBoxMarks));
snapshot.setPickedPackageCount(0); snapshot.setStatus("WAIT_PICK");
if (returned) snapshot.setReturnSkuQuantity((long) line.getDiscardPackages());
snapshot.setVolumeWeightKg(BigDecimal.ZERO); snapshot.setVolumeCbm(BigDecimal.ZERO); snapshot.setCreatedAt(at);
@@ -99,11 +100,13 @@ public class CargoDiscardOutboundService {
}
/** 同步实物箱的拣货进度,退货 SKU 件数不进入箱数汇总。 */
/** 同步废弃实物出库投影,混装 SKU 明细不能重复累计物理箱。 */
public void sync(CargoDiscardApplication application) {
OutboundOrder outbound = outbounds.lockByIdempotency(application.getCustomerId(), key(application));
if (outbound == null) throw conflict("废弃出库单不存在,请联系平台核对审核结果");
var lines = items.listApplication(application.getCustomerId(), application.getId());
var returnBoxIds = new java.util.HashSet<Long>();
var inventoryBoxMarks = new java.util.HashSet<String>();
for (var snapshot : pallets.findByOutbound(application.getCustomerId(), outbound.getId())) {
var line = lines.stream().filter(i -> Objects.equals(i.getId(), snapshot.getId())).findFirst()
.orElseThrow(() -> conflict("废弃出库明细关联失效"));
@@ -114,11 +117,11 @@ public class CargoDiscardOutboundService {
throw conflict("废弃明细关联退货箱不存在");
snapshot.setCartonMarks(com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton));
}
int boxes = returned ? (returnBoxIds.add(line.getReturnCartonId()) ? 1 : 0) : line.getDiscardPackages();
int boxes = returned ? (returnBoxIds.add(line.getReturnCartonId()) ? 1 : 0) : physicalBoxes(line, inventoryBoxMarks);
snapshot.setPackageCount(boxes);
if ("COMPLETED".equals(line.getPdaStatus())) {
snapshot.setPickedPackageCount(returned ? (Objects.requireNonNullElse(line.getActualDiscardPackages(), 0) > 0 ? boxes : 0)
: Objects.requireNonNullElse(line.getActualDiscardPackages(), 0));
: "INVENTORY".equals(line.getSourceType()) && !stockService.cartonMarks(line).isEmpty() ? boxes : Objects.requireNonNullElse(line.getActualDiscardPackages(), 0));
snapshot.setStatus("PICKED");
}
if (CargoDiscardService.CANCELLED.equals(application.getStatus())) snapshot.setStatus("CANCELLED");
@@ -134,5 +137,11 @@ public class CargoDiscardOutboundService {
outbound.setPackageCount(com.baiyue.lastleg.discard.model.CargoDiscardQuantities.boxes(lines, "OUTBOUNDED".equals(status)));
outbound.setUpdatedAt(LocalDateTime.now()); outbounds.updateById(outbound);
}
/** 保留逐 SKU 来源行,已投影过的同一实箱在后续行记零箱。 */
private int physicalBoxes(com.baiyue.lastleg.discard.entity.CargoDiscardItem line, java.util.Set<String> seen) {
if (!"INVENTORY".equals(line.getSourceType())) return line.getDiscardPackages();
var marks = stockService.cartonMarks(line);
return marks.isEmpty() ? line.getDiscardPackages() : (int)marks.stream().filter(mark -> seen.add(line.getInboundCode() + ":" + mark)).count();
}
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -165,7 +165,10 @@ public class CargoDiscardService {
if (input.cartonIds() != null) {
if (input.cartonIds().isEmpty() || input.cartonIds().size() != input.discardPackages()) throw badRequest("请选择具体废弃箱子,箱数须与选择一致");
String source = input.inventoryPositionId() != null ? "INVENTORY" : "DROPSHIP";
for (Long cartonId : input.cartonIds()) if (!requestedBoxes.add(source + ":" + cartonId)) throw badRequest("同一个箱子不能重复废弃");
for (Long cartonId : input.cartonIds()) {
boolean added = requestedBoxes.add(source + ":" + cartonId);
if (!added && input.inventoryPositionId() == null) throw badRequest("同一个箱子不能重复废弃");
}
}
int sources = (returnSource ? 1 : 0) + (input.orderId() != null ? 1 : 0) + (input.inventoryPositionId() != null ? 1 : 0);
if (sources != 1) {
@@ -202,7 +205,7 @@ public class CargoDiscardService {
throw conflict("One cargo discard application cannot span operating warehouses");
}
// 退货明细为件数,整箱只在全部 SKU 校验完成后按箱 ID 计一次。
if (!returnSource) total = Math.addExact(total, input.discardPackages());
if (!returnSource && input.cartonIds() == null) total = Math.addExact(total, input.discardPackages());
}
for (Long cartonId : returnCartonCache.keySet()) {
@@ -214,6 +217,7 @@ public class CargoDiscardService {
if (!availableSkus.equals(requestedSkus)) throw conflict("目前不支持部分废弃,必须选择退货箱内全部 SKU 库存");
}
total = Math.addExact(total, returnCartonCache.size());
total = Math.addExact(total, requestedBoxes.size());
LocalDateTime now = LocalDateTime.now();
if (!StringUtils.hasText(warehouseName)) warehouseName = warehouseNames().get(warehouseId);
CargoDiscardApplication application = new CargoDiscardApplication();
@@ -236,9 +240,10 @@ public class CargoDiscardService {
// 废弃申请独立承载废弃流程,不创建尾程订单。
Set<Long> reservedReturnCartons = new LinkedHashSet<>();
stockService.reserveAll(customerId, operatorId, application, request.items(), now);
for (CargoDiscardRequests.Item input : request.items()) {
if (input.inventoryPositionId() != null) {
stockService.reserve(customerId, operatorId, application, input, now);
// 普通库存已按完整混装箱批量预留。
} else if (input.returnCartonId() != null) {
reserveReturn(customerId, application, returnCartonCache.get(input.returnCartonId()), input, now,
reservedReturnCartons);
@@ -513,10 +518,15 @@ public class CargoDiscardService {
/** 废弃列表与详情按物理箱汇总,并按每箱单价计算应展示费用。 */
private CargoDiscardResponses.Summary summary(CargoDiscardApplication value, Map<String, String> names) {
int boxes = quantities.boxes(value);
var lines = items.listApplication(value.getCustomerId(), value.getId());
var skuCodes = lines.stream().map(CargoDiscardItem::getSkuCode).filter(s -> s != null && !s.isBlank()).distinct().sorted().toList();
int requested = lines.isEmpty() ? value.getTotalPackages() : com.baiyue.lastleg.discard.model.CargoDiscardQuantities.boxes(lines, false);
Integer actual = lines.stream().anyMatch(i -> i.getActualDiscardPackages() != null)
? com.baiyue.lastleg.discard.model.CargoDiscardQuantities.boxes(lines, true) : null;
return new CargoDiscardResponses.Summary(value.getId(), value.getCustomerId(), value.getDiscardNo(), value.getInboundCodes(),
value.getOverseasWarehouseId(), StringUtils.hasText(value.getOverseasWarehouseName()) ? value.getOverseasWarehouseName() : names.get(value.getOverseasWarehouseId()), boxes,
value.getFeePerPackage() == null ? value.getTotalFee() : value.getFeePerPackage().multiply(BigDecimal.valueOf(boxes)), value.getCurrency(), value.getStatus(), value.getCreatedBy(), value.getCreatedAt(),
value.getReviewedAt(), outboundService.outboundNo(value), value.getCustomerConfirmedAt());
value.getReviewedAt(), outboundService.outboundNo(value), value.getCustomerConfirmedAt(), skuCodes, skuCodes.size(), requested, actual);
}
private void history(String customerId, Long applicationId, String from, String to, String operatorId,
@@ -32,8 +32,14 @@ public class CargoDiscardStatisticsService {
for (var line : lines) {
if (line.getSkuCode() != null && !line.getSkuCode().isBlank()) skus.add(line.getSkuCode());
if (line.getReturnCartonId() == null) {
piecesKnown = false;
if (line.getActualDiscardPackages() != null) actualPiecesKnown = false;
var selectedPieces = dimensions.pieces(application.getCustomerId(), line);
if (selectedPieces == null) piecesKnown = false;
else pieces += selectedPieces;
if (line.getActualDiscardPackages() != null) {
if (line.getActualDiscardPackages() == 0) { /* 实际未废弃商品为零,不推测箱规。 */ }
else if (selectedPieces != null && line.getActualDiscardPackages() == line.getDiscardPackages()) actualPieces += selectedPieces;
else actualPiecesKnown = false;
}
} else {
pieces += line.getDiscardPackages();
if (line.getActualDiscardPackages() != null) actualPieces += line.getActualDiscardPackages();
@@ -2,11 +2,9 @@ package com.baiyue.lastleg.discard.service;
import com.baiyue.lastleg.discard.dto.*;
import com.baiyue.lastleg.discard.entity.*;
import com.baiyue.lastleg.discard.mapper.*;
import com.baiyue.lastleg.inventory.command.dto.InventoryCommandRequests;
import com.baiyue.lastleg.inventory.command.service.InventoryCommandService;
import com.baiyue.lastleg.inventory.entity.*;
import com.baiyue.lastleg.inventory.mapper.*;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
@@ -16,129 +14,233 @@ import org.springframework.web.server.ResponseStatusException;
import java.util.*;
import java.time.LocalDateTime;
/** Stock eligibility is based on physical available positions, independent of the source document type. */
/** 根据实际可用仓位校验废弃库存,精确选箱与无对应关系实点分别结算。 */
@Service
public class CargoDiscardStockService {
@Resource private CargoDiscardInventoryMapper stock;
@Resource private InventoryPositionMapper positions;
@Resource private InventoryBalanceMapper balances;
@Resource private com.baiyue.lastleg.discard.repository.CargoDiscardStockRepository repository;
@Resource private InventoryCommandService commands;
@Resource private CargoDiscardItemMapper items;
@Resource private CargoDiscardCartonMapper links;
@Resource private ObjectMapper objectMapper;
/** 展示可用库存及相关托盘,箱唛完整时才提供逐箱选择。 */
public List<CargoDiscardResponses.Candidate> candidates(String customer, String keyword) {
return stock.genericPositions(customer, keyword).stream().map(position -> {
var balance = balances.selectById(position.getBalanceId());
return repository.candidates(customer, keyword).stream().map(position -> {
var balance = repository.balance(position.getBalanceId());
if (balance == null || !customer.equals(balance.getCustomerId())) throw conflict("库存余额不存在");
long available = Math.min(value(position.getAvailablePackages()), value(balance.getAvailablePackages()));
var cartons = stock.genericCartons(customer, position.getId());
boolean complete = cartons.size() == available && cartons.stream().allMatch(c -> c.getCartonMark() != null && !c.getCartonMark().isBlank())
&& cartons.stream().map(c -> c.getCartonMark()).distinct().count() == cartons.size();
var cartons = repository.cartons(customer, position.getId());
boolean complete = completeCartons(cartons, available);
var boxes = complete ? cartons.stream().map(c -> new CargoDiscardResponses.Box(c.getId(), c.getCartonMark(), position.getPalletNo(),
List.of(new CargoDiscardResponses.CandidateSku(c.getSkuCode(), balance.getProductNameZh(), 1)))).toList() : List.<CargoDiscardResponses.Box>of();
contents(c, balance.getProductNameZh()))).toList() : List.<CargoDiscardResponses.Box>of();
return new CargoDiscardResponses.Candidate(null, "INVENTORY", null, null,
balance.getInboundCode(), balance.getInboundOrderNo(), balance.getOverseasWarehouseId(),
balance.getOverseasWarehouseName(), position.getCreatedAt(), available,
List.of(new CargoDiscardResponses.CandidateSku(sku(balance), balance.getProductNameZh(), available)),
complete ? summarizeSkus(cartons, balance) : List.of(new CargoDiscardResponses.CandidateSku(sku(balance), balance.getProductNameZh(), available)),
position.getId(), position.getPalletNo(), boxes, complete,
complete ? null : "当前库存缺少完整箱唛与托盘对应记录,可按全部库存废弃");
complete ? null : "缺少完整箱唛与托盘对应记录,将预留所选库存,由仓库核对相关托盘并填写实际废弃箱数,未废弃部分释放");
}).filter(c -> c.availablePackages() > 0).toList();
}
/** 校验客户、仓库、SKU、预留上限与具体箱子的归属。 */
public InventoryBalance validate(String customer, CargoDiscardRequests.Item request) {
var position = position(customer, request.inventoryPositionId());
var balance = balances.selectById(position.getBalanceId());
var balance = repository.balance(position.getBalanceId());
if (balance == null || !customer.equals(balance.getCustomerId())
|| !Objects.equals(position.getOverseasWarehouseId(), balance.getOverseasWarehouseId()))
throw conflict("库存不属于当前客户或仓库");
if (!sku(balance).equals(request.skuCode().trim())) throw conflict("SKU 不属于所选库存");
long available = Math.min(value(position.getAvailablePackages()), value(balance.getAvailablePackages()));
if (available <= 0 || request.discardPackages() <= 0 || request.discardPackages() > available) throw conflict("所选废弃库存数量不足");
if (request.cartonIds() != null) {
if (request.cartonIds().size() != request.discardPackages() || new HashSet<>(request.cartonIds()).size() != request.cartonIds().size())
throw conflict("废弃箱子数量与所选箱子不一致或重复");
var cartons = stock.genericCartons(customer, position.getId());
var cartons = repository.cartons(customer, position.getId());
var ids = cartons.stream().map(c -> c.getId()).collect(java.util.stream.Collectors.toSet());
if (cartons.size() != available || cartons.stream().anyMatch(c -> c.getCartonMark() == null || c.getCartonMark().isBlank()) || cartons.stream().map(c -> c.getCartonMark()).distinct().count() != cartons.size() || !ids.containsAll(request.cartonIds())) throw conflict("箱唛库存已变化或不属于所选托盘,请刷新后重选");
} else if (request.discardPackages() != available) throw conflict("部分废弃必须选择具体箱子,不能只填写数量");
if (stock.isDropshipPosition(customer, position.getId()) > 0) throw conflict("一件代发库存必须按真实箱唛选择,不能绕过箱级预留");
if (cartons.stream().filter(c -> request.cartonIds().contains(c.getId())).anyMatch(c -> contents(c, null).stream().noneMatch(s -> request.skuCode().trim().equals(s.skuCode())))) throw conflict("SKU 不属于所选箱子");
} else {
if (!sku(balance).equals(request.skuCode().trim())) throw conflict("SKU 不属于所选库存");
if (request.discardPackages() != available) throw conflict("部分废弃必须选择具体箱子,不能只填写数量");
}
if (repository.dropshipPosition(customer, position.getId())) throw conflict("一件代发库存必须按真实箱唛选择,不能绕过箱级预留");
return balance;
}
/** 预留所选实收箱并保存箱号快照,转运箱从已清点状态进入待废弃。 */
public void reserve(String customer, String operator, CargoDiscardApplication application, CargoDiscardRequests.Item request, LocalDateTime at) {
if (stock.lockGenericPosition(customer, request.inventoryPositionId()) == null) throw conflict("库存仓位不存在");
if (repository.lockPosition(customer, request.inventoryPositionId()) == null) throw conflict("库存仓位不存在");
var balance = validate(customer, request);
reserveValidated(customer, operator, application, request, at, balance, repository.cartons(customer, request.inventoryPositionId()), new HashSet<>(), new HashSet<>());
}
/** 整箱混装必须包含全部 SKU 仓位;先锁仓位并校验全部事实,再按实物箱仅锁定一次。 */
public void reserveAll(String customer, String operator, CargoDiscardApplication application, List<CargoDiscardRequests.Item> requests, LocalDateTime at) {
var stocks = requests.stream().filter(r -> r.inventoryPositionId() != null).toList();
stocks.stream().map(CargoDiscardRequests.Item::inventoryPositionId).distinct().sorted().forEach(id -> {
if (repository.lockPosition(customer, id) == null) throw conflict("库存仓位不存在");
});
var balances = new HashMap<Long, InventoryBalance>();
var cartons = new HashMap<Long, List<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow>>();
var selectedSkus = new HashMap<String, Set<String>>();
for (var request : stocks) {
balances.put(request.inventoryPositionId(), validate(customer, request));
var facts = repository.cartons(customer, request.inventoryPositionId());
cartons.put(request.inventoryPositionId(), facts);
for (var carton : facts) if (request.cartonIds() == null || request.cartonIds().contains(carton.getId()))
selectedSkus.computeIfAbsent(carton.getSourceType() + ":" + carton.getId(), k -> new HashSet<>()).add(request.skuCode().trim());
}
for (var request : stocks) for (var carton : cartons.get(request.inventoryPositionId())) {
if (request.cartonIds() != null && !request.cartonIds().contains(carton.getId())) continue;
var required = contents(carton, null).stream().map(CargoDiscardResponses.CandidateSku::skuCode).collect(java.util.stream.Collectors.toSet());
if (required.size() > 1 && request.cartonIds() == null) throw conflict("混装箱必须选择具体箱子及箱内全部 SKU 库存");
if (!selectedSkus.get(carton.getSourceType() + ":" + carton.getId()).containsAll(required)) throw conflict("混装箱必须选择箱内全部 SKU 库存");
}
var lockedBoxes = new HashSet<String>();
var heldBoxes = new HashSet<String>();
for (var request : stocks) reserveValidated(customer, operator, application, request, at,
balances.get(request.inventoryPositionId()), cartons.get(request.inventoryPositionId()), lockedBoxes, heldBoxes);
}
/** 使用本事务变更箱状态前的完整事实,为每个 SKU 分别预留并保存相同箱唛快照。 */
private void reserveValidated(String customer, String operator, CargoDiscardApplication application, CargoDiscardRequests.Item request, LocalDateTime at,
InventoryBalance balance, List<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow> availableCartons, Set<String> lockedBoxes, Set<String> heldBoxes) {
var position = position(customer, request.inventoryPositionId());
var line = new CargoDiscardItem(); line.setId(IdWorker.getId()); line.setApplicationId(application.getId());
line.setCustomerId(customer); line.setSourceType("INVENTORY"); line.setInventoryPositionId(position.getId());
line.setInboundCode(balance.getInboundCode()); line.setSkuCode(sku(balance)); line.setProductName(balance.getProductNameZh());
line.setAvailablePackagesSnapshot(Math.toIntExact(Math.min(value(position.getAvailablePackages()), value(balance.getAvailablePackages())))); line.setDiscardPackages(request.discardPackages()); line.setCreatedAt(at);
var availableCartons = stock.genericCartons(customer, position.getId());
line.setInboundCode(balance.getInboundCode()); line.setSkuCode(request.skuCode().trim()); line.setProductName(sku(balance).equals(line.getSkuCode()) ? balance.getProductNameZh() : null);
line.setAvailablePackagesSnapshot(availableCartons.isEmpty() ? Math.toIntExact(Math.min(value(position.getAvailablePackages()), value(balance.getAvailablePackages()))) : availableCartons.size()); line.setDiscardPackages(request.discardPackages()); line.setCreatedAt(at);
var selected = request.cartonIds() == null
? (availableCartons.size() == request.discardPackages() ? availableCartons : List.<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow>of())
? (completeCartons(availableCartons, request.discardPackages()) ? availableCartons : List.<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow>of())
: availableCartons.stream().filter(c -> request.cartonIds().contains(c.getId())).toList();
if (!selected.isEmpty()) {
for (var carton : selected) {
if (!lockedBoxes.add(carton.getSourceType() + ":" + carton.getId())) continue;
if (changeBox(customer, carton.getId(), carton.getSourceType(), "TRANSFER".equals(carton.getSourceType()) ? "COUNTED" : "AVAILABLE", "DISCARD_PENDING") != 1) throw conflict("箱子已被其他作业占用,请刷新后重选");
var link = new CargoDiscardCarton(); link.setId(IdWorker.getId()); link.setCustomerId(customer); link.setApplicationId(application.getId());
link.setItemId(line.getId()); link.setSourceType(carton.getSourceType()); link.setCartonId(carton.getId()); link.setCartonMark(carton.getCartonMark()); link.setCreatedAt(at); links.insert(link);
link.setItemId(line.getId()); link.setSourceType(carton.getSourceType()); link.setCartonId(carton.getId()); link.setCartonMark(carton.getCartonMark()); link.setCreatedAt(at); repository.saveCarton(link);
}
snapshotMarks(line, selected.stream().map(c -> c.getCartonMark()).toList());
line.setCartonScanRequired(request.discardPackages() < value(position.getAvailablePackages()) + value(position.getHoldPackages()) + value(position.getAllocatedPackages()) + value(position.getPickedPackages()));
} else if (position.getPalletNo() == null || position.getPalletNo().isBlank()) {
var marks = stock.looseCartonMarks(customer, position.getId());
var marks = repository.looseMarks(customer, position.getId());
if (marks.size() != request.discardPackages() || marks.stream().distinct().count() != marks.size()) throw conflict("散箱库存缺少完整箱唛,请先核对实物箱级入库记录");
snapshotMarks(line, marks);
}
commands.hold(customer, operator, move(application, line, request.discardPackages(), "HOLD"));
items.insert(line);
int physical = selected.isEmpty() ? request.discardPackages() : (int)selected.stream().filter(c -> heldBoxes.add(position.getId() + ":" + c.getSourceType() + ":" + c.getId())).count();
if (physical > 0) commands.hold(customer, operator, move(application, line, physical, "HOLD"));
repository.saveItem(line);
}
/** 同一仓位可能承载混装箱,完整 SKU 候选来自实箱而不是库存余额的首 SKU。 */
private List<CargoDiscardResponses.CandidateSku> summarizeSkus(List<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow> cartons, InventoryBalance balance) {
var boxes = new LinkedHashMap<String, Long>(); var pieces = new HashMap<String, Long>(); var unknown = new HashSet<String>();
for (var carton : cartons) for (var content : contents(carton, null)) {
boxes.merge(content.skuCode(), 1L, Math::addExact);
if (content.availablePieces() == null) unknown.add(content.skuCode()); else pieces.merge(content.skuCode(), content.availablePieces(), Math::addExact);
}
return boxes.entrySet().stream().map(e -> new CargoDiscardResponses.CandidateSku(e.getKey(), sku(balance).equals(e.getKey()) ? balance.getProductNameZh() : null,
e.getValue(), unknown.contains(e.getKey()) ? null : pieces.get(e.getKey()))).toList();
}
/** 箱数、箱唛和唯一性均完整时,才允许将库存对应到具体箱子。 */
private boolean completeCartons(List<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow> cartons, long count) {
return cartons.size() == count && cartons.stream().allMatch(c -> c.getCartonMark() != null && !c.getCartonMark().isBlank())
&& cartons.stream().map(c -> c.getCartonMark()).distinct().count() == cartons.size();
}
/** 转运实收 JSON 提供完整 SKU 与件数;无 JSON 的单 SKU 来源保留箱数单位。 */
private List<CargoDiscardResponses.CandidateSku> contents(com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow carton, String productName) {
if (carton.getSkuItemsJson() == null || carton.getSkuItemsJson().isBlank())
return List.of(new CargoDiscardResponses.CandidateSku(carton.getSkuCode(), productName, 1));
try {
var values = objectMapper.readTree(carton.getSkuItemsJson());
if (!values.isArray()) throw conflict("箱内 SKU 事实不完整");
var quantities = new LinkedHashMap<String, Long>();
for (var value : values) {
String code = value.path("skuCode").asText().trim(); long pieces = value.path("quantity").asLong();
if (code.isEmpty() || pieces <= 0) throw conflict("箱内 SKU 事实不完整");
quantities.merge(code, pieces, Math::addExact);
}
if (quantities.isEmpty()) throw conflict("箱内 SKU 事实不完整");
return quantities.entrySet().stream().map(e -> new CargoDiscardResponses.CandidateSku(e.getKey(), Objects.equals(e.getKey(), carton.getSkuCode()) ? productName : null, 1, e.getValue())).toList();
} catch (com.fasterxml.jackson.core.JsonProcessingException e) { throw conflict("箱内 SKU 事实无法读取"); }
}
/** 驳回或取消时恢复所选箱状态并释放本次冻结数量。 */
public void release(String customer, CargoDiscardApplication application, CargoDiscardItem line) {
changeSelectedCartons(customer, application, line, "AVAILABLE");
commands.release(customer, application.getCreatedBy(), move(application, line, line.getDiscardPackages(), "RELEASE"));
int physical = physicalPackages(customer, application, line);
if (physical > 0) commands.release(customer, application.getCreatedBy(), move(application, line, physical, "RELEASE"));
}
/** 无逐箱对应关系时按仓库实点扣冻结库存,未废弃余量在同一作业事务释放。 */
@org.springframework.transaction.annotation.Transactional(propagation = org.springframework.transaction.annotation.Propagation.MANDATORY)
public void discard(String customer, String operator, CargoDiscardApplication application, CargoDiscardItem line, int actual) {
if (actual != line.getDiscardPackages()) throw conflict("必须完成本次申请所选全部箱子,不能漏出");
changeSelectedCartons(customer, application, line, "DISCARDED");
commands.discardHeld(customer, operator, move(application, line, actual, "DISCARD"));
if (actual < 0 || actual > line.getDiscardPackages()) throw conflict("实际废弃箱数不能超过申请预留箱数");
if (!actualQuantityEditable(line) && actual != line.getDiscardPackages())
throw conflict("必须完成本次申请所选全部箱子,不能漏出");
// 已选择具体箱子的作业仍按箱唛结算,不能按数量猜测哪些箱已被废弃。
if (!actualQuantityEditable(line)) changeSelectedCartons(customer, application, line, "DISCARDED");
int physical = actualQuantityEditable(line) ? actual : physicalPackages(customer, application, line);
if (physical > 0) commands.discardHeld(customer, operator, move(application, line, physical, "DISCARD"));
int remaining = line.getDiscardPackages() - actual;
if (remaining > 0) commands.release(customer, operator, move(application, line, remaining, "ACTUAL_RELEASE"));
}
private int changeBox(String customer, Long cartonId, String source, String from, String to) {
if ("TRANSFER".equals(source)) return stock.changeTransferCartonStatus(customer, cartonId, from, to);
if (!"INBOUND".equals(source)) throw conflict("箱子库存来源不正确");
return stock.changeGenericCartonStatus(customer, cartonId, from, to);
/** 同仓位同箱只由首个 SKU 明细执行库存命令;其他 SKU 保存件数事实,不重复扣物理箱桶。 */
private int physicalPackages(String customer, CargoDiscardApplication application, CargoDiscardItem line) {
var marks = cartonMarks(line);
if (marks.isEmpty()) return line.getDiscardPackages();
var previous = new HashSet<String>();
for (var other : repository.applicationItems(customer, application.getId())) {
if (Objects.equals(other.getInventoryPositionId(), line.getInventoryPositionId()) && other.getId() != null && line.getId() != null && other.getId() < line.getId()) previous.addAll(cartonMarks(other));
}
return (int)marks.stream().filter(mark -> !previous.contains(mark)).count();
}
/** 只有未保存具体箱唛的普通仓位库存允许仓库按实点箱数完成。 */
public boolean actualQuantityEditable(CargoDiscardItem line) {
return "INVENTORY".equals(line.getSourceType()) && line.getInventoryPositionId() != null
&& cartonMarks(line).isEmpty() && !Boolean.TRUE.equals(line.getCartonScanRequired());
}
/** 按箱来源执行带原状态条件的变更。 */
private int changeBox(String customer, Long cartonId, String source, String from, String to) {
if ("TRANSFER".equals(source)) return repository.changeTransferCarton(customer, cartonId, from, to);
if (!"INBOUND".equals(source)) throw conflict("箱子库存来源不正确");
return repository.changeInboundCarton(customer, cartonId, from, to);
}
/** 保存本次选箱事实,后续作业不得按数量猜测箱唛。 */
private void snapshotMarks(CargoDiscardItem line, List<String> marks) {
try { line.setCartonMarksJson(objectMapper.writeValueAsString(marks)); }
catch (Exception e) { throw new IllegalStateException("Cannot snapshot carton marks", e); }
}
/** 按真实箱来源完成废弃或释放,转运箱释放后恢复已清点状态。 */
/** 仅变更当前申请明细保存的箱子,转运箱释放后恢复已清点状态。 */
private void changeSelectedCartons(String customer, CargoDiscardApplication application, CargoDiscardItem line, String status) {
for (var link : links.listApplication(customer, application.getId())) {
for (var link : repository.selectedCartons(customer, application.getId())) {
if (Objects.equals(link.getItemId(), line.getId()) && changeBox(customer, link.getCartonId(), link.getSourceType(), "DISCARD_PENDING", "TRANSFER".equals(link.getSourceType()) && "AVAILABLE".equals(status) ? "COUNTED" : status) != 1)
throw conflict("预留箱子的库存状态发生变化");
}
}
/** 库存命令使用申请和明细构成的稳定来源与幂等键。 */
private InventoryCommandRequests.Move move(CargoDiscardApplication application, CargoDiscardItem line, int count, String action) {
String cycle = "CARGO_DISCARD:" + application.getId() + ":" + line.getId();
return new InventoryCommandRequests.Move(line.getInventoryPositionId(), count, application.getDiscardNo(),
null, cycle, cycle + ":" + action, "货物废弃 " + action);
}
/** 读取并核对客户指定库存仓位。 */
public InventoryPosition position(String customer, Long id) {
var position = positions.findTenantPosition(customer, id);
var position = repository.position(customer, id);
if (position == null) throw conflict("废弃库存仓位不存在或不属于当前客户");
return position;
}
/** 只解析申请保存的箱唛,缺失对应关系保留为空。 */
public List<String> cartonMarks(CargoDiscardItem line) {
if (line.getCartonMarksJson() == null) return List.of();
try { return objectMapper.readValue(line.getCartonMarksJson(), new com.fasterxml.jackson.core.type.TypeReference<List<String>>() {}); }
catch (Exception e) { throw new IllegalStateException("Cannot read carton marks", e); }
}
/** 无 SKU 来源保留未指定标记,不猜测商品。 */
private static String sku(InventoryBalance balance) { return balance.getSkuCode() == null || balance.getSkuCode().isBlank() ? "UNSPECIFIED" : balance.getSkuCode(); }
/** 空库存桶按零处理。 */
private static long value(Long value) { return value == null ? 0 : value; }
/** 返回可恢复的业务冲突。 */
private static ResponseStatusException conflict(String message) { return new ResponseStatusException(HttpStatus.CONFLICT, message); }
}
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.dispatch.fleet;
import com.baiyue.lastleg.dispatch.port.DispatchContracts;
import com.baiyue.lastleg.dispatch.port.DispatchDetailReader;
import com.baiyue.lastleg.dispatch.port.DispatchViews;
import com.baiyue.lastleg.dispatch.service.DispatchAggregateService;
import org.springframework.stereotype.Component;
/** 只读委托既有排车应用服务,运营域不引用主流程实现或持久化实体。 */
@Component
public class DispatchDetailReadAdapter implements DispatchDetailReader {
private final DispatchAggregateService dispatch;
/** 复用唯一原排车详情提供者,不建立第二套查询规则。 */
public DispatchDetailReadAdapter(DispatchAggregateService dispatch) {
this.dispatch = dispatch;
}
/** 原单资格与可见性仍由原应用服务核对。 */
@Override
public DispatchViews.Detail detail(DispatchContracts.Actor actor, String dispatchNo) {
return dispatch.detail(actor, dispatchNo);
}
}
@@ -261,7 +261,8 @@ public interface DispatchCandidateMapper {
"<if test='customerId != null and customerId != \"\"'>AND a.customer_id=#{customerId} </if>" +
"<if test='relabelNo != null and relabelNo != \"\"'>AND a.relabel_no=#{relabelNo} </if>" +
"<if test='orderNo != null and orderNo != \"\"'>AND (a.relabel_no LIKE CONCAT('%',#{orderNo},'%') OR ri.source_inbound_code LIKE CONCAT('%',#{orderNo},'%') OR ri.source_inbound_order_no LIKE CONCAT('%',#{orderNo},'%')) </if>" +
"AND pos.hold_packages &gt; 0 " +
// 未绑定实托的位置不是可选运输来源;完整申请中的缺失组成仍由提供者返回阻断原因。
"AND pos.hold_packages &gt; 0 AND pos.pallet_id &gt; 0 " +
"AND NOT EXISTS (SELECT 1 FROM ll_dispatch_item di JOIN ll_dispatch_order existing_dispatch " +
"ON existing_dispatch.id=di.dispatch_order_id " +
"WHERE di.customer_id=a.customer_id AND di.source_stage='RELABEL' AND di.order_refs=a.relabel_no " +
@@ -20,7 +20,7 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import com.baiyue.lastleg.dispatch.repository.DispatchItemSourceRepository;
import com.baiyue.lastleg.dispatch.service.DispatchItemSourceService;
import com.baiyue.lastleg.dispatch.port.DispatchSourceAllocation;
@Service
public class DispatchPickOrderAttributionService {
@@ -39,7 +39,7 @@ public class DispatchPickOrderAttributionService {
/** 第四来源分支链接真实冻结贡献,全部归属、履约计数和库存跟随原扫码事务提交。 */
@org.springframework.transaction.annotation.Transactional(propagation=org.springframework.transaction.annotation.Propagation.MANDATORY)
public void attributeRelabel(String customerId,DispatchPdaPick pick,Long orderId,List<DispatchItemSourceService.Allocation> allocations) {
public void attributeRelabel(String customerId,DispatchPdaPick pick,Long orderId,List<DispatchSourceAllocation> allocations) {
long packages=0,quantity=0;var seen=new java.util.HashSet<Long>();
for(var allocation:allocations) {
var source=allocation.dispatchItemSourceId()==null?null:relabelSources.find(allocation.dispatchItemSourceId());
@@ -0,0 +1,7 @@
package com.baiyue.lastleg.dispatch.port;
/** 原排车详情的只读应用端口,供运营视图组合真实履约事实。 */
public interface DispatchDetailReader {
/** 沿原排车读取及身份守卫,不创建单据、不推进状态。 */
DispatchViews.Detail detail(DispatchContracts.Actor actor, String dispatchNo);
}
@@ -0,0 +1,4 @@
package com.baiyue.lastleg.dispatch.port;
/** 一次真实拣货消费的冻结来源额度;件数未知时保留空,不接受请求伪造来源身份。 */
public record DispatchSourceAllocation(Long dispatchItemSourceId, long packages, Long productQuantity) { }
@@ -10,6 +10,7 @@ import com.baiyue.lastleg.dispatch.model.DispatchPalletCandidate;
import com.baiyue.lastleg.dispatch.port.*;
import com.baiyue.lastleg.dispatch.repository.DispatchAggregateRepository;
import com.baiyue.lastleg.dispatch.repository.DispatchSourceRepository;
import com.baiyue.lastleg.fleet.ownedbusiness.port.OwnedBusinessOwnershipCapture;
import com.baiyue.lastleg.fleet.trip.FleetExecutionModels;
import com.baiyue.lastleg.fleet.trip.FleetTripExecutionService;
import com.fasterxml.jackson.core.JsonProcessingException;
@@ -47,6 +48,7 @@ public class DispatchAggregateService implements DispatchExecutionPort,DispatchA
private final ObjectMapper json;
@jakarta.annotation.Resource private com.baiyue.lastleg.dispatch.gateway.DispatchEvidenceGateway evidence;
@jakarta.annotation.Resource private com.baiyue.lastleg.dispatch.repository.DispatchExecutionRepository executionReads;
@jakarta.annotation.Resource private OwnedBusinessOwnershipCapture ownedBusinessOwnership;
/** 领域编排只访问Repository和提供者应用入口。 */
public DispatchAggregateService(DispatchAggregateRepository repository, DispatchSourceRepository sources,
@@ -522,6 +524,10 @@ public class DispatchAggregateService implements DispatchExecutionPort,DispatchA
fleet.confirmDispatchLoad(number,actor.operatorId(),preview.manifestHash(),cargo,measurements.stream().map(m->new FleetExecutionModels.Measurement(m.warehousePalletId().toString(),m.palletSpaces(),m.weightKg(),m.volumeCbm(),m.deliveryIndex())).toList(),request.remark());
var at=Instant.now().truncatedTo(ChronoUnit.MILLIS);var confirmed=new ConfirmedLoad(preview.manifestHash(),measurements,actor.operatorId(),at);
row.setLoadingConfirmationJson(write(confirmed));row.setLoadingCompletionHash(hashes.source(confirmed));row.setLoadingCompletedAt(utc(at));row.setStage(Stage.AFTER_LOADING.name());
// 同原装车事务保存车辆归属证据;后续档案变化不能改写本趟自有/外配分类。
// 原命令重放已在方法入口返回,不重复捕获,也不在GET或旧单上补造历史。
ownedBusinessOwnership.capture(row.getId(),context.resources().vehicle().vehicleId(),
context.resources().vehicle().mode().name(),row.getLoadingCompletionHash(),at);
return saveCommand(row,actor,identity,request.remark(),new DispatchResults.Loaded(row.getLoadingCompletionHash(),at,confirmed));
}
@@ -6,6 +6,7 @@ import com.baiyue.common.core.exception.BizException;
import com.baiyue.lastleg.dispatch.entity.*;
import com.baiyue.lastleg.dispatch.mapper.DispatchSourceMapper;
import com.baiyue.lastleg.dispatch.repository.DispatchItemSourceRepository;
import com.baiyue.lastleg.dispatch.port.DispatchSourceAllocation;
import com.baiyue.lastleg.relabel.port.RelabelDispatchSourcePort;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
@@ -23,9 +24,6 @@ public class DispatchItemSourceService {
/** 来源事实经提供者读取,冻结贡献及已消费数经本域仓储读取。 */
public DispatchItemSourceService(DispatchItemSourceRepository repository,RelabelDispatchSourcePort relabel,ObjectMapper json){this.repository=repository;this.relabel=relabel;this.json=json;}
/** packages是本次实际消费量,件数未知保留空;不是请求可伪造的来源身份。 */
public record Allocation(Long dispatchItemSourceId,long packages,Long productQuantity) { }
/** 主单原事务已锁齐全部来源与库存;所有当前成员一起核对,仅为新增明细追加不可变快照。 */
@Transactional(propagation=Propagation.MANDATORY)
public void capture(DispatchAggregate root,List<DispatchItem> all,List<DispatchItem> added,LocalDateTime at) {
@@ -108,7 +106,7 @@ public class DispatchItemSourceService {
/** 本客户本实托的全部剩余贡献必须累计核对HOLD,逐item单独足够不能证明共享position总量足够。 */
@Transactional(propagation=Propagation.MANDATORY)
public List<Allocation> allocate(long dispatch,DispatchItem item,long positionId,long packages,long productQuantity,String cartonMark,List<DispatchSourceMapper.Stock> actualStock) {
public List<DispatchSourceAllocation> allocate(long dispatch,DispatchItem item,long positionId,long packages,long productQuantity,String cartonMark,List<DispatchSourceMapper.Stock> actualStock) {
var all=repository.all(dispatch);var consumed=repository.pickedAll(List.of(dispatch)).stream().collect(Collectors.toMap(p->p.sourceId(),p->p));
var expected=new HashMap<Long,Long>();
for(var source:all)if(Objects.equals(item.getCustomerId(),source.getCustomerId()) && Objects.equals(item.getWarehousePalletId(),source.getWarehousePalletId())) {
@@ -127,14 +125,14 @@ public class DispatchItemSourceService {
for(var row:rows){long left=row.getPackageCount()-(consumed.containsKey(row.getId())?consumed.get(row.getId()).packages():0);remaining.put(row.getId(),left);total=Math.addExact(total,left);}
if(packages<=0 || packages>total)throw conflict("实际扫码超过本换标来源本位置的剩余箱数");
if(rows.size()>1 && packages!=total)throw conflict("本位置含多条换标贡献,请扫描具体箱唛后确认部分箱数");
var result=new ArrayList<Allocation>();long knownQuantity=0;
var result=new ArrayList<DispatchSourceAllocation>();long knownQuantity=0;
for(var row:rows)if(row.getProductQuantity()!=null){long used=consumed.containsKey(row.getId())?consumed.get(row.getId()).productQuantity():0;long left=row.getProductQuantity()-used;if(left<0)throw conflict("换标实际件数超过来源贡献");knownQuantity=Math.addExact(knownQuantity,left);}
if(rows.size()>1) {
if(productQuantity!=knownQuantity)throw conflict("多来源件数不能推算,请扫描明确箱唛并确认实际件数");
for(var row:rows){Long quantity=row.getProductQuantity()==null?null:row.getProductQuantity()-(consumed.containsKey(row.getId())?consumed.get(row.getId()).productQuantity():0);result.add(new Allocation(row.getId(),remaining.get(row.getId()),quantity));}
for(var row:rows){Long quantity=row.getProductQuantity()==null?null:row.getProductQuantity()-(consumed.containsKey(row.getId())?consumed.get(row.getId()).productQuantity():0);result.add(new DispatchSourceAllocation(row.getId(),remaining.get(row.getId()),quantity));}
} else {
var row=rows.get(0);if(row.getProductQuantity()!=null && (productQuantity>knownQuantity || packages==total && productQuantity!=knownQuantity))throw conflict("实际扫码件数与本来源剩余件数不一致");
result.add(new Allocation(row.getId(),packages,row.getProductQuantity()==null && productQuantity==0?null:productQuantity));
result.add(new DispatchSourceAllocation(row.getId(),packages,row.getProductQuantity()==null && productQuantity==0?null:productQuantity));
}
return List.copyOf(result);
}
@@ -65,7 +65,7 @@ public class DispatchPickingService {
boolean nativeReturn="RETURN_RELABEL".equals(item.getSourceStage());
if(nativeReturn?request.positionId()!=null:request.positionId()==null)throw bad(nativeReturn?"退货换标请扫描来源箱唛":"普通入仓请选本托实际库存仓位");
long pickId=IdWorker.getId();Long returnCartonId=null;boolean ordinaryRelabel=!nativeReturn && "RELABEL_ORDER".equals(item.getSourceBusinessType());
List<DispatchItemSourceService.Allocation> relabelAllocations=List.of();
List<DispatchSourceAllocation> relabelAllocations=List.of();
if(nativeReturn) {
attribution.prepareNativeReturn(item.getCustomerId(),item.getOrderId());
returnCartonId=returns.pick(item,request.cartonMark(),request.packages(),request.productQuantity(),pickId,number).getId();
@@ -90,7 +90,9 @@ public class DispatchService {
if(facts==null)throw new ResponseStatusException(HttpStatus.CONFLICT,"实托完整来源快照缺失");
reasons.addAll(facts.blockReasons());
if(!facts.complete() && facts.blockReasons().isEmpty())reasons.add("实托实际绑定组成未核齐");
facts.positions().stream().map(RelabelDispatchSourcePort.Position::warehousePalletId).filter(Objects::nonNull).forEach(pallets::add);
// 缺失的实托身份保留在事实与阻断原因中,不能拿零值扩组或传给严格的实托查询入口。
facts.positions().stream().map(RelabelDispatchSourcePort.Position::warehousePalletId)
.filter(id->id!=null && id>0).forEach(pallets::add);
for(var app:facts.applications())applications.put(app.relabelNo(),app.customerId());
var codes=rows.values().stream().map(DispatchPalletCandidate::palletNo).filter(Objects::nonNull).distinct().toList();
for(var app:wholeSources.nativeApplications(seed.overseasWarehouseId(),codes))applications.put(app.relabelNo(),app.customerId());
@@ -75,7 +75,9 @@ public record LastlegOrderSummary(
LocalDateTime updatedAt,
@Schema(description = "同一主单关联的全部换标子单及各自状态,按创建时间排序")
List<RelabelSubOrder> relabelApplications,
BusinessSource businessSource
BusinessSource businessSource,
@Schema(description = "仓储转运专属预报、历史实收及当前箱托数量;其他业务为空")
com.baiyue.lastleg.transfer.dto.TransferQuantityView warehouseTransferQuantity
) {
@Schema(description = "从正式单据关联读取的商业来源;与履约类型 orderType 独立")
public record BusinessSource(String businessType, String label, String businessOrderNo, String externalBookingNo) { }
@@ -0,0 +1,78 @@
package com.baiyue.lastleg.fleet.ownedbusiness.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.baiyue.lastleg.fleet.ownedbusiness.service.*;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import org.springframework.http.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/** 只读原排车装车后事实,仅附加登记和照片可写。 */
@RestController
@Validated
@RequestMapping("/api/platform/v1/last-leg/fleet/owned-business")
public class OwnedBusinessController {
private final OwnedBusinessQueryService queries;
private final OwnedBusinessRecordService records;
private final OwnedBusinessPhotoService photos;
private final OwnedBusinessSupport access;
/** Controller不直调Repository/Mapper,身份只取会话。 */
public OwnedBusinessController(OwnedBusinessQueryService queries,OwnedBusinessRecordService records,OwnedBusinessPhotoService photos,OwnedBusinessSupport access) {
this.queries=queries;this.records=records;this.photos=photos;this.access=access;
}
/** 列表和完整统计一次返回。 */
@GetMapping
@PreAuthorize("hasAuthority('platform:fleet:owned-business:list')")
public ApiResponse<ListResult> list(@AuthenticationPrincipal AuthenticatedUser user,@Valid Query query){return ApiResponse.success(queries.list(access.actor(user),query));}
/** list权限包含独立详情。 */
@GetMapping("/{dispatchNo}")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:list')")
public ApiResponse<Detail> detail(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo){return ApiResponse.success(queries.detail(access.actor(user),dispatchNo));}
/** 原排车和附加历史在同一快照分页,不逐条GET。 */
@GetMapping("/{dispatchNo}/history")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:list')")
public ApiResponse<HistoryPage> history(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,
@RequestParam(defaultValue="1") @Min(1) Integer page,@RequestParam(defaultValue="20") @Min(1) @Max(200) Integer size) {
return ApiResponse.success(queries.history(access.actor(user),dispatchNo,page,size));
}
/** 金额可以更正/清空,但不推进主单或触发财务。 */
@PutMapping("/{dispatchNo}/operations")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:edit')")
public ApiResponse<Detail> save(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,@Valid @RequestBody SaveOperations request) {
return ApiResponse.success(records.save(access.actor(user),dispatchNo,request));
}
/** 上传仅准备File,关联保存另有独立原键。 */
@PostMapping(value="/{dispatchNo}/photos/{slot}/uploads",consumes=MediaType.MULTIPART_FORM_DATA_VALUE)
@PreAuthorize("hasAuthority('platform:fleet:owned-business:upload')")
public ApiResponse<Photo> upload(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,@PathVariable PhotoSlot slot,
@RequestParam @Size(min=8,max=128) String idempotencyKey,@RequestPart("file") MultipartFile file) {
return ApiResponse.success(photos.upload(access.actor(user),dispatchNo,slot,idempotencyKey,file));
}
/** 绑定失败保留fileId和原请求,不重新上传。 */
@PutMapping("/{dispatchNo}/photos/{slot}")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:upload')")
public ApiResponse<Detail> bind(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,@PathVariable PhotoSlot slot,@Valid @RequestBody BindPhoto request) {
return ApiResponse.success(photos.bind(access.actor(user),dispatchNo,slot,request));
}
/** 附件只允许当前或精确历史引用读取。 */
@GetMapping("/{dispatchNo}/photos/{slot}/files/{fileId}/content")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:list')")
public ResponseEntity<byte[]> content(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,
@PathVariable PhotoSlot slot,@PathVariable @Positive long fileId,@RequestParam(required=false) @Min(1) Long revisionVersion) {
var result=photos.content(access.actor(user),dispatchNo,slot,fileId,revisionVersion);
return ResponseEntity.ok().cacheControl(CacheControl.noStore()).contentType(MediaType.parseMediaType(result.photo().contentType()))
.header("X-Content-Type-Options","nosniff").body(result.content());
}
/** 不自动补写或向别的账号披露原命令。 */
@GetMapping("/{dispatchNo}/commands/{idempotencyKey}")
@PreAuthorize("hasAuthority('platform:fleet:owned-business:list')")
public ApiResponse<Command> command(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable String dispatchNo,@PathVariable String idempotencyKey) {
return ApiResponse.success(photos.command(access.actor(user),dispatchNo,idempotencyKey));
}
}
@@ -0,0 +1,86 @@
package com.baiyue.lastleg.fleet.ownedbusiness.gateway;
import com.baiyue.lastleg.config.LastlegRestClientFactory;
import com.baiyue.lastleg.config.LastlegRestClientProperties;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.PhotoSlot;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.http.client.MultipartBodyBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClient;
import java.time.LocalDateTime;
import java.util.Set;
import com.baiyue.common.core.exception.BizException;
import com.baiyue.common.core.api.ResultCode;
/** File保存照片,本域另行授权原排车及分类引用。 */
@Component
public class HttpOwnedBusinessFileGateway implements OwnedBusinessFileGateway {
public static final long MAX_SIZE=10L*1024*1024;
private static final String PATH="/internal/file/v1/business-files/0/{type}/{dispatch}";
private final RestClient client;
private final String token;
/** 沿既有内部File客户端,保持外部访问域封闭。 */
public HttpOwnedBusinessFileGateway(RestClient.Builder builder,LastlegRestClientFactory factory,LastlegRestClientProperties properties,
@Value("${baiyue.clients.file.url:http://127.0.0.1:9205}") String baseUrl,
@Value("${baiyue.security.internal-service-token:}") String token) {
client=factory.build(builder,baseUrl,properties.getCustomerVisitFile());this.token=token;
}
/** MIME和字节签名一起校验,File仍执行其权威校验。 */
public static void validate(Upload upload) {
if(upload==null || upload.fileName()==null || upload.fileName().isBlank() || upload.fileName().length()>255
|| upload.content()==null || upload.content().length==0 || upload.content().length>MAX_SIZE
|| !image(upload.contentType()) || !signature(upload.contentType(),upload.content()))
throw bad("照片须为非空真实JPG/PNG,最大10MiB");
}
/** 使用原图片字节,未知结果不能换键或自动重传。 */
@Override public Evidence upload(long dispatchId,PhotoSlot slot,String operatorId,Upload upload) {
validate(upload);var body=new MultipartBodyBuilder();
body.part("file",new ByteArrayResource(upload.content()){
/** 保留本轮原文件名,不生成占位证据。 */
@Override public String getFilename(){return upload.fileName();}
}).contentType(MediaType.parseMediaType(upload.contentType()));
var result=client.post().uri(PATH,slot.businessType(),dispatchId).header("X-Internal-Service-Token",token)
.header("X-Operator-Id",operatorId).contentType(MediaType.MULTIPART_FORM_DATA).body(body.build()).retrieve().body(Envelope.class);
return verified(result,dispatchId,slot,null);
}
/** 不能借另一客户、另一分类或另一排车的文件授权。 */
@Override public Evidence metadata(long dispatchId,PhotoSlot slot,long fileId) {
return verified(client.get().uri(PATH+"/{file}",slot.businessType(),dispatchId,fileId)
.header("X-Internal-Service-Token",token).retrieve().body(Envelope.class),dispatchId,slot,fileId);
}
/** 防止把错误页或其他内容冒充图片返回。 */
@Override public byte[] content(long dispatchId,PhotoSlot slot,long fileId) {
var info=metadata(dispatchId,slot,fileId);
byte[] bytes=client.get().uri(PATH+"/{file}/content",slot.businessType(),dispatchId,fileId)
.header("X-Internal-Service-Token",token).retrieve().body(byte[].class);
if(bytes==null || bytes.length!=info.sizeBytes() || !signature(info.contentType(),bytes))throw conflict("图片内容与元数据不一致");
return bytes;
}
/** 所有归属及内容元数据必须严格匹配原dispatch内部ID。 */
public static Evidence verified(Envelope response,long dispatchId,PhotoSlot slot,Long expected) {
if(response==null || !"200".equals(response.code()) || response.data()==null)throw conflict("照片服务未返回明确成功");
var m=response.data();
if(m.fileId()==null || m.fileId()<=0 || !Long.valueOf(0).equals(m.tenantId()) || !slot.businessType().equals(m.businessType())
|| !String.valueOf(dispatchId).equals(m.businessId()) || expected!=null && !expected.equals(m.fileId())
|| m.sizeBytes()==null || m.sizeBytes()<=0 || m.sizeBytes()>MAX_SIZE || !image(m.contentType())
|| m.fileName()==null || m.fileName().isBlank() || m.createdAt()==null)throw bad("照片不属于本排车或分类,或文件格式无效");
return new Evidence(m.fileId(),m.fileName(),m.contentType(),m.sizeBytes(),m.createdAt().toString());
}
/** 不放开PDF、SVG或任意image类型。 */
private static boolean image(String type){return Set.of("image/jpeg","image/png").contains(type==null?"":type);}
/** 使用真实文件头,不转换或伪造证据图片。 */
private static boolean signature(String type,byte[] bytes) {
if(bytes==null)return false;
if("image/jpeg".equals(type))return bytes.length>=3 && (bytes[0]&255)==255 && (bytes[1]&255)==216 && (bytes[2]&255)==255;
byte[] png={(byte)137,80,78,71,13,10,26,10};if(!"image/png".equals(type) || bytes.length<png.length)return false;
for(int i=0;i<png.length;i++)if(bytes[i]!=png[i])return false;return true;
}
/** 基础设施错误不反向依赖应用Service,保持单向包依赖。 */
private static BizException bad(String message){return new BizException(ResultCode.BAD_REQUEST,message);}
/** 不明确的文件结果保留为业务冲突,由上传账本记录。 */
private static BizException conflict(String message){return new BizException(ResultCode.CONFLICT,message);}
public record Envelope(String code,Metadata data) {}
public record Metadata(Long fileId,Long tenantId,String businessType,String businessId,String fileName,String contentType,Long sizeBytes,LocalDateTime createdAt) {}
}
@@ -0,0 +1,15 @@
package com.baiyue.lastleg.fleet.ownedbusiness.gateway;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.PhotoSlot;
/** 本页平台图片受控代理,不接收浏览器指定的内部主键或业务类型。 */
public interface OwnedBusinessFileGateway {
record Upload(String fileName,String contentType,byte[] content) {}
record Evidence(long fileId,String fileName,String contentType,long sizeBytes,String uploadedAt) {}
/** 同一原意图只上传一次,未知结果由账本保存。 */
Evidence upload(long dispatchId,PhotoSlot slot,String operatorId,Upload upload);
/** 核验平台、原排车、分类、文件身份和图像格式。 */
Evidence metadata(long dispatchId,PhotoSlot slot,long fileId);
/** 只代理业务层已确认当前或历史引用的内容。 */
byte[] content(long dispatchId,PhotoSlot slot,long fileId);
}
@@ -0,0 +1,88 @@
package com.baiyue.lastleg.fleet.ownedbusiness.mapper;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Record;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 本页4表唯一SQL入口;不更新排车、库存或财务表。 */
@Mapper
public interface OwnedBusinessMapper {
/** 读取已经冻结的装车归属,不查询当前车辆推断历史。 */
@Select("SELECT * FROM ll_fleet_owned_business_ownership WHERE dispatch_id=#{id}")
Ownership ownership(long id);
/** 在主装车事务保存唯一归属证据,重复交由提供者核对原事实。 */
@Insert("""
INSERT INTO ll_fleet_owned_business_ownership(dispatch_id,vehicle_id,resource_mode,vehicle_ownership,
vehicle_record_version,ownership_captured_at,loading_completion_hash,loading_completed_at)
VALUES(#{dispatchId},#{vehicleId},#{resourceMode},#{vehicleOwnership},#{vehicleRecordVersion},
#{ownershipCapturedAt},#{loadingCompletionHash},#{loadingCompletedAt})
""")
int capture(Ownership row);
/** GET不使用此方法;首个写事务建立可锁定的附加0版本行。 */
@Insert("""
INSERT INTO ll_fleet_owned_business_record(id,dispatch_id,record_version,arrivals_json,photos_json,
created_by,updated_by,created_at,updated_at) VALUES(#{id},#{dispatchId},0,'[]','[]',
#{createdBy},#{updatedBy},#{createdAt},#{updatedAt}) ON DUPLICATE KEY UPDATE dispatch_id=dispatch_id
""")
int ensure(Record row);
/** 只锁本页附加行,不反向申请车辆或派送写锁。 */
@Select("SELECT * FROM ll_fleet_owned_business_record WHERE dispatch_id=#{id} FOR UPDATE")
Record lockRecord(long id);
/** 详情只读附加信息,无记录返回虚拟0版本。 */
@Select("SELECT * FROM ll_fleet_owned_business_record WHERE dispatch_id=#{id}")
Record record(long id);
/** 页内批量读取,避免逐车补充GET和SQL。 */
@Select("<script>SELECT * FROM ll_fleet_owned_business_record WHERE dispatch_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
List<Record> records(@Param("ids") List<Long> ids);
/** CAS仅修改运营附加字段,不占用主单recordVersion。 */
@Update("""
UPDATE ll_fleet_owned_business_record SET record_version=#{r.recordVersion},currency=#{r.currency},
total_amount=#{r.totalAmount},actual_distance_miles=#{r.actualDistanceMiles},
fuel_consumption_litres_per_100km=#{r.fuelConsumptionLitresPer100Km},arrivals_json=#{r.arrivalsJson},
photos_json=#{r.photosJson},updated_by=#{r.updatedBy},updated_at=#{r.updatedAt}
WHERE dispatch_id=#{r.dispatchId} AND record_version=#{expected}
""")
int update(@Param("r") Record row,@Param("expected") long expected);
/** 命令键全车唯一,操作者在服务端另行核验。 */
@Select("SELECT * FROM ll_fleet_owned_business_command WHERE dispatch_id=#{id} AND idempotency_key=#{key}")
Command command(@Param("id") long id,@Param("key") String key);
/** 完整意图在文件HTTP之前单独事务提交。 */
@Insert("""
INSERT INTO ll_fleet_owned_business_command(id,dispatch_id,operator_id,idempotency_key,action,
expected_version,request_hash,request_json,status,result_json,error_code,created_at,updated_at)
VALUES(#{id},#{dispatchId},#{operatorId},#{idempotencyKey},#{action},#{expectedVersion},
#{requestHash},#{requestJson},#{status},#{resultJson},#{errorCode},#{createdAt},#{updatedAt})
""")
int insertCommand(Command row);
/** 上传只完成原待定意图,不能把未知结果当新命令重做。 */
@Update("""
UPDATE ll_fleet_owned_business_command SET status=#{status},result_json=#{resultJson},
error_code=#{errorCode},updated_at=#{updatedAt} WHERE id=#{id} AND status='PENDING'
""")
int finishUpload(Command row);
/** 附加写与不可变历史同事务,版本不能重复。 */
@Insert("""
INSERT INTO ll_fleet_owned_business_history(id,dispatch_id,record_version,action,operator_id,
reason,snapshot_json,occurred_at) VALUES(#{id},#{dispatchId},#{recordVersion},#{action},#{operatorId},
#{reason},#{snapshotJson},#{occurredAt})
""")
int insertHistory(History row);
/** 历史按本页版本顺序分页。 */
@Select("""
SELECT * FROM (
SELECT id,dispatch_id,record_version,NULL AS dispatch_record_version,'OPERATIONS' AS event_source,
action,operator_id,reason,snapshot_json,occurred_at FROM ll_fleet_owned_business_history WHERE dispatch_id=#{id}
UNION ALL
SELECT id,dispatch_id,NULL AS record_version,record_version AS dispatch_record_version,'DISPATCH' AS event_source,
action,operator_id,reason,snapshot_json,occurred_at FROM ll_dispatch_history WHERE dispatch_id=#{id}
) events ORDER BY occurred_at DESC,event_source,id DESC LIMIT #{limit} OFFSET #{offset}
""")
List<History> history(@Param("id") long id,@Param("offset") int offset,@Param("limit") int limit);
/** 历史总数不取当前页长度。 */
@Select("SELECT (SELECT COUNT(*) FROM ll_fleet_owned_business_history WHERE dispatch_id=#{id})+(SELECT COUNT(*) FROM ll_dispatch_history WHERE dispatch_id=#{id})")
int historyCount(long id);
/** 历史文件只能从指定真实历史快照读取。 */
@Select("SELECT * FROM ll_fleet_owned_business_history WHERE dispatch_id=#{id} AND record_version=#{version}")
History revision(@Param("id") long id,@Param("version") long version);
}
@@ -0,0 +1,57 @@
package com.baiyue.lastleg.fleet.ownedbusiness.mapper;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.*;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 在原排车事实之上做自有运营分页,不复制或推进履约模型。 */
@Mapper
public interface OwnedBusinessQueryMapper {
String SOURCE="""
SELECT d.id,d.dispatch_no,d.status,d.stage,d.record_version,d.overseas_warehouse_id,
d.overseas_warehouse_code,d.overseas_warehouse_name,d.planned_departure_at,d.loading_completed_at,
d.departed_at,d.delivery_completed_at,d.loading_completion_hash,d.loading_confirmation_json,d.resources_json,
o.vehicle_id AS owned_vehicle_id,o.resource_mode AS owned_resource_mode,
o.vehicle_ownership AS owned_vehicle_ownership,o.vehicle_record_version AS owned_vehicle_record_version,
o.loading_completion_hash AS owned_loading_completion_hash,o.loading_completed_at AS owned_loading_completed_at
FROM ll_dispatch_order d LEFT JOIN ll_fleet_owned_business_ownership o ON o.dispatch_id=d.id
""";
String FILTER="""
d.status='ACTIVE' AND d.stage IN ('AFTER_LOADING','DELIVERING','DELIVERED')
AND d.loading_completed_at IS NOT NULL AND d.loading_confirmation_json IS NOT NULL
AND o.vehicle_ownership='OWNED' AND o.loading_completion_hash=d.loading_completion_hash
<if test='q.from != null'> AND d.planned_departure_at &gt;= #{q.from}</if>
<if test='q.to != null'> AND d.planned_departure_at &lt; #{q.to}</if>
<if test='q.stage != null'> AND d.stage=#{q.stage}</if>
<if test='q.warehouseId != null'> AND d.overseas_warehouse_id=#{q.warehouseId}</if>
<if test='q.keyword != null'> AND (d.dispatch_no LIKE CONCAT('%',#{q.keyword},'%')
OR d.vehicle_plate LIKE CONCAT('%',#{q.keyword},'%') OR EXISTS(SELECT 1 FROM ll_dispatch_item i
WHERE i.dispatch_order_id=d.id AND (i.destination_warehouse_code LIKE CONCAT('%',#{q.keyword},'%')
OR i.fba_warehouse_code LIKE CONCAT('%',#{q.keyword},'%')
OR i.destination_warehouse_name LIKE CONCAT('%',#{q.keyword},'%'))))</if>
""";
/** 只返回当前完整条件下的一车一行。 */
@Select("<script>"+SOURCE+" WHERE "+FILTER+" ORDER BY d.planned_departure_at DESC,d.id DESC LIMIT #{q.limit} OFFSET #{q.offset}</script>")
List<Source> page(@Param("q") Search query);
/** 同一过滤片段不带分页,不能拿当前页长度冒充统计。 */
@Select("<script>SELECT d.stage,COUNT(*) AS quantity FROM ll_dispatch_order d LEFT JOIN ll_fleet_owned_business_ownership o ON o.dispatch_id=d.id WHERE "+FILTER+" GROUP BY d.stage</script>")
List<StageCount> summary(@Param("q") Search query);
/** 先读原主单和可空归属,以明确区别无快照与不存在。 */
@Select(SOURCE+" WHERE d.dispatch_no=#{number}")
Source find(String number);
/** 页内全部货物一次读取,各客户保持原归属。 */
@Select("<script>SELECT id,dispatch_order_id,warehouse_pallet_id,customer_id,customer_name,source_key,order_no,inbound_code,pallet_no,destination_type,destination_warehouse_code,destination_warehouse_name,fba_warehouse_code,delivery_address,postal_code,package_count FROM ll_dispatch_item WHERE dispatch_order_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach> ORDER BY dispatch_order_id,id</script>")
List<CargoRow> cargo(@Param("ids") List<Long> ids);
/** 只聚合真实FBA分配,目的仓与数量保持原事实,不按客户重复整车。 */
@Select("""
<script>SELECT a.dispatch_id,a.destination_key,p.appointment_no,p.confirmation_no,
p.appointment_start_utc AS start_utc,SUM(a.package_count) AS allocated_packages
FROM ll_dispatch_appointment_allocation a JOIN ll_dispatch_item i
ON i.id=a.dispatch_item_id AND i.dispatch_order_id=a.dispatch_id AND i.customer_id=a.customer_id
JOIN ll_inbound_fba_appointment p ON a.batch_key=CONCAT('FBA_APPOINTMENT:',p.id)
WHERE a.dispatch_id IN <foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach>
GROUP BY a.dispatch_id,a.destination_key,p.appointment_no,p.confirmation_no,p.appointment_start_utc
ORDER BY a.dispatch_id,a.destination_key,p.appointment_no</script>
""")
List<Batch> batches(@Param("ids") List<Long> ids);
}
@@ -0,0 +1,64 @@
package com.baiyue.lastleg.fleet.ownedbusiness.model;
import com.baiyue.lastleg.dispatch.port.DispatchViews;
import jakarta.validation.Valid;
import jakarta.validation.constraints.*;
import java.util.List;
import java.util.Set;
/** 原排车只读投影和附加信息,不公开第二套履约命令。 */
public final class OwnedBusinessModels {
/** 工具容器不允许实例化。 */
private OwnedBusinessModels() {}
public static final String LIST="platform:fleet:owned-business:list";
public static final String EDIT="platform:fleet:owned-business:edit";
public static final String UPLOAD="platform:fleet:owned-business:upload";
public enum Stage { AFTER_LOADING, DELIVERING, DELIVERED }
public enum PhotoSlot {
LOADING_SCENE, LOADING_LIST, PRE_DEPARTURE_CHECK, DRIVER_LICENSE, RECEIPT, FUEL_START, FUEL_END;
/** 图片框分类不表示司机审核或真实派送签收。 */
public String category() { return name().startsWith("FUEL_")?"FUEL":"LOADING"; }
/** 文件类型与租户归属由本域固定,浏览器不能指定。 */
public String businessType() { return category().equals("FUEL")?"OVERSEAS_DISPATCH_FUEL_PHOTO":"OVERSEAS_DISPATCH_LOADING_PHOTO"; }
}
public record Actor(String operatorId,String operatorName,Set<String> permissions) {}
public record Query(@Min(1) Integer page,@Min(1) @Max(200) Integer size,
String plannedDepartureFrom,String plannedDepartureTo,@Size(max=128) String keyword,
Stage stage,@Size(max=64) String warehouseId) {}
public record Money(@NotBlank @Pattern(regexp="CNY|USD") String currency,
@NotBlank @Pattern(regexp="(0|[1-9][0-9]{0,15})(\\.[0-9]{1,2})?") String amount) {}
public record Arrival(@NotBlank @Size(max=256) String destinationKey,String actualArrivedAt) {}
public record Operations(@Valid Money money,String actualDistanceMiles,
String fuelConsumptionLitresPer100Km,@NotNull List<@NotNull @Valid Arrival> arrivals) {}
public record SaveOperations(@NotBlank String recordVersion,
@NotBlank @Size(min=8,max=128) String idempotencyKey,@NotNull @Valid Operations operations,
@Size(max=1000) String reason) {}
public record BindPhoto(@NotBlank String recordVersion,
@NotBlank @Size(min=8,max=128) String idempotencyKey,@NotBlank String fileId) {}
public record Gate(boolean allowed,String blockReason) {}
public record Actions(Gate edit,Gate upload) {}
public record Origin(String warehouseId,String warehouseCode,String warehouseName) {}
public record Vehicle(String vehicleId,String plate,String ownership) {}
public record Driver(String name,String phone) {}
public record Appointment(String appointmentNo,String confirmationNo,String scheduledAt,String allocatedPackages) {}
public record Destination(String destinationKey,String warehouseCode,String warehouseName,String address,
List<Appointment> appointments,String actualArrivedAt) {}
public record Photo(PhotoSlot slot,String category,String fileId,String fileName,String contentType,
String sizeBytes,String uploadedAt,String savedAt) {}
public record PhotoSummary(int loadingCount,int fuelCount) {}
public record Row(String dispatchNo,Stage stage,String plannedDepartureAt,String loadingCompletedAt,
String departedAt,String deliveryCompletedAt,Origin origin,Vehicle vehicle,Driver driver,
List<Destination> destinations,Integer actualPalletCount,Operations operations,String unitPrice,
String recordVersion,String dispatchRecordVersion,PhotoSummary photoSummary,Actions actions,List<String> sourceIssues) {}
public record Summary(int dispatchCount,int afterLoadingCount,int deliveringCount,int deliveredCount) {}
public record ListResult(List<Row> records,int page,int size,int total,Summary summary) {}
public record Cargo(String sourceKey,String customerId,String customerName,String orderNo,
String inboundCode,String palletNo,String destinationKey,String packages) {}
public record Detail(Row row,DispatchViews.Detail dispatch,List<Cargo> cargo,List<Photo> photos) {}
public record History(String eventSource,String recordVersion,String dispatchRecordVersion,String action,String operatorName,String occurredAt,String reason,
Operations operations,List<Photo> photos) {}
public record HistoryPage(List<History> records,int page,int size,int total) {}
public record Command(String dispatchNo,String action,String idempotencyKey,String state,
String recordVersion,boolean replayed,Object result,String errorCode,boolean retryAllowed) {}
public record Snapshot(Operations operations,List<Photo> photos,String operatorName) {}
}
@@ -0,0 +1,57 @@
package com.baiyue.lastleg.fleet.ownedbusiness.model;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/** 仅供本包持久化,不向浏览器输出内部主键。 */
public final class OwnedBusinessRows {
/** 持久化容器不允许实例化。 */
private OwnedBusinessRows() {}
@Data public static class Ownership {
private Long dispatchId,vehicleId,vehicleRecordVersion;
private String resourceMode,vehicleOwnership,loadingCompletionHash;
private LocalDateTime ownershipCapturedAt,loadingCompletedAt;
}
@Data public static class Source {
private Long id,recordVersion;
private String dispatchNo,status,stage,overseasWarehouseId,overseasWarehouseCode,overseasWarehouseName;
private String loadingCompletionHash,loadingConfirmationJson,resourcesJson;
private LocalDateTime plannedDepartureAt,loadingCompletedAt,departedAt,deliveryCompletedAt;
private String ownedResourceMode,ownedVehicleOwnership,ownedLoadingCompletionHash;
private Long ownedVehicleId,ownedVehicleRecordVersion;
private LocalDateTime ownedLoadingCompletedAt;
}
/** 原表货物只读字段;不是可写排车实体,不复制来源状态机。 */
@Data public static class CargoRow {
private Long id,dispatchOrderId,warehousePalletId;
private String customerId,customerName,sourceKey,orderNo,inboundCode,palletNo;
private String destinationType,destinationWarehouseCode,destinationWarehouseName,fbaWarehouseCode,deliveryAddress,postalCode;
private Integer packageCount;
}
@Data public static class Record {
private Long id,dispatchId,recordVersion;
private String currency,arrivalsJson,photosJson,createdBy,updatedBy;
private BigDecimal totalAmount,actualDistanceMiles,fuelConsumptionLitresPer100Km;
private LocalDateTime createdAt,updatedAt;
}
@Data public static class Command {
private Long id,dispatchId,expectedVersion;
private String operatorId,idempotencyKey,action,requestHash,requestJson,status,resultJson,errorCode;
private LocalDateTime createdAt,updatedAt;
}
@Data public static class History {
private Long id,dispatchId,recordVersion,dispatchRecordVersion;
private String eventSource,action,operatorId,reason,snapshotJson;
private LocalDateTime occurredAt;
}
@Data public static class Batch {
private Long dispatchId;
private String destinationKey,appointmentNo,confirmationNo;
private LocalDateTime startUtc;
private Long allocatedPackages;
}
public record Search(int offset,int limit,String keyword,String warehouseId,String stage,
LocalDateTime from,LocalDateTime to) {}
@Data public static class StageCount { private String stage;private Long quantity; }
}
@@ -0,0 +1,10 @@
package com.baiyue.lastleg.fleet.ownedbusiness.port;
import java.time.Instant;
/** 装车主事务唯一捕获车辆归属,不创建第二套履约状态。 */
public interface OwnedBusinessOwnershipCapture {
/** 主流程已稳定车辆资格,仅捕获原装车时点的不可变归属。 */
void capture(long dispatchId, Long vehicleId, String resourceMode,
String loadingCompletionHash, Instant loadingCompletedAt);
}
@@ -0,0 +1,53 @@
package com.baiyue.lastleg.fleet.ownedbusiness.repository;
import com.baiyue.lastleg.fleet.ownedbusiness.mapper.OwnedBusinessMapper;
import com.baiyue.lastleg.fleet.ownedbusiness.mapper.OwnedBusinessQueryMapper;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Record;
import org.springframework.stereotype.Repository;
import java.util.List;
/** 只封装本页Mapper,关系库访问不使用JdbcTemplate或直连JDBC。 */
@Repository
public class OwnedBusinessRepository {
private final OwnedBusinessMapper records;
private final OwnedBusinessQueryMapper queries;
/** 注入唯一SQL提供者,Service不能直接访问Mapper。 */
public OwnedBusinessRepository(OwnedBusinessMapper records,OwnedBusinessQueryMapper queries){this.records=records;this.queries=queries;}
/** 原归属已捕获后不按当前车辆回算。 */
public Ownership ownership(long id){return records.ownership(id);}
/** 归属与主装车事务共同提交。 */
public void capture(Ownership row){records.capture(row);}
/** 服务端整车分页。 */
public List<Source> page(Search query){return queries.page(query);}
/** 与分页相同过滤的完整统计。 */
public List<StageCount> summary(Search query){return queries.summary(query);}
/** 读取唯一原排车身份及归属证据。 */
public Source source(String number){return queries.find(number);}
/** 页内货物批量查询。 */
public List<CargoRow> cargo(List<Long> ids){return ids.isEmpty()?List.of():queries.cargo(ids);}
/** 页内实际预约分配批量查询。 */
public List<Batch> batches(List<Long> ids){return ids.isEmpty()?List.of():queries.batches(ids);}
/** GET只读,无记录保留虚拟0版本。 */
public Record record(long id){return records.record(id);}
/** 页内附加信息批量读取。 */
public List<Record> records(List<Long> ids){return ids.isEmpty()?List.of():records.records(ids);}
/** 首个写事务建立行,并按dispatch唯一键串行。 */
public Record lock(Record seed){records.ensure(seed);return records.lockRecord(seed.getDispatchId());}
/** 只CAS修改附加信息。 */
public int update(Record row,long expected){return records.update(row,expected);}
/** 命令先按全车请求键定位,再在服务端检查原操作者。 */
public Command command(long id,String key){return records.command(id,key);}
/** 命令与附加版本同事务保存,或作为独立上传意图持久化。 */
public void command(Command row){records.insertCommand(row);}
/** 上传结果只完成原待定意图。 */
public int finishUpload(Command row){return records.finishUpload(row);}
/** 同一附加版本只记录一次不可变历史。 */
public void history(History row){records.insertHistory(row);}
/** 历史总数只取原dispatch。 */
public int historyCount(long id){return records.historyCount(id);}
/** 历史采用稳定版本倒序。 */
public List<History> history(long id,int offset,int size){return records.history(id,offset,size);}
/** 下载历史附件时精确定位原版本。 */
public History revision(long id,long version){return records.revision(id,version);}
}
@@ -0,0 +1,62 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.Actor;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Command;
import com.baiyue.lastleg.fleet.ownedbusiness.repository.OwnedBusinessRepository;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import org.springframework.web.server.ResponseStatusException;
import java.time.Instant;
import java.util.Objects;
import static com.baiyue.lastleg.fleet.ownedbusiness.service.OwnedBusinessSupport.*;
/** 附加操作与文件准备共用二元唯一账本,不允许异账号复用键。 */
@Service
public class OwnedBusinessCommandService {
private final OwnedBusinessRepository repository;
private final OwnedBusinessSupport codec;
/** 文件意图独立短事务,不持业务行锁跨HTTP。 */
public OwnedBusinessCommandService(OwnedBusinessRepository repository,OwnedBusinessSupport codec){this.repository=repository;this.codec=codec;}
public record Reservation(Command command,boolean created) {}
/** 查找原命令时先核操作者,不披露别人的原载荷。 */
public Command existing(long dispatchId,String key,Actor actor) {
var row=repository.command(dispatchId,key);
if(row!=null && !Objects.equals(row.getOperatorId(),actor.operatorId()))
throw new ResponseStatusException(HttpStatus.FORBIDDEN,"该请求键不属于当前操作账号");
return row;
}
/** 原action、版本和完整规范请求必须一致,不能用当前版本重造旧意图。 */
public void same(Command row,String action,Long version,Object request) {
if(!Objects.equals(row.getAction(),action) || !Objects.equals(row.getExpectedVersion(),version)
|| !Objects.equals(row.getRequestHash(),codec.hash(java.util.Arrays.asList(row.getOperatorId(),action,version,request))))throw conflict("相同请求键的操作、版本或内容不同");
}
/** 完整命令实体只用于本页,不保存浏览器凭据。 */
public Command create(long id,Actor actor,String key,String action,Long version,Object request,String status) {
var now=codec.utc(Instant.now());var row=new Command();row.setId(IdWorker.getId());row.setDispatchId(id);
row.setOperatorId(actor.operatorId());row.setIdempotencyKey(key);row.setAction(action);row.setExpectedVersion(version);
row.setRequestHash(codec.hash(java.util.Arrays.asList(actor.operatorId(),action,version,request)));row.setRequestJson(codec.write(request));row.setStatus(status);row.setCreatedAt(now);row.setUpdatedAt(now);return row;
}
/** 首次上传先持久化意图,竞争者只能读取原状态,不再次调用File。 */
@Transactional(propagation=Propagation.REQUIRES_NEW,isolation=Isolation.READ_COMMITTED)
public Reservation reserveUpload(long id,Actor actor,String key,Object request) {
var previous=existing(id,key,actor);
if(previous!=null){same(previous,"UPLOAD_PHOTO",null,request);return new Reservation(previous,false);}
var row=create(id,actor,key,"UPLOAD_PHOTO",null,request,"PENDING");
try{repository.command(row);return new Reservation(row,true);}
catch(DuplicateKeyException race){var original=existing(id,key,actor);if(original==null)throw race;same(original,"UPLOAD_PHOTO",null,request);return new Reservation(original,false);}
}
/** 已知上传回执或未知结果只完成原意图,不创建新业务记录。 */
@Transactional(propagation=Propagation.REQUIRES_NEW)
public void finishUpload(Command command,String status,Object result,String errorCode) {
command.setStatus(status);command.setResultJson(result==null?null:codec.write(result));command.setErrorCode(errorCode);
command.setUpdatedAt(codec.utc(Instant.now()));
if(repository.finishUpload(command)!=1)throw conflict("上传命令结果已被其他操作确认,请核对原请求");
}
/** 写命令与附加更新、历史在同一外部事务提交。 */
public void success(long id,Actor actor,String key,String action,long version,Object request,Object result) {
var command=create(id,actor,key,action,version,request,"SUCCEEDED");command.setResultJson(codec.write(result));repository.command(command);
}
}
@@ -0,0 +1,52 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baiyue.lastleg.fleet.ownedbusiness.port.OwnedBusinessOwnershipCapture;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Ownership;
import com.baiyue.lastleg.fleet.ownedbusiness.repository.OwnedBusinessRepository;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import java.time.*;
import java.util.Objects;
import static com.baiyue.lastleg.fleet.ownedbusiness.service.OwnedBusinessSupport.*;
/** 装车时车辆归属的唯一捕获实现,GET绝不补造历史。 */
@Service
public class OwnedBusinessOwnershipService implements OwnedBusinessOwnershipCapture {
private final OwnedBusinessRepository repository;
private final VehicleRepository vehicles;
/** 使用真实车辆提供者,不对车辆主档增加反向写锁。 */
public OwnedBusinessOwnershipService(OwnedBusinessRepository repository,VehicleRepository vehicles){this.repository=repository;this.vehicles=vehicles;}
/** 主流程原父事务已经稳定资源,捕获失败必须与装车一起回滚。 */
@Override @Transactional(propagation=Propagation.MANDATORY)
public void capture(long dispatchId,Long vehicleId,String resourceMode,String loadingCompletionHash,Instant loadingCompletedAt) {
if(dispatchId<=0 || loadingCompletionHash==null || loadingCompletionHash.isBlank() || loadingCompletionHash.length()>128 || loadingCompletedAt==null
|| !loadingCompletedAt.equals(loadingCompletedAt.truncatedTo(java.time.temporal.ChronoUnit.MILLIS)))throw bad("装车归属证据不完整");
if(!"MASTER".equals(resourceMode) && !"EXTERNAL".equals(resourceMode))throw bad("车辆资源模式不合法");
if("MASTER".equals(resourceMode)?vehicleId==null || vehicleId<=0:vehicleId!=null)throw bad("车辆资源身份不一致");
var existing=repository.ownership(dispatchId);
if(existing!=null){same(existing,vehicleId,resourceMode,loadingCompletionHash,loadingCompletedAt);return;}
var row=new Ownership();row.setDispatchId(dispatchId);row.setVehicleId(vehicleId);row.setResourceMode(resourceMode);
if("MASTER".equals(resourceMode)) {
var vehicle=vehicles.findById(vehicleId).orElseThrow(()->conflict("原车辆主档不存在"));
if(vehicle.id()!=vehicleId.longValue())throw conflict("车辆归属提供者返回的身份不一致");
if(vehicle.recordVersion()<0)throw conflict("原车辆档案版本无效");
if(!"OWNED".equals(vehicle.ownership()) && !"DISPATCHED".equals(vehicle.ownership()))throw conflict("车辆归属未明确");
row.setVehicleOwnership(vehicle.ownership());row.setVehicleRecordVersion(vehicle.recordVersion());
} else {row.setVehicleOwnership("DISPATCHED");row.setVehicleRecordVersion(null);}
row.setLoadingCompletedAt(LocalDateTime.ofInstant(loadingCompletedAt,ZoneOffset.UTC));
row.setOwnershipCapturedAt(row.getLoadingCompletedAt());row.setLoadingCompletionHash(loadingCompletionHash);
try{repository.capture(row);}catch(DuplicateKeyException duplicate){
var raced=repository.ownership(dispatchId);if(raced==null)throw duplicate;
same(raced,vehicleId,resourceMode,loadingCompletionHash,loadingCompletedAt);
if(!Objects.equals(raced.getVehicleOwnership(),row.getVehicleOwnership()) || !Objects.equals(raced.getVehicleRecordVersion(),row.getVehicleRecordVersion()))throw conflict("装车车辆归属并发变化");
}
}
/** 只允许同一原装车事实重放,不能以新归属重写旧证据。 */
private void same(Ownership row,Long vehicleId,String mode,String hash,Instant at) {
if(!Objects.equals(row.getVehicleId(),vehicleId) || !Objects.equals(row.getResourceMode(),mode)
|| !Objects.equals(row.getLoadingCompletionHash(),hash) || !Objects.equals(row.getLoadingCompletedAt(),LocalDateTime.ofInstant(at,ZoneOffset.UTC)))
throw conflict("原装车车辆归属证据不同");
}
}
@@ -0,0 +1,95 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baiyue.lastleg.fleet.ownedbusiness.gateway.OwnedBusinessFileGateway;
import com.baiyue.lastleg.fleet.ownedbusiness.gateway.HttpOwnedBusinessFileGateway;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.baiyue.lastleg.fleet.ownedbusiness.repository.OwnedBusinessRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.service.OwnedBusinessSupport.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
/** 只有绑定成功才保存照片,上传和绑定各自使用稳定键。 */
@Service
public class OwnedBusinessPhotoService {
private final OwnedBusinessQueryService queries;
private final OwnedBusinessRecordService records;
private final OwnedBusinessRepository repository;
private final OwnedBusinessCommandService commands;
private final OwnedBusinessProjection projection;
private final OwnedBusinessSupport codec;
private final OwnedBusinessFileGateway files;
/** HTTP远程请求不在附加行写事务内持锁等待。 */
public OwnedBusinessPhotoService(OwnedBusinessQueryService queries,OwnedBusinessRecordService records,
OwnedBusinessRepository repository,OwnedBusinessCommandService commands,OwnedBusinessProjection projection,
OwnedBusinessSupport codec,OwnedBusinessFileGateway files) {
this.queries=queries;this.records=records;this.repository=repository;this.commands=commands;this.projection=projection;this.codec=codec;this.files=files;
}
public record UploadIdentity(PhotoSlot slot,String fileName,String contentType,long sizeBytes,String sha256) {}
public record Download(Photo photo,byte[] content) {}
/** 写前落意图,绑定失败须保留原fileId,不能再上传。 */
public Photo upload(Actor actor,String number,PhotoSlot slot,String key,MultipartFile multipart) {
codec.require(actor,UPLOAD);codec.key(key);var source=queries.requireOwned(number);
if(slot==null || multipart==null)throw bad("请选择照片及分类");
if(multipart.isEmpty() || multipart.getSize()>HttpOwnedBusinessFileGateway.MAX_SIZE)throw bad("照片须为非空JPG/PNG,最大10MiB");
byte[] bytes;try{bytes=multipart.getBytes();}catch(IOException error){throw bad("无法读取待上传照片");}
var payload=new OwnedBusinessFileGateway.Upload(multipart.getOriginalFilename(),multipart.getContentType(),bytes);
HttpOwnedBusinessFileGateway.validate(payload);
var identity=new UploadIdentity(slot,payload.fileName(),payload.contentType(),bytes.length,codec.digest(bytes));
var reservation=commands.reserveUpload(source.getId(),actor,key,identity);
if(!reservation.created()) {
if(!"SUCCEEDED".equals(reservation.command().getStatus()))throw conflict("原上传结果尚未明确,请查询原请求,勿换键重传");
return codec.read(reservation.command().getResultJson(),Photo.class);
}
try {
var result=photo(slot,files.upload(source.getId(),slot,actor.operatorId(),payload));
commands.finishUpload(reservation.command(),"SUCCEEDED",result,null);return result;
} catch(RuntimeException failure) {
// 连接异常不能证明File没有写入;持久保留未知结果,禁止自动补造。
try{commands.finishUpload(reservation.command(),"UNKNOWN_RESULT",null,"OWNED_UPLOAD_UNKNOWN_RESULT");}
catch(RuntimeException recordingFailure){failure.addSuppressed(recordingFailure);}
throw conflict("照片上传结果未知,请保留原请求键查询,勿重新上传");
}
}
/** 重放先于File复核,保证原成功结果可以精确恢复。 */
public Detail bind(Actor actor,String number,PhotoSlot slot,BindPhoto request) {
codec.require(actor,UPLOAD);if(request==null || slot==null)throw bad("照片绑定请求缺失");
codec.key(request.idempotencyKey());long version=codec.version(request.recordVersion());long fileId=codec.version(request.fileId());
if(fileId<=0)throw bad("文件编号无效");
var source=queries.requireOwned(number);var previous=commands.existing(source.getId(),request.idempotencyKey(),actor);
if(previous!=null) {
commands.same(previous,"BIND_PHOTO",version,new OwnedBusinessRecordService.PhotoBinding(slot,request));
if(!"SUCCEEDED".equals(previous.getStatus()))throw conflict("绑定结果尚未明确,请查询原命令");
return codec.read(previous.getResultJson(),Detail.class);
}
return records.bind(actor,number,slot,request,photo(slot,files.metadata(source.getId(),slot,fileId)));
}
/** 只有当前或指定真实历史版本中的引用允许代理读取。 */
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Download content(Actor actor,String number,PhotoSlot slot,long fileId,Long revision) {
codec.require(actor,LIST);var source=queries.requireOwned(number);List<Photo> bound;
if(revision==null)bound=projection.photos(repository.record(source.getId()));
else {
if(revision<1)throw bad("历史版本无效");var row=repository.revision(source.getId(),revision);
if(row==null)throw missing();bound=codec.read(row.getSnapshotJson(),Snapshot.class).photos();
}
var photo=bound.stream().filter(p->p.slot()==slot && String.valueOf(fileId).equals(p.fileId())).findFirst().orElseThrow(OwnedBusinessSupport::missing);
return new Download(photo,files.content(source.getId(),slot,fileId));
}
/** 恢复先校验原操作者,不披露他人载荷。 */
@Transactional(readOnly=true)
public Command command(Actor actor,String number,String key) {
codec.require(actor,LIST);codec.key(key);var source=queries.requireOwned(number);var row=commands.existing(source.getId(),key,actor);
if(row==null)throw missing();Object result=row.getResultJson()==null?null:codec.read(row.getResultJson(),Object.class);
String version=row.getExpectedVersion()==null?null:String.valueOf(Math.addExact(row.getExpectedVersion(),1));
return new Command(number,row.getAction(),key,row.getStatus(),version,true,result,row.getErrorCode(),false);
}
/** 上传回执不填写保存时间,避免假称已经关联成功。 */
private Photo photo(PhotoSlot slot,OwnedBusinessFileGateway.Evidence evidence) {
return new Photo(slot,slot.category(),String.valueOf(evidence.fileId()),evidence.fileName(),evidence.contentType(),
String.valueOf(evidence.sizeBytes()),evidence.uploadedAt(),null);
}
}
@@ -0,0 +1,77 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baiyue.lastleg.dispatch.port.DispatchContracts.ConfirmedLoad;
import com.baiyue.lastleg.dispatch.port.DispatchContracts.Resources;
import com.baiyue.lastleg.fleet.trip.FleetDispatchGateway;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Record;
import org.springframework.stereotype.Component;
import java.math.*;
import java.util.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
/** 组合原排车与附加信息;不复制、推进或重新归并订单。 */
@Component
public class OwnedBusinessProjection {
private final OwnedBusinessSupport codec;
/** 所有数值与日期转换沿统一显式规则。 */
public OwnedBusinessProjection(OwnedBusinessSupport codec){this.codec=codec;}
/** 未登记为null,不以默认油耗、金额或到达填充。 */
public Operations operations(Record record) {
if(record==null)return new Operations(null,null,null,List.of());
var money=record.getTotalAmount()==null?null:new Money(record.getCurrency(),record.getTotalAmount().setScale(2).toPlainString());
return new Operations(money,decimal(record.getActualDistanceMiles()),decimal(record.getFuelConsumptionLitresPer100Km()),
codec.list(record.getArrivalsJson(),Arrival.class));
}
/** 照片已绑定才出现在当前记录,无文件不生成占位图。 */
public List<Photo> photos(Record record){return record==null?List.of():codec.list(record.getPhotosJson(),Photo.class);}
/** 使用原货物确定目的地key,保持与排车及到达登记一致。 */
public String destinationKey(CargoRow item) {
String key=FleetDispatchGateway.destinationKey(item.getDestinationType(),item.getDestinationWarehouseCode(),
item.getFbaWarehouseCode(),item.getDeliveryAddress(),item.getPostalCode());
if(key==null || key.isBlank())throw OwnedBusinessSupport.conflict("原货物目的地事实缺失");return key;
}
/** 真实物理托盘唯一计数,标准托位和来源条数不参与除数。 */
public int palletCount(Source source) {
var confirmed=codec.read(source.getLoadingConfirmationJson(),ConfirmedLoad.class);
if(confirmed.pallets()==null)throw OwnedBusinessSupport.conflict("实际装车托盘事实缺失");
var ids=new HashSet<Long>();
for(var pallet:confirmed.pallets()) {
if(pallet==null || pallet.warehousePalletId()==null || pallet.warehousePalletId()<=0)throw OwnedBusinessSupport.conflict("实际装车托盘身份缺失");
ids.add(pallet.warehousePalletId());
}
return ids.size();
}
/** 一车一行;目的地与预约只行内展开,不重复整车金额或托数。 */
public Row row(Source source,Record record,List<CargoRow> cargo,List<Batch> batches,Actor actor) {
var resources=codec.read(source.getResourcesJson(),Resources.class);
if(resources.vehicle()==null)throw OwnedBusinessSupport.conflict("原车辆快照缺失");
var ops=operations(record);var photos=photos(record);int pallets=palletCount(source);
var arrivals=new HashMap<String,String>();for(var a:ops.arrivals())arrivals.put(a.destinationKey(),a.actualArrivedAt());
var destinations=new LinkedHashMap<String,Destination>();
for(var item:cargo) {
String key=destinationKey(item);
destinations.computeIfAbsent(key,k->new Destination(k,item.getDestinationWarehouseCode()==null || item.getDestinationWarehouseCode().isBlank()?item.getFbaWarehouseCode():item.getDestinationWarehouseCode(),item.getDestinationWarehouseName(),
item.getDeliveryAddress(),batches.stream().filter(b->k.equals(b.getDestinationKey())).map(b->new Appointment(
b.getAppointmentNo(),b.getConfirmationNo(),codec.iso(b.getStartUtc()),String.valueOf(b.getAllocatedPackages()))).toList(),arrivals.get(k)));
}
String price=ops.money()==null || pallets==0?null:new BigDecimal(ops.money().amount()).divide(BigDecimal.valueOf(pallets),2,RoundingMode.HALF_UP).toPlainString();
var driver=resources.driver();
return new Row(source.getDispatchNo(),Stage.valueOf(source.getStage()),codec.iso(source.getPlannedDepartureAt()),
codec.iso(source.getLoadingCompletedAt()),codec.iso(source.getDepartedAt()),codec.iso(source.getDeliveryCompletedAt()),
new Origin(source.getOverseasWarehouseId(),source.getOverseasWarehouseCode(),source.getOverseasWarehouseName()),
new Vehicle(String.valueOf(resources.vehicle().vehicleId()),resources.vehicle().plate(),"OWNED"),
new Driver(driver==null?null:driver.name(),driver==null?null:driver.phone()),List.copyOf(destinations.values()),pallets,ops,price,
record==null?"0":String.valueOf(record.getRecordVersion()),String.valueOf(source.getRecordVersion()),
new PhotoSummary((int)photos.stream().filter(p->"LOADING".equals(p.category())).count(),(int)photos.stream().filter(p->"FUEL".equals(p.category())).count()),
new Actions(gate(actor,EDIT),gate(actor,UPLOAD)),pallets==0?List.of("实际装车清单无实托,单价未计算"):List.of());
}
/** 附加权限独立于原排车写动作。 */
private Gate gate(Actor actor,String permission) {
boolean allowed=actor!=null && actor.permissions()!=null && actor.permissions().contains(permission);
return new Gate(allowed,allowed?null:"没有该业务操作权限");
}
/** 数据库十进制保持显式单位,不以空值替换0。 */
private String decimal(BigDecimal value){return value==null?null:value.toPlainString();}
}
@@ -0,0 +1,98 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Source;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Search;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Record;
import com.baiyue.lastleg.fleet.ownedbusiness.repository.OwnedBusinessRepository;
import com.baiyue.lastleg.dispatch.port.DispatchDetailReader;
import com.baiyue.lastleg.dispatch.port.DispatchContracts;
import com.baiyue.lastleg.dispatch.port.DispatchTypes.ActorMode;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import java.time.Instant;
import java.util.*;
import java.util.stream.Collectors;
import static com.baiyue.lastleg.fleet.ownedbusiness.service.OwnedBusinessSupport.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
/** 自有车辆装车后视图;无归属快照的旧单不在GET时回填。 */
@Service
public class OwnedBusinessQueryService {
private final OwnedBusinessRepository repository;
private final OwnedBusinessProjection projection;
private final OwnedBusinessSupport codec;
private final DispatchDetailReader dispatch;
/** 主单详情沿既有真实提供者,列表使用本域批量投影。 */
public OwnedBusinessQueryService(OwnedBusinessRepository repository,OwnedBusinessProjection projection,
OwnedBusinessSupport codec,DispatchDetailReader dispatch){this.repository=repository;this.projection=projection;this.codec=codec;this.dispatch=dispatch;}
/** 四项统计与分页使用同一过滤和快照,GET不写库。 */
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public ListResult list(Actor actor,Query query) {
codec.require(actor,LIST);if(query==null)throw bad("查询条件缺失");
int page=page(query.page()),size=size(query.size());String keyword=optional(query.keyword(),128),warehouse=optional(query.warehouseId(),64);
Instant from=codec.instant(query.plannedDepartureFrom()),to=codec.instant(query.plannedDepartureTo());
if(from!=null && to!=null && !from.isBefore(to))throw bad("计划发车时间范围无效");
int offset;try{offset=Math.multiplyExact(page-1,size);}catch(ArithmeticException error){throw bad("页码过大");}
var search=new Search(offset,size,keyword,warehouse,query.stage()==null?null:query.stage().name(),codec.utc(from),codec.utc(to));
var counts=repository.summary(search);int after=0,delivering=0,delivered=0;
for(var c:counts) {
int n=Math.toIntExact(c.getQuantity());
switch(c.getStage()){case "AFTER_LOADING"->after=n;case "DELIVERING"->delivering=n;case "DELIVERED"->delivered=n;default->throw conflict("阶段统计事实不合法");}
}
int total=Math.addExact(Math.addExact(after,delivering),delivered);
var sources=repository.page(search);var ids=sources.stream().map(Source::getId).toList();
var records=repository.records(ids).stream().collect(Collectors.toMap(Record::getDispatchId,r->r));
var cargo=repository.cargo(ids);var batches=repository.batches(ids);
var rows=sources.stream().map(s->{eligible(s);return projection.row(s,records.get(s.getId()),
cargo.stream().filter(c->Objects.equals(c.getDispatchOrderId(),s.getId())).toList(),
batches.stream().filter(b->Objects.equals(b.getDispatchId(),s.getId())).toList(),actor);}).toList();
return new ListResult(rows,page,size,total,new Summary(total,after,delivering,delivered));
}
/** 对原排车详情做组合,不创建第二份主单或履约状态。 */
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public Detail detail(Actor actor,String number){codec.require(actor,LIST);return detailForWrite(actor,requireOwned(number));}
/** 写入已经有独立权限;回执仍由相同真实来源组成。 */
public Detail detailForWrite(Actor actor,Source source) {
eligible(source);var ids=List.of(source.getId());var cargo=repository.cargo(ids);
var row=projection.row(source,repository.record(source.getId()),cargo,repository.batches(ids),actor);
var original=dispatch.detail(new DispatchContracts.Actor(actor.operatorId(),ActorMode.PLATFORM,null),source.getDispatchNo());
return new Detail(row,original,cargo.stream().map(c->new Cargo(c.getSourceKey(),c.getCustomerId(),c.getCustomerName(),
c.getOrderNo(),c.getInboundCode(),c.getPalletNo(),projection.destinationKey(c),String.valueOf(c.getPackageCount()))).toList(),
projection.photos(repository.record(source.getId())));
}
/** 缺少历史归属必须明确拒绝,不能按当前车辆主档降级猜测。 */
public Source requireOwned(String number) {
if(number==null || number.isBlank() || number.length()>128)throw bad("请指定排车单号");
var source=repository.source(number);if(source==null)throw missing();eligible(source);return source;
}
/** 阶段、真实装车hash及车辆快照须与捕获证据一致。 */
private void eligible(Source source) {
if(source.getOwnedVehicleOwnership()==null)throw conflict("本单缺少装车时车辆归属证据,不能归入自有业务");
if(!"OWNED".equals(source.getOwnedVehicleOwnership()))throw missing();
if(!"ACTIVE".equals(source.getStatus()) || source.getStage()==null || !Set.of("AFTER_LOADING","DELIVERING","DELIVERED").contains(source.getStage())
|| source.getLoadingCompletedAt()==null || source.getLoadingConfirmationJson()==null)throw conflict("本单尚无合法装车完成事实");
var resource=codec.read(source.getResourcesJson(),DispatchContracts.Resources.class).vehicle();
if(resource==null || resource.vehicleId()==null || !Objects.equals(source.getOwnedVehicleId(),resource.vehicleId())
|| !"MASTER".equals(source.getOwnedResourceMode()) || !Objects.equals(source.getOwnedLoadingCompletionHash(),source.getLoadingCompletionHash())
|| !Objects.equals(source.getOwnedLoadingCompletedAt(),source.getLoadingCompletedAt()))throw conflict("车辆归属与原装车事实不一致");
}
/** 操作记录只返回真实附加版本,不制造初始示例事件。 */
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
public HistoryPage history(Actor actor,String number,Integer requestedPage,Integer requestedSize) {
codec.require(actor,LIST);var source=requireOwned(number);int page=page(requestedPage),size=size(requestedSize);
int offset;try{offset=Math.multiplyExact(page-1,size);}catch(ArithmeticException error){throw bad("页码过大");}
return new HistoryPage(repository.history(source.getId(),offset,size).stream().map(h->{
var snapshot="OPERATIONS".equals(h.getEventSource())?codec.read(h.getSnapshotJson(),Snapshot.class):null;
return new History(h.getEventSource(),h.getRecordVersion()==null?null:h.getRecordVersion().toString(),
h.getDispatchRecordVersion()==null?null:h.getDispatchRecordVersion().toString(),h.getAction(),snapshot==null?null:snapshot.operatorName(),codec.iso(h.getOccurredAt()),h.getReason(),
snapshot==null?null:snapshot.operations(),snapshot==null?List.of():snapshot.photos());
}).toList(),page,size,repository.historyCount(source.getId()));
}
/** 页码初始1,缺失与非法值不能混同。 */
private int page(Integer value){if(value==null)return 1;if(value<1)throw bad("页码须大于0");return value;}
/** 列表和历史均限制单页读取量。 */
private int size(Integer value){if(value==null)return 20;if(value<1 || value>200)throw bad("每页条数须为1至200");return value;}
/** 空白可选条件归一化,无限长输入明确拒绝。 */
private String optional(String value,int max){if(value==null || value.isBlank())return null;if(value.length()>max)throw bad("筛选条件过长");return value.trim();}
}
@@ -0,0 +1,122 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Record;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessRows.Source;
import com.baiyue.lastleg.fleet.ownedbusiness.repository.OwnedBusinessRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.*;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.service.OwnedBusinessSupport.*;
import static com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
/** 运营信息和分类照片只写本页附加版本,绝不改主单版本或发布费用。 */
@Service
public class OwnedBusinessRecordService {
private final OwnedBusinessRepository repository;
private final OwnedBusinessQueryService queries;
private final OwnedBusinessProjection projection;
private final OwnedBusinessCommandService commands;
private final OwnedBusinessSupport codec;
/** 业务规则经Repository读写,命令与历史一起提交。 */
public OwnedBusinessRecordService(OwnedBusinessRepository repository,OwnedBusinessQueryService queries,
OwnedBusinessProjection projection,OwnedBusinessCommandService commands,OwnedBusinessSupport codec) {
this.repository=repository;this.queries=queries;this.projection=projection;this.commands=commands;this.codec=codec;
}
/** 整车只保留一份可更正/清空的money,实际油耗为手工L/100km。 */
@Transactional(isolation=Isolation.READ_COMMITTED)
public Detail save(Actor actor,String number,SaveOperations request) {
codec.require(actor,EDIT);if(request==null || request.operations()==null)throw bad("运营登记内容缺失");
codec.key(request.idempotencyKey());long version=codec.version(request.recordVersion());
var source=queries.requireOwned(number);var previous=commands.existing(source.getId(),request.idempotencyKey(),actor);
if(previous!=null){commands.same(previous,"SAVE_OPERATIONS",version,request);return result(previous);}
if(request.reason()!=null && request.reason().length()>1000)throw bad("操作说明过长");
var ops=normalize(source,request.operations());var row=lock(source,actor);
previous=commands.existing(source.getId(),request.idempotencyKey(),actor);
if(previous!=null){commands.same(previous,"SAVE_OPERATIONS",version,request);return result(previous);}
requireVersion(row,version);
row.setCurrency(ops.money()==null?null:ops.money().currency());row.setTotalAmount(ops.money()==null?null:new BigDecimal(ops.money().amount()));
row.setActualDistanceMiles(decimal(ops.actualDistanceMiles()));row.setFuelConsumptionLitresPer100Km(decimal(ops.fuelConsumptionLitresPer100Km()));
row.setArrivalsJson(codec.write(ops.arrivals()));
return commit(source,row,actor,version,"SAVE_OPERATIONS",request.idempotencyKey(),request,request.reason());
}
/** File元数据已经在HTTP外层校验,绑定事务只处理本页行锁。 */
@Transactional(isolation=Isolation.READ_COMMITTED)
public Detail bind(Actor actor,String number,PhotoSlot slot,BindPhoto request,Photo verified) {
codec.require(actor,UPLOAD);if(request==null || slot==null || verified==null)throw bad("照片绑定内容缺失");
codec.key(request.idempotencyKey());long version=codec.version(request.recordVersion());var source=queries.requireOwned(number);
Object identity=new PhotoBinding(slot,request);
var old=commands.existing(source.getId(),request.idempotencyKey(),actor);
if(old!=null){commands.same(old,"BIND_PHOTO",version,identity);return result(old);}
if(slot!=verified.slot() || !Objects.equals(slot.category(),verified.category()) || !Objects.equals(request.fileId(),verified.fileId()))throw bad("照片不属于本框");
var row=lock(source,actor);old=commands.existing(source.getId(),request.idempotencyKey(),actor);
if(old!=null){commands.same(old,"BIND_PHOTO",version,identity);return result(old);}
requireVersion(row,version);
var photos=new EnumMap<PhotoSlot,Photo>(PhotoSlot.class);for(var p:projection.photos(row))photos.put(p.slot(),p);
photos.put(slot,new Photo(slot,slot.category(),verified.fileId(),verified.fileName(),verified.contentType(),
verified.sizeBytes(),verified.uploadedAt(),Instant.now().toString()));
row.setPhotosJson(codec.write(List.copyOf(photos.values())));
return commit(source,row,actor,version,"BIND_PHOTO",request.idempotencyKey(),identity,photoReason(slot));
}
/** 操作记录使用准确中文槽位,不向用户展示内部枚举。 */
private String photoReason(PhotoSlot slot) {
return switch(slot) {
case LOADING_SCENE -> "保存装车现场照片";
case LOADING_LIST -> "保存装车清单照片";
case PRE_DEPARTURE_CHECK -> "保存出车前检查照片";
case DRIVER_LICENSE -> "保存驾驶证附件照片";
case RECEIPT -> "保存签收凭证照片";
case FUEL_START -> "保存起始油耗表盘照片";
case FUEL_END -> "保存结束油耗表盘照片";
};
}
/** 照片框也参与摘要,不能换URL框位复用原键。 */
public record PhotoBinding(PhotoSlot slot,BindPhoto request) {}
/** 先校验所有目的地及数值,再进入附加行写事务。 */
private Operations normalize(Source source,Operations ops) {
Money money=null;
if(ops.money()!=null) {
if(!Set.of("CNY","USD").contains(ops.money().currency()==null?"":ops.money().currency()))throw bad("币种须为CNY或USD");
String amount=codec.decimal(ops.money().amount(),16,2);if(amount==null)throw bad("金额与币种必须同时登记");
money=new Money(ops.money().currency(),amount);
}
if(ops.arrivals()==null)throw bad("目的地到达登记不完整");
var destinations=new HashSet<String>();for(var item:repository.cargo(List.of(source.getId())))destinations.add(projection.destinationKey(item));
var seen=new HashSet<String>();var arrivals=new ArrayList<Arrival>();
for(var arrival:ops.arrivals()) {
if(arrival==null || arrival.destinationKey()==null || !destinations.contains(arrival.destinationKey()) || !seen.add(arrival.destinationKey()))throw bad("到达目的地重复或不属于本车");
var at=codec.instant(arrival.actualArrivedAt());arrivals.add(new Arrival(arrival.destinationKey(),at==null?null:at.toString()));
}
arrivals.sort(Comparator.comparing(Arrival::destinationKey));
return new Operations(money,codec.decimal(ops.actualDistanceMiles(),9,3),
codec.decimal(ops.fuelConsumptionLitresPer100Km(),9,3),List.copyOf(arrivals));
}
/** 首次写建立0版本附加行,仅在成功事务中最终提交。 */
private Record lock(Source source,Actor actor) {
var seed=new Record();seed.setId(IdWorker.getId());seed.setDispatchId(source.getId());seed.setCreatedBy(actor.operatorId());
seed.setUpdatedBy(actor.operatorId());seed.setCreatedAt(codec.utc(Instant.now()));seed.setUpdatedAt(seed.getCreatedAt());
var row=repository.lock(seed);if(row==null)throw conflict("附加记录初始化失败");return row;
}
/** 版本变化必须由浏览器刷新,不能覆盖其他操作者的登记。 */
private void requireVersion(Record row,long expected){if(row.getRecordVersion()==null || row.getRecordVersion()!=expected)throw conflict("运营记录版本已变化,请刷新后重试");}
/** 只保存附加版本和不可变历史,真实主单读取失败也必须回滚。 */
private Detail commit(Source source,Record row,Actor actor,long expected,String action,String key,Object request,String reason) {
row.setRecordVersion(Math.addExact(expected,1));row.setUpdatedBy(actor.operatorId());row.setUpdatedAt(codec.utc(Instant.now()));
if(repository.update(row,expected)!=1)throw conflict("运营记录版本竞争失败");
var history=new OwnedBusinessRows.History();history.setId(IdWorker.getId());history.setDispatchId(source.getId());history.setRecordVersion(row.getRecordVersion());
history.setAction(action);history.setOperatorId(actor.operatorId());history.setReason(reason);history.setOccurredAt(row.getUpdatedAt());
history.setSnapshotJson(codec.write(new Snapshot(projection.operations(row),projection.photos(row),actor.operatorName())));repository.history(history);
var result=queries.detailForWrite(actor,source);commands.success(source.getId(),actor,key,action,expected,request,result);return result;
}
/** 重放返回原成功结果,不能从现在的主单/附加版本重算。 */
private Detail result(OwnedBusinessRows.Command command) {
if(!"SUCCEEDED".equals(command.getStatus()))throw conflict("原命令结果尚未明确,请按原请求恢复");
return codec.read(command.getResultJson(),Detail.class);
}
/** null是未登记,不以0代替。 */
private BigDecimal decimal(String value){return value==null?null:new BigDecimal(value);}
}
@@ -0,0 +1,89 @@
package com.baiyue.lastleg.fleet.ownedbusiness.service;
import com.baiyue.common.core.exception.BizException;
import com.baiyue.common.core.api.ResultCode;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.fleet.ownedbusiness.model.OwnedBusinessModels.*;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.JavaType;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.*;
import java.util.*;
/** 只处理本页格式、身份和JSON,不读写主流程。 */
@Component
public class OwnedBusinessSupport {
private final ObjectMapper json;
/** 复用服务统一Jackson,不建立第二套日期或版本协议。 */
public OwnedBusinessSupport(ObjectMapper json){this.json=json;}
/** 平台身份和操作者均取可信会话,不接收浏览器归属参数。 */
public Actor actor(AuthenticatedUser user) {
if(user==null)throw new ResponseStatusException(HttpStatus.UNAUTHORIZED);
if(!"PLATFORM".equals(user.appCode()) || !Long.valueOf(0).equals(user.tenantId()))
throw new ResponseStatusException(HttpStatus.FORBIDDEN,"仅平台可管理自有业务");
String operator=user.userId()==null?user.username():user.userId().toString();
if(operator==null || operator.isBlank())throw new ResponseStatusException(HttpStatus.FORBIDDEN,"缺少有效操作账号");
String name=user.displayName()==null || user.displayName().isBlank()?user.username():user.displayName();
return new Actor(operator,name,user.permissions()==null?Set.of():Set.copyOf(user.permissions()));
}
/** 写权限独立校验,直接Service调用也不能绕过。 */
public void require(Actor actor,String permission) {
if(actor==null || actor.operatorId()==null || actor.permissions()==null || !actor.permissions().contains(permission))
throw new ResponseStatusException(HttpStatus.FORBIDDEN,"没有该业务操作权限");
}
/** JSON只从本页记录和已确认排车事实读取,损坏不静默恢复空值。 */
public <T>T read(String value,Class<T> type) {
if(value==null || value.isBlank())throw conflict("缺少可靠业务事实");
try{return json.readValue(value,type);}catch(JsonProcessingException error){throw conflict("业务事实读取失败,请核对原记录");}
}
/** 集合记录与声明的元素类型共同校验。 */
public <T>List<T> list(String value,Class<T> type) {
JavaType listType=json.getTypeFactory().constructCollectionType(List.class,type);
try{return json.readValue(value,listType);}catch(Exception error){throw conflict("业务集合事实读取失败");}
}
/** 原请求和原结果完整持久化,序列化失败必须中止命令。 */
public String write(Object value) {
try{return json.writeValueAsString(value);}catch(JsonProcessingException error){throw new IllegalStateException("业务记录序列化失败",error);}
}
/** 请求摘要不包含版本漂移后的当前数据。 */
public String hash(Object value){return digest(write(value).getBytes(StandardCharsets.UTF_8));}
/** 文件内容摘要用于识别相同上传原请求,不保存图片进数据库。 */
public String digest(byte[] bytes) {
try{return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(bytes));}
catch(Exception error){throw new IllegalStateException("无法计算业务摘要",error);}
}
/** 版本0合法,但缺失、负数和超长版本不得降级为0。 */
public long version(String value) {
try{if(value==null || !value.matches("0|[1-9][0-9]*"))throw new IllegalArgumentException();return Long.parseLong(value);}
catch(Exception error){throw bad("请提交有效的原记录版本");}
}
/** 请求键在页面恢复期间保持稳定,不能用空键创建命令。 */
public void key(String key){if(key==null || key.length()<8 || key.length()>128)throw bad("请求键长度须为8至128");}
/** 只接受带时区的真实时间,统一存UTC。 */
public Instant instant(String value) {
try{return value==null?null:OffsetDateTime.parse(value).toInstant();}
catch(Exception error){throw bad("时间须包含明确时区");}
}
/** 关系库时间只表示UTC,不取运行机默认时区。 */
public LocalDateTime utc(Instant value){return value==null?null:LocalDateTime.ofInstant(value,ZoneOffset.UTC);}
/** 展示原真实时间,不根据签收或预计时间填充。 */
public String iso(LocalDateTime value){return value==null?null:value.toInstant(ZoneOffset.UTC).toString();}
/** 规范十进制输入,空值与明确零分别保存。 */
public String decimal(String value,int integers,int scale) {
if(value==null)return null;
if(!value.matches("(0|[1-9][0-9]{0,"+(integers-1)+"})(\\.[0-9]{1,"+scale+"})?"))throw bad("数量或金额须为非负规范十进制");
return new BigDecimal(value).setScale(scale).toPlainString();
}
/** 用户输入错误保持项目业务错误约定。 */
public static BizException bad(String message){return new BizException(ResultCode.BAD_REQUEST,message);}
/** 业务并发或来源事实不符不能返回模拟成功。 */
public static BizException conflict(String message){return new BizException(ResultCode.CONFLICT,message);}
/** 不存在只使用业务提示,不泄露内部主键。 */
public static BizException missing(){return new BizException(ResultCode.NOT_FOUND,"排车单不存在或不属于当前自有业务");}
}
@@ -1,13 +1,14 @@
package com.baiyue.lastleg.fleet.pickup;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 取货持久化只访问 Lastleg 自有库,客户与原业务号始终成对使用。 */
@Mapper
public interface FleetPickupMapper extends BaseMapper<FleetPickupTask> {
String SOURCE_COLUMNS = "id,customer_id,transfer_no,inbound_code,lastleg_order_no,operating_warehouse_id,"
+ "delivery_address,pickup_contact_name,pickup_contact_phone,package_count,status,delivery_method";
String ELIGIBLE = " FROM ll_warehouse_transfer_order w LEFT JOIN ll_fleet_pickup_task p ON p.transfer_order_id=w.id "
+ "WHERE w.delivery_method='WAREHOUSE_PICKUP' AND w.transfer_no=w.inbound_code "
+ "AND w.status='WAIT_PDA_RECEIVING' AND (p.transfer_order_id IS NULL OR p.trip_no IS NULL) "
@@ -21,14 +22,11 @@ public interface FleetPickupMapper extends BaseMapper<FleetPickupTask> {
@Select("SELECT COUNT(*)" + ELIGIBLE)
long countCandidates(@Param("keyword") String keyword);
/** 锁定源订单,串行化补箱、清点与取货任务关联。 */
@Select("SELECT * FROM ll_warehouse_transfer_order WHERE customer_id=#{customer} AND transfer_no=#{number} FOR UPDATE")
WarehouseTransferOrder lockSource(@Param("customer") String customer,@Param("number") String number);
@Select("SELECT " + SOURCE_COLUMNS + " FROM ll_warehouse_transfer_order WHERE customer_id=#{customer} AND transfer_no=#{number} FOR UPDATE")
FleetPickupSource lockSource(@Param("customer") String customer,@Param("number") String number);
/** 读取明确客户下的源订单,不接收来自客户端的客户范围推断。 */
@Select("SELECT * FROM ll_warehouse_transfer_order WHERE customer_id=#{customer} AND transfer_no=#{number}")
WarehouseTransferOrder source(@Param("customer") String customer,@Param("number") String number);
/** PDA 作业仍按已绑定海外仓锁定原单。 */
@Select("SELECT * FROM ll_warehouse_transfer_order WHERE operating_warehouse_id=#{warehouse} AND transfer_no=#{number} FOR UPDATE")
WarehouseTransferOrder lockPdaSource(@Param("warehouse") String warehouse,@Param("number") String number);
@Select("SELECT " + SOURCE_COLUMNS + " FROM ll_warehouse_transfer_order WHERE customer_id=#{customer} AND transfer_no=#{number}")
FleetPickupSource source(@Param("customer") String customer,@Param("number") String number);
/** 读取取货任务,原订单锁负责同票并发互斥。 */
@Select("SELECT * FROM ll_fleet_pickup_task WHERE transfer_order_id=#{id}")
FleetPickupTask task(@Param("id") long id);
@@ -2,7 +2,6 @@ package com.baiyue.lastleg.fleet.pickup;
import com.baiyue.lastleg.fleet.trip.FleetTripEntity;
import com.baiyue.lastleg.fleet.trip.FleetTripMapper;
import com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -18,9 +17,7 @@ public class FleetPickupRepository {
/** 查询匹配需求总数。 */
public long count(String keyword) { return mapper.countCandidates(keyword); }
/** 读取或锁定客户原单。 */
public WarehouseTransferOrder source(String customer,String number,boolean lock) { return lock?mapper.lockSource(customer,number):mapper.source(customer,number); }
/** 按 PDA 仓库范围锁定原单。 */
public WarehouseTransferOrder pdaSource(String warehouse,String number) { return mapper.lockPdaSource(warehouse,number); }
public FleetPickupSource source(String customer,String number,boolean lock) { return lock?mapper.lockSource(customer,number):mapper.source(customer,number); }
/** 读取原单唯一取货记录。 */
public FleetPickupTask task(long id) { return mapper.task(id); }
/** 读取车次全部取货成员。 */
@@ -6,7 +6,6 @@ import com.baiyue.lastleg.fleet.driver.FleetWarehouseDirectory;
import com.baiyue.lastleg.fleet.reporting.TripOperationsEvidenceGateway;
import com.baiyue.lastleg.fleet.trip.*;
import com.baiyue.lastleg.masterdata.vehicle.application.port.out.VehicleRepository;
import com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
@@ -59,7 +58,7 @@ public class FleetPickupService {
var sources=request.sources().stream().sorted(Comparator.comparing(FleetPickupModels.Source::customerId)
.thenComparing(FleetPickupModels.Source::transferNo)).toList();
if(new HashSet<>(sources).size()!=sources.size())throw bad("同一取货单不能重复选择");
var orders=new ArrayList<WarehouseTransferOrder>();
var orders=new ArrayList<FleetPickupSource>();
for(var source:sources) {
var order=source(source.customerId(),source.transferNo(),true);eligible(order);
// 相同请求并发等待原单锁后,允许返回第一次已经成功的车次。
@@ -107,18 +106,10 @@ public class FleetPickupService {
if(!"WAREHOUSE_PICKUP".equals(source.getDeliveryMethod()) || !source.getTransferNo().equals(source.getInboundCode()))return null;
return project(source,repository.task(source.getId()));
}
/** PDA 开始作业前校验已送仓,防止把司机取货冒充仓库实收。 */
public WarehouseTransferOrder requireMeasuringSource(String warehouse,String number) {
var source=repository.pdaSource(warehouse,number);
if(source==null)throw missing("仓储转运单不存在");
if(!"WAIT_PDA_RECEIVING".equals(source.getStatus()))throw conflict("当前转运单不允许测量");
requireArrived(source);
return source;
}
/** 已有原单行锁的清点、照片和完成入口复用相同到仓门禁。 */
public void requireArrived(WarehouseTransferOrder source) {
if("WAREHOUSE_PICKUP".equals(source.getDeliveryMethod()) && source.getTransferNo().equals(source.getInboundCode())) {
var task=repository.task(source.getId());
public void requireArrived(Long sourceId,String deliveryMethod,String transferNo,String inboundCode) {
if("WAREHOUSE_PICKUP".equals(deliveryMethod) && transferNo.equals(inboundCode)) {
var task=repository.task(sourceId);
if(task==null || !"ARRIVED".equals(task.getStatus()))throw conflict("该单为仓库上门取货,请先完成车辆取货送仓");
}
}
@@ -198,7 +189,7 @@ public class FleetPickupService {
var trip=pickupTrip(task.getTripNo(),false);return files.download(trip.getId(),fileId);
}
/** 组装运输进度,车次资源修改后自然回显最新分配。 */
private FleetPickupModels.Task project(WarehouseTransferOrder source,FleetPickupTask task) {
private FleetPickupModels.Task project(FleetPickupSource source,FleetPickupTask task) {
var trip=task==null || task.getTripNo()==null?null:repository.trip(task.getTripNo(),false);
String status=task==null || task.getTripNo()==null?("PENDING_REVIEW".equals(source.getStatus()) || "DRAFT".equals(source.getStatus())?"PENDING_REVIEW":"WAITING"):task.getStatus();
return new FleetPickupModels.Task(source.getCustomerId(),source.getTransferNo(),source.getLastlegOrderNo(),source.getOperatingWarehouseId(),
@@ -215,11 +206,11 @@ public class FleetPickupService {
if(task==null || !trip.getTripNo().equals(task.getTripNo()))throw missing("当前车次没有该取货订单");return task;
}
/** 按客户与单号读取原订单。 */
private WarehouseTransferOrder source(String customer,String number,boolean lock) {
private FleetPickupSource source(String customer,String number,boolean lock) {
var source=repository.source(customer,number,lock);if(source==null)throw missing("仓储转运单不存在");return source;
}
/** 原业务资格每次执行复核,禁止未审、自送、库存转运和已完成测量单进入。 */
private static void eligible(WarehouseTransferOrder order) {
private static void eligible(FleetPickupSource order) {
if(!"WAREHOUSE_PICKUP".equals(order.getDeliveryMethod()) || !order.getTransferNo().equals(order.getInboundCode())
|| !"WAIT_PDA_RECEIVING".equals(order.getStatus()))throw conflict("该单不是已审核待收货的仓库上门取货单");
if(blank(order.getDeliveryAddress())==null || blank(order.getPickupContactName())==null || blank(order.getPickupContactPhone())==null)
@@ -0,0 +1,20 @@
package com.baiyue.lastleg.fleet.pickup;
import lombok.Data;
/** 车队只读取货资格和展示所需来源摘要,不共享转运领域实体或写入原订单。 */
@Data
public class FleetPickupSource {
private Long id;
private String customerId;
private String transferNo;
private String inboundCode;
private String lastlegOrderNo;
private String operatingWarehouseId;
private String deliveryAddress;
private String pickupContactName;
private String pickupContactPhone;
private Integer packageCount;
private String status;
private String deliveryMethod;
}
@@ -0,0 +1,12 @@
package com.baiyue.lastleg.fleet.trip;
/** 日历专用只读查询投影,真实排车号不属于车次持久化字段。 */
public class FleetTripCalendarRow extends FleetTripEntity {
private String dispatchNo;
/** 返回关联整车主单的业务号。 */
public String getDispatchNo() { return dispatchNo; }
/** 仅供日历SQL结果映射,不写入车次表。 */
public void setDispatchNo(String dispatchNo) { this.dispatchNo = dispatchNo; }
}
@@ -11,10 +11,10 @@ import org.springframework.web.server.ResponseStatusException;
import java.time.*;
import java.util.*;
/** Read-only transport plans. A trip is never evidence of a receiving appointment confirmation. */
/** 排车日历沿真实整车主单读取运输时间,不代表已取得目的仓收货确认。 */
@Service
public class FleetTripCalendarService {
public record Entry(String sourceType, String tripNo, String status, String originWarehouseId,
public record Entry(String sourceType, String dispatchNo, String status, String originWarehouseId,
String originWarehouseCode, String originWarehouseName, String originCountryCode,
String originTimezone, String originWarehouseStatus, Instant plannedDepartureAt,
Instant expectedDriverEndAt, Instant departedAt, Instant completedAt,
@@ -31,12 +31,13 @@ public class FleetTripCalendarService {
this.trips=trips; this.warehouses=warehouses; this.json=json; this.token=token;
}
/** 一次读取真实排车及一次仓库资料查询,按业务地点判定日历归属。 */
@Transactional(readOnly=true)
public Result calendar(Instant from, Instant to) {
if (from==null || to==null || !to.isAfter(from) || Duration.between(from,to).compareTo(Duration.ofDays(44))>0)
throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"查询须为不超过44天的UTC时间范围");
var rows=trips.calendar(LocalDateTime.ofInstant(from,ZoneOffset.UTC),LocalDateTime.ofInstant(to,ZoneOffset.UTC));
if (rows.size()>2000) throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"车次过多,请缩小查询日期范围");
if (rows.size()>2000) throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"排车过多,请缩小查询日期范围");
if (rows.isEmpty()) return new Result(List.of(),List.of());
var ids=rows.stream().map(FleetTripEntity::getWarehouseId).filter(Objects::nonNull).filter(id->id>0).distinct().sorted().toList();
var metadata=metadata(ids);
@@ -60,7 +61,7 @@ public class FleetTripCalendarService {
throw new IllegalArgumentException("incomplete route");
stops=List.copyOf(stops);
} catch (Exception invalid) { stops=List.of(); reasons.add("ROUTE_INCOMPLETE"); }
var entry=new Entry("TRIP_PLAN",row.getTripNo(),row.getStatus(),row.getWarehouseId()==null?null:row.getWarehouseId().toString(),
var entry=new Entry("DISPATCH",row.getDispatchNo(),row.getStatus(),row.getWarehouseId()==null?null:row.getWarehouseId().toString(),
warehouse==null?row.getWarehouseCode():warehouse.warehouseCode(),warehouse==null?row.getWarehouseName():warehouse.warehouseName(),
country,zone,warehouse==null?null:warehouse.status(),instant(row.getPlannedDepartureAt()),instant(row.getExpectedDriverEndAt()),
instant(row.getDepartedAt()),instant(row.getCompletedAt()),stops,List.copyOf(reasons));
@@ -7,17 +7,18 @@ import org.apache.ibatis.annotations.Select;
@Mapper
public interface FleetTripMapper extends BaseMapper<FleetTripEntity> {
/** 预约日历只读海外仓出库派送,取货入仓车次不属于排车类型。 */
/** 日历只读真实整车主单的出库派送,一单一条;独立车次及取消主单不进入排车日历。 */
@Select("""
SELECT trip_no,status,warehouse_id,warehouse_code,warehouse_name,planned_departure_at,
expected_driver_end_at,departed_at,completed_at,stops_json
FROM ll_fleet_trip
WHERE trip_purpose='DELIVERY' AND (
(departed_at IS NOT NULL AND departed_at>=#{from} AND departed_at<#{to})
OR (departed_at IS NULL AND planned_departure_at>=#{from} AND planned_departure_at<#{to}))
ORDER BY COALESCE(departed_at,planned_departure_at),trip_no LIMIT 2001
SELECT d.dispatch_no,t.trip_no,t.status,t.warehouse_id,t.warehouse_code,t.warehouse_name,t.planned_departure_at,
t.expected_driver_end_at,t.departed_at,t.completed_at,t.stops_json
FROM ll_dispatch_order d JOIN ll_fleet_trip t ON t.id=d.trip_id
WHERE d.status='ACTIVE' AND d.dispatch_no IS NOT NULL AND TRIM(d.dispatch_no)<>''
AND t.trip_purpose='DELIVERY' AND (
(t.departed_at IS NOT NULL AND t.departed_at>=#{from} AND t.departed_at<#{to})
OR (t.departed_at IS NULL AND t.planned_departure_at>=#{from} AND t.planned_departure_at<#{to}))
ORDER BY COALESCE(t.departed_at,t.planned_departure_at),d.dispatch_no LIMIT 2001
""")
java.util.List<FleetTripEntity> calendar(@Param("from") java.time.LocalDateTime from,@Param("to") java.time.LocalDateTime to);
java.util.List<FleetTripCalendarRow> calendar(@Param("from") java.time.LocalDateTime from,@Param("to") java.time.LocalDateTime to);
@Select("SELECT * FROM ll_fleet_trip WHERE trip_no=#{tripNo} FOR UPDATE")
FleetTripEntity lockByNo(@Param("tripNo") String tripNo);
@Select("SELECT * FROM ll_fleet_trip WHERE trip_no=#{tripNo}")
@@ -18,13 +18,14 @@ import org.springframework.web.server.ResponseStatusException;
@RequestMapping("/api/platform/v1/last-leg/fleet/trips")
public class PlatformFleetTripController {
@jakarta.annotation.Resource private FleetTripCalendarService calendar;
/** 预约排车日历沿用真实排车列表读取权限,不要求已退出菜单的车次管理权限。 */
@GetMapping("/calendar")
@PreAuthorize("hasAuthority('platform:fleet:trip:list')")
@PreAuthorize("hasAuthority('platform:overseas-warehouse:dispatch:list')")
public ApiResponse<FleetTripCalendarService.Result> calendar(@AuthenticationPrincipal AuthenticatedUser user,
@RequestParam java.time.Instant from,@RequestParam java.time.Instant to) {
operator(user);
if (!"PLATFORM".equals(user.appCode()) || !Long.valueOf(0).equals(user.tenantId()))
throw new ResponseStatusException(HttpStatus.FORBIDDEN,"仅平台主体可读取车次日历");
throw new ResponseStatusException(HttpStatus.FORBIDDEN,"仅平台主体可读取排车日历");
return ApiResponse.success(calendar.calendar(from,to));
}
@@ -35,6 +35,16 @@ public class InventoryQueryController {
private static final String BASE_PATH = "/api/platform/v1/last-leg/inventory";
@Resource private InventoryQueryService service;
@Resource private com.baiyue.lastleg.inventory.query.service.InventoryPieceService pieces;
/** 完整筛选读取当前可用件数、箱内全部SKU及未知箱数,不改变原有箱数契约。 */
@GetMapping(BASE_PATH + "/piece-projection")
@PreAuthorize("hasAuthority('" + OverseasPermissions.INVENTORY_LIST + "')")
public ApiResponse<com.baiyue.lastleg.inventory.query.dto.InventoryPieceProjection> pieceProjection(
@AuthenticationPrincipal AuthenticatedUser user,@RequestParam(required=false) String customerId,
@Valid InventoryQueryRequests.BalanceQuery query) {
return ApiResponse.success(pieces.project(platformScope(user,customerId),query));
}
@GetMapping(BASE_PATH + "/summary")
@PreAuthorize("hasAuthority('" + OverseasPermissions.INVENTORY_LIST + "')")
@@ -0,0 +1,14 @@
package com.baiyue.lastleg.inventory.query.dto;
import java.util.List;
/** 当前严格可用件数与完整混箱SKU内容;不完整映射保持未知,不覆盖原有箱数API。 */
public record InventoryPieceProjection(Long availablePieceCount,long knownAvailablePieceCount,long unknownCartonCount,
long availableCartonCount,long availablePalletCount,List<Group> groups) {
/** 与通用库存按客户、仓、目的仓、记账SKU分组对齐,箱内SKU不重复累计物理箱。 */
public record Group(String customerId,String warehouseId,String destinationCode,String anchorSkuCode,
Long availablePieceCount,long knownAvailablePieceCount,long unknownCartonCount,long availableCartonCount,
long availablePalletCount,List<Sku> skuContents,List<Carton> cartons) { }
/** 箱内实际SKU件数。 */
public record Sku(String skuCode,long quantity) { }
/** 保留箱唛及所在仓位,混箱SKU共享同一物理箱。 */
public record Carton(String cartonMark,Long inventoryPositionId,Long palletId,Long quantity,List<Sku> items) { }
}
@@ -0,0 +1,73 @@
package com.baiyue.lastleg.inventory.query.mapper;
import com.baiyue.lastleg.inventory.query.dto.InventoryQueryRequests;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 从原箱清点事实及实际目的仓签收定位箱内SKU,不按首SKU或箱规换算件数。 */
@Mapper
public interface InventoryPieceMapper {
String POSITION_CTE = "WITH balances AS (SELECT * FROM ll_inventory_balance " + InventoryQueryMapper.BALANCE_FILTER + """
), occupied AS (
SELECT DISTINCT t.customer_id,t.operating_warehouse_id warehouse_id,t.inbound_code,
COALESCE(NULLIF(c.customer_carton_mark,''),c.carton_mark) carton_mark
FROM ll_warehouse_transfer_order t JOIN ll_warehouse_transfer_carton c
ON c.transfer_order_id=t.id AND c.customer_id=t.customer_id
-- 出库已扣减来源箱,后续签收生成目的仓库存,不再把同一原箱当作待出库预留。
WHERE t.transfer_no&lt;&gt;t.inbound_code AND t.status NOT IN
('DRAFT','REJECTED','CANCELLED','OUTBOUNDED','PARTIALLY_RECEIVED','RECEIVED')
), raw_positions AS (SELECT p.* FROM ll_inventory_position p JOIN balances b
ON b.id=p.balance_id AND b.customer_id=p.customer_id WHERE p.available_packages>0),
located AS (
SELECT p.id position_id,c.id carton_id,c.carton_mark,c.counted_quantity,c.sku_items_json
FROM raw_positions p JOIN balances b ON b.id=p.balance_id AND b.customer_id=p.customer_id
JOIN ll_warehouse_transfer_order t ON t.customer_id=b.customer_id AND t.inbound_order_id=b.inbound_order_id
AND t.operating_warehouse_id=b.overseas_warehouse_id AND t.transfer_no=t.inbound_code
JOIN ll_warehouse_transfer_pallet tp ON tp.transfer_order_id=t.id AND tp.customer_id=t.customer_id AND tp.warehouse_pallet_id=p.pallet_id
JOIN ll_warehouse_transfer_carton c ON c.transfer_order_id=t.id AND c.customer_id=t.customer_id
AND c.transfer_pallet_id=tp.id AND c.status='COUNTED'
JOIN ll_warehouse_transfer_item i ON i.id=c.transfer_item_id AND i.customer_id=c.customer_id AND (b.sku_code='MIXED' OR i.sku_code=b.sku_code)
UNION
SELECT p.id,c.id,c.carton_mark,c.counted_quantity,c.sku_items_json
FROM raw_positions p JOIN balances b ON b.id=p.balance_id AND b.customer_id=p.customer_id
JOIN ll_warehouse_transfer_receipt r ON r.destination_inventory_position_id=p.id AND r.customer_id=p.customer_id
JOIN ll_warehouse_transfer_inventory_allocation a ON a.id=r.allocation_id AND a.customer_id=r.customer_id AND a.status='RECEIVED'
JOIN ll_inventory_position sp ON sp.id=a.inventory_position_id AND sp.customer_id=a.customer_id
JOIN ll_warehouse_transfer_order outgoing ON outgoing.id=a.transfer_order_id AND outgoing.customer_id=a.customer_id
JOIN ll_warehouse_transfer_carton chosen ON chosen.transfer_order_id=outgoing.id AND chosen.customer_id=outgoing.customer_id
JOIN ll_warehouse_transfer_order origin ON origin.customer_id=outgoing.customer_id AND origin.inbound_code=outgoing.inbound_code
AND origin.operating_warehouse_id=outgoing.operating_warehouse_id AND origin.transfer_no=origin.inbound_code
JOIN ll_warehouse_transfer_carton c ON c.transfer_order_id=origin.id AND c.customer_id=origin.customer_id
AND c.carton_mark=COALESCE(NULLIF(chosen.customer_carton_mark,''),chosen.carton_mark) AND c.status='SHIPPED'
JOIN ll_warehouse_transfer_pallet tp ON tp.id=c.transfer_pallet_id AND tp.customer_id=c.customer_id AND tp.warehouse_pallet_id=sp.pallet_id
JOIN ll_warehouse_transfer_item i ON i.id=c.transfer_item_id AND i.customer_id=c.customer_id AND (b.sku_code='MIXED' OR i.sku_code=b.sku_code)
), reservations AS (
SELECT p.id position_id,COUNT(DISTINCT l.carton_id) reserved_count
FROM raw_positions p JOIN balances b ON b.id=p.balance_id AND b.customer_id=p.customer_id
JOIN located l ON l.position_id=p.id JOIN occupied o ON o.customer_id=b.customer_id
AND o.warehouse_id=b.overseas_warehouse_id AND o.inbound_code=b.inbound_code AND o.carton_mark=l.carton_mark
GROUP BY p.id
), positions AS (
SELECT p.*,GREATEST(0,p.available_packages-COALESCE(r.reserved_count,0)) free_packages
FROM raw_positions p LEFT JOIN reservations r ON r.position_id=p.id
)
SELECT p.id positionId,p.balance_id balanceId,b.customer_id customerId,b.overseas_warehouse_id warehouseId,
b.destination_warehouse_code destinationCode,b.sku_code anchorSkuCode,p.pallet_id palletId,
p.free_packages availablePackages,l.carton_id cartonId,l.carton_mark cartonMark,
l.counted_quantity countedQuantity,l.sku_items_json skuItemsJson
FROM positions p JOIN balances b ON b.id=p.balance_id AND b.customer_id=p.customer_id
LEFT JOIN located l ON l.position_id=p.id AND NOT EXISTS (
SELECT 1 FROM occupied o WHERE o.customer_id=b.customer_id AND o.warehouse_id=b.overseas_warehouse_id
AND o.inbound_code=b.inbound_code AND o.carton_mark=l.carton_mark)
WHERE p.free_packages>0
ORDER BY p.id,l.carton_id
""";
/** 完整筛选取箱级投影;页码/每页大小不参与查询。 */
@Select("<script>" + POSITION_CTE + "</script>")
List<PieceRow> rows(@Param("customerId") String customerId,@Param("q") InventoryQueryRequests.BalanceQuery query);
/** 每个当前可用仓位及其匹配箱事实;未知箱以空cartonId表达。 */
record PieceRow(Long positionId,Long balanceId,String customerId,String warehouseId,String destinationCode,
String anchorSkuCode,Long palletId,long availablePackages,Long cartonId,String cartonMark,Long countedQuantity,String skuItemsJson) { }
}
@@ -24,7 +24,7 @@ public interface InventoryQueryMapper {
"<if test='q.inboundOrderNo != null and q.inboundOrderNo != \"\"'> AND inbound_order_no LIKE CONCAT('%',#{q.inboundOrderNo},'%')</if>" +
"<if test='q.inboundCode != null and q.inboundCode != \"\"'> AND inbound_code LIKE CONCAT('%',#{q.inboundCode},'%')</if>" +
"<if test='q.businessOrderNo != null and q.businessOrderNo != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_ledger l WHERE l.balance_id=ll_inventory_balance.id AND l.customer_id=ll_inventory_balance.customer_id AND l.business_order_no LIKE CONCAT('%',#{q.businessOrderNo},'%'))</if>" +
"<if test='q.skuCode != null and q.skuCode != \"\"'> AND sku_code LIKE CONCAT('%',#{q.skuCode},'%')</if>" +
"<if test='q.skuCode != null and q.skuCode != \"\"'> AND (sku_code LIKE CONCAT('%',#{q.skuCode},'%') OR EXISTS (SELECT 1 FROM ll_warehouse_transfer_order tq JOIN ll_warehouse_transfer_carton cq ON cq.transfer_order_id=tq.id AND cq.customer_id=tq.customer_id WHERE tq.customer_id=ll_inventory_balance.customer_id AND tq.inbound_order_id=ll_inventory_balance.inbound_order_id AND tq.operating_warehouse_id=ll_inventory_balance.overseas_warehouse_id AND tq.transfer_no=tq.inbound_code AND cq.status IN ('COUNTED','DISCARD_PENDING') AND EXISTS (SELECT 1 FROM ll_warehouse_transfer_item iq WHERE iq.id=cq.transfer_item_id AND iq.customer_id=cq.customer_id AND (ll_inventory_balance.sku_code='MIXED' OR iq.sku_code=ll_inventory_balance.sku_code)) AND JSON_SEARCH(cq.sku_items_json,'one',CONCAT('%',#{q.skuCode},'%'),NULL,'$[*].skuCode') IS NOT NULL) OR EXISTS (SELECT 1 FROM ll_inventory_position dp JOIN ll_warehouse_transfer_receipt rr ON rr.destination_inventory_position_id=dp.id AND rr.customer_id=dp.customer_id JOIN ll_warehouse_transfer_inventory_allocation aa ON aa.id=rr.allocation_id AND aa.customer_id=rr.customer_id AND aa.status='RECEIVED' JOIN ll_inventory_position sp ON sp.id=aa.inventory_position_id AND sp.customer_id=aa.customer_id JOIN ll_warehouse_transfer_order ot ON ot.id=aa.transfer_order_id AND ot.customer_id=aa.customer_id JOIN ll_warehouse_transfer_carton chosen ON chosen.transfer_order_id=ot.id AND chosen.customer_id=ot.customer_id JOIN ll_warehouse_transfer_order origin ON origin.customer_id=ot.customer_id AND origin.inbound_code=ot.inbound_code AND origin.operating_warehouse_id=ot.operating_warehouse_id AND origin.transfer_no=origin.inbound_code JOIN ll_warehouse_transfer_carton cc ON cc.transfer_order_id=origin.id AND cc.customer_id=origin.customer_id AND cc.carton_mark=COALESCE(NULLIF(chosen.customer_carton_mark,''),chosen.carton_mark) AND cc.status='SHIPPED' JOIN ll_warehouse_transfer_pallet pp ON pp.id=cc.transfer_pallet_id AND pp.customer_id=cc.customer_id AND pp.warehouse_pallet_id=sp.pallet_id JOIN ll_warehouse_transfer_item ii ON ii.id=cc.transfer_item_id AND ii.customer_id=cc.customer_id WHERE dp.balance_id=ll_inventory_balance.id AND dp.customer_id=ll_inventory_balance.customer_id AND dp.available_packages>0 AND (ll_inventory_balance.sku_code='MIXED' OR ii.sku_code=ll_inventory_balance.sku_code) AND JSON_SEARCH(cc.sku_items_json,'one',CONCAT('%',#{q.skuCode},'%'),NULL,'$[*].skuCode') IS NOT NULL))</if>" +
"<if test='q.productName != null and q.productName != \"\"'> AND (product_name_zh LIKE CONCAT('%',#{q.productName},'%') OR product_name_en LIKE CONCAT('%',#{q.productName},'%'))</if>" +
"<if test='q.batchNo != null and q.batchNo != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_position p WHERE p.balance_id=ll_inventory_balance.id AND p.customer_id=ll_inventory_balance.customer_id AND p.batch_no LIKE CONCAT('%',#{q.batchNo},'%'))</if>" +
"<if test='q.warehouseLocationCode != null and q.warehouseLocationCode != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_position p WHERE p.balance_id=ll_inventory_balance.id AND p.customer_id=ll_inventory_balance.customer_id AND p.warehouse_location_code LIKE CONCAT('%',#{q.warehouseLocationCode},'%'))</if>" +
@@ -48,7 +48,7 @@ public interface InventoryQueryMapper {
"<if test='q.inboundOrderNo != null and q.inboundOrderNo != \"\"'> AND b.inbound_order_no LIKE CONCAT('%',#{q.inboundOrderNo},'%')</if>" +
"<if test='q.inboundCode != null and q.inboundCode != \"\"'> AND b.inbound_code LIKE CONCAT('%',#{q.inboundCode},'%')</if>" +
"<if test='q.businessOrderNo != null and q.businessOrderNo != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_ledger l WHERE l.balance_id=b.id AND l.customer_id=b.customer_id AND l.business_order_no LIKE CONCAT('%',#{q.businessOrderNo},'%'))</if>" +
"<if test='q.skuCode != null and q.skuCode != \"\"'> AND b.sku_code LIKE CONCAT('%',#{q.skuCode},'%')</if>" +
"<if test='q.skuCode != null and q.skuCode != \"\"'> AND (b.sku_code LIKE CONCAT('%',#{q.skuCode},'%') OR EXISTS (SELECT 1 FROM ll_warehouse_transfer_order tq JOIN ll_warehouse_transfer_carton cq ON cq.transfer_order_id=tq.id AND cq.customer_id=tq.customer_id WHERE tq.customer_id=b.customer_id AND tq.inbound_order_id=b.inbound_order_id AND tq.operating_warehouse_id=b.overseas_warehouse_id AND tq.transfer_no=tq.inbound_code AND cq.status IN ('COUNTED','DISCARD_PENDING') AND EXISTS (SELECT 1 FROM ll_warehouse_transfer_item iq WHERE iq.id=cq.transfer_item_id AND iq.customer_id=cq.customer_id AND (b.sku_code='MIXED' OR iq.sku_code=b.sku_code)) AND JSON_SEARCH(cq.sku_items_json,'one',CONCAT('%',#{q.skuCode},'%'),NULL,'$[*].skuCode') IS NOT NULL) OR EXISTS (SELECT 1 FROM ll_inventory_position dp JOIN ll_warehouse_transfer_receipt rr ON rr.destination_inventory_position_id=dp.id AND rr.customer_id=dp.customer_id JOIN ll_warehouse_transfer_inventory_allocation aa ON aa.id=rr.allocation_id AND aa.customer_id=rr.customer_id AND aa.status='RECEIVED' JOIN ll_inventory_position sp ON sp.id=aa.inventory_position_id AND sp.customer_id=aa.customer_id JOIN ll_warehouse_transfer_order ot ON ot.id=aa.transfer_order_id AND ot.customer_id=aa.customer_id JOIN ll_warehouse_transfer_carton chosen ON chosen.transfer_order_id=ot.id AND chosen.customer_id=ot.customer_id JOIN ll_warehouse_transfer_order origin ON origin.customer_id=ot.customer_id AND origin.inbound_code=ot.inbound_code AND origin.operating_warehouse_id=ot.operating_warehouse_id AND origin.transfer_no=origin.inbound_code JOIN ll_warehouse_transfer_carton cc ON cc.transfer_order_id=origin.id AND cc.customer_id=origin.customer_id AND cc.carton_mark=COALESCE(NULLIF(chosen.customer_carton_mark,''),chosen.carton_mark) AND cc.status='SHIPPED' JOIN ll_warehouse_transfer_pallet pp ON pp.id=cc.transfer_pallet_id AND pp.customer_id=cc.customer_id AND pp.warehouse_pallet_id=sp.pallet_id JOIN ll_warehouse_transfer_item ii ON ii.id=cc.transfer_item_id AND ii.customer_id=cc.customer_id WHERE dp.balance_id=b.id AND dp.customer_id=b.customer_id AND dp.available_packages>0 AND (b.sku_code='MIXED' OR ii.sku_code=b.sku_code) AND JSON_SEARCH(cc.sku_items_json,'one',CONCAT('%',#{q.skuCode},'%'),NULL,'$[*].skuCode') IS NOT NULL))</if>" +
"<if test='q.productName != null and q.productName != \"\"'> AND (b.product_name_zh LIKE CONCAT('%',#{q.productName},'%') OR b.product_name_en LIKE CONCAT('%',#{q.productName},'%'))</if>" +
"<if test='q.batchNo != null and q.batchNo != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_position p2 WHERE p2.balance_id=b.id AND p2.customer_id=b.customer_id AND p2.batch_no LIKE CONCAT('%',#{q.batchNo},'%'))</if>" +
"<if test='q.warehouseLocationCode != null and q.warehouseLocationCode != \"\"'> AND EXISTS (SELECT 1 FROM ll_inventory_position p2 WHERE p2.balance_id=b.id AND p2.customer_id=b.customer_id AND p2.warehouse_location_code LIKE CONCAT('%',#{q.warehouseLocationCode},'%'))</if>" +
@@ -0,0 +1,15 @@
package com.baiyue.lastleg.inventory.query.repository;
import com.baiyue.lastleg.inventory.query.dto.InventoryQueryRequests;
import com.baiyue.lastleg.inventory.query.mapper.InventoryPieceMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import java.util.List;
/** 统一库存混箱事实查询入口。 */
@Repository
public class InventoryPieceRepository {
@Resource private InventoryPieceMapper mapper;
/** 读取相同筛选范围的全部当前可用箱。 */
public List<InventoryPieceMapper.PieceRow> rows(String customerId,InventoryQueryRequests.BalanceQuery query) {
return mapper.rows(customerId,query);
}
}
@@ -0,0 +1,71 @@
package com.baiyue.lastleg.inventory.query.service;
import com.baiyue.lastleg.inventory.query.dto.*;
import com.baiyue.lastleg.inventory.query.mapper.InventoryPieceMapper.PieceRow;
import com.baiyue.lastleg.inventory.query.repository.InventoryPieceRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.stream.Collectors;
/** 用完整箱内清点投影当前可用件数,对缺失或不完整映射显式返回未知。 */
@Service
public class InventoryPieceService {
@Resource private InventoryPieceRepository repository;
@Resource private ObjectMapper objectMapper;
/** 完整筛选的多分组汇总,同一物理托盘按客户及仓去重而非相减。 */
@Transactional(readOnly=true)
public InventoryPieceProjection project(String customerId,InventoryQueryRequests.BalanceQuery query) {
var rows=repository.rows(customerId,query);
var groups=rows.stream().collect(Collectors.groupingBy(r -> Arrays.asList(r.customerId(),r.warehouseId(),r.destinationCode(),r.anchorSkuCode()),LinkedHashMap::new,Collectors.toList()));
var result=new ArrayList<InventoryPieceProjection.Group>(); var pallets=new HashSet<String>();
for(var group:groups.values()) {
result.add(group(group));
for(var row:group) if(row.palletId()!=null) pallets.add(row.customerId()+":"+row.warehouseId()+":"+row.palletId());
}
long known=0,unknown=0,cartons=0;
for(var group:result) { known=Math.addExact(known,group.knownAvailablePieceCount()); unknown+=group.unknownCartonCount(); cartons+=group.availableCartonCount(); }
return new InventoryPieceProjection(unknown==0?known:null,known,unknown,cartons,pallets.size(),result);
}
/** 每个仓位只有精确箱映射完整时才计入已知件数,不能从多余箱中截取或按比例推算。 */
private InventoryPieceProjection.Group group(List<PieceRow> rows) {
var positions=rows.stream().collect(Collectors.groupingBy(PieceRow::positionId,LinkedHashMap::new,Collectors.toList()));
var contents=new TreeMap<String,Long>(); var cartons=new ArrayList<InventoryPieceProjection.Carton>();
var pallets=new HashSet<Long>(); long available=0,unknown=0,known=0;
for(var position:positions.values()) {
var first=position.get(0); available+=first.availablePackages(); if(first.palletId()!=null) pallets.add(first.palletId());
var boxes=position.stream().filter(r -> r.cartonId()!=null).collect(Collectors.toMap(PieceRow::cartonId,r -> r,(a,b)->a,LinkedHashMap::new));
var parsed=new ArrayList<InventoryPieceProjection.Carton>();
for(var row:boxes.values()) parsed.add(carton(row));
if(boxes.size()!=first.availablePackages() || parsed.stream().anyMatch(c -> c.quantity()==null)) { unknown+=first.availablePackages(); continue; }
for(var box:parsed) {
cartons.add(box); known=Math.addExact(known,box.quantity());
for(var sku:box.items()) contents.merge(sku.skuCode(),sku.quantity(),Math::addExact);
}
}
var first=rows.get(0);
return new InventoryPieceProjection.Group(first.customerId(),first.warehouseId(),first.destinationCode(),first.anchorSkuCode(),
unknown==0?known:null,known,unknown,available,pallets.size(),contents.entrySet().stream().map(e -> new InventoryPieceProjection.Sku(e.getKey(),e.getValue())).toList(),cartons);
}
/** 清点JSON与箱总件数必须一致;缺失信息保持未知,不拿首SKU替代混箱。 */
private InventoryPieceProjection.Carton carton(PieceRow row) {
var items=new ArrayList<InventoryPieceProjection.Sku>(); Long quantity=null;
try {
var lines=objectMapper.readTree(row.skuItemsJson()); long sum=0;
if(lines.isArray() && !lines.isEmpty()) {
for(var line:lines) {
String sku=line.path("skuCode").asText(""); var count=line.path("quantity");
if(sku.isBlank() || !count.asText().matches("[0-9]+")) throw new IllegalArgumentException("无效箱内SKU事实");
long pieces=Long.parseLong(count.asText());
if(pieces<=0) throw new IllegalArgumentException("箱内件数必须为正整数");
items.add(new InventoryPieceProjection.Sku(sku,pieces)); sum=Math.addExact(sum,pieces);
}
if(row.countedQuantity()!=null && sum==row.countedQuantity()) quantity=sum;
}
} catch(Exception invalid) { items.clear(); }
return new InventoryPieceProjection.Carton(row.cartonMark(),row.positionId(),row.palletId(),quantity,items);
}
}
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.palletops.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.common.security.AuthenticatedUser;
import com.baiyue.lastleg.palletops.service.PalletOperationRecoveryService;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import jakarta.validation.Valid;
/** 受库存管理权限保护的人工恢复入口,不允许PDA自行批准技术状态关闭。 */
@RestController
@RequestMapping("/api/platform/v1/last-leg/pallet-operation-recoveries")
@PreAuthorize("hasAuthority('lastleg:inventory:manage')")
public class PlatformPalletOperationRecoveryController {
private final PalletOperationRecoveryService service;
/** 注入恢复业务服务。 */
public PlatformPalletOperationRecoveryController(PalletOperationRecoveryService service){this.service=service;}
/** 管理员读取原作业证据。 */
@GetMapping("/{id}") public ApiResponse<PalletOperationRecoveryService.State> inspect(@PathVariable long id){return ApiResponse.success(service.inspect(id));}
/** 以认证管理员身份审计关闭。 */
@PostMapping("/{id}/close-no-effect")
public ApiResponse<PalletOperationRecoveryService.Recovery> close(@PathVariable long id,@AuthenticationPrincipal AuthenticatedUser user,@Valid @RequestBody PalletOperationRecoveryService.Close request){return ApiResponse.success(service.close(id,String.valueOf(user.userId()),request));}
}
@@ -0,0 +1,25 @@
package com.baiyue.lastleg.palletops.mapper;
import com.baiyue.lastleg.palletops.entity.PdaPalletOperation;
import org.apache.ibatis.annotations.*;
import java.time.LocalDateTime;
/** 恢复与远端意图使用同一行CAS,恢复关闭后旧执行线程不能继续发起远端写入。 */
@Mapper
public interface PalletOperationRecoveryMapper {
/** 读取原作业技术状态。 */
@Select("SELECT * FROM ll_pda_pallet_operation WHERE id=#{id}")
PdaPalletOperation find(@Param("id") long id);
/** 恢复审批与远端意图按原行串行。 */
@Select("SELECT * FROM ll_pda_pallet_operation WHERE id=#{id} FOR UPDATE")
PdaPalletOperation lock(@Param("id") long id);
/** 恢复关闭后拒绝继续持久化远端意图。 */
@Update("UPDATE ll_pda_pallet_operation SET remote_transitions_json=#{json},updated_at=#{at} WHERE id=#{id} AND status='PROCESSING'")
int journal(@Param("id") long id,@Param("json") String json,@Param("at") LocalDateTime at);
/** 条件关闭原作业并保存恢复审计。 */
@Update("UPDATE ll_pda_pallet_operation SET status='RECOVERED_NO_EFFECT',result_json=#{audit},updated_at=#{at} WHERE id=#{id} AND status IN ('PROCESSING','FAILED_COMPENSATED')")
int close(@Param("id") long id,@Param("audit") String audit,@Param("at") LocalDateTime at);
/** 旧执行线程不能用失败结果覆盖已恢复或已完成终态。 */
@Update("UPDATE ll_pda_pallet_operation SET status=#{status},last_error=#{error},updated_at=#{at} WHERE id=#{id} AND status NOT IN ('RECOVERED_NO_EFFECT','COMPLETED')")
int fail(@Param("id") long id,@Param("status") String status,@Param("error") String error,@Param("at") LocalDateTime at);
}
@@ -53,11 +53,15 @@ public interface PdaPalletOperationMapper extends BaseMapper<PdaPalletOperation>
@Options(useCache=false, flushCache=Options.FlushCachePolicy.TRUE)
List<MutationPallet> mutationPallets(@Param("warehouseId") String warehouseId, @Param("applicationNos") List<String> applicationNos);
/** 收齐原入仓、退回实收、计划及原生退货业务订单,不使用MIN或其他客户代表行。 */
/** 收齐真实尾程订单;入仓快照ID经同客户来源分片解析,缺失关联保留空值以拒绝改绑。 */
@Select("<script>SELECT a.customer_id AS customerId,a.lastleg_order_id AS orderId FROM ll_relabel_application a WHERE a.relabel_no IN " + MUTATION_APPS
+ " UNION SELECT i.customer_id,i.source_inbound_order_id FROM ll_relabel_item i JOIN ll_relabel_application a ON a.id=i.application_id AND a.customer_id=i.customer_id "
+ " UNION SELECT i.customer_id,original.id FROM ll_relabel_item i JOIN ll_relabel_application a ON a.id=i.application_id AND a.customer_id=i.customer_id "
+ "LEFT JOIN ll_inbound_order inbound ON inbound.id=i.source_inbound_order_id AND inbound.customer_id=i.customer_id "
+ "LEFT JOIN ll_order original ON original.customer_id=inbound.customer_id AND original.source_inbound_id=inbound.source_inbound_id "
+ "WHERE a.relabel_no IN " + MUTATION_APPS + " AND i.return_carton_id IS NULL"
+ " UNION SELECT p.customer_id,b.inbound_order_id FROM ll_inventory_position p JOIN ll_inventory_balance b ON b.id=p.balance_id AND b.customer_id=p.customer_id "
+ " UNION SELECT p.customer_id,original.id FROM ll_inventory_position p JOIN ll_inventory_balance b ON b.id=p.balance_id AND b.customer_id=p.customer_id "
+ "LEFT JOIN ll_inbound_order inbound ON inbound.id=b.inbound_order_id AND inbound.customer_id=b.customer_id "
+ "LEFT JOIN ll_order original ON original.customer_id=inbound.customer_id AND original.source_inbound_id=inbound.source_inbound_id "
+ "WHERE p.overseas_warehouse_id=#{warehouseId} AND p.pallet_id IN " + MUTATION_IDS
+ " UNION SELECT r.customer_id,r.order_id FROM ll_inbound_stock_receipt r JOIN ll_inventory_position p ON p.id=r.inventory_position_id AND p.customer_id=r.customer_id "
+ "WHERE p.overseas_warehouse_id=#{warehouseId} AND r.warehouse_pallet_id IN " + MUTATION_IDS
@@ -0,0 +1,24 @@
package com.baiyue.lastleg.palletops.repository;
import com.baiyue.lastleg.palletops.mapper.PalletOperationRecoveryMapper;
import com.baiyue.lastleg.palletops.entity.PdaPalletOperation;
import org.springframework.stereotype.Repository;
import java.time.LocalDateTime;
/** 只封装本域作业记录的读取、串行锁和条件写入。 */
@Repository
public class PalletOperationRecoveryRepository {
private final PalletOperationRecoveryMapper mapper;
/** 注入本域作业条件写入映射。 */
public PalletOperationRecoveryRepository(PalletOperationRecoveryMapper mapper){this.mapper=mapper;}
/** 读取原作业。 */
public PdaPalletOperation find(long id){return mapper.find(id);}
/** 为恢复审批锁定原记录。 */
public PdaPalletOperation lock(long id){return mapper.lock(id);}
/** 条件持久化远端意图。 */
public boolean journal(long id,String json,LocalDateTime at){return mapper.journal(id,json,at)==1;}
/** 条件保存恢复终态和审计。 */
public boolean close(long id,String audit,LocalDateTime at){return mapper.close(id,audit,at)==1;}
/** 失败写入同样保护已恢复终态。 */
public boolean fail(long id,String status,String error,LocalDateTime at){return mapper.fail(id,status,error,at)==1;}
}
@@ -0,0 +1,58 @@
package com.baiyue.lastleg.palletops.service;
import com.baiyue.lastleg.palletops.repository.PalletOperationRecoveryRepository;
import com.baiyue.lastleg.palletops.entity.PdaPalletOperation;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
import jakarta.validation.constraints.*;
import java.time.LocalDateTime;
/** 只关闭已超时且从未发出远端请求的换标组托,不把未知远端结果推定为无效果。 */
@Service
public class PalletOperationRecoveryService {
private final PalletOperationRecoveryRepository repository;
private final ObjectMapper json;
/** 注入本域作业仓储和统一序列化器。 */
public PalletOperationRecoveryService(PalletOperationRecoveryRepository repository,ObjectMapper json){this.repository=repository;this.json=json;}
public record Close(@Positive long warehouseId,@NotNull LocalDateTime expectedUpdatedAt,
@NotBlank @Size(max=255) String idempotencyKey,@NotBlank @Size(max=1000) String reason){}
public record Recovery(String operationId,String status,String recoveryKey,String operatorId,String reason,
String previousStatus,String previousError,LocalDateTime closedAt,boolean replayed){}
public record State(String operationId,String status,String operatorKey,long warehouseId,String operationType,
String requestHash,String remoteTransitionsJson,String lastError,LocalDateTime updatedAt){}
/** 管理员只读核对原记录和不可变请求哈希,不返回其他账号会话。 */
@Transactional(readOnly=true)
public State inspect(long id){var row=required(repository.find(id));return new State(String.valueOf(id),row.getStatus(),row.getOperatorKey(),row.getOverseasWarehouseId(),row.getOperationType(),row.getRequestHash(),row.getRemoteTransitionsJson(),row.getLastError(),row.getUpdatedAt());}
/** 行锁与远端意图CAS互斥;审计写在原作业结果中,原错误和请求哈希保留。 */
@Transactional
public Recovery close(long id,String operatorId,Close request){
var row=required(repository.lock(id));
if(row.getOverseasWarehouseId()!=request.warehouseId())throw conflict("作业不属于指定仓库");
if("RECOVERED_NO_EFFECT".equals(row.getStatus())){
var existing=read(row.getResultJson());
if(!existing.recoveryKey().equals(request.idempotencyKey())||!existing.reason().equals(request.reason())||!existing.operatorId().equals(operatorId))throw conflict("恢复幂等键或载荷不一致");
return new Recovery(existing.operationId(),existing.status(),existing.recoveryKey(),existing.operatorId(),existing.reason(),existing.previousStatus(),existing.previousError(),existing.closedAt(),true);
}
// 已补偿失败仍须核对没有任何远端意图,不能仅凭补偿状态推断无效果。
if(!"RELABEL_PALLET_DISASSEMBLE".equals(row.getOperationType())||!("PROCESSING".equals(row.getStatus())||"FAILED_COMPENSATED".equals(row.getStatus())))throw conflict("只允许恢复超时的处理中或已补偿失败换标组托");
if(!request.expectedUpdatedAt().equals(row.getUpdatedAt())||row.getUpdatedAt()==null||row.getUpdatedAt().isAfter(LocalDateTime.now().minusMinutes(15)))throw conflict("作业仍活跃或版本已变化,请刷新后核对");
if(row.getResultJson()!=null&&!row.getResultJson().isBlank())throw conflict("作业已有结果,不能关闭为无效果");
try{if(row.getRemoteTransitionsJson()!=null&&!row.getRemoteTransitionsJson().isBlank()){
var attempts=json.readTree(row.getRemoteTransitionsJson());
if(!attempts.isArray()||!attempts.isEmpty())throw conflict("存在远端意图或回执,必须先核实远端效果,不能执行无效果恢复");
}}catch(com.fasterxml.jackson.core.JsonProcessingException e){throw conflict("远端意图记录不可解析,禁止恢复");}
var result=new Recovery(String.valueOf(id),"RECOVERED_NO_EFFECT",request.idempotencyKey(),operatorId,request.reason(),row.getStatus(),row.getLastError(),LocalDateTime.now(),false);
try{if(!repository.close(id,json.writeValueAsString(result),result.closedAt()))throw conflict("作业状态已变化,恢复未写入");}
catch(com.fasterxml.jackson.core.JsonProcessingException e){throw new IllegalStateException("恢复审计序列化失败",e);}
return result;
}
/** 重放只读取已持久化的恢复审计。 */
private Recovery read(String value){try{return json.readValue(value,Recovery.class);}catch(Exception e){throw conflict("恢复审计不可读取");}}
/** 原记录不存在时明确拒绝,不新建作业。 */
private PdaPalletOperation required(PdaPalletOperation row){if(row==null)throw new ResponseStatusException(HttpStatus.NOT_FOUND,"托盘作业不存在");return row;}
/** 统一表达恢复条件或幂等载荷冲突。 */
private ResponseStatusException conflict(String message){return new ResponseStatusException(HttpStatus.CONFLICT,message);}
}
@@ -54,6 +54,7 @@ import java.util.HexFormat;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -63,6 +64,7 @@ import java.util.stream.Collectors;
public class PdaPalletOperationService {
@Resource private PdaPalletOperationMapper mapper;
@Resource private PdaPalletOperationRepository mutationRepository;
@Resource private com.baiyue.lastleg.palletops.repository.PalletOperationRecoveryRepository recoveryRepository;
@Resource private PhysicalPalletSerialPort physicalPalletSerial;
private Clock mutationClock = Clock.systemUTC();
@Resource private com.baiyue.lastleg.inventory.command.mapper.InventoryCommandMapper inventoryCommands;
@@ -257,7 +259,10 @@ public class PdaPalletOperationService {
List<RelabelItem> selected = relabelItems.selectList(new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<RelabelItem>()
.eq("application_id", application.getId()).eq("customer_id", application.getCustomerId())
.in("carton_mark", marks));
if (selected.size() != marks.size()
// 同一退货实物来源允许多个SKU按件任务;普通箱任务仍必须一箱一项。
boolean bulkSkuSource = selected.stream().allMatch(item -> item.getReturnCartonId() != null
&& "RETURN_BULK_SKU_LABEL".equals(item.getOperationType()));
if ((!bulkSkuSource && selected.size() != marks.size())
|| selected.stream().map(RelabelItem::getCartonMark).distinct().count() != marks.size()) {
throw conflict("提交的箱唛不属于当前换标单");
}
@@ -417,8 +422,10 @@ public class PdaPalletOperationService {
// 先取得共同串行锁再触碰远端;本地失败补偿也必须在该锁释放前结束。
try {
applyPhysical(operation,identity.overseasWarehouseId(),target,"OCCUPIED",target.locationId(),key,"退货换标组托",journal);
Set<Long> movedCartons = new HashSet<>();
for (int index = 0; index < cartons.size(); index++) {
RelabelItem item = selected.get(index);
if (!movedCartons.add(item.getReturnCartonId())) continue;
ReturnInventoryCarton carton = returnCartons.lockId(item.getReturnCartonId());
if (carton == null || !Objects.equals(carton.getCustomerId(), application.getCustomerId())
|| (unboundSource ? (org.springframework.util.StringUtils.hasText(carton.getPalletCode()) && !"UNBOUND".equalsIgnoreCase(carton.getPalletCode()))
@@ -426,8 +433,18 @@ public class PdaPalletOperationService {
|| !Objects.equals(carton.getRelabelApplicationId(), application.getId())
|| !"RELABEL_PENDING".equals(carton.getStatus()))
throw conflict("退货换标来源库存已变化,请刷新后重试");
var sameSource = selected.stream().filter(line -> Objects.equals(line.getReturnCartonId(), carton.getId())).toList();
long move = "RETURN_BULK_SKU_LABEL".equals(item.getOperationType())
? value(item.getNotifiedPackageCount()) : value(carton.getTotalQuantity());
? sameSource.stream().mapToLong(line -> value(line.getNotifiedPackageCount())).sum() : value(carton.getTotalQuantity());
if (sameSource.size() > 1) {
// 同一实物的多SKU整批只移动一次;部分混源必须先拆成独立实物,不能逐SKU虚构新箱。
var requestedSkus = new HashMap<String, Long>();
sameSource.forEach(line -> requestedSkus.merge(line.getSkuCode().toUpperCase(Locale.ROOT), (long) value(line.getNotifiedPackageCount()), Long::sum));
var actualSkus = new HashMap<String, Long>();
returnCartonItems.lockCarton(carton.getId()).forEach(line -> actualSkus.merge(line.getSkuCode().toUpperCase(Locale.ROOT), value(line.getQuantity()), Long::sum));
if (move != value(carton.getTotalQuantity()) || !requestedSkus.equals(actualSkus))
throw conflict("多SKU来源须整批完成并核平;部分贴标请先分拣为独立实物");
}
if (move <= 0 || move > value(carton.getTotalQuantity())) throw conflict("来源托盘可拆数量不足");
if (move < value(carton.getTotalQuantity())) {
splitReturnRelabelCarton(application, item, carton, target, move);
@@ -439,7 +456,7 @@ public class PdaPalletOperationService {
returnCartons.updateById(carton);
}
}
recordReturnRelabelBinding(identity, application, selected, target.palletCode());
recordReturnRelabelBinding(identity, application, selected, source == null ? "" : source.palletCode(), target.palletCode());
List<PalletOperationResponses.PalletContent> contents = source == null
? List.of(content(identity.overseasWarehouseId(), physical.resolve(target.palletCode())))
: List.of(content(identity.overseasWarehouseId(), physical.resolve(source.palletCode())),
@@ -972,6 +989,7 @@ public class PdaPalletOperationService {
return marks;
}
/** 记录经过实物来源校验的逐任务绑定,避免多来源数组失去箱与托盘的精确关系。 */
private void recordRelabelBinding(PdaWarehouseIdentity identity, RelabelMutation mutation,
Map<Long, InventoryPosition> targets) {
var app = mutation.application();
@@ -987,7 +1005,11 @@ public class PdaPalletOperationService {
mutation.itemsByPosition().values().stream().flatMap(List::stream).toList(),
mutation.itemsByPosition().keySet().stream().map(positions::selectById).filter(Objects::nonNull).findFirst().orElseThrow().getPalletId(),
targets.values().iterator().next().getPalletId(), targets.values().iterator().next().getPalletNo(), mutation.measuredCartons());
record.setDetailJson(write(Map.of("round", Objects.toString(task.getReviewedAt(), "INITIAL"),
var itemBindings = mutation.itemsByPosition().entrySet().stream().flatMap(entry -> entry.getValue().stream().map(item ->
Map.of("itemId", String.valueOf(item.getId()), "sourceKnown", true,
"sourcePalletCode", Objects.toString(positions.selectById(entry.getKey()).getPalletNo(), ""),
"targetPalletCode", targets.get(entry.getKey()).getPalletNo()))).toList();
record.setDetailJson(write(Map.of("round", Objects.toString(task.getReviewedAt(), "INITIAL"), "itemBindings", itemBindings,
"measuredCartons", measured,
"cartonMarks", mutation.itemsByPosition().values().stream().flatMap(List::stream).map(RelabelItem::getCartonMark).toList(),
"targetPallets", targets.values().stream().map(InventoryPosition::getPalletNo).distinct().toList(),
@@ -996,8 +1018,9 @@ public class PdaPalletOperationService {
relabelWorkHistory.insert(record);
}
/** 来源实托在变更前已经核对,历史只记录该次校验值,不反查变更后的库存托盘。 */
private void recordReturnRelabelBinding(PdaWarehouseIdentity identity, RelabelApplication app,
List<RelabelItem> items, String targetPallet) {
List<RelabelItem> items, String sourcePallet, String targetPallet) {
var task = relabelWorkTasks.find(app.getCustomerId(), app.getId());
if (task == null) throw conflict("退货换标作业任务不存在,不能记录组托");
var record = new com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory();
@@ -1007,6 +1030,8 @@ public class PdaPalletOperationService {
record.setOperatorKey(identity.operatorKey()); record.setOperatorName(identity.operatorName());
record.setCreatedAt(LocalDateTime.now());
record.setDetailJson(write(Map.of("round", Objects.toString(task.getReviewedAt(), "INITIAL"),
"itemBindings", items.stream().map(item -> Map.of("itemId", String.valueOf(item.getId()), "sourceKnown", true,
"sourcePalletCode", sourcePallet, "targetPalletCode", targetPallet)).toList(),
"cartonMarks", items.stream().map(RelabelItem::getCartonMark).toList(),
"targetPallets", List.of(targetPallet))));
relabelWorkHistory.insert(record);
@@ -1200,17 +1225,18 @@ public class PdaPalletOperationService {
newTransaction.executeWithoutResult(status -> {
PdaPalletOperation operation = mapper.selectById(operationId);
if (operation == null) throw new IllegalStateException("实托作业意图记录不存在,不能发出远端请求");
operation.setRemoteTransitionsJson(write(attempts)); operation.setUpdatedAt(LocalDateTime.now());
mapper.updateById(operation);
if (!recoveryRepository.journal(operationId, write(attempts), LocalDateTime.now()))
throw conflict("作业已由管理员恢复关闭,禁止继续发出远端请求");
});
}
/** 条件记录失败,避免旧线程覆盖管理员已恢复的原记录。 */
private void fail(long operationId, RuntimeException failure, boolean compensated) {
newTransaction.executeWithoutResult(status -> {
PdaPalletOperation operation = mapper.selectById(operationId);
if (operation == null || "COMPLETED".equals(operation.getStatus())) return;
if (operation == null || "COMPLETED".equals(operation.getStatus()) || "RECOVERED_NO_EFFECT".equals(operation.getStatus())) return;
operation.setStatus(compensated ? "FAILED_COMPENSATED" : "COMPENSATION_REQUIRED");
operation.setLastError(limit(failure.getMessage(), 2000)); operation.setUpdatedAt(LocalDateTime.now());
mapper.updateById(operation);
recoveryRepository.fail(operationId, operation.getStatus(), operation.getLastError(), operation.getUpdatedAt());
});
}
private boolean compensate(long warehouseId, List<PalletPhysicalGateway.Transition> transitions) {
@@ -0,0 +1,52 @@
package com.baiyue.lastleg.query;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import com.baiyue.lastleg.dto.LastlegOrderRequests;
import com.baiyue.lastleg.mapper.LastlegOrderMapper;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.http.HttpStatus;
/** 列表与退货全筛选统计共用筛选,避免分页和汇总的客户、状态或时间边界漂移。 */
public final class LastlegOrderFilter {
/** 纯筛选工具不允许实例化。 */
private LastlegOrderFilter() { }
/** 只生成参数绑定的筛选,不读取数据库,不包含分页和排序。 */
public static LambdaQueryWrapper<LastlegOrder> create(String customerId, LastlegOrderRequests.Query query, String relabelNo) {
if (query.createdFrom() != null && query.createdTo() != null && query.createdFrom().isAfter(query.createdTo())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "createdFrom must not be after createdTo");
}
String currentStatus = StringUtils.hasText(query.currentStatus()) ? query.currentStatus() : query.status();
String warehouse = StringUtils.hasText(query.warehouse()) ? query.warehouse().trim() : null;
return new LambdaQueryWrapper<LastlegOrder>()
.ne(LastlegOrder::getOrderType, "CARGO_DISCARD")
.eq(StringUtils.hasText(customerId), LastlegOrder::getCustomerId, customerId)
.and(StringUtils.hasText(query.orderNo()), nested -> nested
.like(LastlegOrder::getOrderNo, query.orderNo())
.or()
.like(LastlegOrder::getSourceOrderNo, query.orderNo()))
.and(StringUtils.hasText(relabelNo), nested -> nested
.like(LastlegOrder::getRelabelOrderNo, relabelNo)
.or().apply("EXISTS (SELECT 1 FROM ll_relabel_application r WHERE r.lastleg_order_id=ll_order.id " +
"AND r.customer_id=ll_order.customer_id AND r.relabel_no LIKE CONCAT('%',{0},'%'))", relabelNo))
.eq(StringUtils.hasText(query.orderType()), LastlegOrder::getOrderType, query.orderType())
.apply(StringUtils.hasText(query.businessType()), LastlegOrderMapper.BUSINESS_TYPE_FILTER_SQL, query.businessType())
.apply(StringUtils.hasText(query.businessOrderNo()), LastlegOrderMapper.BUSINESS_ORDER_NO_FILTER_SQL, query.businessOrderNo())
.apply(StringUtils.hasText(query.externalBookingNo()), LastlegOrderMapper.EXTERNAL_BOOKING_NO_SQL + " LIKE CONCAT('%',{0},'%')", query.externalBookingNo())
.apply(query.sailingStage() != null, LastlegOrderMapper.SAILING_STAGE_FILTER_SQL,
query.sailingStage() == LastlegOrderRequests.SailingStage.AFTER_DEPARTURE ? 1 : 0)
.like(StringUtils.hasText(query.inboundCode()), LastlegOrder::getInboundCode, query.inboundCode())
.like(StringUtils.hasText(query.lxCode()), LastlegOrder::getLxCode, query.lxCode())
.like(StringUtils.hasText(query.sourceOrderNo()), LastlegOrder::getSourceOrderNo, query.sourceOrderNo())
.like(StringUtils.hasText(query.containerNo()), LastlegOrder::getContainerNo, query.containerNo())
.eq(StringUtils.hasText(currentStatus), LastlegOrder::getCurrentStatus, currentStatus)
.apply(StringUtils.hasText(warehouse), LastlegOrderMapper.WAREHOUSE_FILTER_SQL, warehouse)
.eq(StringUtils.hasText(query.transferWarehouseCode()), LastlegOrder::getTransferWarehouseCode,
query.transferWarehouseCode())
.eq(query.abnormal() != null, LastlegOrder::getAbnormal, query.abnormal())
.eq(query.detained() != null, LastlegOrder::getDetained, query.detained())
.ge(query.createdFrom() != null, LastlegOrder::getCreatedAt, query.createdFrom())
.le(query.createdTo() != null, LastlegOrder::getCreatedAt, query.createdTo());
}
}
@@ -37,6 +37,16 @@ public class RelabelApplicationController {
}
@Resource private com.baiyue.lastleg.relabel.pda.service.PdaRelabelService pdaService;
/** 平台代客创建时仍按显式客户和公共作业仓返回正式库存候选。 */
@GetMapping("/inventory-candidates")
@PreAuthorize("hasAuthority('" + OverseasPermissions.RELABEL_ORDER_CREATE + "')")
public ApiResponse<java.util.List<RelabelResponses.InventoryCandidate>> candidates(
@AuthenticationPrincipal AuthenticatedUser user, @RequestParam String customerId,
@RequestParam String operationWarehouseId, @RequestParam(required = false) String inboundCode) {
requirePlatform(user);
return ApiResponse.success(service.candidates(requiredCustomer(customerId), operationWarehouseId, inboundCode));
}
@PostMapping("/{relabelNo}/rework")
@PreAuthorize("hasAuthority('" + OverseasPermissions.RELABEL_ORDER_STATUS + "')")
public ApiResponse<com.baiyue.lastleg.relabel.pda.dto.PdaRelabelResponses.Detail> rework(
@@ -98,6 +98,7 @@ public class PdaRelabelService {
@Resource private PdaRelabelOperationMapper operations;
@Resource private PdaRelabelHistoryMapper histories;
@Resource private RelabelApplicationService applicationService;
@Resource private com.baiyue.lastleg.relabel.repository.RelabelQuantityRepository quantityRepository;
@Resource private RelabelPhotoFileGateway photoFiles;
@Resource private ObjectMapper sourceObjectMapper;
@Resource private com.baiyue.lastleg.mapper.LastlegOrderMapper tailOrders;
@@ -143,6 +144,7 @@ public class PdaRelabelService {
return detail(application, tasks.find(application.getCustomerId(), application.getId()));
}
/** 认领当前仓作业,并在首次实物移动前保存退货来源的不可变快照。 */
@Transactional
public PdaRelabelResponses.Detail claim(String operatorKey, String operatorName, long overseasWarehouseId,
String relabelNo, PdaRelabelRequests.Claim request) {
@@ -191,6 +193,8 @@ public class PdaRelabelService {
}
insertHistory(task, "CLAIM", null, PROCESSING, operatorKey, operatorName,
Map.of("relabelNo", relabelNo));
insertHistory(task, "SOURCE_SNAPSHOT", PROCESSING, PROCESSING, operatorKey, operatorName,
quantityRepository.sourceSnapshot(application));
}
PdaRelabelResponses.Detail result = detail(application, task);
saveOperation(task, operatorKey, "CLAIM", request.idempotencyKey(), command, result);
@@ -444,6 +448,7 @@ public class PdaRelabelService {
return photoFiles.download(application.getCustomerId(), task.getId(), fileId);
}
/** 先核对作业数量,失败不得触发组托或实测的下游校验与写入。 */
@Transactional
public PdaRelabelResponses.Detail complete(String operatorKey, String operatorName, long overseasWarehouseId,
String relabelNo, PdaRelabelRequests.Complete request) {
@@ -454,14 +459,14 @@ public class PdaRelabelService {
RelabelApplication application = requireApplication(relabelNo, overseasWarehouseId, true);
PdaRelabelTask task = requireOwnedTask(application, operatorKey, true);
requireVersion(task, request.expectedVersion());
if (!request.manualCompletion()) bindingGuard.requireBound(application);
palletMeasurements.requireMeasured(application);
List<RelabelItem> detailItems = itemList(application);
List<PdaRelabelUnitFact> facts = factList(task);
boolean incomplete = detailItems.stream().anyMatch(item -> processedQuantity(facts, item.getId()) < value(item.getNotifiedPackageCount()));
if ((incomplete || request.manualCompletion()) && !StringUtils.hasText(request.remark()))
throw conflict("手动完成必须填写仓库异常作业备注");
if (incomplete && !request.manualCompletion()) throw conflict("仍有未处理箱,请选择手动完成并填写作业备注");
if (!request.manualCompletion()) bindingGuard.requireBound(application);
palletMeasurements.requireMeasured(application);
if (request.photoFileIds() == null || request.photoFileIds().isEmpty() || request.photoFileIds().size() > 20) throw conflict("完成换标必须上传 1 至 20 张作业照片");
if (request.manualCompletion() && request.remark().trim().length() > 900) throw conflict("手动作业备注不能超过 900 字");
for (RelabelItem item : detailItems) {
@@ -68,7 +68,9 @@ public class RelabelDispatchSourceRepository {
if (position == null) position = mapper.position(item.getSourceInventoryPositionId());
if (position == null) continue;
positions.put(position.getId(), position);
// 无效身份只作为本申请缺失组成保留,不能把其他未绑定位置误连为同一实托。
if (warehouseId.equals(position.getOverseasWarehouseId()) && position.getPalletId() != null
&& position.getPalletId() > 0
&& !visitedPallets.contains(position.getPalletId())) pending.add(position.getPalletId());
}
}
@@ -16,6 +16,8 @@ import java.util.List;
public class RelabelQuantityRepository {
@Resource private RelabelApplicationMapper applications;
@Resource private RelabelItemMapper items;
@Resource private com.baiyue.lastleg.relabel.pda.mapper.PdaRelabelHistoryMapper histories;
@Resource private com.baiyue.lastleg.returnreceipt.mapper.ReturnInventoryCartonMapper returnCartons;
/** 读取全部筛选结果,不附加当前页限制。 */
public List<RelabelApplication> filtered(String customerId, RelabelRequests.Query query) {
@@ -28,4 +30,33 @@ public class RelabelQuantityRepository {
.eq(RelabelItem::getApplicationId, application.getId())
.eq(RelabelItem::getCustomerId, application.getCustomerId()));
}
/** 只读取同客户同申请的事实历史,按稳定顺序重建首个来源和本轮最终目标。 */
public List<com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory> history(RelabelApplication application) {
return histories.selectList(new LambdaQueryWrapper<com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory>()
.eq(com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory::getApplicationId, application.getId())
.eq(com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory::getCustomerId, application.getCustomerId())
.orderByAsc(com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory::getCreatedAt)
.orderByAsc(com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory::getId));
}
/** 认领前按精确退货库存主键校验客户、仓库及占用归属,保存实物来源事实。 */
public java.util.Map<String, Object> sourceSnapshot(RelabelApplication application) {
var bindings = new java.util.ArrayList<java.util.Map<String, Object>>();
for (var item : items(application)) {
if (item.getReturnCartonId() == null) continue;
var carton = returnCartons.selectById(item.getReturnCartonId());
if (carton == null || !java.util.Objects.equals(carton.getCustomerId(), application.getCustomerId())
|| !java.util.Objects.equals(carton.getOverseasWarehouseId(), application.getOverseasWarehouseId())
|| !java.util.Objects.equals(carton.getRelabelApplicationId(), application.getId())
|| !"RELABEL_PENDING".equals(carton.getStatus()) || !"CONFIRMED".equals(carton.getCountStatus())) continue;
var row = new java.util.LinkedHashMap<String, Object>();
row.put("itemId", String.valueOf(item.getId())); row.put("sourceUnitId", String.valueOf(carton.getId()));
row.put("sourceUnitType", java.util.Objects.toString(carton.getSourceUnitType(), "UNKNOWN"));
// 无托盘仅在权威记录明确为空或UNBOUND时计零;不是用箱唛推断托盘。
row.put("sourceKnown", true); row.put("sourcePalletCode", java.util.Objects.toString(carton.getPalletCode(), ""));
bindings.add(row);
}
return java.util.Map.of("schemaVersion", 1, "basis", "CONFIRMED_RETURN_INVENTORY_AT_FIRST_CLAIM", "itemBindings", bindings);
}
}
@@ -149,8 +149,9 @@ public class RelabelDispatchSourceService implements RelabelDispatchSourcePort {
long notified = number(item.getNotifiedPackageCount());
if (!Objects.equals(item.getCustomerId(), app.getCustomerId()) || position == null
|| !Objects.equals(position.getCustomerId(), app.getCustomerId())
|| !Objects.equals(warehouseId, position.getOverseasWarehouseId()) || position.getPalletId() == null) {
reasons.add(app.getRelabelNo() + ":明细当前位置缺失或客户、仓库归属不一致");
|| !Objects.equals(warehouseId, position.getOverseasWarehouseId()) || position.getPalletId() == null
|| position.getPalletId() <= 0) {
reasons.add(app.getRelabelNo() + ":明细当前位置缺失、实托身份无效或客户、仓库归属不一致");
bound = false;
}
if (item.getReturnCartonId() != null || "RETURN_BULK_SKU_LABEL".equals(item.getOperationType())) {
@@ -0,0 +1,65 @@
package com.baiyue.lastleg.relabel.service;
import com.baiyue.lastleg.relabel.entity.RelabelItem;
import com.baiyue.lastleg.relabel.pda.entity.PdaRelabelHistory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
/** 只从不可变事实重建原托及本轮目标,不读取已移动的当前库存位置。 */
public final class RelabelPalletDimensions {
/** 纯事实投影工具不允许实例化。 */
private RelabelPalletDimensions() { }
public record Result(Set<String> sources, Set<String> targets, Long cartons, Map<String, Long> sourceUnits) { }
/** 首次来源跨返工保留;返工后清空目标,随后每个任务仅采用最新绑定。 */
public static Result measure(List<RelabelItem> items, List<PdaRelabelHistory> history, ObjectMapper mapper) {
Map<String, String> sources = new HashMap<>(), targets = new HashMap<>();
Map<String, String> unitIds = new HashMap<>(), unitTypes = new HashMap<>();
Set<String> expected = new HashSet<>();
items.forEach(item -> expected.add(String.valueOf(item.getId())));
for (var event : history) {
if ("REWORK_ARCHIVE".equals(event.getAction())) { targets.clear(); continue; }
if (!Set.of("SOURCE_SNAPSHOT", "PALLET_BIND").contains(event.getAction())) continue;
try {
JsonNode detail = mapper.readTree(event.getDetailJson());
for (var binding : detail.path("itemBindings")) {
String id = binding.path("itemId").asText();
if (!expected.contains(id)) continue;
if (binding.path("sourceKnown").asBoolean(false)) sources.putIfAbsent(id, binding.path("sourcePalletCode").asText(""));
if ("PALLET_BIND".equals(event.getAction()) && binding.hasNonNull("targetPalletCode")) targets.put(id, binding.path("targetPalletCode").asText());
if ("SOURCE_SNAPSHOT".equals(event.getAction()) && binding.hasNonNull("sourceUnitId")) {
unitIds.putIfAbsent(id, binding.path("sourceUnitId").asText());
unitTypes.putIfAbsent(id, binding.path("sourceUnitType").asText());
}
}
// 旧历史只有单一来源和目标时才能确定箱任务关联;多来源数组及散货标识不作猜测。
if (!detail.has("itemBindings") && "PALLET_BIND".equals(event.getAction())) {
var marks = new HashSet<String>(); detail.path("cartonMarks").forEach(mark -> marks.add(mark.asText()));
for (var item : items) {
if ("RETURN_BULK_SKU_LABEL".equals(item.getOperationType()) || !marks.contains(item.getCartonMark())) continue;
String id = String.valueOf(item.getId());
if (detail.path("sourcePallets").size() == 1) sources.putIfAbsent(id, detail.path("sourcePallets").get(0).asText());
if (detail.path("targetPallets").size() == 1) targets.put(id, detail.path("targetPallets").get(0).asText());
}
}
} catch (Exception ignored) { /* 历史缺失或损坏只影响可知维度,不能从当前位置补推。 */ }
}
Long cartons = null;
Map<String, Long> units = null;
if (!items.isEmpty() && unitIds.keySet().containsAll(expected)) {
var grouped = new HashMap<String, Set<String>>();
expected.forEach(id -> grouped.computeIfAbsent(unitTypes.get(id), ignored -> new HashSet<>()).add(unitIds.get(id)));
units = new TreeMap<>();
for (var entry : grouped.entrySet()) units.put(entry.getKey(), (long) entry.getValue().size());
if (grouped.keySet().equals(Set.of("BOX"))) cartons = (long) grouped.get("BOX").size();
}
return new Result(complete(sources, expected), complete(targets, expected), cartons, units);
}
/** 明确无托盘的实物来源可计零;缺少任一任务的快照则整单维度未知。 */
private static Set<String> complete(Map<String, String> values, Set<String> expected) {
if (expected.isEmpty() || !values.keySet().containsAll(expected)) return null;
var result = new HashSet<>(values.values()); result.remove(""); result.remove("UNBOUND"); return result;
}
}
@@ -15,10 +15,12 @@ public class RelabelQuantityService {
@Resource private RelabelQuantityRepository repository;
@Resource private ObjectMapper objectMapper;
public record Quantity(Long labelPieceCount, Long cartonCount, int skuCount, boolean duplicateCarton,
String quantityUnit, Long sourcePalletCount, Long targetPalletCount) { }
String quantityUnit, Long sourcePalletCount, Long targetPalletCount,
Map<String, Long> sourceUnitCounts) { }
public record Totals(long orderCount, long skuCount, long knownLabelPieceCount, long unknownPieceOrders,
long knownCartonCount, long unknownCartonOrders,
Map<String, Quantity> orders) { }
Map<String, Quantity> orders, long knownSourcePalletCount, long unknownSourcePalletOrders,
long knownTargetPalletCount, long unknownTargetPalletOrders) { }
/** 按全部筛选单据聚合;未知件数和箱数保留未知单数,不伪造为零。 */
@Transactional(readOnly = true)
@@ -26,20 +28,32 @@ public class RelabelQuantityService {
var dimensions = new LinkedHashMap<String, Quantity>();
var skus = new HashSet<String>();
long pieces = 0, cartons = 0, unknownPieces = 0, unknownCartons = 0;
long unknownSources = 0, unknownTargets = 0;
var sourcePallets = new HashSet<String>(); var targetPallets = new HashSet<String>();
for (var application : repository.filtered(customerId, query)) {
var detail = repository.items(application);
Quantity quantity = measure(detail);
var pallets = RelabelPalletDimensions.measure(detail, repository.history(application), objectMapper);
quantity = new Quantity(quantity.labelPieceCount(), quantity.cartonCount() == null ? pallets.cartons() : quantity.cartonCount(),
quantity.skuCount(), quantity.duplicateCarton(), quantity.quantityUnit(),
pallets.sources() == null ? null : (long) pallets.sources().size(),
pallets.targets() == null ? null : (long) pallets.targets().size(), pallets.sourceUnits());
if (pallets.sources() == null) unknownSources++;
else for (var code : pallets.sources()) sourcePallets.add(application.getOverseasWarehouseId() + "|" + code);
if (pallets.targets() == null) unknownTargets++;
else for (var code : pallets.targets()) targetPallets.add(application.getOverseasWarehouseId() + "|" + code);
dimensions.put(application.getRelabelNo(), quantity);
detail.forEach(item -> collectSkus(item, skus));
if (quantity.labelPieceCount() == null) unknownPieces++; else pieces = Math.addExact(pieces, quantity.labelPieceCount());
if (quantity.cartonCount() == null) unknownCartons++; else cartons = Math.addExact(cartons, quantity.cartonCount());
}
return new Totals(dimensions.size(), skus.size(), pieces, unknownPieces, cartons, unknownCartons, dimensions);
return new Totals(dimensions.size(), skus.size(), pieces, unknownPieces, cartons, unknownCartons, dimensions,
sourcePallets.size(), unknownSources, targetPallets.size(), unknownTargets);
}
/** 箱级任务按箱唛去重;历史重复关联不重复增加件数并显式告警。 */
public Quantity measure(List<RelabelItem> items) {
if (items.isEmpty()) return new Quantity(null, null, 0, false, "UNKNOWN", null, null);
if (items.isEmpty()) return new Quantity(null, null, 0, false, "UNKNOWN", null, null, null);
long pieces = 0;
boolean unknownPieces = false, bulk = false, duplicate = false, missingCarton = false;
var cartons = new HashSet<String>();
@@ -72,7 +86,7 @@ public class RelabelQuantityService {
}
// 按件退货来源可能是托盘或包裹标识,不能将标识数冒充真实箱数。
return new Quantity(unknownPieces || duplicate ? null : pieces, bulk || missingCarton ? null : (long) cartons.size(),
skus.size(), duplicate, bulk ? "PIECE" : "CARTON", null, null);
skus.size(), duplicate, bulk ? "PIECE" : "CARTON", null, null, null);
}
/** SKU种数来自子项;旧快照无子项时才采用旧SKU汇总字段。 */
@@ -21,6 +21,13 @@ import org.springframework.web.server.ResponseStatusException;
@RequestMapping("/api/merchant/v1/last-leg/return-orders")
public class MerchantReturnOrderController {
@Resource private ReturnReceiptService service;
@Resource private com.baiyue.lastleg.returnreceipt.service.ReturnOrderStatisticsService statistics;
/** 全筛选权威汇总,客户身份及权限与列表保持一致。 */
@GetMapping("/statistics") @PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_RETURN_ORDER_LIST + "')")
public ApiResponse<com.baiyue.lastleg.returnreceipt.dto.ReturnOrderStatistics> statistics(
@AuthenticationPrincipal AuthenticatedUser user, @Valid ReturnOrderRequests.Query query) {
return ApiResponse.success(statistics.merchant(customer(user),query));
}
@PostMapping @PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_RETURN_ORDER_CREATE + "')")
public ApiResponse<ReturnOrderResponses.Detail> create(@AuthenticationPrincipal AuthenticatedUser user,
@Valid @RequestBody ReturnOrderRequests.Create request) { return ApiResponse.success(service.create(customer(user), operator(user), request)); }
@@ -0,0 +1,23 @@
package com.baiyue.lastleg.returnreceipt.controller;
import com.baiyue.common.core.api.ApiResponse;
import com.baiyue.lastleg.returnreceipt.dto.ReturnOrderStatistics;
import com.baiyue.lastleg.returnreceipt.service.ReturnOrderStatisticsService;
import com.baiyue.lastleg.dto.LastlegOrderRequests;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import jakarta.validation.Valid;
/** 退货专属统计沿用尾程订单列表权限与全部筛选条件。 */
@RestController
@RequestMapping("/api/platform/v1/last-leg/return-orders/statistics")
@PreAuthorize("hasAuthority('platform:overseas-warehouse:last-mile-order:list')")
public class PlatformReturnOrderStatisticsController {
private final ReturnOrderStatisticsService service;
/** 注入只读统计服务。 */
public PlatformReturnOrderStatisticsController(ReturnOrderStatisticsService service) { this.service=service; }
/** 接受与尾程列表相同筛选。 */
@GetMapping
public ApiResponse<ReturnOrderStatistics> statistics(@Valid LastlegOrderRequests.Query query,
@RequestParam(required=false) String relabelNo) { return ApiResponse.success(service.platform(query,relabelNo)); }
}
@@ -0,0 +1,13 @@
package com.baiyue.lastleg.returnreceipt.dto;
import java.util.List;
/** 件数与签收载体分别统计;未知的预报箱托数不从件数推算。 */
public record ReturnOrderStatistics(Totals totals, List<Dimensions> pageDimensions) {
public record Totals(long orderCount, long skuTypes, long expectedQuantity, long receivedQuantity,
long remainingQuantity, long receivedBoxCount, long receivedParcelCount,
long receivedPalletCount) { }
public record Dimensions(String returnNo, String lastlegOrderId, long expectedQuantity,
long receivedQuantity, long remainingQuantity, long receivedBoxCount,
long receivedParcelCount, long receivedPalletCount) { }
}
@@ -0,0 +1,43 @@
package com.baiyue.lastleg.returnreceipt.mapper;
import com.baiyue.lastleg.returnreceipt.dto.ReturnOrderStatistics;
import org.apache.ibatis.annotations.*;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import java.util.List;
/** 全筛选先固定订单集合,子项分别聚合,禁止多表连接放大件数。 */
@Mapper
public interface ReturnOrderStatisticsMapper {
String MERCHANT_FILTER = " WHERE ro.customer_id=#{customerId} "
+ "<if test='q.returnNo != null and q.returnNo.trim() != &quot;&quot;'>AND ro.return_no LIKE CONCAT('%',TRIM(#{q.returnNo}),'%')</if>"
+ "<if test='q.status != null and q.status.trim() != &quot;&quot;'>AND ro.status=UPPER(TRIM(#{q.status}))</if>"
+ "<if test='q.skuCode != null and q.skuCode.trim() != &quot;&quot;'>AND EXISTS(SELECT 1 FROM ll_return_order_item i WHERE i.return_order_id=ro.id AND i.customer_id=ro.customer_id AND i.sku_code LIKE CONCAT('%',TRIM(#{q.skuCode}),'%'))</if>"
+ "<if test='q.trackingNo != null and q.trackingNo.trim() != &quot;&quot;'>AND EXISTS(SELECT 1 FROM ll_return_receipt r WHERE r.return_order_id=ro.id AND r.customer_id=ro.customer_id AND r.tracking_no LIKE CONCAT('%',TRIM(#{q.trackingNo}),'%'))</if>";
String MERCHANT_SET = "WITH selected AS (SELECT ro.* FROM ll_return_order ro " + MERCHANT_FILTER + ") ";
String PLATFORM_SET = "WITH selected AS (SELECT ro.* FROM (SELECT ll_order.* FROM ll_order ${ew.customSqlSegment}) p JOIN ll_return_order ro ON ro.lastleg_order_id=p.id AND ro.customer_id=p.customer_id) ";
String PLATFORM_PAGE_SET = "WITH selected AS (SELECT ro.* FROM (SELECT ll_order.* FROM ll_order ${ew.customSqlSegment} ORDER BY ll_order.created_at DESC,ll_order.id DESC LIMIT #{size} OFFSET #{offset}) p JOIN ll_return_order ro ON ro.lastleg_order_id=p.id AND ro.customer_id=p.customer_id) ";
String RECEIPT_SET = ", units AS (SELECT r.* FROM ll_return_receipt r JOIN selected s ON s.id=r.return_order_id AND s.customer_id=r.customer_id), "
+ "carriers AS (SELECT return_order_id,COALESCE(SUM(CASE WHEN unit_type='PARCEL' THEN 0 ELSE total_box_count END),0) AS boxes,"
+ "COUNT(DISTINCT CASE WHEN unit_type='PARCEL' THEN CONCAT(customer_id,':',COALESCE(NULLIF(unit_code,''),receipt_no)) END) AS parcels,"
+ "COUNT(DISTINCT CASE WHEN unit_type='PALLET' THEN CONCAT(customer_id,':',COALESCE(NULLIF(pallet_code,''),unit_code)) END) AS pallets FROM units GROUP BY return_order_id) ";
String TOTALS = "SELECT COUNT(*) AS orderCount,"
+ "(SELECT COUNT(DISTINCT UPPER(TRIM(i.sku_code))) FROM ll_return_order_item i JOIN selected s ON s.id=i.return_order_id AND s.customer_id=i.customer_id) AS skuTypes,"
+ "COALESCE(SUM(expected_quantity),0) AS expectedQuantity,COALESCE(SUM(received_quantity),0) AS receivedQuantity,"
+ "COALESCE(SUM(GREATEST(expected_quantity-received_quantity,0)),0) AS remainingQuantity,"
+ "COALESCE((SELECT SUM(CASE WHEN unit_type='PARCEL' THEN 0 ELSE total_box_count END) FROM units),0) AS receivedBoxCount,"
+ "(SELECT COUNT(DISTINCT CASE WHEN unit_type='PARCEL' THEN CONCAT(customer_id,':',COALESCE(NULLIF(unit_code,''),receipt_no)) END) FROM units) AS receivedParcelCount,"
+ "(SELECT COUNT(DISTINCT CASE WHEN unit_type='PALLET' THEN CONCAT(customer_id,':',COALESCE(NULLIF(pallet_code,''),unit_code)) END) FROM units) AS receivedPalletCount FROM selected";
String DIMENSIONS = "SELECT s.return_no AS returnNo,CAST(s.lastleg_order_id AS CHAR) AS lastlegOrderId,s.expected_quantity AS expectedQuantity,s.received_quantity AS receivedQuantity,"
+ "GREATEST(s.expected_quantity-s.received_quantity,0) AS remainingQuantity,COALESCE(c.boxes,0) AS receivedBoxCount,COALESCE(c.parcels,0) AS receivedParcelCount,COALESCE(c.pallets,0) AS receivedPalletCount "
+ "FROM selected s LEFT JOIN carriers c ON c.return_order_id=s.id ORDER BY s.created_at DESC,s.id DESC LIMIT #{size} OFFSET #{offset}";
@Select("<script>" + MERCHANT_SET + RECEIPT_SET + TOTALS + "</script>")
ReturnOrderStatistics.Totals merchantTotals(@Param("customerId") String customerId, @Param("q") com.baiyue.lastleg.returnreceipt.dto.ReturnOrderRequests.Query query);
@Select("<script>" + MERCHANT_SET + RECEIPT_SET + DIMENSIONS + "</script>")
List<ReturnOrderStatistics.Dimensions> merchantDimensions(@Param("customerId") String customerId, @Param("q") com.baiyue.lastleg.returnreceipt.dto.ReturnOrderRequests.Query query, @Param("size") long size, @Param("offset") long offset);
@Select("<script>" + PLATFORM_SET + RECEIPT_SET + TOTALS + "</script>")
ReturnOrderStatistics.Totals platformTotals(@Param("ew") Wrapper<LastlegOrder> wrapper);
@Select("<script>" + PLATFORM_PAGE_SET + RECEIPT_SET + "SELECT s.return_no AS returnNo,CAST(s.lastleg_order_id AS CHAR) AS lastlegOrderId,s.expected_quantity AS expectedQuantity,s.received_quantity AS receivedQuantity,GREATEST(s.expected_quantity-s.received_quantity,0) AS remainingQuantity,COALESCE(c.boxes,0) AS receivedBoxCount,COALESCE(c.parcels,0) AS receivedParcelCount,COALESCE(c.pallets,0) AS receivedPalletCount FROM selected s LEFT JOIN carriers c ON c.return_order_id=s.id</script>")
List<ReturnOrderStatistics.Dimensions> platformDimensions(@Param("ew") Wrapper<LastlegOrder> wrapper, @Param("size") long size, @Param("offset") long offset);
}
@@ -0,0 +1,27 @@
package com.baiyue.lastleg.returnreceipt.repository;
import com.baiyue.lastleg.returnreceipt.dto.*;
import com.baiyue.lastleg.returnreceipt.mapper.ReturnOrderStatisticsMapper;
import com.baiyue.lastleg.dto.LastlegOrderRequests;
import com.baiyue.lastleg.query.LastlegOrderFilter;
import com.baiyue.lastleg.entity.LastlegOrder;
import org.springframework.stereotype.Repository;
/** 列表统计只经本域Mapper读取正式订单与签收事实。 */
@Repository
public class ReturnOrderStatisticsRepository {
private final ReturnOrderStatisticsMapper mapper;
/** 注入订单统计映射。 */
public ReturnOrderStatisticsRepository(ReturnOrderStatisticsMapper mapper) { this.mapper=mapper; }
/** 客户范围来自认证身份,分页不进入总计查询。 */
public ReturnOrderStatistics merchant(String customerId, ReturnOrderRequests.Query query) {
return new ReturnOrderStatistics(mapper.merchantTotals(customerId,query),
mapper.merchantDimensions(customerId,query,query.size(),Math.multiplyExact(query.page()-1,query.size())));
}
/** 与平台尾程列表使用同一筛选构造器,只统计其中原生退货单。 */
public ReturnOrderStatistics platform(LastlegOrderRequests.Query query, String relabelNo) {
var filter=LastlegOrderFilter.create(null,query,relabelNo);
return new ReturnOrderStatistics(mapper.platformTotals(filter),
mapper.platformDimensions(filter,query.size(),Math.multiplyExact(query.page()-1,query.size())));
}
}
@@ -0,0 +1,21 @@
package com.baiyue.lastleg.returnreceipt.service;
import com.baiyue.lastleg.returnreceipt.dto.*;
import com.baiyue.lastleg.returnreceipt.repository.ReturnOrderStatisticsRepository;
import com.baiyue.lastleg.dto.LastlegOrderRequests;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/** 汇总和当前页维度在同一只读快照内返回,避免签收并发时前后口径不一致。 */
@Service
public class ReturnOrderStatisticsService {
private final ReturnOrderStatisticsRepository repository;
/** 注入只读统计仓储。 */
public ReturnOrderStatisticsService(ReturnOrderStatisticsRepository repository) { this.repository=repository; }
/** 当前客户的总计与页内维度使用同一只读快照。 */
@Transactional(readOnly=true, isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public ReturnOrderStatistics merchant(String customerId, ReturnOrderRequests.Query query) { return repository.merchant(customerId,query); }
/** 平台筛选范围中的退货总计与混合列表页内维度。 */
@Transactional(readOnly=true, isolation=org.springframework.transaction.annotation.Isolation.REPEATABLE_READ)
public ReturnOrderStatistics platform(LastlegOrderRequests.Query query, String relabelNo) { return repository.platform(query,relabelNo); }
}
@@ -86,6 +86,7 @@ public class LastlegOrderService {
@Resource private WarehouseResourceGateway warehouseResourceGateway;
@Resource private ContainerShippingGateMapper containerShippingGates;
@Resource private ReturnOrderReferenceResolver returnOrderReferences;
@Resource private com.baiyue.lastleg.transfer.service.TransferQuantityService transferQuantities;
public PageResult<LastlegOrderSummary> page(String customerId, LastlegOrderRequests.Query query) {
return page(customerId, query, null);
@@ -102,11 +103,12 @@ public class LastlegOrderService {
Map<Long, LastlegOrderMapper.OrderWeightRow> weights = orderWeights(page.getRecords());
Map<Long, List<com.baiyue.lastleg.dto.RelabelSubOrder>> relabels = relabelSubOrders(page.getRecords());
Map<Long, LastlegOrderSummary.BusinessSource> businessSources = businessSources(page.getRecords());
var quantities = transferQuantities.forOrders(page.getRecords());
return new PageResult<>(page.getRecords().stream().map(order -> summary(order, mergeRelations.get(order.getId()),
StringUtils.hasText(order.getSourceContainerBookingId())
? containerNodes.get(order.getSourceContainerBookingId()) : null,
dispatchStatuses.getOrDefault(order.getId(), "UNSCHEDULED"), weights.get(order.getId()),
relabels.getOrDefault(order.getId(), List.of()), businessSources.get(order.getId()))).toList(),
relabels.getOrDefault(order.getId(), List.of()), businessSources.get(order.getId()), quantities.get(order.getId()))).toList(),
page.getCurrent(), page.getSize(), page.getTotal(), page.getPages());
}
@@ -363,7 +365,7 @@ public class LastlegOrderService {
return new LastlegOrderDetailResponse(summary(order, palletMergeRelations(List.of(order)).get(order.getId()),
containerNode(order), dispatchStatuses(List.of(order)).getOrDefault(order.getId(), "UNSCHEDULED"),
orderWeights(List.of(order)).get(order.getId()), relabelSubOrders(List.of(order)).getOrDefault(order.getId(), List.of()),
businessSources(List.of(order)).get(order.getId())), manualNodes, cargo, history.stream()
businessSources(List.of(order)).get(order.getId()), transferQuantities.forOrders(List.of(order)).get(order.getId())), manualNodes, cargo, history.stream()
.map(value -> new LastlegOrderDetailResponse.History(value.getId(), value.getFromStatus(),
value.getToStatus(), value.getRemark(), value.getCreatedAt())).toList(), fees, operations.stream()
.map(value -> new LastlegOrderDetailResponse.Operation(value.getId(), value.getOperationNode(),
@@ -532,45 +534,18 @@ public class LastlegOrderService {
return orders.size();
}
/** 与主列表复用同一筛选,汇总只纳入仓储转运且不使用分页参数。 */
public com.baiyue.lastleg.transfer.dto.TransferQuantityTotals transferQuantityTotals(
String customerId, LastlegOrderRequests.Query query, String relabelNo) {
return transferQuantities.totals(filter(customerId, query, relabelNo).eq(LastlegOrder::getOrderType,"WAREHOUSE_TRANSFER"));
}
private LambdaQueryWrapper<LastlegOrder> filter(String customerId, LastlegOrderRequests.Query query) {
return filter(customerId, query, null);
}
private LambdaQueryWrapper<LastlegOrder> filter(String customerId, LastlegOrderRequests.Query query, String relabelNo) {
if (query.createdFrom() != null && query.createdTo() != null && query.createdFrom().isAfter(query.createdTo())) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "createdFrom must not be after createdTo");
}
String currentStatus = StringUtils.hasText(query.currentStatus()) ? query.currentStatus() : query.status();
String warehouse = StringUtils.hasText(query.warehouse()) ? query.warehouse().trim() : null;
return new LambdaQueryWrapper<LastlegOrder>()
.ne(LastlegOrder::getOrderType, "CARGO_DISCARD")
.eq(StringUtils.hasText(customerId), LastlegOrder::getCustomerId, customerId)
.and(StringUtils.hasText(query.orderNo()), nested -> nested
.like(LastlegOrder::getOrderNo, query.orderNo())
.or()
.like(LastlegOrder::getSourceOrderNo, query.orderNo()))
.and(StringUtils.hasText(relabelNo), nested -> nested
.like(LastlegOrder::getRelabelOrderNo, relabelNo)
.or().apply("EXISTS (SELECT 1 FROM ll_relabel_application r WHERE r.lastleg_order_id=ll_order.id " +
"AND r.customer_id=ll_order.customer_id AND r.relabel_no LIKE CONCAT('%',{0},'%'))", relabelNo))
.eq(StringUtils.hasText(query.orderType()), LastlegOrder::getOrderType, query.orderType())
.apply(StringUtils.hasText(query.businessType()), LastlegOrderMapper.BUSINESS_TYPE_FILTER_SQL, query.businessType())
.apply(StringUtils.hasText(query.businessOrderNo()), LastlegOrderMapper.BUSINESS_ORDER_NO_FILTER_SQL, query.businessOrderNo())
.apply(StringUtils.hasText(query.externalBookingNo()), LastlegOrderMapper.EXTERNAL_BOOKING_NO_SQL + " LIKE CONCAT('%',{0},'%')", query.externalBookingNo())
.apply(query.sailingStage() != null, LastlegOrderMapper.SAILING_STAGE_FILTER_SQL,
query.sailingStage() == LastlegOrderRequests.SailingStage.AFTER_DEPARTURE ? 1 : 0)
.like(StringUtils.hasText(query.inboundCode()), LastlegOrder::getInboundCode, query.inboundCode())
.like(StringUtils.hasText(query.lxCode()), LastlegOrder::getLxCode, query.lxCode())
.like(StringUtils.hasText(query.sourceOrderNo()), LastlegOrder::getSourceOrderNo, query.sourceOrderNo())
.like(StringUtils.hasText(query.containerNo()), LastlegOrder::getContainerNo, query.containerNo())
.eq(StringUtils.hasText(currentStatus), LastlegOrder::getCurrentStatus, currentStatus)
.apply(StringUtils.hasText(warehouse), LastlegOrderMapper.WAREHOUSE_FILTER_SQL, warehouse)
.eq(StringUtils.hasText(query.transferWarehouseCode()), LastlegOrder::getTransferWarehouseCode,
query.transferWarehouseCode())
.eq(query.abnormal() != null, LastlegOrder::getAbnormal, query.abnormal())
.eq(query.detained() != null, LastlegOrder::getDetained, query.detained())
.ge(query.createdFrom() != null, LastlegOrder::getCreatedAt, query.createdFrom())
.le(query.createdTo() != null, LastlegOrder::getCreatedAt, query.createdTo());
return com.baiyue.lastleg.query.LastlegOrderFilter.create(customerId, query, relabelNo);
}
private LastlegOrder findOwned(String customerId, long orderId) {
@@ -647,7 +622,8 @@ public class LastlegOrderService {
String containerNode, String dispatchStatus,
LastlegOrderMapper.OrderWeightRow weight,
List<com.baiyue.lastleg.dto.RelabelSubOrder> relabelApplications,
LastlegOrderSummary.BusinessSource businessSource) {
LastlegOrderSummary.BusinessSource businessSource,
com.baiyue.lastleg.transfer.dto.TransferQuantityView transferQuantity) {
List<LastlegOrderMapper.PalletMergeRelationRow> related = relations == null ? List.of() : relations;
return new LastlegOrderSummary(o.getId(), displayOrderNo(o), o.getOrderType(),
LastlegOrderType.labelOf(o.getOrderType()), o.getDestinationType(), o.getSourceInboundId(),
@@ -665,7 +641,7 @@ public class LastlegOrderService {
o.getPalletMergeFlag(), related.stream().map(LastlegOrderMapper.PalletMergeRelationRow::mergeGroupNo).distinct().findFirst().orElse(null),
related.stream().map(LastlegOrderMapper.PalletMergeRelationRow::relatedInboundNo).filter(Objects::nonNull).distinct().toList(),
o.getCurrentStatus(), o.getSubOrderStatus(), o.getPrivateRemark(),
o.getCustomerRemark(), o.getWarehouseRemark(), o.getCreatedAt(), o.getUpdatedAt(), relabelApplications, businessSource);
o.getCustomerRemark(), o.getWarehouseRemark(), o.getCreatedAt(), o.getUpdatedAt(), relabelApplications, businessSource, transferQuantity);
}
private static Integer packageDifference(LastlegOrder order) {
@@ -722,3 +698,4 @@ public class LastlegOrderService {
}
}
@@ -77,6 +77,14 @@ public class MerchantWarehouseTransferController {
return ApiResponse.success(service.submit(customer(user), transferNo, operator(user)));
}
/** 客户当前筛选的全部转运数量,不受页码影响。 */
@GetMapping("/quantities")
@PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_TRANSFER_LIST + "')")
public ApiResponse<com.baiyue.lastleg.transfer.dto.TransferQuantityTotals> quantities(
@AuthenticationPrincipal AuthenticatedUser user,@Valid WarehouseTransferRequests.Query query) {
return ApiResponse.success(service.quantityTotals(customer(user),query));
}
@GetMapping
@PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_TRANSFER_LIST + "')")
public ApiResponse<PageResult<WarehouseTransferResponses.Summary>> page(@AuthenticationPrincipal AuthenticatedUser user,
@@ -0,0 +1,8 @@
package com.baiyue.lastleg.transfer.dto;
/** 全筛选结果汇总,不受分页影响;已知小计与未知票数同时返回。 */
public record TransferQuantityTotals(long orderCount, Long declaredPieceCount, long knownDeclaredPieceCount,
long unknownDeclaredOrderCount, Long receivedPieceCount, long knownReceivedPieceCount,
long unknownReceivedOrderCount, long declaredCartonCount, long receivedCartonCount,
long receivedPalletCount, long availableCartonCount, long shippedCartonCount,
long remainingPalletCount, long shippedPalletCount) { }
@@ -0,0 +1,6 @@
package com.baiyue.lastleg.transfer.dto;
/** 分离客户预报、历史实收和当前箱状态;未知件数保持空值。 */
public record TransferQuantityView(Long lastlegOrderId, Long declaredPieceCount, Long receivedPieceCount,
long declaredCartonCount, long receivedCartonCount, long receivedPalletCount,
long availableCartonCount, long shippedCartonCount, long remainingPalletCount, long shippedPalletCount) { }
@@ -212,7 +212,10 @@ public final class WarehouseTransferRequests {
public record Query(@Min(1) long page, @Min(1) @Max(200) long size,
String transferNo, String inboundCode, String operatingWarehouseId,
String fbaWarehouseCode, String status, Boolean needRelabel,
LocalDateTime createdFrom, LocalDateTime createdTo) {
LocalDateTime createdFrom, LocalDateTime createdTo,
LocalDateTime reviewedFrom, LocalDateTime reviewedTo,
LocalDateTime measuredFrom, LocalDateTime measuredTo,
LocalDateTime outboundFrom, LocalDateTime outboundTo) {
public Query { if (page == 0) page = 1; if (size == 0) size = 20; }
}
}
@@ -0,0 +1,78 @@
package com.baiyue.lastleg.transfer.mapper;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import com.baiyue.lastleg.transfer.dto.TransferQuantityView;
import org.apache.ibatis.annotations.*;
import java.util.List;
/** 使用主订单相同筛选读取转运数量事实,不把历史实收与剩余库存相减。 */
@Mapper
public interface TransferQuantityMapper {
String SELECTED = "SELECT id,customer_id FROM ll_order ${ew.customSqlSegment}";
String RECEIVED = "c.counted_at IS NOT NULL AND c.status IN ('COUNTED','DISCARD_PENDING','DISCARDED','SHIPPED')";
String FACTS = """
SELECT t.lastleg_order_id lastlegOrderId,
(SELECT CASE WHEN COUNT(*)=0 OR COUNT(*)&lt;&gt;COUNT(i.declared_quantity) THEN NULL ELSE SUM(i.declared_quantity) END
FROM ll_warehouse_transfer_item i WHERE i.customer_id=t.customer_id AND i.transfer_order_id=t.id) declaredPieceCount,
(SELECT CASE WHEN COUNT(*)=0 OR COUNT(*)&lt;&gt;COUNT(c.counted_quantity) THEN NULL ELSE SUM(c.counted_quantity) END
FROM ll_warehouse_transfer_carton c WHERE c.customer_id=t.customer_id AND c.transfer_order_id=t.id AND
""" + RECEIVED + """
) receivedPieceCount,
t.package_count declaredCartonCount,
COALESCE(f.receivedCartonCount,0) receivedCartonCount, COALESCE(f.receivedPalletCount,0) receivedPalletCount,
COALESCE(f.availableCartonCount,0) availableCartonCount, COALESCE(f.shippedCartonCount,0) shippedCartonCount,
COALESCE(f.remainingPalletCount,0) remainingPalletCount, COALESCE(f.shippedPalletCount,0) shippedPalletCount
FROM ll_warehouse_transfer_order t JOIN (
""" + SELECTED + """
) selected ON selected.id=t.lastleg_order_id AND selected.customer_id=t.customer_id
LEFT JOIN (
SELECT c.customer_id,c.transfer_order_id,
""" + "SUM(" + RECEIVED + ") receivedCartonCount," +
"COUNT(DISTINCT CASE WHEN " + RECEIVED + " THEN p.warehouse_pallet_id END) receivedPalletCount," + """
SUM(c.status='COUNTED') availableCartonCount, SUM(c.status='SHIPPED') shippedCartonCount,
COUNT(DISTINCT CASE WHEN c.status IN ('COUNTED','DISCARD_PENDING') THEN p.warehouse_pallet_id END) remainingPalletCount,
COUNT(DISTINCT CASE WHEN c.status='SHIPPED' THEN p.warehouse_pallet_id END) shippedPalletCount
FROM ll_warehouse_transfer_carton c LEFT JOIN ll_warehouse_transfer_pallet p
ON p.id=c.transfer_pallet_id AND p.customer_id=c.customer_id
GROUP BY c.customer_id,c.transfer_order_id
) f ON f.transfer_order_id=t.id AND f.customer_id=t.customer_id
""";
/** 一次读取筛选范围或本页订单的预报及实收事实。 */
@Select("<script>" + FACTS + "</script>")
List<TransferQuantityView> rows(@Param("ew") Wrapper<LastlegOrder> filter);
/** 按真实托盘身份在完整筛选集合去重,同托部分出库可同时属于实收、剩余、出库集合。 */
@Select("<script>SELECT DISTINCT c.customer_id customerId,p.warehouse_pallet_id palletId,c.status status " +
"FROM ll_warehouse_transfer_order t JOIN (" + SELECTED + ") selected " +
"ON selected.id=t.lastleg_order_id AND selected.customer_id=t.customer_id " +
"JOIN ll_warehouse_transfer_carton c ON c.transfer_order_id=t.id AND c.customer_id=t.customer_id " +
"JOIN ll_warehouse_transfer_pallet p ON p.id=c.transfer_pallet_id AND p.customer_id=c.customer_id " +
"WHERE " + RECEIVED + " AND p.warehouse_pallet_id IS NOT NULL</script>")
List<PalletFact> pallets(@Param("ew") Wrapper<LastlegOrder> filter);
/** 物理托盘事实,保留客户隔离。 */
record PalletFact(String customerId, Long palletId, String status) { }
/** 库存转运目的仓实收依正式签收凭据;件数只取精确选箱对应原清点事实。 */
@Select("<script>SELECT t.lastleg_order_id lastlegOrderId,t.customer_id customerId,a.package_count cartonCount," +
"a.pallet_id sourcePalletId,a.status status,r.id receiptId,dp.pallet_id destinationPalletId," +
"(SELECT CASE WHEN COUNT(DISTINCT c.id)=a.package_count AND COUNT(*)=COUNT(c.counted_quantity) THEN SUM(c.counted_quantity) ELSE NULL END " +
"FROM ll_warehouse_transfer_carton chosen JOIN ll_warehouse_transfer_order origin " +
"ON origin.customer_id=t.customer_id AND origin.inbound_code=t.inbound_code AND origin.operating_warehouse_id=t.operating_warehouse_id AND origin.transfer_no=origin.inbound_code " +
"JOIN ll_warehouse_transfer_carton c ON c.customer_id=origin.customer_id AND c.transfer_order_id=origin.id " +
"AND c.carton_mark=COALESCE(NULLIF(chosen.customer_carton_mark,''),chosen.carton_mark) " +
"JOIN ll_warehouse_transfer_pallet cp ON cp.id=c.transfer_pallet_id AND cp.customer_id=c.customer_id AND cp.warehouse_pallet_id=a.pallet_id " +
"WHERE chosen.transfer_order_id=t.id AND chosen.customer_id=t.customer_id AND c.counted_at IS NOT NULL) pieceCount " +
"FROM ll_warehouse_transfer_order t JOIN (" + SELECTED + ") selected ON selected.id=t.lastleg_order_id AND selected.customer_id=t.customer_id " +
"JOIN ll_warehouse_transfer_inventory_allocation a ON a.transfer_order_id=t.id AND a.customer_id=t.customer_id " +
"LEFT JOIN ll_warehouse_transfer_receipt r ON r.allocation_id=a.id AND r.customer_id=a.customer_id " +
"LEFT JOIN ll_inventory_position dp ON dp.id=r.destination_inventory_position_id AND dp.customer_id=r.customer_id " +
"WHERE t.transfer_no&lt;&gt;t.inbound_code AND a.status IN ('RESERVED','SHIPPED','RECEIVED')</script>")
List<MovementFact> movements(@Param("ew") Wrapper<LastlegOrder> filter);
/** 每个分配来源的实际出库与目的仓签收事实。 */
record MovementFact(Long lastlegOrderId,String customerId,long cartonCount,Long sourcePalletId,String status,
Long receiptId,Long destinationPalletId,Long pieceCount) { }
}
@@ -0,0 +1,28 @@
package com.baiyue.lastleg.transfer.repository;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import com.baiyue.lastleg.transfer.dto.TransferQuantityView;
import com.baiyue.lastleg.transfer.mapper.TransferQuantityMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Repository;
import java.util.List;
/** 转运数量只读持久化入口。 */
@Repository
public class TransferQuantityRepository {
@Resource private TransferQuantityMapper mapper;
@Resource private com.baiyue.lastleg.transfer.mapper.WarehouseTransferOrderMapper transfers;
/** 以客户列表相同筛选读取关联主订单,不读取分页参数。 */
public List<Long> selectedOrderIds(Wrapper<com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder> filter) {
return transfers.selectList(filter).stream()
.map(com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder::getLastlegOrderId)
.filter(java.util.Objects::nonNull).distinct().toList();
}
/** 读取完整筛选集合的事实,分页由主列表单独处理。 */
public List<TransferQuantityView> rows(Wrapper<LastlegOrder> filter) { return mapper.rows(filter); }
/** 读取完整筛选集合的物理托盘。 */
public List<TransferQuantityMapper.PalletFact> pallets(Wrapper<LastlegOrder> filter) { return mapper.pallets(filter); }
/** 读取库存转运实际出库及目的仓签收,按来源分配去重。 */
public List<TransferQuantityMapper.MovementFact> movements(Wrapper<LastlegOrder> filter) { return mapper.movements(filter); }
}
@@ -0,0 +1,87 @@
package com.baiyue.lastleg.transfer.service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baiyue.lastleg.entity.LastlegOrder;
import com.baiyue.lastleg.transfer.dto.*;
import com.baiyue.lastleg.transfer.repository.TransferQuantityRepository;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
import java.util.function.ToLongFunction;
import java.util.stream.Collectors;
/** 预报、实收、当前剩余分别汇总,空件数不会被零值掩盖。 */
@Service
public class TransferQuantityService {
@Resource private TransferQuantityRepository repository;
/** 客户列表共享完整筛选,主订单查询仍显式限定客户。 */
@Transactional(readOnly=true)
public TransferQuantityTotals merchantTotals(Wrapper<com.baiyue.lastleg.transfer.entity.WarehouseTransferOrder> filter, String customerId) {
var ids = repository.selectedOrderIds(filter);
var orders = new LambdaQueryWrapper<LastlegOrder>().eq(LastlegOrder::getCustomerId, customerId);
if (ids.isEmpty()) orders.apply("1=0"); else orders.in(LastlegOrder::getId, ids);
return totals(orders);
}
/** 主列表批量加载本页转运,其他业务不改变字段语义。 */
public Map<Long,TransferQuantityView> forOrders(List<LastlegOrder> orders) {
var ids=orders.stream().filter(o -> "WAREHOUSE_TRANSFER".equals(o.getOrderType())).map(LastlegOrder::getId).toList();
if(ids.isEmpty()) return Map.of();
var filter = new LambdaQueryWrapper<LastlegOrder>().in(LastlegOrder::getId,ids);
return withMovements(repository.rows(filter),repository.movements(filter))
.stream().collect(Collectors.toMap(TransferQuantityView::lastlegOrderId, v -> v));
}
/** 同一只读事务按完整筛选汇总,page/size不参与数量计算。 */
@Transactional(readOnly=true)
public TransferQuantityTotals totals(Wrapper<LastlegOrder> filter) {
var movements=repository.movements(filter);
var rows=withMovements(repository.rows(filter),movements); var pallets=repository.pallets(filter);
long unknownDeclared=rows.stream().filter(v -> v.declaredPieceCount()==null).count();
long unknownReceived=rows.stream().filter(v -> v.receivedPieceCount()==null).count();
long declared=sum(rows,v -> v.declaredPieceCount()==null?0:v.declaredPieceCount());
long received=sum(rows,v -> v.receivedPieceCount()==null?0:v.receivedPieceCount());
var all=new HashSet<String>(); var remaining=new HashSet<String>(); var shipped=new HashSet<String>();
for(var pallet:pallets) {
String key=pallet.customerId()+":"+pallet.palletId(); all.add(key);
if(Set.of("COUNTED","DISCARD_PENDING").contains(pallet.status())) remaining.add(key);
if("SHIPPED".equals(pallet.status())) shipped.add(key);
}
for (var move:movements) {
if (move.receiptId()!=null && move.destinationPalletId()!=null) all.add(move.customerId()+":"+move.destinationPalletId());
if (Set.of("SHIPPED","RECEIVED").contains(move.status()) && move.sourcePalletId()!=null) shipped.add(move.customerId()+":"+move.sourcePalletId());
}
return new TransferQuantityTotals(rows.size(),unknownDeclared==0?declared:null,declared,unknownDeclared,
unknownReceived==0?received:null,received,unknownReceived,sum(rows,TransferQuantityView::declaredCartonCount),
sum(rows,TransferQuantityView::receivedCartonCount),all.size(),sum(rows,TransferQuantityView::availableCartonCount),
sum(rows,TransferQuantityView::shippedCartonCount),remaining.size(),shipped.size());
}
/** 库存转运的实收来自目的仓凭据,原仓出库事实保留独立维度。 */
private List<TransferQuantityView> withMovements(List<TransferQuantityView> rows,
List<com.baiyue.lastleg.transfer.mapper.TransferQuantityMapper.MovementFact> movements) {
var grouped=movements.stream().collect(Collectors.groupingBy(com.baiyue.lastleg.transfer.mapper.TransferQuantityMapper.MovementFact::lastlegOrderId));
return rows.stream().map(row -> {
var facts=grouped.get(row.lastlegOrderId()); if(facts==null) return row;
long received=0,pieces=0,shipped=0; boolean known=true; var targets=new HashSet<Long>(); var sources=new HashSet<Long>();
for(var fact:facts) {
if(fact.receiptId()!=null) {
received=Math.addExact(received,fact.cartonCount());
if(fact.pieceCount()==null) known=false; else pieces=Math.addExact(pieces,fact.pieceCount());
if(fact.destinationPalletId()!=null) targets.add(fact.destinationPalletId());
}
if(Set.of("SHIPPED","RECEIVED").contains(fact.status())) { shipped=Math.addExact(shipped,fact.cartonCount()); if(fact.sourcePalletId()!=null) sources.add(fact.sourcePalletId()); }
}
return new TransferQuantityView(row.lastlegOrderId(),row.declaredPieceCount(),received>0&&known?pieces:null,
row.declaredCartonCount(),received,targets.size(),0,shipped,0,sources.size());
}).toList();
}
/** 使用精确整数累加,溢出不能静默返回错误汇总。 */
private long sum(List<TransferQuantityView> rows,ToLongFunction<TransferQuantityView> measure) {
long value=0; for(var row:rows) value=Math.addExact(value,measure.applyAsLong(row)); return value;
}
}
@@ -92,6 +92,7 @@ import java.util.stream.Collectors;
@Service
public class WarehouseTransferService {
@Resource private TransferQuantityService transferQuantityService;
@Resource private com.baiyue.lastleg.fleet.pickup.FleetPickupService pickupService;
/** 退货单在转运来源中的展示编码,避免把退货单号误当成普通入仓码查询。 */
public static final String RETURN_ORDER_PREFIX = "RETURN_ORDER:";
@@ -551,19 +552,15 @@ public class WarehouseTransferService {
transferCartons.updateById(carton);
}
}
@Transactional(readOnly = true)
public PageResult<WarehouseTransferResponses.Summary> page(String customerId, WarehouseTransferRequests.Query query) {
return page(customerId, query, true);
}
@Transactional(readOnly = true)
public PageResult<WarehouseTransferResponses.Summary> page(String customerId, WarehouseTransferRequests.Query query,
boolean includeDrafts) {
if (query.createdFrom() != null && query.createdTo() != null && query.createdFrom().isAfter(query.createdTo())) {
throw badRequest("createdFrom must not be after createdTo");
}
/** 列表和全筛选数量共享条件,避免翻页或状态分组后口径漂移。 */
private LambdaQueryWrapper<WarehouseTransferOrder> transferPageFilter(String customerId,
WarehouseTransferRequests.Query query, boolean includeDrafts) {
validateQuantityRange(query.createdFrom(), query.createdTo(), "创建");
validateQuantityRange(query.reviewedFrom(), query.reviewedTo(), "审核");
validateQuantityRange(query.measuredFrom(), query.measuredTo(), "清点完成");
validateQuantityRange(query.outboundFrom(), query.outboundTo(), "出库");
List<String> groupedStatuses = customerMainStatuses(query.status());
LambdaQueryWrapper<WarehouseTransferOrder> wrapper = new LambdaQueryWrapper<WarehouseTransferOrder>()
return new LambdaQueryWrapper<WarehouseTransferOrder>()
.eq(StringUtils.hasText(customerId), WarehouseTransferOrder::getCustomerId, customerId)
.like(StringUtils.hasText(query.transferNo()), WarehouseTransferOrder::getTransferNo, query.transferNo())
.like(StringUtils.hasText(query.inboundCode()), WarehouseTransferOrder::getInboundCode, query.inboundCode())
@@ -577,7 +574,35 @@ public class WarehouseTransferService {
.eq(query.needRelabel() != null, WarehouseTransferOrder::getNeedRelabel, query.needRelabel())
.ge(query.createdFrom() != null, WarehouseTransferOrder::getCreatedAt, query.createdFrom())
.le(query.createdTo() != null, WarehouseTransferOrder::getCreatedAt, query.createdTo())
.ge(query.reviewedFrom() != null, WarehouseTransferOrder::getReviewedAt, query.reviewedFrom())
.le(query.reviewedTo() != null, WarehouseTransferOrder::getReviewedAt, query.reviewedTo())
.ge(query.outboundFrom() != null, WarehouseTransferOrder::getOutboundAt, query.outboundFrom())
.le(query.outboundTo() != null, WarehouseTransferOrder::getOutboundAt, query.outboundTo())
.apply(query.measuredFrom() != null, "(SELECT MAX(qp.completed_at) FROM ll_warehouse_transfer_pallet qp WHERE qp.transfer_order_id=ll_warehouse_transfer_order.id AND qp.customer_id=ll_warehouse_transfer_order.customer_id) >= {0}", query.measuredFrom())
.apply(query.measuredTo() != null, "(SELECT MAX(qp.completed_at) FROM ll_warehouse_transfer_pallet qp WHERE qp.transfer_order_id=ll_warehouse_transfer_order.id AND qp.customer_id=ll_warehouse_transfer_order.customer_id) <= {0}", query.measuredTo())
.orderByDesc(WarehouseTransferOrder::getCreatedAt).orderByDesc(WarehouseTransferOrder::getId);
}
/** 日期区间统一校验,列表与数量汇总均拒绝反向区间。 */
private void validateQuantityRange(LocalDateTime from, LocalDateTime to, String name) {
if (from != null && to != null && from.isAfter(to)) throw badRequest(name + "开始时间不能晚于结束时间");
}
/** 客户侧完整筛选数量,不读取其他客户且不使用页码。 */
@Transactional(readOnly = true)
public com.baiyue.lastleg.transfer.dto.TransferQuantityTotals quantityTotals(String customerId, WarehouseTransferRequests.Query query) {
return transferQuantityService.merchantTotals(transferPageFilter(customerId, query, true), customerId);
}
@Transactional(readOnly = true)
public PageResult<WarehouseTransferResponses.Summary> page(String customerId, WarehouseTransferRequests.Query query) {
return page(customerId, query, true);
}
@Transactional(readOnly = true)
public PageResult<WarehouseTransferResponses.Summary> page(String customerId, WarehouseTransferRequests.Query query,
boolean includeDrafts) {
var wrapper = transferPageFilter(customerId, query, includeDrafts);
Page<WarehouseTransferOrder> result = transfers.selectPage(Page.of(query.page(), query.size()), wrapper);
Map<String, RelabelApplication> relabelApplicationsByNo = relabelApplications(result.getRecords());
Map<Long, LocalDateTime> measurementTimes = measurementTimes(result.getRecords());
@@ -961,7 +986,7 @@ public class WarehouseTransferService {
WarehouseTransferRequests.CountCartons request) {
WarehouseTransferOrder transfer = transfers.lockForPda(transferNo, String.valueOf(warehouseId));
if (transfer == null) throw notFound("当前仓没有该转运单");
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer);
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer.getId(), transfer.getDeliveryMethod(), transfer.getTransferNo(), transfer.getInboundCode());
String customerId = transfer.getCustomerId();
List<WarehouseTransferCarton> cartons = transferCartons.listOrder(customerId, transfer.getId());
// 客户补箱后旧设备快照不可确认短收,必须刷新取得新增的预报箱唛。
@@ -1096,7 +1121,11 @@ public class WarehouseTransferService {
/** 上门取货必须先送仓;按 PDA 绑定仓锁定后继续使用原测量流程。 */
private WarehouseTransferOrder requirePdaMeasuringTransfer(long warehouseId, String transferNo) {
return pickupService.requireMeasuringSource(String.valueOf(warehouseId), transferNo);
WarehouseTransferOrder transfer = transfers.lockForPda(transferNo, String.valueOf(warehouseId));
if (transfer == null) throw notFound("仓储转运单不存在");
if (!WAIT_PDA_RECEIVING.equals(transfer.getStatus())) throw conflict("当前转运单不允许测量");
pickupService.requireArrived(transfer.getId(), transfer.getDeliveryMethod(), transfer.getTransferNo(), transfer.getInboundCode());
return transfer;
}
private void validatePalletMeasurement(BigDecimal length, BigDecimal width, BigDecimal height, BigDecimal volume) {
@@ -1114,7 +1143,7 @@ public class WarehouseTransferService {
WarehouseTransferRequests.Palletize request) {
WarehouseTransferOrder transfer = transfers.lockForPda(transferNo, String.valueOf(overseasWarehouseId));
if (transfer == null) throw notFound("Warehouse transfer order not found");
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer);
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer.getId(), transfer.getDeliveryMethod(), transfer.getTransferNo(), transfer.getInboundCode());
if (!String.valueOf(overseasWarehouseId).equals(transfer.getOperatingWarehouseId())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Warehouse transfer belongs to another warehouse");
}
@@ -1683,7 +1712,7 @@ public class WarehouseTransferService {
String transferNo, MultipartFile file) {
WarehouseTransferOrder transfer = transfers.lockForPda(transferNo, String.valueOf(overseasWarehouseId));
if (transfer == null) throw notFound("Warehouse transfer order not found");
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer);
if ("WAREHOUSE_PICKUP".equals(transfer.getDeliveryMethod())) pickupService.requireArrived(transfer.getId(), transfer.getDeliveryMethod(), transfer.getTransferNo(), transfer.getInboundCode());
if (!WAIT_PDA_RECEIVING.equals(transfer.getStatus())) {
throw conflict("Measurement photos can only be uploaded before palletization completes");
}
@@ -4553,3 +4553,82 @@ CREATE TABLE IF NOT EXISTS ll_fleet_pickup_history (
KEY idx_pickup_history_source(customer_id,transfer_no,id),
KEY idx_pickup_history_trip(trip_no,id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='取货不可变操作历史';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_ownership (
dispatch_id BIGINT NOT NULL COMMENT '原排车内部主键',
resource_mode VARCHAR(16) NOT NULL COMMENT '原排车资源模式MASTER或EXTERNAL',
vehicle_id BIGINT NULL COMMENT '真实车辆档案主键,临时外配为空',
vehicle_ownership VARCHAR(16) NOT NULL COMMENT '装车完成时车辆归属OWNED或DISPATCHED',
vehicle_record_version BIGINT NULL COMMENT '捕获归属时真实车辆档案版本',
ownership_captured_at DATETIME(3) NOT NULL COMMENT '归属捕获UTC时间',
loading_completion_hash VARCHAR(128) NOT NULL COMMENT '原排车装车确认事实摘要',
loading_completed_at DATETIME(3) NOT NULL COMMENT '原排车实际装车完成UTC时间',
PRIMARY KEY (dispatch_id),
KEY idx_owned_business_vehicle (vehicle_ownership,vehicle_id),
CONSTRAINT fk_owned_business_ownership_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_ownership CHECK (vehicle_ownership IN ('OWNED','DISPATCHED')),
CONSTRAINT ck_owned_business_resource_mode CHECK (
(resource_mode='MASTER' AND vehicle_id IS NOT NULL AND vehicle_record_version IS NOT NULL AND vehicle_record_version>=0)
OR (resource_mode='EXTERNAL' AND vehicle_id IS NULL AND vehicle_record_version IS NULL AND vehicle_ownership='DISPATCHED'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车装车完成时的车辆归属证据';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_record (
id BIGINT NOT NULL COMMENT '附加运营记录内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
record_version BIGINT NOT NULL COMMENT '附加运营记录并发版本,独立于原排车版本',
currency VARCHAR(3) NULL COMMENT '整车运营金额币种CNY或USD,未登记为空',
total_amount DECIMAL(18,2) NULL COMMENT '人工登记整车总金额,不自动形成账务费用',
actual_distance_miles DECIMAL(12,3) NULL COMMENT '实际行驶英里数,未登记为空',
fuel_consumption_litres_per_100km DECIMAL(12,3) NULL COMMENT '人工登记油耗率,单位升每百公里',
arrivals_json JSON NOT NULL COMMENT '按原目的地键记录的实际到达UTC时间',
photos_json JSON NOT NULL COMMENT '七个照片框当前已绑定文件的分类快照',
created_by VARCHAR(64) NOT NULL COMMENT '首次登记操作人标识',
updated_by VARCHAR(64) NOT NULL COMMENT '最近登记操作人标识',
created_at DATETIME(3) NOT NULL COMMENT '首次登记UTC时间',
updated_at DATETIME(3) NOT NULL COMMENT '最近登记UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_record_dispatch (dispatch_id),
CONSTRAINT fk_owned_business_record_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_record_version CHECK (record_version>=0),
CONSTRAINT ck_owned_business_money CHECK (
(currency IS NULL AND total_amount IS NULL)
OR (currency IS NOT NULL AND currency IN ('CNY','USD') AND total_amount IS NOT NULL AND total_amount>=0)),
CONSTRAINT ck_owned_business_distance CHECK (actual_distance_miles IS NULL OR actual_distance_miles>=0),
CONSTRAINT ck_owned_business_fuel CHECK (fuel_consumption_litres_per_100km IS NULL OR fuel_consumption_litres_per_100km>=0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车自有业务附加运营信息';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_command (
id BIGINT NOT NULL COMMENT '附加运营命令内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
operator_id VARCHAR(64) NOT NULL COMMENT '原命令操作人标识',
idempotency_key VARCHAR(128) COLLATE utf8mb4_bin NOT NULL COMMENT '同一原排车内唯一请求键,不按操作者分组',
action VARCHAR(32) NOT NULL COMMENT '运营登记或照片上传绑定动作',
expected_version BIGINT NULL COMMENT '原请求附加版本,纯文件上传可为空',
request_hash CHAR(64) NOT NULL COMMENT '原操作者动作版本与完整请求摘要',
request_json JSON NOT NULL COMMENT '不含文件内容或凭据的完整原请求',
status VARCHAR(24) NOT NULL COMMENT 'PENDING或SUCCEEDED或REJECTED或UNKNOWN_RESULT',
result_json JSON NULL COMMENT '原命令已知成功结果或明确拒绝事实',
error_code VARCHAR(64) NULL COMMENT '明确拒绝或未知结果诊断码',
created_at DATETIME(3) NOT NULL COMMENT '命令意图创建UTC时间',
updated_at DATETIME(3) NOT NULL COMMENT '命令结果更新UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_command_key (dispatch_id,idempotency_key),
CONSTRAINT fk_owned_business_command_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_command_version CHECK (expected_version IS NULL OR expected_version>=0),
CONSTRAINT ck_owned_business_command_status CHECK (status IN ('PENDING','SUCCEEDED','REJECTED','UNKNOWN_RESULT'))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车附加运营写命令及可恢复结果';
CREATE TABLE IF NOT EXISTS ll_fleet_owned_business_history (
id BIGINT NOT NULL COMMENT '附加运营历史内部主键',
dispatch_id BIGINT NOT NULL COMMENT '所属原排车内部主键',
record_version BIGINT NOT NULL COMMENT '成功写入后的附加记录版本',
action VARCHAR(32) NOT NULL COMMENT '运营登记或照片绑定动作',
operator_id VARCHAR(64) NOT NULL COMMENT '真实操作人标识',
reason VARCHAR(1000) NULL COMMENT '人工填写的登记或更正说明',
snapshot_json JSON NOT NULL COMMENT '操作后附加运营信息与分类照片不可变快照',
occurred_at DATETIME(3) NOT NULL COMMENT '操作UTC时间',
PRIMARY KEY (id),
UNIQUE KEY uk_owned_business_history_version (dispatch_id,record_version),
CONSTRAINT fk_owned_business_history_dispatch FOREIGN KEY (dispatch_id) REFERENCES ll_dispatch_order(id),
CONSTRAINT ck_owned_business_history_version CHECK (record_version>0)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='原排车自有业务附加运营不可变历史';
@@ -86,6 +86,7 @@ paths:
- $ref: '#/components/parameters/PalletNo'
post:
summary: Confirm actual disposal with owned pallet photos
description: PalletTask.skus返回actualQuantityEditable布尔值。仅普通库存未保存具体箱唛时为true,PDA展示相关托盘并要求填写实际废弃箱数;库存和费用按实际数结算,未废弃预留释放。已完成任务相同数量重放不重复扣减,修改数量拒绝。
x-permissions: [lastleg:pda:operate, ROLE_OVERSEAS_WAREHOUSE_PDA_OPERATOR]
requestBody:
required: true
@@ -103,7 +104,7 @@ paths:
required: [itemId, actualPackages]
properties:
itemId: { type: string, pattern: '^[1-9][0-9]*$' }
actualPackages: { type: integer, minimum: 1, description: Must equal plannedPackages; must finish the application selection }
actualPackages: { type: integer, minimum: 0, description: 无精确箱唛对应关系的普通库存允许0至plannedPackages的实际箱数,剩余预留释放;有具体选箱的明细必须等于plannedPackages }
scannedCartonMarks:
type: array
uniqueItems: true
@@ -0,0 +1,94 @@
openapi: 3.0.3
info:
title: 货物废弃全部筛选数量统计
version: 1.1.0
paths:
/api/platform/v1/last-leg/cargo-discards/statistics:
get:
summary: 按平台允许的客户范围汇总全部筛选结果
description: 与废弃列表共用筛选条件,page和size不限制统计范围。未记录的实际数量、商品件数或托盘事实返回null。实际数取PDA确认事实,不从申请数或状态推算。
parameters:
- {name: customerId, in: query, schema: {type: string}}
- {$ref: '#/components/parameters/DiscardNo'}
- {$ref: '#/components/parameters/InboundCode'}
- {$ref: '#/components/parameters/Warehouse'}
- {$ref: '#/components/parameters/Status'}
- {$ref: '#/components/parameters/CreatedFrom'}
- {$ref: '#/components/parameters/CreatedTo'}
- {$ref: '#/components/parameters/CompletedFrom'}
- {$ref: '#/components/parameters/CompletedTo'}
- {$ref: '#/components/parameters/Page'}
- {$ref: '#/components/parameters/Size'}
responses:
'200':
description: 标准ApiResponse,data为全部筛选数量统计
content:
application/json:
schema: {$ref: '#/components/schemas/Envelope'}
/api/merchant/v1/last-leg/cargo-discards/statistics:
get:
summary: 按当前认证客户汇总全部筛选结果
description: 需要merchant:overseas-warehouse:discard:list权限;客户归属只取认证身份。完成时间筛选同时适用于列表。
parameters:
- {$ref: '#/components/parameters/DiscardNo'}
- {$ref: '#/components/parameters/InboundCode'}
- {$ref: '#/components/parameters/Warehouse'}
- {$ref: '#/components/parameters/Status'}
- {$ref: '#/components/parameters/CreatedFrom'}
- {$ref: '#/components/parameters/CreatedTo'}
- {$ref: '#/components/parameters/CompletedFrom'}
- {$ref: '#/components/parameters/CompletedTo'}
- {$ref: '#/components/parameters/Page'}
- {$ref: '#/components/parameters/Size'}
responses:
'200':
description: 标准ApiResponse,data为当前客户全部筛选统计
content:
application/json:
schema: {$ref: '#/components/schemas/Envelope'}
components:
parameters:
DiscardNo: {name: discardNo, in: query, schema: {type: string}}
InboundCode: {name: inboundCode, in: query, schema: {type: string}}
Warehouse: {name: overseasWarehouseId, in: query, schema: {type: string}}
Status: {name: status, in: query, schema: {type: string}}
CreatedFrom: {name: createdFrom, in: query, schema: {type: string, format: date-time}}
CreatedTo: {name: createdTo, in: query, schema: {type: string, format: date-time}}
CompletedFrom: {name: completedFrom, in: query, description: 客户确认完成时间下界,包含边界, schema: {type: string, format: date-time}}
CompletedTo: {name: completedTo, in: query, description: 客户确认完成时间上界,包含边界, schema: {type: string, format: date-time}}
Page: {name: page, in: query, required: true, schema: {type: integer, minimum: 1}}
Size: {name: size, in: query, required: true, schema: {type: integer, minimum: 1, maximum: 200}}
schemas:
SummaryDimensions:
type: object
description: 平台及客户废弃列表records与详情summary均返回这些维度;totalPackages保留作业阶段展示箱数,申请箱数须读取requestedPackages。
required: [skuCodes, skuCount, requestedPackages, actualPackages]
properties:
skuCodes: {type: array, items: {type: string}, description: 申请明细去重并排序后的全部SKU}
skuCount: {type: integer, description: 本单SKU种数}
requestedPackages: {type: integer, description: 申请物理箱数,同一混装箱跨SKU仅计一次}
actualPackages: {type: integer, nullable: true, description: PDA已确认实际物理箱数,未作业为null}
CandidateSku:
type: object
description: 库存仓位按物理箱计量,箱内全部SKU从真实实收JSON投影;完整混箱必须携带全部SKU明细,库存冻结和扣减按仓位及箱身份去重。
properties:
skuCode: {type: string}
productName: {type: string, nullable: true}
availablePackages: {type: string, description: 包含本SKU的可选物理箱数}
availablePieces: {type: string, nullable: true, description: 真实箱内本SKU件数,缺失时null,不按箱规推算}
Envelope:
type: object
properties:
code: {type: string}
data: {$ref: '#/components/schemas/Statistics'}
Statistics:
type: object
description: Long值遵循全局序列化配置,可能以十进制字符串返回;退货SKU按件汇总并按实物箱去重,转运件数只取所选箱实点SKU事实,其他缺失事实保留null。
properties:
orderCount: {type: string, description: 筛选订单票数}
skuCount: {type: integer, description: 筛选内去重SKU种数}
requestedPackages: {type: string, description: 申请物理箱数}
actualPackages: {type: string, nullable: true, description: 已确认实际物理箱数}
requestedPieces: {type: string, nullable: true, description: 申请商品件数}
actualPieces: {type: string, nullable: true, description: 已确认实际商品件数}
palletCount: {type: integer, nullable: true, description: 客户和仓范围内去重真实来源托盘数,缺失或散箱返回null}
@@ -0,0 +1,972 @@
openapi: "3.0.3"
info:
title: "原排车自有车辆运营视图"
version: "1.0.0"
description: "装车完成时冻结车辆OWNED/DISPATCHED;所有主单事实来自原dispatch。新增数据仅附加运营记录、命令、历史及归属证据。油耗L/100km手工登记,金额CNY/USD不默认、不换汇;零与未登记不同。"
security:
-
bearerAuth: []
paths:
"/api/platform/v1/last-leg/fleet/owned-business":
get:
operationId: "listOwnedBusiness"
summary: "自有车辆装车后视图及同筛选四项统计"
description: "权限:platform:fleet:owned-business:list。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:list"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/ListResult"
nullable: true
parameters:
-
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
-
name: "plannedDepartureFrom"
in: "query"
required: false
schema:
type: "string"
format: "date-time"
-
name: "plannedDepartureTo"
in: "query"
required: false
schema:
type: "string"
format: "date-time"
-
name: "keyword"
in: "query"
required: false
schema:
type: "string"
maxLength: 128
-
name: "stage"
in: "query"
required: false
schema:
"$ref": "#/components/schemas/Stage"
-
name: "warehouseId"
in: "query"
required: false
schema:
type: "string"
maxLength: 64
x-filter-contract: "plannedDepartureAt [from,to),统计同全部过滤、不带分页;无归属快照不降级按当前主档推断。"
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
get:
operationId: "getOwnedBusiness"
summary: "组合原排车详情及附加运营信息"
description: "权限:platform:fleet:owned-business:list。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:list"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/Detail"
nullable: true
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/history":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
get:
operationId: "historyOwnedBusiness"
summary: "原排车及附加真实流水聚合分页"
description: "权限:platform:fleet:owned-business:list。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:list"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/HistoryPage"
nullable: true
parameters:
-
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
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/operations":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
put:
operationId: "saveOwnedBusinessOperations"
summary: "按附加版本登记、更正或清空运营信息"
description: "权限:platform:fleet:owned-business:edit。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:edit"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/Detail"
nullable: true
requestBody:
required: true
content:
"application/json":
schema:
"$ref": "#/components/schemas/SaveOperations"
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/photos/{slot}/uploads":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
-
name: "slot"
in: "path"
required: true
schema:
"$ref": "#/components/schemas/PhotoSlot"
post:
operationId: "uploadOwnedBusinessPhoto"
summary: "逐框准备照片,尚未保存绑定"
description: "权限:platform:fleet:owned-business:upload。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:upload"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/Photo"
nullable: true
requestBody:
required: true
content:
"multipart/form-data":
schema:
type: "object"
required:
- "file"
- "idempotencyKey"
properties:
idempotencyKey:
type: "string"
minLength: 8
maxLength: 128
description: "原上传请求键,以multipart表单字段提交,绑定使用独立请求键。"
file:
type: "string"
format: "binary"
description: "真实JPG/PNG,非空,最大10MiB;与独立绑定命令使用不同请求键。"
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/photos/{slot}":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
-
name: "slot"
in: "path"
required: true
schema:
"$ref": "#/components/schemas/PhotoSlot"
put:
operationId: "bindOwnedBusinessPhoto"
summary: "保存原上传fileId;失败保留原键恢复,不重新上传"
description: "权限:platform:fleet:owned-business:upload。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:upload"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/Detail"
nullable: true
requestBody:
required: true
content:
"application/json":
schema:
"$ref": "#/components/schemas/BindPhoto"
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/photos/{slot}/files/{fileId}/content":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
-
name: "slot"
in: "path"
required: true
schema:
"$ref": "#/components/schemas/PhotoSlot"
-
name: "fileId"
in: "path"
required: true
schema:
type: "string"
pattern: "^[1-9][0-9]*$"
get:
operationId: "readOwnedBusinessPhoto"
summary: "授权读取当前或原历史绑定图片"
description: "权限:platform:fleet:owned-business:list。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:list"
responses:
200:
description: "仅当前或指定历史引用的图片字节,Cache-Control:no-store,X-Content-Type-Options:nosniff"
content:
"image/jpeg":
schema:
type: "string"
format: "binary"
"image/png":
schema:
type: "string"
format: "binary"
parameters:
-
name: "revisionVersion"
in: "query"
required: false
schema:
type: "integer"
format: "int64"
minimum: 1
"/api/platform/v1/last-leg/fleet/owned-business/{dispatchNo}/commands/{idempotencyKey}":
parameters:
-
name: "dispatchNo"
in: "path"
required: true
schema:
type: "string"
maxLength: 128
-
name: "idempotencyKey"
in: "path"
required: true
schema:
type: "string"
minLength: 8
maxLength: 128
get:
operationId: "recoverOwnedBusinessCommand"
summary: "恢复本操作者原命令,未知结果不得换键重发"
description: "权限:platform:fleet:owned-business:list。仅可信平台主体;只读原排车事实,不改变其状态/版本,不发布费用。"
x-permission-code: "platform:fleet:owned-business:list"
responses:
200:
description: "统一ApiResponse:成功code=200;业务错误保留A0400/A0403/A0404/A0409及诊断requestId/traceId。"
content:
"application/json":
schema:
type: "object"
properties:
code:
type: "string"
message:
type: "string"
data:
allOf:
-
"$ref": "#/components/schemas/Command"
nullable: true
components:
securitySchemes:
bearerAuth:
type: "http"
scheme: "bearer"
bearerFormat: "JWT"
schemas:
Stage:
type: "string"
enum:
- "AFTER_LOADING"
- "DELIVERING"
- "DELIVERED"
PhotoSlot:
type: "string"
enum:
- "LOADING_SCENE"
- "LOADING_LIST"
- "PRE_DEPARTURE_CHECK"
- "DRIVER_LICENSE"
- "RECEIPT"
- "FUEL_START"
- "FUEL_END"
Money:
type: "object"
x-java-record: "OwnedBusinessModels.Money"
required:
- "currency"
- "amount"
properties:
currency:
type: "string"
enum:
- "CNY"
- "USD"
amount:
type: "string"
pattern: "^(0|[1-9][0-9]{0,15})(\\.[0-9]{1,2})?$"
Arrival:
type: "object"
x-java-record: "OwnedBusinessModels.Arrival"
required:
- "destinationKey"
- "actualArrivedAt"
properties:
destinationKey:
type: "string"
minLength: 1
maxLength: 256
actualArrivedAt:
type: "string"
nullable: true
format: "date-time"
Operations:
type: "object"
x-java-record: "OwnedBusinessModels.Operations"
required:
- "money"
- "actualDistanceMiles"
- "fuelConsumptionLitresPer100Km"
- "arrivals"
properties:
money:
allOf:
-
"$ref": "#/components/schemas/Money"
nullable: true
actualDistanceMiles:
type: "string"
nullable: true
pattern: "^(0|[1-9][0-9]{0,8})(\\.[0-9]{1,3})?$"
fuelConsumptionLitresPer100Km:
type: "string"
nullable: true
pattern: "^(0|[1-9][0-9]{0,8})(\\.[0-9]{1,3})?$"
arrivals:
type: "array"
items:
"$ref": "#/components/schemas/Arrival"
SaveOperations:
type: "object"
x-java-record: "OwnedBusinessModels.SaveOperations"
required:
- "recordVersion"
- "idempotencyKey"
- "operations"
properties:
recordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
idempotencyKey:
type: "string"
minLength: 8
maxLength: 128
operations:
"$ref": "#/components/schemas/Operations"
reason:
type: "string"
nullable: true
maxLength: 1000
BindPhoto:
type: "object"
x-java-record: "OwnedBusinessModels.BindPhoto"
required:
- "recordVersion"
- "idempotencyKey"
- "fileId"
properties:
recordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
idempotencyKey:
type: "string"
minLength: 8
maxLength: 128
fileId:
type: "string"
pattern: "^[1-9][0-9]*$"
Gate:
type: "object"
x-java-record: "OwnedBusinessModels.Gate"
required:
- "allowed"
- "blockReason"
properties:
allowed:
type: "boolean"
blockReason:
type: "string"
nullable: true
Actions:
type: "object"
x-java-record: "OwnedBusinessModels.Actions"
required:
- "edit"
- "upload"
properties:
edit:
"$ref": "#/components/schemas/Gate"
upload:
"$ref": "#/components/schemas/Gate"
Origin:
type: "object"
x-java-record: "OwnedBusinessModels.Origin"
required:
- "warehouseId"
- "warehouseCode"
- "warehouseName"
properties:
warehouseId:
type: "string"
warehouseCode:
type: "string"
warehouseName:
type: "string"
Vehicle:
type: "object"
x-java-record: "OwnedBusinessModels.Vehicle"
required:
- "vehicleId"
- "plate"
- "ownership"
properties:
vehicleId:
type: "string"
plate:
type: "string"
ownership:
type: "string"
enum:
- "OWNED"
Driver:
type: "object"
x-java-record: "OwnedBusinessModels.Driver"
required:
- "name"
- "phone"
properties:
name:
type: "string"
nullable: true
phone:
type: "string"
nullable: true
Appointment:
type: "object"
x-java-record: "OwnedBusinessModels.Appointment"
required:
- "appointmentNo"
- "confirmationNo"
- "scheduledAt"
- "allocatedPackages"
properties:
appointmentNo:
type: "string"
confirmationNo:
type: "string"
nullable: true
scheduledAt:
type: "string"
nullable: true
format: "date-time"
allocatedPackages:
type: "string"
pattern: "^[1-9][0-9]*$"
Destination:
type: "object"
x-java-record: "OwnedBusinessModels.Destination"
required:
- "destinationKey"
- "warehouseCode"
- "warehouseName"
- "address"
- "appointments"
- "actualArrivedAt"
properties:
destinationKey:
type: "string"
warehouseCode:
type: "string"
nullable: true
warehouseName:
type: "string"
nullable: true
address:
type: "string"
nullable: true
appointments:
type: "array"
items:
"$ref": "#/components/schemas/Appointment"
actualArrivedAt:
type: "string"
nullable: true
format: "date-time"
Photo:
type: "object"
x-java-record: "OwnedBusinessModels.Photo"
required:
- "slot"
- "category"
- "fileId"
- "fileName"
- "contentType"
- "sizeBytes"
- "uploadedAt"
- "savedAt"
properties:
slot:
"$ref": "#/components/schemas/PhotoSlot"
category:
type: "string"
enum:
- "LOADING"
- "FUEL"
fileId:
type: "string"
fileName:
type: "string"
contentType:
type: "string"
enum:
- "image/jpeg"
- "image/png"
sizeBytes:
type: "string"
pattern: "^[1-9][0-9]*$"
uploadedAt:
type: "string"
savedAt:
type: "string"
nullable: true
format: "date-time"
description: "上传回执savedAt为空;绑定成功才填写savedAt。File类型分别为OVERSEAS_DISPATCH_LOADING_PHOTO和OVERSEAS_DISPATCH_FUEL_PHOTO,平台0、原dispatch内部ID,最多10MiB。"
PhotoSummary:
type: "object"
x-java-record: "OwnedBusinessModels.PhotoSummary"
required:
- "loadingCount"
- "fuelCount"
properties:
loadingCount:
type: "integer"
minimum: 0
fuelCount:
type: "integer"
minimum: 0
Row:
type: "object"
x-java-record: "OwnedBusinessModels.Row"
required:
- "dispatchNo"
- "stage"
- "plannedDepartureAt"
- "loadingCompletedAt"
- "departedAt"
- "deliveryCompletedAt"
- "origin"
- "vehicle"
- "driver"
- "destinations"
- "actualPalletCount"
- "operations"
- "unitPrice"
- "recordVersion"
- "dispatchRecordVersion"
- "photoSummary"
- "actions"
- "sourceIssues"
properties:
dispatchNo:
type: "string"
stage:
"$ref": "#/components/schemas/Stage"
plannedDepartureAt:
type: "string"
format: "date-time"
loadingCompletedAt:
type: "string"
format: "date-time"
departedAt:
type: "string"
nullable: true
format: "date-time"
deliveryCompletedAt:
type: "string"
nullable: true
format: "date-time"
origin:
"$ref": "#/components/schemas/Origin"
vehicle:
"$ref": "#/components/schemas/Vehicle"
driver:
"$ref": "#/components/schemas/Driver"
destinations:
type: "array"
items:
"$ref": "#/components/schemas/Destination"
actualPalletCount:
type: "integer"
minimum: 0
nullable: true
operations:
"$ref": "#/components/schemas/Operations"
unitPrice:
type: "string"
nullable: true
pattern: "^(0|[1-9][0-9]{0,15})(\\.[0-9]{1,2})?$"
recordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
dispatchRecordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
photoSummary:
"$ref": "#/components/schemas/PhotoSummary"
actions:
"$ref": "#/components/schemas/Actions"
sourceIssues:
type: "array"
items:
type: "string"
Summary:
type: "object"
x-java-record: "OwnedBusinessModels.Summary"
required:
- "dispatchCount"
- "afterLoadingCount"
- "deliveringCount"
- "deliveredCount"
properties:
dispatchCount:
type: "integer"
minimum: 0
afterLoadingCount:
type: "integer"
minimum: 0
deliveringCount:
type: "integer"
minimum: 0
deliveredCount:
type: "integer"
minimum: 0
ListResult:
type: "object"
x-java-record: "OwnedBusinessModels.ListResult"
required:
- "records"
- "page"
- "size"
- "total"
- "summary"
properties:
records:
type: "array"
items:
"$ref": "#/components/schemas/Row"
page:
type: "integer"
minimum: 1
size:
type: "integer"
minimum: 1
maximum: 200
total:
type: "integer"
minimum: 0
summary:
"$ref": "#/components/schemas/Summary"
Cargo:
type: "object"
x-java-record: "OwnedBusinessModels.Cargo"
required:
- "sourceKey"
- "customerId"
- "customerName"
- "orderNo"
- "inboundCode"
- "palletNo"
- "destinationKey"
- "packages"
properties:
sourceKey:
type: "string"
customerId:
type: "string"
customerName:
type: "string"
nullable: true
orderNo:
type: "string"
nullable: true
inboundCode:
type: "string"
nullable: true
palletNo:
type: "string"
destinationKey:
type: "string"
packages:
type: "string"
Detail:
type: "object"
x-java-record: "OwnedBusinessModels.Detail"
required:
- "row"
- "dispatch"
- "cargo"
- "photos"
properties:
row:
"$ref": "#/components/schemas/Row"
dispatch:
"$ref": "./overseas-business-v1.yaml#/components/schemas/DispatchDetail"
cargo:
type: "array"
items:
"$ref": "#/components/schemas/Cargo"
photos:
type: "array"
items:
"$ref": "#/components/schemas/Photo"
History:
type: "object"
x-java-record: "OwnedBusinessModels.History"
required:
- "eventSource"
- "recordVersion"
- "dispatchRecordVersion"
- "action"
- "operatorName"
- "occurredAt"
- "reason"
- "operations"
- "photos"
properties:
eventSource:
type: "string"
enum:
- "DISPATCH"
- "OPERATIONS"
recordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
nullable: true
dispatchRecordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
nullable: true
action:
type: "string"
operatorName:
type: "string"
nullable: true
occurredAt:
type: "string"
format: "date-time"
reason:
type: "string"
nullable: true
operations:
allOf:
-
"$ref": "#/components/schemas/Operations"
nullable: true
photos:
type: "array"
items:
"$ref": "#/components/schemas/Photo"
description: "UNION ALL读取原排车真实流水与附加流水,一次排序分页;DISPATCH事件recordVersion=null、operations=null、photos=[];OPERATIONS事件dispatchRecordVersion=null。"
HistoryPage:
type: "object"
x-java-record: "OwnedBusinessModels.HistoryPage"
required:
- "records"
- "page"
- "size"
- "total"
properties:
records:
type: "array"
items:
"$ref": "#/components/schemas/History"
page:
type: "integer"
minimum: 1
size:
type: "integer"
minimum: 1
maximum: 200
total:
type: "integer"
minimum: 0
Command:
type: "object"
x-java-record: "OwnedBusinessModels.Command"
required:
- "dispatchNo"
- "action"
- "idempotencyKey"
- "state"
- "recordVersion"
- "replayed"
- "result"
- "errorCode"
- "retryAllowed"
properties:
dispatchNo:
type: "string"
action:
type: "string"
enum:
- "SAVE_OPERATIONS"
- "UPLOAD_PHOTO"
- "BIND_PHOTO"
idempotencyKey:
type: "string"
state:
type: "string"
enum:
- "SUCCEEDED"
- "PENDING"
- "UNKNOWN_RESULT"
- "REJECTED"
recordVersion:
type: "string"
pattern: "^(0|[1-9][0-9]*)$"
nullable: true
replayed:
type: "boolean"
result:
nullable: true
oneOf:
-
"$ref": "#/components/schemas/Detail"
-
"$ref": "#/components/schemas/Photo"
errorCode:
type: "string"
nullable: true
retryAllowed:
type: "boolean"
enum:
- false
@@ -48,13 +48,14 @@ paths:
available: {type: boolean}
/api/platform/v1/last-leg/fleet/trips/calendar:
get:
summary: 读取美国车次用车日历来源
summary: 读取美国真实整车排车日历来源
description: >-
仅PLATFORM且平台公共主体(tenantId=0),权限 platform:fleet:trip:list。from/to 是明确UTC时间点,已发车按实际发车时间、尚未发车按计划发车时间读取半开区间,最多44天;
仅PLATFORM且平台公共主体(tenantId=0),权限 platform:overseas-warehouse:dispatch:list,与排车列表及详情一致。from/to 是明确UTC时间点,已发车按实际发车时间、尚未发车按计划发车时间读取半开区间,最多44天;
该保护性窗口供界面最多42个当地日历日加时区边界使用,不扩大界面范围。
仅出库派送用途(DELIVERY);上门取货入仓用途(PICKUP)不属于此日历排车来源。
最多2000条候选,超限明确拒绝并要求缩小日期范围,不分页扫描、不静默截断。
一车一条,保留取消及完成状态;保留原计划与实际时间,已执行事实不随计划改期移动,不表示收货预约已确认。
仅关联ll_dispatch_order中ACTIVE真实主单,返回dispatchNo;独立旧车次和取消排车主单排除,一张排车主单一条。
保留原计划与实际时间,已执行事实不随计划改期移动,不表示收货预约已确认;日历跳排车详情,不使用内部车次号拼排车路径。
已知非美国仓排除;未知仓库/国家/地理IANA时区进入unresolvedRecords,不落入美国当地日槽。
一次车次查询加一次仓库批量资料请求,包含停用仓历史资料,资料服务失败返回错误而非空日历。
parameters:
@@ -358,10 +359,10 @@ components:
schemas:
TripCalendarEntry:
type: object
required: [sourceType, tripNo, status, plannedDepartureAt, expectedDriverEndAt, stops, incompleteReasons]
required: [sourceType, dispatchNo, status, plannedDepartureAt, expectedDriverEndAt, stops, incompleteReasons]
properties:
sourceType: {type: string, enum: [TRIP_PLAN]}
tripNo: {type: string}
sourceType: {type: string, enum: [DISPATCH]}
dispatchNo: {type: string, description: 真实整车主单排车号,用于排车详情路由}
status: {type: string, enum: [PLANNED, IN_TRANSIT, COMPLETED, CANCELLED]}
originWarehouseId: {type: string, nullable: true}
originWarehouseCode: {type: string, nullable: true}
@@ -4,6 +4,17 @@ info:
version: 1.0.0
description: 全部筛选结果汇总,不受 page/size 影响。件、箱、SKU分别统计;未知不能解释为零,禁止固定箱规换算。
paths:
/api/platform/v1/last-leg/relabel-applications/inventory-candidates:
get:
operationId: platformRelabelInventoryCandidates
description: 平台代客创建候选;权限platform:overseas-warehouse:relabel:create。客户和公共作业仓均必须显式选择,返回与客户创建端相同的InventoryCandidate结构。
parameters:
- {name: customerId, in: query, required: true, schema: {type: string}}
- {name: operationWarehouseId, in: query, required: true, schema: {type: string}}
- {name: inboundCode, in: query, schema: {type: string}}
responses:
'200':
description: 标准ApiResponse,data为正式库存候选数组;普通库存包含inventoryBalanceId/inboundOrderId/positions,退货包含returnCartonId/cartonMark/cartonSkuItems/cartonAvailablePackages。所有Long ID为十进制字符串。
/api/platform/v1/last-leg/relabel-applications/quantity-summary:
get:
operationId: platformRelabelQuantitySummary
@@ -61,12 +72,16 @@ components:
type: object
required: [orderCount, skuCount, knownLabelPieceCount, unknownPieceOrders, knownCartonCount, unknownCartonOrders, orders]
properties:
orderCount: {type: integer, format: int64, minimum: 0}
skuCount: {type: integer, format: int64, minimum: 0, description: 全部筛选结果的不同旧SKU数}
knownLabelPieceCount: {type: integer, format: int64, minimum: 0}
unknownPieceOrders: {type: integer, format: int64, minimum: 0}
knownCartonCount: {type: integer, format: int64, minimum: 0}
unknownCartonOrders: {type: integer, format: int64, minimum: 0}
orderCount: {type: string, pattern: '^[0-9]+$'}
skuCount: {type: string, pattern: '^[0-9]+$', description: 全部筛选结果的不同旧SKU数}
knownLabelPieceCount: {type: string, pattern: '^[0-9]+$'}
unknownPieceOrders: {type: string, pattern: '^[0-9]+$'}
knownCartonCount: {type: string, pattern: '^[0-9]+$'}
unknownCartonOrders: {type: string, pattern: '^[0-9]+$'}
knownSourcePalletCount: {type: string, pattern: '^[0-9]+$', description: 已知完整原托快照按仓库和托盘码在全部筛选单据间去重}
unknownSourcePalletOrders: {type: string, pattern: '^[0-9]+$'}
knownTargetPalletCount: {type: string, pattern: '^[0-9]+$', description: 本轮完整目标快照按仓库和托盘码去重;返工旧轮目标不计}
unknownTargetPalletOrders: {type: string, pattern: '^[0-9]+$'}
orders:
type: object
description: 以换标业务单号为键,覆盖全部筛选单据
@@ -74,10 +89,15 @@ components:
Quantity:
type: object
properties:
labelPieceCount: {type: integer, format: int64, nullable: true, description: 按件任务采用通知件数;箱任务采用SKU子项件数;重复关联或缺失为null}
cartonCount: {type: integer, format: int64, nullable: true, description: 箱级任务按箱唛去重;按件来源标识不作为箱数}
labelPieceCount: {type: string, pattern: '^[0-9]+$', nullable: true, description: 按件任务采用通知件数;箱任务采用SKU子项件数;重复关联或缺失为null}
cartonCount: {type: string, pattern: '^[0-9]+$', nullable: true, description: 箱级任务按箱唛去重;按件任务仅在全部精确来源快照都是BOX时按来源主键去重,PALLET/PARCEL不冒充箱数}
skuCount: {type: integer, minimum: 0}
duplicateCarton: {type: boolean, description: 历史重复任务关联提示,不将同一来源不同SKU按件任务视为重复}
quantityUnit: {type: string, enum: [PIECE, CARTON, UNKNOWN]}
sourcePalletCount: {type: integer, format: int64, nullable: true, description: 缺少不可变原托快照时为null}
targetPalletCount: {type: integer, format: int64, nullable: true, description: 未提供汇总,详情以本轮有效绑定历史为准}
sourcePalletCount: {type: string, pattern: '^[0-9]+$', nullable: true, description: 缺少不可变原托快照时为null}
targetPalletCount: {type: string, pattern: '^[0-9]+$', nullable: true, description: 每个任务本轮最后一次可信绑定的不同目标托盘数;未绑定完整为null}
sourceUnitCounts:
type: object
nullable: true
description: 首次认领时已清点且精确关联的退货来源主键按BOX/PARCEL/PALLET分类去重;任一来源缺失时为null,不按标识外形猜测
additionalProperties: {type: string, pattern: '^[0-9]+$'}
@@ -0,0 +1,60 @@
openapi: 3.0.3
info:
title: 退货全筛选统计与托盘无效果恢复
version: 1.0.0
paths:
/api/merchant/v1/last-leg/return-orders/statistics:
get:
summary: 当前客户退货全筛选统计
description: 使用与退货分页列表一致的 returnNo、status、skuCode、trackingNo 条件。客户由认证身份确定,忽略客户端归属输入。totals 不受 page/size 影响;pageDimensions 仅对应当前页。SKU 跨订单按去空白大写后的编码去重。件、箱、包裹、托独立统计;未提供的预报载体数不推算为零。需要 MERCHANT_RETURN_ORDER_LIST 对应正式权限。
operationId: merchantReturnOrderStatistics
responses:
'200':
description: ApiResponse,data 为 totals 与 pageDimensions;失败按统一响应契约返回。
/api/platform/v1/last-leg/return-orders/statistics:
get:
summary: 尾程筛选集合中原生退货订单的统计
description: 需要 platform:overseas-warehouse:last-mile-order:list。完整复用尾程列表筛选;totals 只聚合其中有原生退货记录的订单。pageDimensions 对应混合尾程列表当前页中的退货行,不单独分页退货子集。实收载体来自签收事实,出库不扣减历史签收数量。
operationId: platformReturnOrderStatistics
responses:
'200':
description: ApiResponse,data 为 totals 与 pageDimensions。
/api/platform/v1/last-leg/pallet-operation-recoveries/{id}:
parameters:
- in: path
name: id
required: true
schema: { type: integer, format: int64 }
get:
summary: 管理员只读核对原托盘作业
description: 需要 lastleg:inventory:manage,返回原状态、请求哈希、远端意图、原错误和更新时间,不返回会话凭据。
operationId: inspectPalletOperationRecovery
responses:
'200': { description: 原作业技术审计状态 }
/api/platform/v1/last-leg/pallet-operation-recoveries/{id}/close-no-effect:
parameters:
- in: path
name: id
required: true
schema: { type: integer, format: int64 }
post:
summary: 审计关闭无远端效果的超时换标组托
description: 需要 lastleg:inventory:manage。仅 RELABEL_PALLET_DISASSEMBLE、PROCESSING 或 FAILED_COMPENSATED、超过15分钟、版本一致、无结果且无任何远端意图允许关闭。未知/已确认/损坏远端记录均拒绝。原行行锁与远端意图条件写互斥;旧线程失败写不能覆盖恢复终态。原请求哈希及原错误不变,恢复管理员、原因、幂等键、原状态和时间写入原 result_json。相同管理员/键/原因重放返回同一审计,不另造业务成功结果。无需新增表,不写库存或远端实托。
operationId: closePalletOperationNoEffect
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [warehouseId, expectedUpdatedAt, idempotencyKey, reason]
properties:
warehouseId: { type: integer, format: int64, minimum: 1 }
expectedUpdatedAt: { type: string, format: date-time }
idempotencyKey: { type: string, minLength: 1, maxLength: 255 }
reason: { type: string, minLength: 1, maxLength: 1000 }
responses:
'200': { description: ApiResponse 恢复审计或正式业务拒绝 }
'403': { description: 权限不足 }
'404': { description: 原作业不存在 }
'409': { description: 原状态、版本、归属或远端效果不满足恢复条件 }
@@ -0,0 +1,120 @@
openapi: 3.0.3
info:
title: 仓储转运与混箱库存数量
version: 1.0.0
description: 件、箱、托分开记录。所有Long数量序列化为十进制字符串;未知件数保持null,空筛选返回零。同托部分出库可同时属于历史实收、剩余、出库集合,禁止托数相减。
paths:
/api/platform/v1/last-leg/orders/warehouse-transfer-quantities:
get:
operationId: platformWarehouseTransferQuantityTotals
description: 权限platform:overseas-warehouse:last-mile-order:list,平台访问域与主订单列表一致。复用主订单全部Query筛选及relabelNo,额外限定WAREHOUSE_TRANSFER;page/size不参与汇总。
responses:
'200':
description: ApiResponse.data为TransferQuantityTotals。
content:
application/json:
schema: { $ref: '#/components/schemas/TotalsEnvelope' }
/api/merchant/v1/last-leg/warehouse-transfers/quantities:
get:
operationId: merchantWarehouseTransferQuantityTotals
description: 权限merchant:overseas-warehouse:transfer:list,客户范围只从会话获取。复用转运列表完整筛选,包括transferNo/inboundCode/operatingWarehouseId/fbaWarehouseCode/status/needRelabel和创建、审核、清点完成、出库日期区间;日期区间上界包含端点。page/size不参与汇总。
responses:
'200':
description: ApiResponse.data为TransferQuantityTotals。
content:
application/json:
schema: { $ref: '#/components/schemas/TotalsEnvelope' }
/api/platform/v1/last-leg/inventory/piece-projection:
get:
operationId: platformInventoryPieceProjection
description: 权限platform:overseas-warehouse:inventory:list,与库存列表相同平台客户访问域及BalanceQuery完整筛选,不分页。按原箱清点及正式目的仓签收凭据投影当前未占用可用库存。每仓位精确箱映射数量须等于available_packages,箱内SKU件数须等于箱总清点件数;缺失、不一致、无法追溯的非转运库存均为未知,不按箱规或首SKU推算。通用余额MIXED也逐箱读取全部SKU。SKU查询可命中混箱第二SKU。
responses:
'200':
description: ApiResponse.data为InventoryPieceProjection。
content:
application/json:
schema:
type: object
properties:
code: { type: string }
data: { $ref: '#/components/schemas/InventoryPieceProjection' }
components:
schemas:
Count:
type: string
pattern: '^[0-9]+$'
NullableCount:
type: string
nullable: true
pattern: '^[0-9]+$'
TransferQuantityView:
type: object
description: 主订单列表与详情summary.warehouseTransferQuantity,仅转运订单提供。新到仓历史实收取counted_at非空且COUNTED/DISCARD_PENDING/DISCARDED/SHIPPED原箱;库存转运实收取正式目的仓签收凭据,件数取精确原箱清点。
properties:
lastlegOrderId: { $ref: '#/components/schemas/Count' }
declaredPieceCount: { $ref: '#/components/schemas/NullableCount' }
receivedPieceCount: { $ref: '#/components/schemas/NullableCount' }
declaredCartonCount: { $ref: '#/components/schemas/Count' }
receivedCartonCount: { $ref: '#/components/schemas/Count' }
receivedPalletCount: { $ref: '#/components/schemas/Count' }
availableCartonCount: { type: string, description: 原箱当前COUNTED数,非扣除其他业务预留后的可用库存。真实可用数读取库存投影。 }
shippedCartonCount: { $ref: '#/components/schemas/Count' }
remainingPalletCount: { $ref: '#/components/schemas/Count' }
shippedPalletCount: { $ref: '#/components/schemas/Count' }
TransferQuantityTotals:
allOf:
- { $ref: '#/components/schemas/TransferQuantityView' }
- type: object
properties:
orderCount: { $ref: '#/components/schemas/Count' }
knownDeclaredPieceCount: { $ref: '#/components/schemas/Count' }
unknownDeclaredOrderCount: { $ref: '#/components/schemas/Count' }
knownReceivedPieceCount: { $ref: '#/components/schemas/Count' }
unknownReceivedOrderCount: { $ref: '#/components/schemas/Count' }
TotalsEnvelope:
type: object
properties:
code: { type: string }
data: { $ref: '#/components/schemas/TransferQuantityTotals' }
Sku:
type: object
properties:
skuCode: { type: string }
quantity: { $ref: '#/components/schemas/Count' }
InventoryPieceProjection:
type: object
properties:
availablePieceCount: { $ref: '#/components/schemas/NullableCount' }
knownAvailablePieceCount: { $ref: '#/components/schemas/Count' }
unknownCartonCount: { $ref: '#/components/schemas/Count' }
availableCartonCount: { $ref: '#/components/schemas/Count' }
availablePalletCount: { $ref: '#/components/schemas/Count' }
groups:
type: array
items:
type: object
properties:
customerId: { type: string }
warehouseId: { type: string }
destinationCode: { type: string, nullable: true }
anchorSkuCode: { type: string, nullable: true, description: 原余额记账SKU,可能为MIXED。完整SKU在skuContents中。 }
availablePieceCount: { $ref: '#/components/schemas/NullableCount' }
knownAvailablePieceCount: { $ref: '#/components/schemas/Count' }
unknownCartonCount: { $ref: '#/components/schemas/Count' }
availableCartonCount: { $ref: '#/components/schemas/Count' }
availablePalletCount: { $ref: '#/components/schemas/Count' }
skuContents:
type: array
items: { $ref: '#/components/schemas/Sku' }
cartons:
type: array
items:
type: object
properties:
cartonMark: { type: string }
inventoryPositionId: { type: string }
palletId: { type: string, nullable: true }
quantity: { $ref: '#/components/schemas/NullableCount' }
items:
type: array
items: { $ref: '#/components/schemas/Sku' }
@@ -0,0 +1,118 @@
package com.baiyue.lastleg.delivery.service;
import com.baiyue.lastleg.delivery.dto.DeliveryRequests;
import com.baiyue.lastleg.delivery.entity.*;
import com.baiyue.lastleg.delivery.mapper.*;
import com.baiyue.lastleg.inventory.command.dto.InventoryCommandRequests;
import com.baiyue.lastleg.inventory.command.service.InventoryCommandService;
import com.baiyue.lastleg.inventory.entity.*;
import com.baiyue.lastleg.inventory.mapper.*;
import com.baiyue.lastleg.relabel.entity.*;
import com.baiyue.lastleg.relabel.mapper.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.*;
import org.junit.jupiter.api.*;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.server.ResponseStatusException;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.mockito.ArgumentMatchers.*;
class RelabelOutboundPickingTest {
private DeliveryTransferService service;
private InventoryCommandService commands;
private InventoryPosition position;
private InventoryBalance balance;
private OutboundPalletItem item;
private OutboundPdaPickMapper picks;
private OutboundPdaTaskMapper tasks;
private OutboundOrderMapper orders;
private OutboundPalletItemMapper pallets;
private InventoryPositionMapper positions;
private InventoryBalanceMapper balances;
private RelabelApplicationMapper applications;
private RelabelItemMapper items;
/** 构造返工后新目标位:两箱冻结,账面混合SKU,与空出库SKU不作通配匹配。 */
@BeforeEach void prepare() {
service = new DeliveryTransferService(); commands = mock(InventoryCommandService.class);
picks=mock(OutboundPdaPickMapper.class); tasks=mock(OutboundPdaTaskMapper.class);
orders=mock(OutboundOrderMapper.class); pallets=mock(OutboundPalletItemMapper.class);
positions=mock(InventoryPositionMapper.class); balances=mock(InventoryBalanceMapper.class);
applications=mock(RelabelApplicationMapper.class); items=mock(RelabelItemMapper.class);
Map.of("inventoryCommands",commands,"pdaPicks",picks,"pdaTasks",tasks,"outboundOrders",orders,
"outboundPallets",pallets,"inventoryPositions",positions,"inventoryBalances",balances,
"relabelApplications",applications,"relabelItems",items,"objectMapper",new ObjectMapper())
.forEach((name,value)->ReflectionTestUtils.setField(service,name,value));
var outbound=new OutboundOrder(); outbound.setId(1L); outbound.setCustomerId("C");
outbound.setOverseasWarehouseId("W"); outbound.setOutboundNo("OUT"); outbound.setOutboundType("RELABEL_OUTBOUND");
var task=new OutboundPdaTask(); task.setId(2L); task.setCustomerId("C"); task.setOutboundOrderId(1L);
task.setTaskNo("TASK"); task.setStatus("PENDING");
item=new OutboundPalletItem(); item.setId(3L); item.setCustomerId("C"); item.setOutboundOrderId(1L);
item.setWarehousePalletId(4L); item.setPalletNo("NEW-TARGET"); item.setInboundCode("IN");
item.setPackageCount(2); item.setPickedPackageCount(0); item.setCartonMarks("BOX-A,BOX-B");
item.setOrderRefs("""
{"sourceType":"RELABEL_ORDER","relabelNo":"RL","sourceInventoryPositionId":9,
"items":[{"itemId":11,"cartonMark":"BOX-A","packages":1},{"itemId":12,"cartonMark":"BOX-B","packages":1}]}
""");
position=new InventoryPosition(); position.setId(9L); position.setCustomerId("C"); position.setBalanceId(8L);
position.setOverseasWarehouseId("W"); position.setPalletId(4L); position.setPalletNo("NEW-TARGET");
position.setAvailablePackages(0L); position.setHoldPackages(2L);
balance=new InventoryBalance(); balance.setId(8L); balance.setCustomerId("C");
balance.setOverseasWarehouseId("W"); balance.setInboundCode("IN"); balance.setSkuCode("MIXED");
when(tasks.lockByNoAndWarehouse("TASK","W")).thenReturn(task);
when(tasks.findByNoAndWarehouse("TASK","W")).thenReturn(task);
when(orders.selectById(1L)).thenReturn(outbound); when(orders.lockByNo("C","OUT")).thenReturn(outbound);
when(pallets.findByOutbound("C",1L)).thenReturn(List.of(item)); when(pallets.selectById(3L)).thenReturn(item);
when(positions.listPallet("C",4L)).thenReturn(List.of(position)); when(positions.selectById(9L)).thenReturn(position);
when(balances.selectById(8L)).thenReturn(balance);
var app=new RelabelApplication(); app.setId(10L); app.setRelabelNo("RL"); app.setStatus("READY_FOR_OUTBOUND");
when(applications.lockByOutbound("C","OUT")).thenReturn(app);
var first=new RelabelItem(); first.setId(11L); first.setCartonMark("BOX-A"); first.setNotifiedPackageCount(1);
var second=new RelabelItem(); second.setId(12L); second.setCartonMark("BOX-B"); second.setNotifiedPackageCount(1);
when(items.selectList(any())).thenReturn(List.of(first,second));
}
/** 指定箱从冻结到出库数量守恒;整托重扫不重复释放或出库。 */
@Test void picksExactFrozenBoxesAndReplayDoesNotShipAgain() {
assertEquals(List.of("BOX-A","BOX-B"),service.pdaTaskDetail("W","TASK").items().get(0).positions()
.stream().map(value->value.cartonMark()).toList());
service.pdaPickPallet("W","U","TASK","NEW-TARGET",new DeliveryRequests.PdaPalletPick("KEY"));
service.pdaPickPallet("W","U","TASK","NEW-TARGET",new DeliveryRequests.PdaPalletPick("KEY"));
var release=org.mockito.ArgumentCaptor.forClass(InventoryCommandRequests.Move.class);
verify(commands,times(2)).release(eq("C"),eq("U"),release.capture());
assertEquals(2,release.getAllValues().stream().mapToLong(InventoryCommandRequests.Move::packages).sum());
assertTrue(release.getAllValues().stream().allMatch(move->move.positionId()==9L&&"RELABEL:RL".equals(move.sourceEventId())));
var shipped=org.mockito.ArgumentCaptor.forClass(InventoryCommandRequests.Move.class);
verify(commands).ship(eq("C"),eq("U"),shipped.capture());
assertEquals(2,shipped.getValue().packages()); assertEquals(9L,shipped.getValue().positionId());
verify(commands).allocate(eq("C"),eq("U"),any()); verify(commands).pick(eq("C"),eq("U"),any());
verify(picks).insert(any(OutboundPdaPick.class)); assertEquals(2,item.getPickedPackageCount());
}
/** 其他位置、客户、仓、入仓或不足冻结均拒绝,不能用空SKU放宽范围。 */
@ParameterizedTest @ValueSource(strings={"POSITION","CUSTOMER","WAREHOUSE","INBOUND","HOLD","SNAPSHOT"})
void rejectsUnrelatedOrIncompleteSourcesWithoutInventoryEffects(String invalid) {
switch(invalid) {
case "POSITION" -> position.setId(99L);
case "CUSTOMER" -> balance.setCustomerId("OTHER");
case "WAREHOUSE" -> position.setOverseasWarehouseId("OTHER");
case "INBOUND" -> balance.setInboundCode("OTHER");
case "HOLD" -> position.setHoldPackages(1L);
case "SNAPSHOT" -> item.setOrderRefs("{\"sourceType\":\"RELABEL_ORDER\"}");
}
assertTrue(service.pdaTaskDetail("W","TASK").items().get(0).positions().isEmpty());
assertThrows(ResponseStatusException.class,()->service.pdaPickPallet("W","U","TASK","NEW-TARGET",new DeliveryRequests.PdaPalletPick("KEY")));
verifyNoInteractions(commands,picks);
}
/** 同箱唛也不能代替来源任务主键,损坏ID必须在释放冻结前拒绝。 */
@Test void rejectsWrongSnapshotItemIdBeforeReleasingAnyStock() {
item.setOrderRefs(item.getOrderRefs().replace("\"itemId\":11", "\"itemId\":999"));
assertEquals(2,service.pdaTaskDetail("W","TASK").items().get(0).positions().size());
assertThrows(ResponseStatusException.class,()->service.pdaPickPallet("W","U","TASK","NEW-TARGET",new DeliveryRequests.PdaPalletPick("KEY")));
verifyNoInteractions(commands); verify(picks,never()).insert(any(OutboundPdaPick.class));
}
}

Some files were not shown because too many files have changed in this diff Show More