Compare commits
11
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7c6a3af473 | ||
|
|
03a7e66fab | ||
|
|
6f31fa2131 | ||
|
|
da6b4685d7 | ||
|
|
e0c0316487 | ||
|
|
bf2508b6d6 | ||
|
|
a870b920fe | ||
|
|
19745e46c1 | ||
|
|
e829519044 | ||
|
|
6fa5d281ec | ||
|
|
16ac817524 |
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
+1
-2
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责边界
|
||||
|
||||
|
||||
@@ -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,7 @@
|
||||
# 单测试环境数据库空库初始化
|
||||
|
||||
客户计费重独立确认新增 `fl_chargeable_weight_confirmation`,源表与国内空库基线同步;存量 TEST 使用 `migrations/cn/baiyue_firstleg/V8__chargeable_weight_confirmation.sql`,不回填费用确认。须随 Firstleg、Order、Lastleg、Admin 和 Client 匹配版本核对;本次未执行 SQL、未部署。
|
||||
|
||||
费用项目默认价格结构:Firstleg 源基线 `phase2-fee-item-and-inbound-detail.sql` 与国内统一空库基线均增加可空的 `fl_fee_item.default_price DECIMAL(12,2)`。字段业务规则见工作区 `docs/入库测量与计费/README.md`;需与匹配的 Firstleg 和 Admin 一起发布。本次仅修改基线,不表示 SQL 已执行,也不能向已有测试库重放空库脚本。
|
||||
|
||||
排车整车作业结构同步于 Lastleg 源基线及海外统一空库基线:整车主单移除客户头部,真实客户归属保留在货物、出库、派送和费用;新增公共命令账本、主单历史、派送安排及签收待汇总信号。空排车的计划时间可暂缺,提交审核前由业务校验补齐;`ll_dispatch_physical_pallet_lock` 独立保存无代表客户的实托排他占用,`ll_dispatch_pallet_lock.physical_lock_id` 关联逐客户逻辑来源,同车可共享、跨主单或草稿容器仍排他。`ll_dispatch_item` 按主单和完整来源键唯一,`ll_dispatch_item_source` 冻结换标明细的实际位置、绑定箱数、真实件数(未知为空)及原货源事实;拣货归属新增 `dispatch_item_source_id`,与实收、退回实收、原生退货箱三类凭据四者互斥,不伪造普通收货凭据。智能草稿按拥有者、起运仓和版本维护,一容器转换一整车;独立草稿命令保存原请求和结果。必须与匹配的 Lastleg、IAM、File、Admin 和 PDA 一起核对,空库脚本不能向已有 TEST 重放。本条仅说明代码基线,不表示 SQL 已执行、已部署或全流程已验收;唯一业务规则见工作区 `docs/海外仓业务/排车列表统一作业改造契约.md`。
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
-- 仅为已初始化的头程库新增独立确认历史;不回填费用确认,不修改订单事实。
|
||||
-- 由单 schema 执行器选择 baiyue_firstleg,不在迁移内部切库。
|
||||
-- 客户独立确认计费重,不回填既有费用确认。
|
||||
CREATE TABLE IF NOT EXISTS fl_chargeable_weight_confirmation (
|
||||
id BIGINT NOT NULL COMMENT '确认记录ID',
|
||||
tenant_id BIGINT NOT NULL COMMENT '客户隔离ID',
|
||||
inbound_id BIGINT NOT NULL COMMENT '独立来源入仓单ID',
|
||||
operator_id BIGINT NOT NULL COMMENT '确认客户成员ID',
|
||||
command_key VARCHAR(128) NOT NULL COMMENT '成员确认幂等键',
|
||||
fingerprint CHAR(64) NOT NULL COMMENT '计费重及测量轮次摘要',
|
||||
chargeable_weight_kg DECIMAL(18,4) NOT NULL COMMENT '客户确认计费重千克',
|
||||
confirmed_at DATETIME(3) NOT NULL COMMENT '客户确认时间',
|
||||
PRIMARY KEY(id), UNIQUE KEY uk_weight_confirmation_command(tenant_id,operator_id,command_key),
|
||||
KEY idx_weight_confirmation_inbound(tenant_id,inbound_id,id)
|
||||
) ENGINE=InnoDB COMMENT='客户计费重独立确认历史';
|
||||
+1
-3
@@ -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;
|
||||
|
||||
@@ -4437,6 +4437,20 @@ CREATE TABLE fl_inbound_split_item (
|
||||
|
||||
SET SESSION foreign_key_checks = 1;
|
||||
|
||||
-- 客户独立确认计费重,不回填既有费用确认。
|
||||
CREATE TABLE fl_chargeable_weight_confirmation (
|
||||
id BIGINT NOT NULL COMMENT '确认记录ID',
|
||||
tenant_id BIGINT NOT NULL COMMENT '客户隔离ID',
|
||||
inbound_id BIGINT NOT NULL COMMENT '独立来源入仓单ID',
|
||||
operator_id BIGINT NOT NULL COMMENT '确认客户成员ID',
|
||||
command_key VARCHAR(128) NOT NULL COMMENT '成员确认幂等键',
|
||||
fingerprint CHAR(64) NOT NULL COMMENT '计费重及测量轮次摘要',
|
||||
chargeable_weight_kg DECIMAL(18,4) NOT NULL COMMENT '客户确认计费重千克',
|
||||
confirmed_at DATETIME(3) NOT NULL COMMENT '客户确认时间',
|
||||
PRIMARY KEY(id), UNIQUE KEY uk_weight_confirmation_command(tenant_id,operator_id,command_key),
|
||||
KEY idx_weight_confirmation_inbound(tenant_id,inbound_id,id)
|
||||
) ENGINE=InnoDB COMMENT='客户计费重独立确认历史';
|
||||
|
||||
-- 服务 schema:baiyue_file
|
||||
CREATE DATABASE IF NOT EXISTS baiyue_file DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;
|
||||
USE baiyue_file;
|
||||
@@ -8371,4 +8385,4 @@ INSERT INTO iam_role_permission (role_id, permission_id, tenant_id, created_at)
|
||||
INSERT INTO iam_permission (id, tenant_id, app_code, permission_type, parent_id, permission_code, permission_name, route_path, http_method, sort_no, status, built_in, created_at, updated_at, deleted) VALUES (5102213,0,'PLATFORM','BUTTON',5102200,'platform:firstleg:terminal-drayage:direct-unload:confirm','登记直送目的仓实际卸货',NULL,'POST',60,'ACTIVE',1,CURRENT_TIMESTAMP(3),CURRENT_TIMESTAMP(3),0);
|
||||
INSERT INTO iam_role_permission (role_id, permission_id, tenant_id, created_at) VALUES (4000001,5102213,0,CURRENT_TIMESTAMP(3));
|
||||
|
||||
SELECT 'PASS' AS initialization_status, 'CN' AS region, 227 AS initialized_tables;
|
||||
SELECT 'PASS' AS initialization_status, 'CN' AS region, 228 AS initialized_tables;
|
||||
|
||||
@@ -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;
|
||||
|
||||
+1
-2
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
|
||||
+1
-2
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 模块定位
|
||||
|
||||
|
||||
+18
@@ -157,6 +157,24 @@ public class InternalInboundOrderController {
|
||||
return ApiResponse.success(workbenchFilters.read(request));
|
||||
}
|
||||
|
||||
/** 当前页摘要继续应用原筛选,防止父子或分片入库投影错配。 */
|
||||
@PostMapping("/unified-orders/status-summaries")
|
||||
public ApiResponse<List<UnifiedInboundSummary>> unifiedStatusSummaries(
|
||||
@RequestHeader(value = "X-Internal-Service-Token", required = false) String token,
|
||||
@Valid @RequestBody UnifiedInboundQuery request) {
|
||||
requireToken(token);
|
||||
return ApiResponse.success(unifiedQueryService.statusSummaries(request));
|
||||
}
|
||||
|
||||
/** 服务令牌保护的轻量状态投影,供 Order 统计和分页校正。 */
|
||||
@PostMapping("/unified-orders/status-rows")
|
||||
public ApiResponse<List<UnifiedInboundQueryService.StatusRow>> unifiedStatusRows(
|
||||
@RequestHeader(value = "X-Internal-Service-Token", required = false) String token,
|
||||
@Valid @RequestBody UnifiedInboundQuery request) {
|
||||
requireToken(token);
|
||||
return ApiResponse.success(unifiedQueryService.statusRows(request));
|
||||
}
|
||||
|
||||
@PostMapping("/unified-orders/query")
|
||||
public ApiResponse<PageResult<UnifiedInboundSummary>> unifiedPage(
|
||||
@RequestHeader(value = "X-Internal-Service-Token", required = false) String token,
|
||||
|
||||
+5
-5
@@ -140,7 +140,7 @@ public class PlatformContainerController {
|
||||
public ApiResponse<BusinessDocument> clearance(@AuthenticationPrincipal AuthenticatedUser user,
|
||||
@PathVariable @Positive long id) {
|
||||
FirstlegScopeGuard.platform(user);
|
||||
service.requireOverseas(id);
|
||||
service.requireClearanceAccess(id);
|
||||
return ApiResponse.success(loadingLists.containerClearance(id));
|
||||
}
|
||||
|
||||
@@ -151,7 +151,7 @@ public class PlatformContainerController {
|
||||
@AuthenticationPrincipal AuthenticatedUser user, @PathVariable @Positive long id,
|
||||
@PathVariable @Positive long fileId) {
|
||||
FirstlegScopeGuard.platform(user);
|
||||
service.requireOverseas(id);
|
||||
service.requireClearanceAccess(id);
|
||||
var download = loadingLists.downloadContainerClearance(id, fileId);
|
||||
return ResponseEntity.ok().cacheControl(CacheControl.noStore())
|
||||
.header(HttpHeaders.CONTENT_DISPOSITION, org.springframework.http.ContentDisposition.attachment()
|
||||
@@ -168,7 +168,7 @@ public class PlatformContainerController {
|
||||
@RequestHeader("Idempotency-Key") String key,
|
||||
@Valid @RequestBody DocumentAttachRequest request) {
|
||||
FirstlegScopeGuard.platform(user);
|
||||
service.requireOverseas(id);
|
||||
service.requireClearanceAccess(id);
|
||||
return ApiResponse.success(loadingLists.attachContainerClearance(
|
||||
id, user.userId(), user.username(), key, request));
|
||||
}
|
||||
@@ -183,7 +183,7 @@ public class PlatformContainerController {
|
||||
@RequestParam("expectedVersion") @Min(0) int expectedVersion,
|
||||
@RequestParam(value = "operationReason", required = false) @Size(max = 500) String operationReason) {
|
||||
FirstlegScopeGuard.platform(user);
|
||||
service.requireOverseas(id);
|
||||
service.requireClearanceAccess(id);
|
||||
return ApiResponse.success(loadingLists.uploadContainerClearance(
|
||||
id, user.userId(), user.username(), key, expectedVersion, operationReason, file));
|
||||
}
|
||||
@@ -196,7 +196,7 @@ public class PlatformContainerController {
|
||||
@RequestHeader("Idempotency-Key") String key,
|
||||
@Valid @RequestBody DocumentCompleteRequest request) {
|
||||
FirstlegScopeGuard.platform(user);
|
||||
service.requireOverseas(id);
|
||||
service.requireClearanceAccess(id);
|
||||
return ApiResponse.success(loadingLists.completeContainerClearance(
|
||||
id, user.userId(), user.username(), key, request));
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public record UnifiedInboundQuery(
|
||||
@Size(max = 64) String keyword,
|
||||
@Size(max = 64) String orderNo,
|
||||
@Schema(allowableValues = {"PENDING_REVIEW", "WAIT_MEASURE", "WAIT_PALLETIZE", "WAIT_SPLIT",
|
||||
"LOADING", "LOADED", "DELIVERED"})
|
||||
"LOADING", "LOADED", "DELIVERED", "WAIT_WEIGHT_CONFIRM", "WEIGHT_CONFIRMED", "WAIT_CUSTOMS_DOCS", "EXPORT_CUSTOMS", "SAILING_CLEARANCE", "WAIT_UNLOAD", "WAIT_DISPATCH", "OUTBOUND_DOCUMENT", "DELIVERING", "SIGNED", "MEASUREMENT_REVIEW"})
|
||||
@Size(max = 32) String mainStatus,
|
||||
Long customerId,
|
||||
Long receivingWarehouseId,
|
||||
|
||||
@@ -158,6 +158,14 @@ public interface ContainerBookingMapper extends BaseMapper<ContainerBookingEntit
|
||||
""")
|
||||
int hasActiveOutboundDeparture(@Param("id") long id);
|
||||
|
||||
/** 手动或拉取的实际开船节点均可作为清关资料入口依据。 */
|
||||
@Select("""
|
||||
SELECT COUNT(1) FROM fl_carrier_schedule_node_fact
|
||||
WHERE container_booking_id=#{id} AND standard_node='DEPARTED_ORIGIN_PORT'
|
||||
AND actual_at IS NOT NULL
|
||||
""")
|
||||
int hasActualVesselDeparture(@Param("id") long id);
|
||||
|
||||
@Update("""
|
||||
UPDATE fl_container_booking SET pickup_code=#{pickupCode},pickup_code_updated_by=#{operatorId},
|
||||
pickup_code_updated_by_name=#{operatorName},pickup_code_updated_at=CURRENT_TIMESTAMP(3),
|
||||
|
||||
@@ -25,6 +25,8 @@ public class ContainerRepository {
|
||||
public ContainerBookingEntity findForUpdate(long id) { return mapper.selectBookingForUpdate(id); }
|
||||
public ContainerBookingEntity findActiveForUpdate(long id) { return mapper.selectActiveBookingForUpdate(id); }
|
||||
public boolean departed(long id) { return mapper.hasActiveOutboundDeparture(id) > 0; }
|
||||
/** 读取本服务维护的实际开船事实,不依赖第三方查询任务是否建立。 */
|
||||
public boolean sailed(long id) { return mapper.hasActualVesselDeparture(id) > 0; }
|
||||
public boolean containerNoExists(long oceanBookingId, String no, Long excludedId) {
|
||||
if (no == null) return false;
|
||||
return mapper.selectCount(new LambdaQueryWrapper<ContainerBookingEntity>()
|
||||
|
||||
@@ -114,9 +114,27 @@ public class InboundOrderRepository {
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
/** Internal unified-query accessors. They always retain the tenant predicate when one is supplied. */
|
||||
/** 统一订单列表按共享筛选分页。 */
|
||||
public Page<InboundOrderEntity> pageUnifiedEntities(UnifiedInboundQuery query, List<String> processStatuses) {
|
||||
LambdaQueryWrapper<InboundOrderEntity> wrapper = new LambdaQueryWrapper<InboundOrderEntity>()
|
||||
return orders.selectPage(new Page<>(query.page(), query.size()), unifiedFilter(query, processStatuses));
|
||||
}
|
||||
|
||||
/** 只读取身份和流程状态,顺序与列表一致;空候选不能扩大查询范围。 */
|
||||
public List<InboundOrderEntity> unifiedStatusEntities(UnifiedInboundQuery query) {
|
||||
if (query.candidateOrderIds() != null && query.candidateOrderIds().isEmpty()) return List.of();
|
||||
return orders.selectList(unifiedFilter(query, List.of()).select(InboundOrderEntity::getId,
|
||||
InboundOrderEntity::getTenantId, InboundOrderEntity::getOrderId, InboundOrderEntity::getProcessStatus));
|
||||
}
|
||||
|
||||
/** 当前页候选订单沿原筛选读取匹配的入库记录,避免读到另一条不匹配投影。 */
|
||||
public List<InboundOrderEntity> unifiedMatchedEntities(UnifiedInboundQuery query, List<String> processStatuses) {
|
||||
if (query.candidateOrderIds() == null || query.candidateOrderIds().isEmpty()) return List.of();
|
||||
return orders.selectList(unifiedFilter(query, processStatuses));
|
||||
}
|
||||
|
||||
/** 列表与统计共享客户隔离、费用、测量及船期等筛选语义。 */
|
||||
private LambdaQueryWrapper<InboundOrderEntity> unifiedFilter(UnifiedInboundQuery query, List<String> processStatuses) {
|
||||
return new LambdaQueryWrapper<InboundOrderEntity>()
|
||||
.eq(query.tenantId() != null, InboundOrderEntity::getTenantId, query.tenantId())
|
||||
.eq(query.taxMode() != null, InboundOrderEntity::getTaxMode, query.taxMode())
|
||||
.in(processStatuses != null && !processStatuses.isEmpty(), InboundOrderEntity::getProcessStatus, processStatuses)
|
||||
@@ -187,7 +205,6 @@ public class InboundOrderRepository {
|
||||
.ge(query.createdFrom() != null, InboundOrderEntity::getCreatedAt, query.createdFrom())
|
||||
.le(query.createdTo() != null, InboundOrderEntity::getCreatedAt, query.createdTo())
|
||||
.orderByDesc(InboundOrderEntity::getCreatedAt).orderByDesc(InboundOrderEntity::getId);
|
||||
return orders.selectPage(new Page<>(query.page(), query.size()), wrapper);
|
||||
}
|
||||
|
||||
public List<InboundOrderEntity> findByOrderIds(Long tenantId, List<Long> orderIds) {
|
||||
|
||||
@@ -45,6 +45,13 @@ public class ContainerService {
|
||||
if (!repository.departed(id)) throw new BizException(ResultCode.NOT_FOUND, "国外工作台货柜不存在");
|
||||
}
|
||||
|
||||
/** 目的港清关资料允许已离仓或已实际开船货柜维护,不改写国内出仓事实。 */
|
||||
public void requireClearanceAccess(long id) {
|
||||
required(id);
|
||||
if (!repository.departed(id) && !repository.sailed(id))
|
||||
throw new BizException(ResultCode.NOT_FOUND, "货柜尚未离仓或实际开船,不能维护目的港清关资料");
|
||||
}
|
||||
|
||||
public void requireDomestic(long id) {
|
||||
required(id);
|
||||
if (repository.departed(id)) throw new BizException(ResultCode.NOT_FOUND, "国内工作台货柜不存在");
|
||||
|
||||
+3
-1
@@ -9,7 +9,9 @@ import org.springframework.stereotype.Service;
|
||||
public class MerchantWorkbenchFilterService {
|
||||
@Resource private MerchantWorkbenchFilterMapper mapper;
|
||||
@Resource private UnifiedInboundQueryService unified;
|
||||
@Resource private com.baiyue.firstleg.workflow.ChargeableWeightService weights;
|
||||
|
||||
/** 精确详情只读进度;工作台待确认队列使用计费重事实,金额确认不能代替。 */
|
||||
@org.springframework.transaction.annotation.Transactional(readOnly=true)
|
||||
public MerchantWorkbenchFilters.Response read(MerchantWorkbenchFilters.Request request) {
|
||||
if (request.orderIds() != null) {
|
||||
@@ -19,7 +21,7 @@ public class MerchantWorkbenchFilterService {
|
||||
return new MerchantWorkbenchFilters.Response(
|
||||
request.mainStatus() == null ? null : mapper.byProcessStatuses(request.tenantId(),
|
||||
unified.internalStatuses(request.mainStatus())),
|
||||
mapper.pendingFees(request.tenantId()), mapper.pendingCustoms(request.tenantId()),
|
||||
weights.pendingOrders(request.tenantId()), mapper.pendingCustoms(request.tenantId()),
|
||||
progress(mapper.progressFragments(request.tenantId(), null)));
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,38 @@ public class UnifiedInboundQueryService {
|
||||
@Resource private FbaPricingRepository pricing;
|
||||
@Resource private UnifiedInboundReadRepository operations;
|
||||
@Resource private ObjectMapper json;
|
||||
@Resource private com.baiyue.firstleg.workflow.WorkflowTabService workflowTabs;
|
||||
|
||||
/** 以稳定列表顺序返回去重履约状态,不触发逐票摘要及费用查询。 */
|
||||
public List<StatusRow> statusRows(UnifiedInboundQuery query) {
|
||||
validate(query);
|
||||
Map<String, StatusRow> byOrder = new LinkedHashMap<>();
|
||||
List<InboundOrderEntity> matched = inbounds.unifiedStatusEntities(query);
|
||||
for (InboundOrderEntity inbound : matched) {
|
||||
String status = mainStatus(inbound.getProcessStatus());
|
||||
// 分片订单可同时命中不同履约页签;同一页签内每个订单只统计一次。
|
||||
byOrder.putIfAbsent(inbound.getOrderId() + ":" + status, new StatusRow(inbound.getTenantId(),
|
||||
inbound.getOrderId(), status));
|
||||
}
|
||||
workflowTabs.rows(matched).forEach(row -> byOrder.putIfAbsent(row.orderId() + ":" + row.mainStatus(), row));
|
||||
return List.copyOf(byOrder.values());
|
||||
}
|
||||
|
||||
/** 只对当前页最多200个订单读取匹配摘要,选取规则与状态投影一致。 */
|
||||
public List<UnifiedInboundSummary> statusSummaries(UnifiedInboundQuery query) {
|
||||
validate(query);
|
||||
if (query.candidateOrderIds() == null || query.candidateOrderIds().size() > 200) {
|
||||
throw new com.baiyue.common.core.exception.BizException(
|
||||
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "状态摘要必须提供最多200个候选订单");
|
||||
}
|
||||
Map<Long, InboundOrderEntity> byOrder = new LinkedHashMap<>();
|
||||
for (InboundOrderEntity inbound : inbounds.unifiedMatchedEntities(query, internalStatuses(query.mainStatus()))) {
|
||||
byOrder.putIfAbsent(inbound.getOrderId(), inbound);
|
||||
}
|
||||
return summaries(List.copyOf(byOrder.values()));
|
||||
}
|
||||
|
||||
public record StatusRow(Long tenantId, Long orderId, String mainStatus) {}
|
||||
|
||||
public PageResult<UnifiedInboundSummary> page(UnifiedInboundQuery query) {
|
||||
validate(query);
|
||||
@@ -43,11 +75,45 @@ public class UnifiedInboundQueryService {
|
||||
|| query.candidateOrderIds() != null && query.candidateOrderIds().isEmpty()) {
|
||||
return new PageResult<>(List.of(), query.page(), query.size(), 0, 0);
|
||||
}
|
||||
if (StringUtils.hasText(query.mainStatus())
|
||||
&& com.baiyue.firstleg.workflow.WorkflowTabService.KEYS.contains(query.mainStatus())) {
|
||||
return workflowPage(query);
|
||||
}
|
||||
Page<InboundOrderEntity> source = inbounds.pageUnifiedEntities(query, internalStatuses(query.mainStatus()));
|
||||
List<UnifiedInboundSummary> records = summaries(source.getRecords());
|
||||
return new PageResult<>(records, source.getCurrent(), source.getSize(), source.getTotal(), source.getPages());
|
||||
}
|
||||
|
||||
/** 独立事实页签先筛选完整来源再分页,内部查询也不能把业务页签解释成全部状态。 */
|
||||
private PageResult<UnifiedInboundSummary> workflowPage(UnifiedInboundQuery query) {
|
||||
List<InboundOrderEntity> matched = inbounds.unifiedStatusEntities(query);
|
||||
Set<Long> matchingOrders = workflowTabs.rows(matched).stream()
|
||||
.filter(row -> query.mainStatus().equals(row.mainStatus())).map(StatusRow::orderId)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, InboundOrderEntity> unique = new LinkedHashMap<>();
|
||||
// 轻量事实不能用于摘要,重新读取当前条件下的完整来源。
|
||||
for (InboundOrderEntity inbound : inbounds.unifiedMatchedEntities(
|
||||
withCandidates(query, matchingOrders.stream().toList()), List.of())) {
|
||||
if (matchingOrders.contains(inbound.getOrderId())) unique.putIfAbsent(inbound.getOrderId(), inbound);
|
||||
}
|
||||
List<InboundOrderEntity> records = List.copyOf(unique.values());
|
||||
long total = records.size();
|
||||
long start = query.page() - 1 > Long.MAX_VALUE / query.size()
|
||||
? total : Math.min((query.page() - 1) * query.size(), total);
|
||||
var current = records.subList((int) start, (int) Math.min(start + query.size(), total));
|
||||
return new PageResult<>(summaries(current), query.page(), query.size(), total,
|
||||
total / query.size() + (total % query.size() == 0 ? 0 : 1));
|
||||
}
|
||||
|
||||
/** 保留全部过滤条件,只收窄为业务事实已命中的订单。 */
|
||||
private UnifiedInboundQuery withCandidates(UnifiedInboundQuery q, List<Long> candidates) {
|
||||
return new UnifiedInboundQuery(q.tenantId(), q.keyword(), q.orderNo(), q.mainStatus(), q.customerId(),
|
||||
q.receivingWarehouseId(), q.destinationWarehouseId(), q.inboundCode(), q.internalOrderStatus(),
|
||||
q.expectedArrivalDate(), q.feeReviewStatus(), q.channelName(), q.containerNo(), q.cabinetNo(),
|
||||
q.sailingDate(), q.loaded(), q.fullContainer(), q.measurementReviewStatus(), candidates,
|
||||
q.createdFrom(), q.createdTo(), q.page(), q.size(), q.taxMode());
|
||||
}
|
||||
|
||||
public List<UnifiedInboundSummary> summaries(Long tenantId, List<Long> orderIds) {
|
||||
Map<Long, UnifiedInboundSummary> byOrder = new LinkedHashMap<>();
|
||||
for (UnifiedInboundSummary item : summaries(inbounds.findByOrderIds(tenantId, orderIds)))
|
||||
@@ -203,7 +269,7 @@ public class UnifiedInboundQueryService {
|
||||
}
|
||||
|
||||
List<String> internalStatuses(String mainStatus) {
|
||||
if (!StringUtils.hasText(mainStatus)) return List.of();
|
||||
if (!StringUtils.hasText(mainStatus) || com.baiyue.firstleg.workflow.WorkflowTabService.KEYS.contains(mainStatus)) return List.of();
|
||||
return switch (mainStatus) {
|
||||
case "WAIT_MEASURE" -> List.of("WAIT_MEASURE", "MEASURING", "MEASURE_PENDING", "MEASURE_REJECTED",
|
||||
"WAIT_PRICING", "FEE_CONFIRMING", "INBOUNDING");
|
||||
@@ -231,6 +297,7 @@ public class UnifiedInboundQueryService {
|
||||
}
|
||||
if (StringUtils.hasText(query.mainStatus())
|
||||
&& !MAIN_STATUSES.contains(query.mainStatus())
|
||||
&& !com.baiyue.firstleg.workflow.WorkflowTabService.KEYS.contains(query.mainStatus())
|
||||
) {
|
||||
throw new com.baiyue.common.core.exception.BizException(
|
||||
com.baiyue.common.core.api.ResultCode.BAD_REQUEST, "统一订单主状态不合法");
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.baiyue.common.core.api.ResultCode;
|
||||
import com.baiyue.common.core.exception.BizException;
|
||||
import java.util.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.time.LocalDateTime;
|
||||
/** 客户独立确认计费重,金额确认和主流程不受影响。 */
|
||||
@Service
|
||||
public class ChargeableWeightService {
|
||||
private final WorkflowFactRepository repository;
|
||||
/** 注入当前事实和确认历史。 */
|
||||
public ChargeableWeightService(WorkflowFactRepository repository) { this.repository=repository; }
|
||||
/** 客户仅能读取本订单已审核的计费重。 */
|
||||
public List<WorkflowFacts.Weight> read(long tenant,long orderId) {
|
||||
return repository.facts(repository.orderInbounds(tenant,orderId)).stream().filter(f->f.tenantId()==tenant && eligible(f)).map(ChargeableWeightService::weight).toList();
|
||||
}
|
||||
/** 客户工作台按独立确认事实计算待办,不借用费用确认。 */
|
||||
public List<Long> pendingOrders(long tenant) {
|
||||
var ids=repository.weightCandidates(tenant);var orders=new LinkedHashSet<Long>();
|
||||
for(int offset=0;offset<ids.size();offset+=500) for(var f:repository.facts(ids.subList(offset,Math.min(offset+500,ids.size()))))
|
||||
if(f.tenantId()==tenant && eligible(f) && !weight(f).confirmed()) orders.add(f.orderId());
|
||||
return List.copyOf(orders);
|
||||
}
|
||||
/** 值和测量轮次变化使旧确认失效,金额变化不影响计费重。 */
|
||||
public static String fingerprint(WorkflowFacts.Fact f) {
|
||||
try { String value=f.inboundId()+"|"+f.chargeableWeightKg().stripTrailingZeros().toPlainString()+"|"+f.measureCompletedAt();
|
||||
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
|
||||
} catch(java.security.NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
|
||||
}
|
||||
/** 未审核或非正数不允许确认。 */
|
||||
public static boolean eligible(WorkflowFacts.Fact f) { return "APPROVED".equals(f.reviewStatus()) && f.chargeableWeightKg()!=null && f.chargeableWeightKg().signum()>0; }
|
||||
/** 只认可当前版本的确认。 */
|
||||
public static WorkflowFacts.Weight weight(WorkflowFacts.Fact f) {
|
||||
String hash=fingerprint(f);boolean confirmed=hash.equals(f.confirmationFingerprint());
|
||||
return new WorkflowFacts.Weight(f.inboundId(),f.orderId(),f.chargeableWeightKg(),hash,confirmed,confirmed?f.confirmedAt():null);
|
||||
}
|
||||
/** 入仓锁、预期版本和幂等键防止确认旧值或异参重放。 */
|
||||
@Transactional
|
||||
public WorkflowFacts.Weight confirm(long tenant,long operator,long id,String key,WorkflowFacts.Confirm request) {
|
||||
if(key==null || key.isBlank() || key.length()>128) throw new BizException(ResultCode.BAD_REQUEST,"确认幂等键不能为空且最多128字符");
|
||||
var inbound=repository.lock(tenant,id);
|
||||
if(inbound==null || "CANCELLED".equals(inbound.getProcessStatus())) throw new BizException(ResultCode.NOT_FOUND,"入仓单不存在");
|
||||
var replay=repository.command(tenant,operator,key);
|
||||
if(replay!=null && (replay.inboundId()!=id || !replay.fingerprint().equals(request.expectedFingerprint()))) throw new BizException(ResultCode.CONFLICT,"同一幂等键不能确认不同计费重");
|
||||
var facts=repository.facts(List.of(id));
|
||||
if(facts.isEmpty()) throw new BizException(ResultCode.CONFLICT,"请分别确认分柜后的独立订单计费重");
|
||||
var f=facts.get(0);
|
||||
if(!eligible(f)) throw new BizException(ResultCode.CONFLICT,"计费重尚未审核通过");
|
||||
var current=weight(f);
|
||||
if(!current.fingerprint().equals(request.expectedFingerprint())) throw new BizException(ResultCode.CONFLICT,"计费重已变化,请刷新后重新确认");
|
||||
if(replay==null) repository.insert(new WorkflowFacts.Confirmation(com.baomidou.mybatisplus.core.toolkit.IdWorker.getId(),tenant,id,operator,key,current.fingerprint(),current.chargeableWeightKg(),LocalDateTime.now()));
|
||||
return weight(repository.facts(List.of(id)).get(0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import com.baiyue.common.core.api.ApiResponse;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import java.util.List;
|
||||
/** 经内部接口读取尾程,禁止跨库查询。 */
|
||||
@FeignClient(name="lastleg-service",contextId="firstlegWorkflowFacts",url="${LASTLEG_SERVICE_URL:${baiyue.clients.lastleg.url:}}")
|
||||
public interface LastlegWorkflowClient {
|
||||
/** 最多500个精确来源,不转发客户JWT。 */
|
||||
@PostMapping("/internal/lastleg/v1/order-workflow-facts")
|
||||
ApiResponse<List<WorkflowFacts.Overseas>> read(@RequestHeader("X-Internal-Service-Token") String token,@RequestBody WorkflowFacts.Request request);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import com.baiyue.common.core.api.ApiResponse;
|
||||
import com.baiyue.common.security.AuthenticatedUser;
|
||||
import com.baiyue.firstleg.service.FirstlegScopeGuard;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.security.core.annotation.AuthenticationPrincipal;
|
||||
import jakarta.validation.Valid;
|
||||
import java.util.List;
|
||||
/** 客户计费重确认入口,独立于费用确认。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/merchant/v1/first-leg")
|
||||
public class MerchantChargeableWeightController {
|
||||
private final ChargeableWeightService service;
|
||||
/** 注入独立确认服务。 */
|
||||
public MerchantChargeableWeightController(ChargeableWeightService service) { this.service=service; }
|
||||
/** 客户范围取认证上下文。 */
|
||||
@GetMapping("/orders/{orderId}/chargeable-weights")
|
||||
@PreAuthorize("hasAuthority('merchant:order:view')")
|
||||
public ApiResponse<List<WorkflowFacts.Weight>> read(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable long orderId) { return ApiResponse.success(service.read(FirstlegScopeGuard.merchant(user),orderId)); }
|
||||
/** 不触发费用确认与金额锁定。 */
|
||||
@com.baiyue.common.audit.BusinessAudit(event="CUSTOMER_CHARGEABLE_WEIGHT_CONFIRM",resourceType="INBOUND_ORDER",resourceId="#inboundId",description="客户独立确认计费重")
|
||||
@PostMapping("/chargeable-weights/{inboundId}/confirm")
|
||||
@PreAuthorize("hasAuthority('merchant:order:edit')")
|
||||
public ApiResponse<WorkflowFacts.Weight> confirm(@AuthenticationPrincipal AuthenticatedUser user,@PathVariable long inboundId,@RequestHeader("Idempotency-Key") String key,@Valid @RequestBody WorkflowFacts.Confirm request) { return ApiResponse.success(service.confirm(FirstlegScopeGuard.merchant(user),user.userId(),inboundId,key,request)); }
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.apache.ibatis.annotations.*;
|
||||
import java.util.List;
|
||||
/** 柜事实和独立确认SQL入口。 */
|
||||
@Mapper
|
||||
public interface WorkflowFactMapper {
|
||||
String ACTUAL="""
|
||||
FROM fl_loading_plan_item li JOIN fl_loading_plan p ON p.id=li.loading_plan_id AND p.plan_status='COMPLETED'
|
||||
JOIN fl_loading_pick_task t ON t.loading_plan_id=p.id AND t.task_status='COMPLETED'
|
||||
JOIN fl_loading_pick_item pk ON pk.pick_task_id=t.id AND pk.loading_plan_item_id=li.id
|
||||
JOIN fl_container_booking b ON b.id=p.container_booking_id AND b.record_status='ACTIVE'
|
||||
WHERE li.inbound_id=i.id AND li.account_id=i.tenant_id AND li.deleted=0
|
||||
AND pk.item_status IN ('PICKED','PARTIAL') AND pk.picked_package_count>0
|
||||
""";
|
||||
/** 按独立实装票核验资料;来源单承接实装时,余量子单不能将来源票排除。 */
|
||||
@Select("<script>SELECT i.tenant_id,i.id inbound_id,i.order_id,i.measure_review_status review_status,i.chargeable_weight_kg,i.measure_completed_at,"
|
||||
+"EXISTS(SELECT 1 "+ACTUAL+" AND EXISTS(SELECT 1 FROM fl_carrier_schedule_node_fact n WHERE n.container_booking_id=b.id AND n.standard_node='DEPARTED_ORIGIN_PORT' AND n.actual_at IS NOT NULL)) departed,"
|
||||
+"EXISTS(SELECT 1 "+ACTUAL+" AND EXISTS(SELECT 1 FROM fl_container_document d WHERE d.container_booking_id=b.id AND d.document_type='DESTINATION_CLEARANCE' AND d.file_id IS NOT NULL)) clearance_uploaded,"
|
||||
+"EXISTS(SELECT 1 "+ACTUAL+" AND i.tax_mode='TAX_REFUND' AND NOT EXISTS(SELECT 1 FROM fl_customs_customer_document_inbound s JOIN fl_customs_customer_document d ON d.id=s.document_id AND d.tenant_id=i.tenant_id AND d.status='ACTIVE' JOIN fl_customs_container c ON c.id=d.customs_container_id AND c.loading_plan_id=p.id WHERE s.inbound_id=i.id AND s.tenant_id=i.tenant_id)) missing_customs,"
|
||||
+"EXISTS(SELECT 1 "+ACTUAL+" AND (i.tax_mode='BUY_DECLARATION' OR EXISTS(SELECT 1 FROM fl_customs_customer_document_inbound s JOIN fl_customs_customer_document d ON d.id=s.document_id AND d.tenant_id=i.tenant_id AND d.status='ACTIVE' JOIN fl_customs_container c ON c.id=d.customs_container_id AND c.loading_plan_id=p.id WHERE s.inbound_id=i.id AND s.tenant_id=i.tenant_id))) export_customs_ready,"
|
||||
+"(SELECT w.fingerprint FROM fl_chargeable_weight_confirmation w WHERE w.tenant_id=i.tenant_id AND w.inbound_id=i.id ORDER BY w.id DESC LIMIT 1) confirmation_fingerprint,"
|
||||
+"(SELECT w.confirmed_at FROM fl_chargeable_weight_confirmation w WHERE w.tenant_id=i.tenant_id AND w.inbound_id=i.id ORDER BY w.id DESC LIMIT 1) confirmed_at "
|
||||
+"FROM fl_inbound_order i WHERE i.deleted=0 AND NOT EXISTS(SELECT 1 FROM fl_inbound_order child WHERE child.tenant_id=i.tenant_id AND child.parent_inbound_id=i.id AND child.inbound_role='CHILD' AND (child.split_purpose IS NULL OR child.split_purpose != 'REMAINDER') AND child.deleted=0) AND i.process_status != 'CANCELLED' AND i.id IN "
|
||||
+"<foreach collection='ids' item='id' open='(' separator=',' close=')'>#{id}</foreach></script>")
|
||||
List<WorkflowFacts.Fact> facts(@Param("ids") List<Long> ids);
|
||||
/** 锁定客户自己的入仓单,串行确认与测量写入。 */
|
||||
@Select("SELECT * FROM fl_inbound_order WHERE tenant_id=#{tenantId} AND id=#{id} AND deleted=0 FOR UPDATE")
|
||||
com.baiyue.firstleg.entity.InboundOrderEntity lock(@Param("tenantId") long tenantId,@Param("id") long id);
|
||||
/** 客户订单下全部独立入仓单。 */
|
||||
@Select("SELECT id FROM fl_inbound_order WHERE tenant_id=#{tenantId} AND order_id=#{orderId} AND deleted=0 AND process_status != 'CANCELLED' ORDER BY id")
|
||||
List<Long> orderInbounds(@Param("tenantId") long tenantId,@Param("orderId") long orderId);
|
||||
/** 客户工作台只读取审核通过且有正计费重的来源。 */
|
||||
@Select("SELECT id FROM fl_inbound_order WHERE tenant_id=#{tenantId} AND deleted=0 AND process_status != 'CANCELLED' AND measure_review_status='APPROVED' AND chargeable_weight_kg>0 ORDER BY id")
|
||||
List<Long> weightCandidates(@Param("tenantId") long tenantId);
|
||||
/** 成员幂等键不允许跨确认对象复用。 */
|
||||
@Select("SELECT * FROM fl_chargeable_weight_confirmation WHERE tenant_id=#{tenantId} AND operator_id=#{operatorId} AND command_key=#{key}")
|
||||
WorkflowFacts.Confirmation command(@Param("tenantId") long tenantId,@Param("operatorId") long operatorId,@Param("key") String key);
|
||||
/** 独立记录,不修改费用或物流主状态。 */
|
||||
@Insert("INSERT INTO fl_chargeable_weight_confirmation(id,tenant_id,inbound_id,operator_id,command_key,fingerprint,chargeable_weight_kg,confirmed_at) VALUES(#{id},#{tenantId},#{inboundId},#{operatorId},#{commandKey},#{fingerprint},#{chargeableWeightKg},#{confirmedAt})")
|
||||
int insert(WorkflowFacts.Confirmation value);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.List;
|
||||
/** 本地柜事实与确认记录的持久化入口。 */
|
||||
@Repository
|
||||
public class WorkflowFactRepository {
|
||||
private final WorkflowFactMapper mapper;
|
||||
/** 注入SQL提供者。 */
|
||||
public WorkflowFactRepository(WorkflowFactMapper mapper) { this.mapper=mapper; }
|
||||
/** 空候选不读取数据。 */
|
||||
public List<WorkflowFacts.Fact> facts(List<Long> ids) { return ids.isEmpty()?List.of():mapper.facts(ids); }
|
||||
/** 锁定所属客户来源。 */
|
||||
public com.baiyue.firstleg.entity.InboundOrderEntity lock(long tenant,long id) { return mapper.lock(tenant,id); }
|
||||
/** 查询订单下独立来源。 */
|
||||
public List<Long> orderInbounds(long tenant,long order) { return mapper.orderInbounds(tenant,order); }
|
||||
/** 客户计费重待确认候选。 */
|
||||
public List<Long> weightCandidates(long tenant) { return mapper.weightCandidates(tenant); }
|
||||
/** 读取成员确认命令。 */
|
||||
public WorkflowFacts.Confirmation command(long tenant,long operator,String key) { return mapper.command(tenant,operator,key); }
|
||||
/** 追加确认历史。 */
|
||||
public void insert(WorkflowFacts.Confirmation value) { mapper.insert(value); }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
/** 页签事实与独立计费重确认契约。 */
|
||||
public final class WorkflowFacts {
|
||||
/** 仅承载查询及确认契约,不允许实例化。 */
|
||||
private WorkflowFacts() {}
|
||||
public record Fact(long tenantId,long inboundId,long orderId,String reviewStatus,BigDecimal chargeableWeightKg,LocalDateTime measureCompletedAt,
|
||||
boolean departed,boolean clearanceUploaded,boolean missingCustoms,boolean exportCustomsReady,String confirmationFingerprint,LocalDateTime confirmedAt) {}
|
||||
public record Source(long tenantId,long inboundId) {}
|
||||
public record Request(List<Source> sources) {}
|
||||
public record Overseas(long tenantId,long inboundId,boolean outboundExists,boolean pendingOutbound,boolean delivering,boolean unloaded) {}
|
||||
public record Weight(long inboundId,long orderId,BigDecimal chargeableWeightKg,String fingerprint,boolean confirmed,LocalDateTime confirmedAt) {}
|
||||
public record Confirm(@jakarta.validation.constraints.Pattern(regexp="[a-f0-9]{64}") @jakarta.validation.constraints.NotNull String expectedFingerprint) {}
|
||||
public record Confirmation(long id,long tenantId,long inboundId,long operatorId,String commandKey,String fingerprint,BigDecimal chargeableWeightKg,LocalDateTime confirmedAt) {}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import com.baiyue.firstleg.entity.InboundOrderEntity;
|
||||
import com.baiyue.firstleg.service.UnifiedInboundQueryService.StatusRow;
|
||||
import com.baiyue.common.core.api.ResultCode;
|
||||
import com.baiyue.common.core.exception.BizException;
|
||||
import java.util.*;
|
||||
/** 将已确认的独立业务维度映射为页签,不改物流主状态。 */
|
||||
@Service
|
||||
public class WorkflowTabService {
|
||||
public static final Set<String> KEYS=Set.of("WAIT_WEIGHT_CONFIRM","WEIGHT_CONFIRMED","WAIT_CUSTOMS_DOCS","EXPORT_CUSTOMS","SAILING_CLEARANCE","WAIT_UNLOAD","WAIT_DISPATCH","OUTBOUND_DOCUMENT","DELIVERING","SIGNED","MEASUREMENT_REVIEW");
|
||||
private final WorkflowFactRepository repository;
|
||||
private final LastlegWorkflowClient lastleg;
|
||||
@Value("${baiyue.security.internal-service-token}") private String token;
|
||||
/** 注入本地事实与尾程内部契约。 */
|
||||
public WorkflowTabService(WorkflowFactRepository repository,LastlegWorkflowClient lastleg) { this.repository=repository;this.lastleg=lastleg; }
|
||||
/** 分批取事实,失败整体关闭,不能把服务异常伪装成零。 */
|
||||
public List<StatusRow> rows(List<InboundOrderEntity> inbounds) {
|
||||
var result=new LinkedHashMap<String,StatusRow>();
|
||||
for(int offset=0;offset<inbounds.size();offset+=500) {
|
||||
var batch=inbounds.subList(offset,Math.min(offset+500,inbounds.size()));
|
||||
var expected=new HashMap<Long,InboundOrderEntity>();batch.forEach(i->expected.put(i.getId(),i));
|
||||
var facts=repository.facts(batch.stream().map(InboundOrderEntity::getId).toList());
|
||||
var sources=facts.stream().filter(WorkflowFacts.Fact::departed).map(f->new WorkflowFacts.Source(f.tenantId(),f.inboundId())).distinct().toList();
|
||||
Map<String,WorkflowFacts.Overseas> overseas=new HashMap<>();
|
||||
if(!sources.isEmpty()) {
|
||||
try {
|
||||
var response=lastleg.read(token,new WorkflowFacts.Request(sources));
|
||||
if(response==null || !response.successful() || response.data()==null) throw unavailable();
|
||||
var allowed=new HashSet<>(sources);
|
||||
for(var fact:response.data()) {
|
||||
if(fact==null || !allowed.contains(new WorkflowFacts.Source(fact.tenantId(),fact.inboundId()))) throw unavailable();
|
||||
overseas.merge(fact.tenantId()+":"+fact.inboundId(),fact,(a,b)->new WorkflowFacts.Overseas(a.tenantId(),a.inboundId(),a.outboundExists()||b.outboundExists(),a.pendingOutbound()||b.pendingOutbound(),a.delivering()||b.delivering(),a.unloaded()&&b.unloaded()));
|
||||
}
|
||||
if(overseas.size()!=sources.size()) throw unavailable();
|
||||
} catch(BizException e) { throw e; } catch(Exception e) { throw unavailable(); }
|
||||
}
|
||||
// SQL排除仅作汇总的父票;保留承接实际装柜数量的来源票及独立余量票。
|
||||
for(var fact:facts) {
|
||||
var inbound=expected.get(fact.inboundId());
|
||||
if(inbound==null || !Objects.equals(inbound.getTenantId(),fact.tenantId()) || !Objects.equals(inbound.getOrderId(),fact.orderId())) throw unavailable();
|
||||
var o=overseas.get(fact.tenantId()+":"+fact.inboundId());
|
||||
for(String key:classify(fact,inbound.getProcessStatus(),o)) result.putIfAbsent(fact.orderId()+":"+key,new StatusRow(fact.tenantId(),fact.orderId(),key));
|
||||
}
|
||||
}
|
||||
return List.copyOf(result.values());
|
||||
}
|
||||
/** 分类为可重叠的待办/证据集合,计费重确认独立于费用确认。 */
|
||||
public static Set<String> classify(WorkflowFacts.Fact f,String process,WorkflowFacts.Overseas o) {
|
||||
Set<String> keys=new LinkedHashSet<>();
|
||||
if("MEASURE_PENDING".equals(process) && "PENDING".equals(f.reviewStatus())) keys.add("MEASUREMENT_REVIEW");
|
||||
if(ChargeableWeightService.eligible(f)) keys.add(ChargeableWeightService.weight(f).confirmed()?"WEIGHT_CONFIRMED":"WAIT_WEIGHT_CONFIRM");
|
||||
boolean signed="DELIVERED".equals(process);
|
||||
// 报关页签按资料与实装事实汇总,不依赖点击开始报关;实际开船后转入清关链路。
|
||||
if(!f.departed() && !signed) {
|
||||
if(f.missingCustoms()) keys.add("WAIT_CUSTOMS_DOCS");
|
||||
if(f.exportCustomsReady()) keys.add("EXPORT_CUSTOMS");
|
||||
}
|
||||
if(signed) keys.add("SIGNED");
|
||||
if(f.departed() && !signed) {
|
||||
if(!f.clearanceUploaded()) keys.add("SAILING_CLEARANCE");
|
||||
if(o!=null) {
|
||||
if(f.clearanceUploaded() && !o.unloaded()) keys.add("WAIT_UNLOAD");
|
||||
// 取消的出库不构成有效覆盖,读取事实后自动回显,不能保存永久隐藏标志。
|
||||
if(!o.outboundExists()) keys.add("WAIT_DISPATCH");
|
||||
if(o.pendingOutbound()) keys.add("OUTBOUND_DOCUMENT");
|
||||
if(o.delivering()) keys.add("DELIVERING");
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
/** 下游缺失或归属异常不能生成部分数量。 */
|
||||
private static BizException unavailable() { return new BizException(ResultCode.SERVICE_UNAVAILABLE,"订单业务页签事实暂不可用,请稍后重试"); }
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
-- 客户独立确认计费重,不回填既有费用确认。
|
||||
CREATE TABLE IF NOT EXISTS fl_chargeable_weight_confirmation (
|
||||
id BIGINT NOT NULL COMMENT '确认记录ID',
|
||||
tenant_id BIGINT NOT NULL COMMENT '客户隔离ID',
|
||||
inbound_id BIGINT NOT NULL COMMENT '独立来源入仓单ID',
|
||||
operator_id BIGINT NOT NULL COMMENT '确认客户成员ID',
|
||||
command_key VARCHAR(128) NOT NULL COMMENT '成员确认幂等键',
|
||||
fingerprint CHAR(64) NOT NULL COMMENT '计费重及测量轮次摘要',
|
||||
chargeable_weight_kg DECIMAL(18,4) NOT NULL COMMENT '客户确认计费重千克',
|
||||
confirmed_at DATETIME(3) NOT NULL COMMENT '客户确认时间',
|
||||
PRIMARY KEY(id), UNIQUE KEY uk_weight_confirmation_command(tenant_id,operator_id,command_key),
|
||||
KEY idx_weight_confirmation_inbound(tenant_id,inbound_id,id)
|
||||
) ENGINE=InnoDB COMMENT='客户计费重独立确认历史';
|
||||
@@ -134,8 +134,11 @@ BEGIN
|
||||
OR NOT (NEW.cabinet_no <=> OLD.cabinet_no) THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'PDA拣货任务稳定归属不可修改';
|
||||
END IF;
|
||||
IF NOT (OLD.task_status = 'LOADING' AND NEW.task_status IN ('LOADING', 'COMPLETED')) THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'PDA拣货任务状态只允许完成';
|
||||
-- 与装柜主基线一致,允许持久化完成命令的处理中、失败重试及最终完成。
|
||||
IF NOT ((OLD.task_status = 'LOADING' AND NEW.task_status IN ('LOADING','COMPLETING'))
|
||||
OR (OLD.task_status = 'COMPLETING' AND NEW.task_status IN ('COMPLETING','COMPLETION_FAILED','COMPLETED'))
|
||||
OR (OLD.task_status = 'COMPLETION_FAILED' AND NEW.task_status = 'COMPLETING')) THEN
|
||||
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'PDA拣货任务状态流转非法';
|
||||
END IF;
|
||||
END$$
|
||||
DELIMITER ;
|
||||
|
||||
@@ -355,7 +355,7 @@ paths:
|
||||
/internal/firstleg/v1/inbounds/unified-orders/workbench-filters:
|
||||
post:
|
||||
summary: 查询单一客户工作台履约筛选标识(Order内部)
|
||||
description: 只读返回命中状态、最新待确认费用及待上传资料的订单标识。客户必须明确且为正数;不创建报关聚合,不跨Schema读取。传入orderIds为精确进度模式,仅计算progress,matchingStatusOrderIds为null,feeOrderIds和customsOrderIds为空;mainStatus在该模式不参与查询。
|
||||
description: 只读返回命中状态、待独立确认计费重及待上传报关资料的订单标识。feeOrderIds沿用既有字段名,值为尚未确认当前计费重的订单,不代表金额确认。客户必须明确且为正数;不创建报关聚合,不跨Schema读取。传入orderIds为精确进度模式,仅计算progress,matchingStatusOrderIds为null,feeOrderIds和customsOrderIds为空;mainStatus在该模式不参与查询。
|
||||
security: [{internalServiceToken: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -366,7 +366,7 @@ paths:
|
||||
required: [tenantId]
|
||||
properties:
|
||||
tenantId: {type: integer, format: int64, minimum: 1}
|
||||
mainStatus: {type: string, nullable: true, enum: [WAIT_MEASURE, WAIT_PALLETIZE, WAIT_SPLIT, LOADING, LOADED, DELIVERED]}
|
||||
mainStatus: {type: string, nullable: true, enum: [WAIT_MEASURE, WAIT_PALLETIZE, WAIT_SPLIT, LOADING, LOADED, DELIVERED, WAIT_WEIGHT_CONFIRM, WEIGHT_CONFIRMED, WAIT_CUSTOMS_DOCS, EXPORT_CUSTOMS, SAILING_CLEARANCE, WAIT_UNLOAD, WAIT_DISPATCH, OUTBOUND_DOCUMENT, DELIVERING, SIGNED, MEASUREMENT_REVIEW]}
|
||||
orderIds:
|
||||
type: array
|
||||
nullable: true
|
||||
@@ -388,7 +388,7 @@ paths:
|
||||
required: [feeOrderIds, customsOrderIds, progress]
|
||||
properties:
|
||||
matchingStatusOrderIds: {type: array, nullable: true, items: {type: integer, format: int64}}
|
||||
feeOrderIds: {type: array, items: {type: integer, format: int64}}
|
||||
feeOrderIds: {type: array, description: 待客户独立确认当前计费重的订单ID, items: {type: integer, format: int64}}
|
||||
customsOrderIds: {type: array, items: {type: integer, format: int64}}
|
||||
progress:
|
||||
type: array
|
||||
@@ -401,6 +401,47 @@ paths:
|
||||
stage: {type: string, enum: [loaded, declared, cleared]}
|
||||
partial: {type: boolean}
|
||||
|
||||
/internal/firstleg/v1/inbounds/unified-orders/status-summaries:
|
||||
post:
|
||||
summary: 当前页订单按原筛选读取履约摘要(Order 内部)
|
||||
description: candidateOrderIds 必须提供且最多200项;保留统一筛选,避免读到不匹配的其他入库分片。
|
||||
security: [{internalServiceToken: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/UnifiedInboundQuery'}
|
||||
responses:
|
||||
'200':
|
||||
description: 标准 ApiResponse,data 为 UnifiedInboundSummary 数组
|
||||
/internal/firstleg/v1/inbounds/unified-orders/status-rows:
|
||||
post:
|
||||
summary: 统一订单筛选后的轻量状态投影(Order 内部)
|
||||
description: 非分页查询,共享统一履约筛选;按创建时间和ID降序排列,同一订单同一主状态去重,保留不同分片主状态,不查询逐票详情。调用方不传mainStatus。
|
||||
security: [{internalServiceToken: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/UnifiedInboundQuery'}
|
||||
responses:
|
||||
'200':
|
||||
description: 标准 ApiResponse;依赖失败不能返回空成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string}
|
||||
data:
|
||||
type: array
|
||||
items:
|
||||
type: object
|
||||
required: [tenantId, orderId]
|
||||
properties:
|
||||
tenantId: {type: string}
|
||||
orderId: {type: string}
|
||||
mainStatus: {type: string, nullable: true}
|
||||
/internal/firstleg/v1/inbounds/unified-orders/query:
|
||||
post:
|
||||
summary: 按统一订单条件分页查询履约摘要(Order 内部)
|
||||
@@ -594,13 +635,13 @@ paths:
|
||||
/api/platform/v1/containers/{id}/clearance:
|
||||
get:
|
||||
summary: 查询货柜目的港清关资料
|
||||
description: 需要 platform:firstleg:terminal-drayage:list 权限;仅国外工作台货柜
|
||||
description: 需要 platform:firstleg:terminal-drayage:list 权限;有效货柜已确认国内离仓,或已记录 DEPARTED_ORIGIN_PORT 且 actual_at 非空时可读取;人工与拉取节点使用相同事实
|
||||
parameters: [{$ref: '#/components/parameters/ContainerBookingId'}]
|
||||
responses: {'200': {description: 成功或货柜不存在}}
|
||||
/api/platform/v1/containers/{id}/clearance/document:
|
||||
post:
|
||||
summary: 上传或替换货柜目的港清关资料
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit 权限,fileId 必须严格绑定当前货柜
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit 权限;有效货柜已离仓或已实际开船,fileId 必须严格绑定当前货柜
|
||||
parameters: [{$ref: '#/components/parameters/ContainerBookingId'}, {$ref: '#/components/parameters/IdempotencyKey'}]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -609,7 +650,7 @@ paths:
|
||||
/api/platform/v1/containers/{id}/clearance/document/{fileId}/download:
|
||||
get:
|
||||
summary: 下载货柜目的港清关附件
|
||||
description: 需要 platform:firstleg:terminal-drayage:list 权限;服务端校验当前 DESTINATION_CLEARANCE fileId 及 File 业务归属,完成态仍可下载,响应禁止缓存
|
||||
description: 需要 platform:firstleg:terminal-drayage:list 权限;有效货柜已离仓或已实际开船;服务端校验当前 DESTINATION_CLEARANCE fileId 及 File 业务归属,完成态仍可下载,响应禁止缓存
|
||||
parameters:
|
||||
- {$ref: '#/components/parameters/ContainerBookingId'}
|
||||
- {name: fileId, in: path, required: true, schema: {type: string, pattern: '^[1-9][0-9]*$'}}
|
||||
@@ -619,7 +660,7 @@ paths:
|
||||
/api/platform/v1/containers/{id}/clearance/document/upload:
|
||||
post:
|
||||
summary: 直接选择文件上传或替换货柜目的港清关资料
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit;Firstleg 使用内部服务令牌上传 File,浏览器不得传递 fileId 或内部令牌。
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit;有效货柜已离仓或已实际开船;Firstleg 使用内部服务令牌上传 File,浏览器不得传递 fileId 或内部令牌。上传成功即作为待拆柜的资料事实,不要求另行确认清关完成。
|
||||
parameters: [{$ref: '#/components/parameters/ContainerBookingId'}, {$ref: '#/components/parameters/IdempotencyKey'}]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -630,7 +671,7 @@ paths:
|
||||
/api/platform/v1/containers/{id}/clearance/complete:
|
||||
post:
|
||||
summary: 点击完成目的港清关
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit 权限
|
||||
description: 需要 platform:firstleg:terminal-drayage:document:edit 权限;有效货柜已离仓或已实际开船;此完成动作不作为上传后进入待拆柜的附加条件
|
||||
parameters: [{$ref: '#/components/parameters/ContainerBookingId'}, {$ref: '#/components/parameters/IdempotencyKey'}]
|
||||
requestBody:
|
||||
required: true
|
||||
@@ -1631,9 +1672,9 @@ components:
|
||||
orderNo: {type: string, maxLength: 64, nullable: true}
|
||||
mainStatus:
|
||||
type: string
|
||||
enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_PALLETIZE, WAIT_SPLIT, LOADING, LOADED, DELIVERED]
|
||||
enum: [PENDING_REVIEW, WAIT_MEASURE, WAIT_PALLETIZE, WAIT_SPLIT, LOADING, LOADED, DELIVERED, WAIT_WEIGHT_CONFIRM, WEIGHT_CONFIRMED, WAIT_CUSTOMS_DOCS, EXPORT_CUSTOMS, SAILING_CLEARANCE, WAIT_UNLOAD, WAIT_DISPATCH, OUTBOUND_DOCUMENT, DELIVERING, SIGNED, MEASUREMENT_REVIEW]
|
||||
nullable: true
|
||||
description: WAIT_SPLIT 为唯一待分柜筛选值
|
||||
description: WAIT_SPLIT 为唯一待分柜筛选值;WAIT_CUSTOMS_DOCS 为实际装柜后缺少本票客户报关资料;EXPORT_CUSTOMS 按本票资料已上传且实际装柜完成汇总,买单无需客户退税资料,不依赖点击开始报关,实际开船后移出;SAILING_CLEARANCE 按手动或拉取的实际离港节点进入,清关资料上传后进入 WAIT_UNLOAD,实际卸柜完成后移出。
|
||||
customerId: {type: integer, format: int64, nullable: true}
|
||||
receivingWarehouseId: {type: integer, format: int64, nullable: true}
|
||||
destinationWarehouseId: {type: integer, format: int64, nullable: true}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
openapi: 3.0.3
|
||||
info: {title: 客户独立计费重确认, version: 1.0.0}
|
||||
security: [{bearerAuth: []}]
|
||||
paths:
|
||||
/api/merchant/v1/first-leg/orders/{orderId}/chargeable-weights:
|
||||
get:
|
||||
summary: 客户读取本票全部独立入仓计费重
|
||||
description: 认证客户隔离,要求merchant:order:view;仅返回测量审核通过且计费重为正的分片。
|
||||
parameters:
|
||||
- {name: orderId, in: path, required: true, schema: {type: integer, format: int64}}
|
||||
responses:
|
||||
'200':
|
||||
description: 标准ApiResponse,认证客户无可确认来源时返回空数组
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string, example: '200'}
|
||||
message: {type: string}
|
||||
data:
|
||||
type: array
|
||||
items: {$ref: '#/components/schemas/Weight'}
|
||||
/api/merchant/v1/first-leg/chargeable-weights/{inboundId}/confirm:
|
||||
post:
|
||||
summary: 客户独立确认当前计费重
|
||||
description: 要求merchant:order:edit。与费用金额确认独立;值或测量轮次变化后旧确认失效。客户范围取认证主体。
|
||||
parameters:
|
||||
- {name: inboundId, in: path, required: true, schema: {type: integer, format: int64}}
|
||||
- {name: Idempotency-Key, in: header, required: true, schema: {type: string, maxLength: 128}}
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [expectedFingerprint]
|
||||
properties:
|
||||
expectedFingerprint: {type: string, pattern: '^[a-f0-9]{64}$'}
|
||||
responses:
|
||||
'200':
|
||||
description: 标准ApiResponse;版本或异参冲突返回业务冲突码,不改变费用状态
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code: {type: string, example: '200'}
|
||||
message: {type: string}
|
||||
data: {$ref: '#/components/schemas/Weight'}
|
||||
components:
|
||||
securitySchemes:
|
||||
bearerAuth: {type: http, scheme: bearer, bearerFormat: JWT}
|
||||
schemas:
|
||||
Weight:
|
||||
type: object
|
||||
required: [inboundId, orderId, chargeableWeightKg, fingerprint, confirmed]
|
||||
properties:
|
||||
inboundId: {type: string, description: 独立来源入仓单ID}
|
||||
orderId: {type: string, description: 独立订单ID}
|
||||
chargeableWeightKg: {type: number}
|
||||
fingerprint: {type: string}
|
||||
confirmed: {type: boolean}
|
||||
confirmedAt: {type: string, format: date-time, nullable: true}
|
||||
+14
@@ -44,6 +44,20 @@ class InternalInboundOrderReferenceControllerTest {
|
||||
@Resource
|
||||
private InternalInboundOrderController controller;
|
||||
|
||||
/** 新增状态查询和摘要入口都必须校验内部服务身份。 */
|
||||
@Test
|
||||
void statusEndpointsRequireInternalTokenBeforeDelegation() {
|
||||
var request = new UnifiedInboundQuery(10001L, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, List.of(77L), null, null, 1, 20, null);
|
||||
assertThatThrownBy(() -> controller.unifiedStatusRows(null, request)).isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(() -> controller.unifiedStatusSummaries("wrong", request)).isInstanceOf(BizException.class);
|
||||
org.mockito.Mockito.verifyNoInteractions(unifiedQueryService);
|
||||
when(unifiedQueryService.statusRows(request)).thenReturn(List.of());
|
||||
when(unifiedQueryService.statusSummaries(request)).thenReturn(List.of());
|
||||
assertThat(controller.unifiedStatusRows("internal-token", request).data()).isEmpty();
|
||||
assertThat(controller.unifiedStatusSummaries("internal-token", request).data()).isEmpty();
|
||||
}
|
||||
|
||||
@Test void workbenchFiltersRejectMissingAndWrongInternalIdentity() {
|
||||
var request = new com.baiyue.firstleg.dto.MerchantWorkbenchFilters.Request(11L, "LOADED", null);
|
||||
assertThatThrownBy(() -> controller.workbenchFilters(null, request)).isInstanceOf(BizException.class);
|
||||
|
||||
+10
@@ -9,6 +9,16 @@ import java.nio.file.Path;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
class LoadingCompletionSqlContractTest {
|
||||
/** 后执行的渠道柜次脚本不能恢复旧触发器并阻断持久化完成命令。 */
|
||||
@Test
|
||||
void channelMigrationKeepsTheDurableCompletionTransitions() throws Exception {
|
||||
String sql = Files.readString(Path.of("src", "main", "resources", "db",
|
||||
"phase3-channel-container-migration.sql"), StandardCharsets.UTF_8);
|
||||
assertThat(sql).contains("OLD.task_status = 'LOADING' AND NEW.task_status IN ('LOADING','COMPLETING')")
|
||||
.contains("OLD.task_status = 'COMPLETING' AND NEW.task_status IN ('COMPLETING','COMPLETION_FAILED','COMPLETED')")
|
||||
.contains("OLD.task_status = 'COMPLETION_FAILED' AND NEW.task_status = 'COMPLETING'")
|
||||
.doesNotContain("任务状态只允许完成");
|
||||
}
|
||||
@Test
|
||||
void baselineAndUnifiedSqlDefineDurableCompletionStateMachine() throws Exception {
|
||||
assertContract(Files.readString(Path.of("src", "main", "resources", "db",
|
||||
|
||||
+1
-1
@@ -80,7 +80,7 @@ class Phase3FinalUnifiedSqlContractTest {
|
||||
@Test
|
||||
void initializationPassIsUniqueAndFinal() throws Exception {
|
||||
String sql = sql();
|
||||
int expectedTables = 227;
|
||||
int expectedTables = 228;
|
||||
long actualTables = java.util.regex.Pattern.compile("(?m)^CREATE TABLE\\s+")
|
||||
.matcher(sql).results().count();
|
||||
assertThat(actualTables).isEqualTo(expectedTables);
|
||||
|
||||
+11
@@ -69,6 +69,17 @@ class UnifiedInboundTaxModePaginationTest {
|
||||
assertPage(null, 1, 4, 6);
|
||||
assertPage(null, 2, 4, 4);
|
||||
}
|
||||
/** 轻量统计读取全量状态,不能把第二页当作全量,也不能越过客户和软删除条件。 */
|
||||
@Test
|
||||
void statusProjectionUsesFullFilteredSetAndEmptyCandidatesStayEmpty() {
|
||||
var query = new UnifiedInboundQuery(11L, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, null, 2, 1, "TAX_REFUND");
|
||||
assertThat(repository.unifiedStatusEntities(query)).extracting(InboundOrderEntity::getId).containsExactly(6L, 2L);
|
||||
var empty = new UnifiedInboundQuery(11L, null, null, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, List.of(), null, null, 2, 1, "TAX_REFUND");
|
||||
assertThat(repository.unifiedStatusEntities(empty)).isEmpty();
|
||||
}
|
||||
|
||||
private void assertPage(String taxMode, long page, long total, long expectedId) {
|
||||
var query = new UnifiedInboundQuery(11L, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, page, 1, taxMode);
|
||||
var result = repository.pageUnifiedEntities(query, List.of("LOADED"));
|
||||
|
||||
@@ -50,6 +50,18 @@ class ContainerServiceTest {
|
||||
@MockBean private SmartLoadingService smartLoadingService;
|
||||
@Resource private ContainerService service;
|
||||
|
||||
/** 实际开船可独立打开清关资料,预估节点与缺失货柜不能绕过校验。 */
|
||||
@Test void clearanceAcceptsActualSailingWithoutInventingOutboundConfirmation() {
|
||||
when(repository.find(91L)).thenReturn(new ContainerBookingEntity());
|
||||
assertThatThrownBy(() -> service.requireClearanceAccess(91L)).isInstanceOf(BizException.class);
|
||||
when(repository.sailed(91L)).thenReturn(true);
|
||||
service.requireClearanceAccess(91L);
|
||||
assertThatThrownBy(() -> service.requireClearanceAccess(92L)).isInstanceOf(BizException.class);
|
||||
when(repository.sailed(91L)).thenReturn(false);
|
||||
when(repository.departed(91L)).thenReturn(true);
|
||||
service.requireClearanceAccess(91L);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setUpWarehouse() {
|
||||
when(documentNumbers.nextCabinetNo()).thenReturn("D0001");
|
||||
|
||||
+14
@@ -9,6 +9,20 @@ import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
class MerchantWorkbenchFilterServiceTest {
|
||||
/** 金额待确认与计费重待确认不同,客户工作台只能使用后者。 */
|
||||
@Test void customerQueueUsesIndependentWeightConfirmation() {
|
||||
var mapper=mock(MerchantWorkbenchFilterMapper.class);
|
||||
var weights=mock(com.baiyue.firstleg.workflow.ChargeableWeightService.class);
|
||||
var service=new MerchantWorkbenchFilterService();
|
||||
ReflectionTestUtils.setField(service,"mapper",mapper);
|
||||
ReflectionTestUtils.setField(service,"weights",weights);
|
||||
when(weights.pendingOrders(11)).thenReturn(List.of(101L));
|
||||
var response=service.read(new MerchantWorkbenchFilters.Request(11L,null,null));
|
||||
assertThat(response.feeOrderIds()).containsExactly(101L);
|
||||
verify(weights).pendingOrders(11);
|
||||
verify(mapper,never()).pendingFees(anyLong());
|
||||
}
|
||||
|
||||
@Test void exactDetailProgressSkipsUnrelatedCustomerQueues() {
|
||||
var mapper=mock(MerchantWorkbenchFilterMapper.class);
|
||||
var unified=mock(UnifiedInboundQueryService.class);
|
||||
|
||||
+67
@@ -24,11 +24,77 @@ import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
class UnifiedInboundQueryServiceTest {
|
||||
/** 直接内部查询同样先按业务事实筛选再分页,不能返回未命中的订单。 */
|
||||
@Test
|
||||
void workflowPageFiltersBeforePagination() {
|
||||
var repository = mock(InboundOrderRepository.class);
|
||||
var workflow = mock(com.baiyue.firstleg.workflow.WorkflowTabService.class);
|
||||
var service = new UnifiedInboundQueryService();
|
||||
ReflectionTestUtils.setField(service, "inbounds", repository);
|
||||
ReflectionTestUtils.setField(service, "workflowTabs", workflow);
|
||||
ReflectionTestUtils.setField(service, "operations", mock(UnifiedInboundReadRepository.class));
|
||||
ReflectionTestUtils.setField(service, "pricing", mock(FbaPricingRepository.class));
|
||||
var query = new UnifiedInboundQuery(10001L, null, null, "WAIT_WEIGHT_CONFIRM", null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, 2, 1, null);
|
||||
var first = new InboundOrderEntity(); first.setId(1L); first.setTenantId(10001L); first.setOrderId(77L); first.setProcessStatus("WAIT_SPLIT");
|
||||
var second = new InboundOrderEntity(); second.setId(2L); second.setTenantId(10001L); second.setOrderId(78L); second.setProcessStatus("WAIT_SPLIT");
|
||||
var other = new InboundOrderEntity(); other.setId(3L); other.setTenantId(10001L); other.setOrderId(79L); other.setProcessStatus("WAIT_SPLIT");
|
||||
var sources = List.of(first, second, other);
|
||||
when(repository.unifiedStatusEntities(query)).thenReturn(sources);
|
||||
when(workflow.rows(sources)).thenReturn(List.of(
|
||||
new UnifiedInboundQueryService.StatusRow(10001L,77L,"WAIT_WEIGHT_CONFIRM"),
|
||||
new UnifiedInboundQueryService.StatusRow(10001L,78L,"WAIT_WEIGHT_CONFIRM"),
|
||||
new UnifiedInboundQueryService.StatusRow(10001L,79L,"WEIGHT_CONFIRMED")));
|
||||
when(repository.unifiedMatchedEntities(org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.eq(List.of())))
|
||||
.thenReturn(sources);
|
||||
var result = service.page(query);
|
||||
assertThat(result.total()).isEqualTo(2);
|
||||
assertThat(result.records()).singleElement().satisfies(row -> assertThat(row.inbound().orderId()).isEqualTo(78));
|
||||
}
|
||||
|
||||
/** 分片订单保留各状态命中,同一状态内去重;不触发逐票富化查询。 */
|
||||
@Test
|
||||
void statusRowsDeduplicateLatestMatchingInboundWithoutEnrichment() {
|
||||
var repository = mock(InboundOrderRepository.class);
|
||||
var operations = mock(UnifiedInboundReadRepository.class);
|
||||
var pricing = mock(FbaPricingRepository.class);
|
||||
var service = new UnifiedInboundQueryService();
|
||||
ReflectionTestUtils.setField(service, "workflowTabs", mock(com.baiyue.firstleg.workflow.WorkflowTabService.class));
|
||||
ReflectionTestUtils.setField(service, "inbounds", repository);
|
||||
ReflectionTestUtils.setField(service, "operations", operations);
|
||||
ReflectionTestUtils.setField(service, "pricing", pricing);
|
||||
var query = new UnifiedInboundQuery(10001L, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, 9, 1, null);
|
||||
var newest = new InboundOrderEntity(); newest.setTenantId(10001L); newest.setOrderId(77L);
|
||||
newest.setProcessStatus("MEASURE_PENDING");
|
||||
var older = new InboundOrderEntity(); older.setTenantId(10001L); older.setOrderId(77L);
|
||||
older.setProcessStatus("LOADED");
|
||||
when(repository.unifiedStatusEntities(query)).thenReturn(List.of(newest, newest, older));
|
||||
assertThat(service.statusRows(query)).containsExactly(
|
||||
new UnifiedInboundQueryService.StatusRow(10001L, 77L, "WAIT_MEASURE"),
|
||||
new UnifiedInboundQueryService.StatusRow(10001L, 77L, "LOADED"));
|
||||
verifyNoInteractions(operations, pricing);
|
||||
}
|
||||
|
||||
/** 摘要入口必须提供当前页候选,不能误触发全量明细读取。 */
|
||||
@Test
|
||||
void statusSummariesRejectUnboundedCandidateRequest() {
|
||||
var repository = mock(InboundOrderRepository.class);
|
||||
var service = new UnifiedInboundQueryService();
|
||||
ReflectionTestUtils.setField(service, "workflowTabs", mock(com.baiyue.firstleg.workflow.WorkflowTabService.class));
|
||||
ReflectionTestUtils.setField(service, "inbounds", repository);
|
||||
var query = new UnifiedInboundQuery(10001L, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, 1, 20, null);
|
||||
assertThatThrownBy(() -> service.statusSummaries(query)).isInstanceOf(BizException.class);
|
||||
verifyNoInteractions(repository);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@ValueSource(strings = {"", " ", "tax_refund", "TAX_REFUND ", "OTHER", "TAX_INCLUDED"})
|
||||
void illegalTaxModeFailsBeforeRepository(String taxMode) {
|
||||
var repository = mock(InboundOrderRepository.class);
|
||||
var service = new UnifiedInboundQueryService();
|
||||
ReflectionTestUtils.setField(service, "workflowTabs", mock(com.baiyue.firstleg.workflow.WorkflowTabService.class));
|
||||
ReflectionTestUtils.setField(service, "inbounds", repository);
|
||||
var query = new UnifiedInboundQuery(10001L, null, null, null, null, null, null, null,
|
||||
null, null, null, null, null, null, null, null, null, null, null, null, null, 1, 20, taxMode);
|
||||
@@ -144,6 +210,7 @@ class UnifiedInboundQueryServiceTest {
|
||||
var operations = mock(UnifiedInboundReadRepository.class);
|
||||
var pricing = mock(FbaPricingRepository.class);
|
||||
var service = new UnifiedInboundQueryService();
|
||||
ReflectionTestUtils.setField(service, "workflowTabs", mock(com.baiyue.firstleg.workflow.WorkflowTabService.class));
|
||||
ReflectionTestUtils.setField(service,"inbounds",inbounds);
|
||||
ReflectionTestUtils.setField(service,"operations",operations);
|
||||
ReflectionTestUtils.setField(service,"pricing",pricing);
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
|
||||
import com.baiyue.common.core.api.ApiResponse;
|
||||
import com.baiyue.common.core.exception.BizException;
|
||||
import com.baiyue.firstleg.entity.InboundOrderEntity;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/** 跨服务缺项和客户归属异常不能生成看似成功的部分统计。 */
|
||||
class WorkflowBoundaryTest {
|
||||
/** 真实开船来源的测试事实。 */
|
||||
private WorkflowFacts.Fact fact() {
|
||||
return new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,
|
||||
LocalDateTime.of(2026,10,19,10,0),true,false,false,false,null,null);
|
||||
}
|
||||
|
||||
/** 下游漏来源或返回其他客户均整体失败。 */
|
||||
@Test void rejectsMissingAndForeignDownstreamFacts() {
|
||||
var repository=mock(WorkflowFactRepository.class);
|
||||
var downstream=mock(LastlegWorkflowClient.class);
|
||||
var service=new WorkflowTabService(repository,downstream);
|
||||
var inbound=new InboundOrderEntity();inbound.setId(1L);inbound.setTenantId(11L);
|
||||
inbound.setOrderId(101L);inbound.setProcessStatus("LOADED");
|
||||
when(repository.facts(List.of(1L))).thenReturn(List.of(fact()));
|
||||
when(downstream.read(any(),any())).thenReturn(ApiResponse.success(List.of()));
|
||||
assertThatThrownBy(()->service.rows(List.of(inbound))).isInstanceOf(BizException.class);
|
||||
when(downstream.read(any(),any())).thenReturn(ApiResponse.success(List.of(
|
||||
new WorkflowFacts.Overseas(22,1,true,true,false,true))));
|
||||
assertThatThrownBy(()->service.rows(List.of(inbound))).isInstanceOf(BizException.class);
|
||||
when(downstream.read(any(),any())).thenThrow(new IllegalStateException("unavailable"));
|
||||
assertThatThrownBy(()->service.rows(List.of(inbound))).isInstanceOf(BizException.class);
|
||||
}
|
||||
|
||||
/** 重测同值也要求重新确认,金额没有参与摘要。 */
|
||||
@Test void repeatedMeasurementRequiresNewConfirmation() {
|
||||
var original=fact();
|
||||
var measuredAgain=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,
|
||||
original.measureCompletedAt().plusSeconds(1),true,false,false,false,
|
||||
ChargeableWeightService.fingerprint(original),LocalDateTime.now());
|
||||
assertThat(ChargeableWeightService.weight(measuredAgain).confirmed()).isFalse();
|
||||
}
|
||||
|
||||
/** 平台主体不得冒充客户,客户和操作者只取认证上下文。 */
|
||||
@Test void confirmationUsesAuthenticatedCustomerAndOperator() {
|
||||
var service=mock(ChargeableWeightService.class);
|
||||
var controller=new MerchantChargeableWeightController(service);
|
||||
var platform=new com.baiyue.common.security.AuthenticatedUser(7L,0L,0L,9L,"platform","PLATFORM","WEB",java.util.Set.of());
|
||||
var request=new WorkflowFacts.Confirm("a".repeat(64));
|
||||
assertThatThrownBy(()->controller.read(platform,101)).isInstanceOf(BizException.class);
|
||||
assertThatThrownBy(()->controller.confirm(platform,1,"key",request)).isInstanceOf(BizException.class);
|
||||
verifyNoInteractions(service);
|
||||
var merchant=new com.baiyue.common.security.AuthenticatedUser(7L,11L,0L,9L,"member","MERCHANT","WEB",java.util.Set.of());
|
||||
controller.read(merchant,101);
|
||||
controller.confirm(merchant,1,"key",request);
|
||||
verify(service).read(11,101);
|
||||
verify(service).confirm(11,7,1,"key",request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
/** 取消回显、分柜隔离和独立计费重版本回归。 */
|
||||
class WorkflowBusinessTest {
|
||||
/** 报关资料齐备进入汇总,实际开船及清关资料分别驱动后续页签。 */
|
||||
@Test void customsDocumentsDepartureAndClearanceDriveTabs() {
|
||||
var time=LocalDateTime.of(2026,10,19,10,0);
|
||||
var missing=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,time,false,false,true,false,null,null);
|
||||
var uploaded=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,time,false,false,false,true,null,null);
|
||||
var departed=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,time,true,false,false,true,null,null);
|
||||
var cleared=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,time,true,true,false,true,null,null);
|
||||
var uploadedBeforeDeparture=new WorkflowFacts.Fact(11,1,101,"APPROVED",BigDecimal.TEN,time,false,true,false,true,null,null);
|
||||
var pendingUnload=new WorkflowFacts.Overseas(11,1,false,false,false,false);
|
||||
var unloaded=new WorkflowFacts.Overseas(11,1,false,false,false,true);
|
||||
assertThat(WorkflowTabService.classify(missing,"LOADED",null))
|
||||
.contains("WAIT_CUSTOMS_DOCS").doesNotContain("EXPORT_CUSTOMS","SAILING_CLEARANCE","WAIT_UNLOAD");
|
||||
assertThat(WorkflowTabService.classify(uploaded,"LOADED",null))
|
||||
.contains("EXPORT_CUSTOMS").doesNotContain("WAIT_CUSTOMS_DOCS","SAILING_CLEARANCE","WAIT_UNLOAD");
|
||||
assertThat(WorkflowTabService.classify(uploadedBeforeDeparture,"LOADED",pendingUnload))
|
||||
.contains("EXPORT_CUSTOMS").doesNotContain("SAILING_CLEARANCE","WAIT_UNLOAD");
|
||||
assertThat(WorkflowTabService.classify(departed,"LOADED",pendingUnload))
|
||||
.contains("SAILING_CLEARANCE").doesNotContain("WAIT_CUSTOMS_DOCS","EXPORT_CUSTOMS","WAIT_UNLOAD");
|
||||
assertThat(WorkflowTabService.classify(cleared,"LOADED",pendingUnload))
|
||||
.contains("WAIT_UNLOAD").doesNotContain("WAIT_CUSTOMS_DOCS","EXPORT_CUSTOMS","SAILING_CLEARANCE");
|
||||
assertThat(WorkflowTabService.classify(cleared,"LOADED",unloaded))
|
||||
.doesNotContain("WAIT_UNLOAD","SAILING_CLEARANCE","EXPORT_CUSTOMS");
|
||||
assertThat(WorkflowTabService.classify(uploaded,"DELIVERED",unloaded))
|
||||
.contains("SIGNED").doesNotContain("EXPORT_CUSTOMS","WAIT_CUSTOMS_DOCS");
|
||||
}
|
||||
/** 构造独立分柜来源。 */
|
||||
private WorkflowFacts.Fact fact(long id,String kg,String confirmed,boolean uploaded) {
|
||||
return new WorkflowFacts.Fact(11,id,100+id,"APPROVED",new BigDecimal(kg),LocalDateTime.of(2026,10,19,10,0),true,uploaded,false,false,confirmed,null);
|
||||
}
|
||||
/** 有效建单移出待排车,取消后恢复;实际出库不计未出库单。 */
|
||||
@Test void cancellationRestoresDispatchQueue() {
|
||||
var f=fact(1,"100",null,true);
|
||||
var waiting=new WorkflowFacts.Overseas(11,1,false,false,false,true);
|
||||
var created=new WorkflowFacts.Overseas(11,1,true,true,false,true);
|
||||
var shipped=new WorkflowFacts.Overseas(11,1,true,false,true,true);
|
||||
assertThat(WorkflowTabService.classify(f,"LOADED",waiting)).contains("WAIT_DISPATCH").doesNotContain("OUTBOUND_DOCUMENT");
|
||||
assertThat(WorkflowTabService.classify(f,"LOADED",created)).contains("OUTBOUND_DOCUMENT").doesNotContain("WAIT_DISPATCH");
|
||||
assertThat(WorkflowTabService.classify(f,"LOADED",shipped)).contains("DELIVERING").doesNotContain("WAIT_DISPATCH","OUTBOUND_DOCUMENT");
|
||||
assertThat(WorkflowTabService.classify(f,"LOADED",waiting)).contains("WAIT_DISPATCH");
|
||||
}
|
||||
/** 一柜资料上传不覆盖另一柜;签收不再进入待排。 */
|
||||
@Test void independentSlicesAndUploadedClearance() {
|
||||
assertThat(WorkflowTabService.classify(fact(1,"100",null,false),"LOADED",new WorkflowFacts.Overseas(11,1,false,false,false,false)))
|
||||
.contains("SAILING_CLEARANCE","WAIT_DISPATCH").doesNotContain("WAIT_UNLOAD");
|
||||
assertThat(WorkflowTabService.classify(fact(2,"200",null,true),"LOADED",new WorkflowFacts.Overseas(11,2,true,true,false,false)))
|
||||
.contains("WAIT_UNLOAD","OUTBOUND_DOCUMENT").doesNotContain("SAILING_CLEARANCE","WAIT_DISPATCH");
|
||||
assertThat(WorkflowTabService.classify(fact(1,"100",null,false),"DELIVERED",null)).contains("SIGNED").doesNotContain("WAIT_DISPATCH");
|
||||
}
|
||||
/** 数值格式不改变版本,值或来源变化必须重新确认。 */
|
||||
@Test void independentWeightVersion() {
|
||||
var hash=ChargeableWeightService.fingerprint(fact(1,"100.0000",null,false));
|
||||
assertThat(ChargeableWeightService.weight(fact(1,"100",hash,false)).confirmed()).isTrue();
|
||||
assertThat(ChargeableWeightService.weight(fact(1,"101",hash,false)).confirmed()).isFalse();
|
||||
assertThat(ChargeableWeightService.weight(fact(2,"100",hash,false)).confirmed()).isFalse();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package com.baiyue.firstleg.workflow;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.h2.jdbcx.JdbcDataSource;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.mybatis.spring.SqlSessionTemplate;
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
|
||||
import java.nio.file.*;
|
||||
import java.util.List;
|
||||
import static org.assertj.core.api.Assertions.*;
|
||||
/** 真实Mapper和隔离内存库验证资料归属、计费重确认和历史失效。 */
|
||||
class WorkflowFactPersistenceTest {
|
||||
/** 测试建表不连接业务数据库。 */
|
||||
@Test void clearanceAndWeightConfirmationPersistIndependently() throws Exception {
|
||||
var ds=new JdbcDataSource();ds.setURL("jdbc:h2:mem:weight-"+java.util.UUID.randomUUID()+";MODE=MySQL;DB_CLOSE_DELAY=-1");
|
||||
var db=new JdbcTemplate(ds);
|
||||
db.execute("CREATE TABLE fl_inbound_order(id BIGINT PRIMARY KEY,tenant_id BIGINT,order_id BIGINT,measure_review_status VARCHAR(30),chargeable_weight_kg DECIMAL(18,4),measure_completed_at TIMESTAMP,deleted INT,process_status VARCHAR(30))");
|
||||
db.execute("CREATE TABLE fl_loading_plan_item(id BIGINT,inbound_id BIGINT,account_id BIGINT,loading_plan_id BIGINT,deleted INT)");
|
||||
db.execute("CREATE TABLE fl_loading_plan(id BIGINT,plan_status VARCHAR(30),container_booking_id BIGINT)");
|
||||
db.execute("CREATE TABLE fl_loading_pick_task(id BIGINT,loading_plan_id BIGINT,task_status VARCHAR(30))");
|
||||
db.execute("CREATE TABLE fl_loading_pick_item(pick_task_id BIGINT,loading_plan_item_id BIGINT,item_status VARCHAR(30),picked_package_count INT)");
|
||||
db.execute("CREATE TABLE fl_container_booking(id BIGINT,record_status VARCHAR(30))");
|
||||
db.execute("CREATE TABLE fl_carrier_schedule_node_fact(container_booking_id BIGINT,standard_node VARCHAR(40),actual_at TIMESTAMP)");
|
||||
db.execute("CREATE TABLE fl_container_document(container_booking_id BIGINT,document_type VARCHAR(40),file_id BIGINT)");
|
||||
db.execute("CREATE TABLE fl_customs_customer_document_inbound(inbound_id BIGINT,tenant_id BIGINT,document_id BIGINT)");
|
||||
db.execute("CREATE TABLE fl_customs_customer_document(id BIGINT,tenant_id BIGINT,status VARCHAR(30),customs_container_id BIGINT)");
|
||||
db.execute("CREATE TABLE fl_customs_container(id BIGINT,loading_plan_id BIGINT,status VARCHAR(40))");
|
||||
db.execute("ALTER TABLE fl_inbound_order ADD tax_mode VARCHAR(30)");
|
||||
db.execute("ALTER TABLE fl_inbound_order ADD parent_inbound_id BIGINT");
|
||||
db.execute("ALTER TABLE fl_inbound_order ADD inbound_role VARCHAR(30)");
|
||||
db.execute("ALTER TABLE fl_inbound_order ADD split_purpose VARCHAR(30)");
|
||||
db.execute(Files.readString(Path.of("src/main/resources/db/chargeable-weight-confirmation.sql")));
|
||||
db.update("INSERT INTO fl_inbound_order(id,tenant_id,order_id,measure_review_status,chargeable_weight_kg,measure_completed_at,deleted,process_status,tax_mode) VALUES(1,11,101,'APPROVED',100,CURRENT_TIMESTAMP,0,'LOADED','TAX_REFUND'),(2,22,102,'APPROVED',200,CURRENT_TIMESTAMP,0,'LOADED','BUY_DECLARATION')");
|
||||
db.update("INSERT INTO fl_loading_plan_item VALUES(3,1,11,4,0)");
|
||||
db.update("INSERT INTO fl_loading_plan VALUES(4,'COMPLETED',5)");
|
||||
db.update("INSERT INTO fl_container_booking VALUES(5,'ACTIVE')");
|
||||
db.update("INSERT INTO fl_loading_pick_task VALUES(6,4,'COMPLETED')");
|
||||
db.update("INSERT INTO fl_loading_pick_item VALUES(6,3,'PICKED',2)");
|
||||
db.update("INSERT INTO fl_carrier_schedule_node_fact VALUES(5,'DEPARTED_ORIGIN_PORT',CURRENT_TIMESTAMP)");
|
||||
var config=new MybatisConfiguration();config.setMapUnderscoreToCamelCase(true);config.addMapper(WorkflowFactMapper.class);
|
||||
config.addMapper(com.baiyue.firstleg.mapper.ContainerBookingMapper.class);
|
||||
var factory=new MybatisSqlSessionFactoryBean();factory.setDataSource(ds);factory.setConfiguration(config);
|
||||
var mapper=new SqlSessionTemplate(factory.getObject()).getMapper(WorkflowFactMapper.class);
|
||||
var containers=new SqlSessionTemplate(factory.getObject()).getMapper(com.baiyue.firstleg.mapper.ContainerBookingMapper.class);
|
||||
assertThat(containers.hasActualVesselDeparture(5)).isOne();
|
||||
assertThat(containers.hasActualVesselDeparture(6)).isZero();
|
||||
db.update("INSERT INTO fl_carrier_schedule_node_fact VALUES(6,'DEPARTED_ORIGIN_PORT',NULL),(6,'ARRIVED_DESTINATION_PORT',CURRENT_TIMESTAMP)");
|
||||
assertThat(containers.hasActualVesselDeparture(6)).isZero();
|
||||
var repository=new WorkflowFactRepository(mapper);var service=new ChargeableWeightService(repository);
|
||||
assertThat(service.read(22,101)).isEmpty();
|
||||
assertThat(mapper.facts(List.of(1L))).singleElement().satisfies(f->{assertThat(f.departed()).isTrue();assertThat(f.clearanceUploaded()).isFalse();assertThat(f.missingCustoms()).isTrue();});
|
||||
db.update("INSERT INTO fl_container_document VALUES(5,'DESTINATION_CLEARANCE',99)");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).clearanceUploaded()).isTrue();
|
||||
db.update("INSERT INTO fl_customs_container VALUES(8,4,'WAITING_CUSTOMER_DOCUMENTS')");
|
||||
db.update("INSERT INTO fl_customs_customer_document VALUES(9,22,'ACTIVE',8)");
|
||||
db.update("INSERT INTO fl_customs_customer_document_inbound VALUES(1,22,9)");
|
||||
assertThat(mapper.facts(List.of(1L))).singleElement().satisfies(f->{
|
||||
assertThat(f.missingCustoms()).isTrue();assertThat(f.exportCustomsReady()).isFalse();
|
||||
});
|
||||
db.update("INSERT INTO fl_customs_customer_document VALUES(10,11,'ACTIVE',8)");
|
||||
db.update("INSERT INTO fl_customs_customer_document_inbound VALUES(1,11,10)");
|
||||
assertThat(mapper.facts(List.of(1L))).singleElement().satisfies(f->{assertThat(f.missingCustoms()).isFalse();assertThat(f.exportCustomsReady()).isTrue();});
|
||||
// 本票上传后即可汇总,不必等同柜其他票或点击开始报关;完成报关后仍等待实际开船。
|
||||
for (String status : List.of("READY_TO_START", "DECLARING", "COMPLETED")) {
|
||||
db.update("UPDATE fl_customs_container SET status=? WHERE id=8", status);
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).exportCustomsReady()).isTrue();
|
||||
}
|
||||
db.update("UPDATE fl_customs_customer_document SET status='DELETED' WHERE id=10");
|
||||
assertThat(mapper.facts(List.of(1L))).singleElement().satisfies(f->{
|
||||
assertThat(f.missingCustoms()).isTrue();assertThat(f.exportCustomsReady()).isFalse();
|
||||
});
|
||||
db.update("UPDATE fl_customs_customer_document SET status='ACTIVE' WHERE id=10");
|
||||
db.update("INSERT INTO fl_customs_container VALUES(18,14,'READY_TO_START')");
|
||||
db.update("UPDATE fl_customs_customer_document SET customs_container_id=18 WHERE id=10");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).exportCustomsReady()).isFalse();
|
||||
db.update("UPDATE fl_customs_customer_document SET customs_container_id=8 WHERE id=10");
|
||||
db.update("UPDATE fl_loading_plan SET plan_status='LOADING' WHERE id=4");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).exportCustomsReady()).isFalse();
|
||||
db.update("UPDATE fl_loading_plan SET plan_status='COMPLETED' WHERE id=4");
|
||||
db.update("UPDATE fl_loading_pick_item SET picked_package_count=0");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).exportCustomsReady()).isFalse();
|
||||
db.update("UPDATE fl_loading_pick_item SET picked_package_count=2");
|
||||
// 不把预计开船当成实际开船;手动或拉取写入的实际节点都读同一事实表。
|
||||
db.update("UPDATE fl_carrier_schedule_node_fact SET actual_at=NULL");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).departed()).isFalse();
|
||||
db.update("UPDATE fl_carrier_schedule_node_fact SET actual_at=CURRENT_TIMESTAMP");
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).departed()).isTrue();
|
||||
// 买单票无需客户上传退税资料,但同样必须有实际装柜证据。
|
||||
assertThat(mapper.facts(List.of(2L)).get(0).exportCustomsReady()).isFalse();
|
||||
db.update("INSERT INTO fl_loading_plan_item VALUES(13,2,22,4,0)");
|
||||
db.update("INSERT INTO fl_loading_pick_item VALUES(6,13,'PICKED',1)");
|
||||
assertThat(mapper.facts(List.of(2L))).singleElement().satisfies(f->{
|
||||
assertThat(f.missingCustoms()).isFalse();assertThat(f.exportCustomsReady()).isTrue();
|
||||
});
|
||||
var current=service.read(11,101).get(0);
|
||||
assertThat(service.confirm(11,7,1,"cmd",new WorkflowFacts.Confirm(current.fingerprint())).confirmed()).isTrue();
|
||||
assertThat(service.confirm(11,7,1,"cmd",new WorkflowFacts.Confirm(current.fingerprint())).confirmed()).isTrue();
|
||||
assertThat(db.queryForObject("SELECT COUNT(*) FROM fl_chargeable_weight_confirmation",Integer.class)).isEqualTo(1);
|
||||
assertThatThrownBy(()->service.confirm(11,7,1,"cmd",new WorkflowFacts.Confirm("0".repeat(64)))).isInstanceOf(com.baiyue.common.core.exception.BizException.class);
|
||||
db.update("UPDATE fl_inbound_order SET chargeable_weight_kg=101 WHERE id=1");
|
||||
assertThat(service.read(11,101).get(0).confirmed()).isFalse();
|
||||
assertThatThrownBy(()->service.confirm(11,7,1,"old",new WorkflowFacts.Confirm(current.fingerprint()))).isInstanceOf(com.baiyue.common.core.exception.BizException.class);
|
||||
assertThatThrownBy(()->service.confirm(22,7,1,"foreign",new WorkflowFacts.Confirm(current.fingerprint()))).isInstanceOf(com.baiyue.common.core.exception.BizException.class);
|
||||
// 现行部分装柜由来源单承接实装,余量子单独立继续分柜,两票均应保留。
|
||||
db.update("INSERT INTO fl_inbound_order(id,tenant_id,order_id,measure_review_status,chargeable_weight_kg,measure_completed_at,deleted,process_status,tax_mode,parent_inbound_id,inbound_role,split_purpose) VALUES(3,11,103,'APPROVED',50,CURRENT_TIMESTAMP,0,'WAIT_SPLIT','BUY_DECLARATION',1,'CHILD','REMAINDER')");
|
||||
assertThat(mapper.facts(List.of(1L,3L))).hasSize(2);
|
||||
assertThat(mapper.facts(List.of(1L)).get(0).departed()).isTrue();
|
||||
assertThat(mapper.facts(List.of(3L)).get(0).departed()).isFalse();
|
||||
assertThat(service.read(11,101)).hasSize(1);
|
||||
assertThat(service.read(11,103)).hasSize(1);
|
||||
// 旧模型已将实装移至独立子票时,父汇总不能重复进入页签或确认。
|
||||
db.update("UPDATE fl_inbound_order SET process_status='LOADED',split_purpose='LOADED' WHERE id=3");
|
||||
assertThat(service.read(11,101)).isEmpty();
|
||||
assertThatThrownBy(()->service.confirm(11,7,1,"parent",new WorkflowFacts.Confirm(current.fingerprint()))).isInstanceOf(com.baiyue.common.core.exception.BizException.class);
|
||||
var child=service.read(11,103).get(0);
|
||||
assertThat(child.confirmed()).isFalse();
|
||||
assertThatThrownBy(()->service.confirm(11,7,3,"cmd",new WorkflowFacts.Confirm(child.fingerprint()))).isInstanceOf(com.baiyue.common.core.exception.BizException.class);
|
||||
assertThat(service.confirm(11,7,3,"child",new WorkflowFacts.Confirm(child.fingerprint())).confirmed()).isTrue();
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
|
||||
+1
-2
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
|
||||
@@ -2,8 +2,7 @@
|
||||
|
||||
## 数据库访问与中文注释约束
|
||||
|
||||
- 强制遵守根 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则:正常业务访问统一为 `Controller → Service → Repository → Mapper`,不得省略 Repository 或跨层直调;生产 SQL 由 Mapper 执行,Repository 不得直接使用 JdbcTemplate 或原生 JDBC。非 HTTP 入口从 Service 进入;无数据库模块不引入数据库访问。
|
||||
- 每个手写方法及构造器须有简短中文说明;核心业务规则、复杂 SQL、事务、锁、幂等、并发及失败处理须补充适量中文注释,重点说明原因和边界。新增、修改方法立即执行,触及的存量代码同步整改。
|
||||
- 强制继承 `../AGENTS.md` 的“数据库访问与中文代码注释”全部规则;该节是分层、SQL 执行和方法/核心逻辑中文注释的唯一维护处,本模块不另设例外。
|
||||
|
||||
## 职责与边界
|
||||
|
||||
|
||||
+9
@@ -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) {
|
||||
|
||||
+7
-5
@@ -11,20 +11,22 @@ import java.util.HashSet;
|
||||
public class OutboundQuantityRepository {
|
||||
@Resource private OutboundPalletItemMapper pallets;
|
||||
|
||||
/** 废弃退货来源依据已冻结箱唛计数,读取已有单据也不会把件数当箱数。 */
|
||||
/** 废弃来源依据已冻结箱唛去重计数,无箱唛的库存明细保留箱数快照。 */
|
||||
public Integer boxes(OutboundOrder outbound) {
|
||||
if (!"DISCARD_OUTBOUND".equals(outbound.getOutboundType())) return outbound.getPackageCount();
|
||||
var lines = pallets.findByOutbound(outbound.getCustomerId(), outbound.getId());
|
||||
if (lines.isEmpty()) return outbound.getPackageCount();
|
||||
var returnBoxes = new HashSet<String>();
|
||||
var markedBoxes = new HashSet<String>();
|
||||
int count = 0;
|
||||
for (var line : lines) {
|
||||
if (line.getReturnSkuQuantity() != null && line.getCartonMarks() != null && !line.getCartonMarks().isBlank()) {
|
||||
returnBoxes.add(line.getInboundCode() + ":" + line.getCartonMarks());
|
||||
if (line.getCartonMarks() != null && !line.getCartonMarks().isBlank()) {
|
||||
// 同一箱的多个 SKU 共用箱唛,只计一个实物箱;一行也可能冻结多个箱唛。
|
||||
java.util.Arrays.stream(line.getCartonMarks().split(",")).map(String::trim)
|
||||
.filter(mark -> !mark.isEmpty()).forEach(markedBoxes::add);
|
||||
} else {
|
||||
count = Math.addExact(count, java.util.Objects.requireNonNullElse(line.getPackageCount(), 0));
|
||||
}
|
||||
}
|
||||
return Math.addExact(count, returnBoxes.size());
|
||||
return Math.addExact(count, markedBoxes.size());
|
||||
}
|
||||
}
|
||||
|
||||
+65
-5
@@ -130,6 +130,7 @@ public class DeliveryTransferService {
|
||||
@Resource private DeliveryExecutionGuard deliveryExecution;
|
||||
@Resource private com.baiyue.lastleg.dispatch.port.DispatchExecutionPort execution;
|
||||
@Resource private com.baiyue.lastleg.delivery.repository.DeliveryCancellationRepository cancellations;
|
||||
@Resource private com.baiyue.lastleg.delivery.repository.OutboundQuantityRepository outboundQuantities;
|
||||
|
||||
@Transactional
|
||||
public DeliveryResponses.PdaTask createOneClick(String customerId, String operatorId, DeliveryRequests.OneClickOutbound request) {
|
||||
@@ -596,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(
|
||||
@@ -719,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) {
|
||||
@@ -768,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;
|
||||
@@ -1048,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"),
|
||||
@@ -1060,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);
|
||||
}
|
||||
|
||||
@@ -1118,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());
|
||||
@@ -1146,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) {
|
||||
@@ -1341,7 +1397,11 @@ public class DeliveryTransferService {
|
||||
} catch (JsonProcessingException exception) { throw new IllegalStateException("费用覆盖确认无法读取", exception); }
|
||||
}
|
||||
|
||||
private DeliveryResponses.OutboundRow outboundRow(OutboundOrder o) { return new DeliveryResponses.OutboundRow(o.getId(), o.getOutboundNo(), o.getDispatchNo(), o.getOverseasWarehouseId(), "DISCARD_OUTBOUND".equals(o.getOutboundType()) ? null : o.getLxCodes(), o.getStatus(), o.getPalletCount(), o.getPackageCount(), o.getGrossWeightKg(), o.getVolumeWeightKg(), o.getVolumeCbm(), o.getCreatedAt(), o.getOutboundType()); }
|
||||
/** 废弃出库按冻结实物箱汇总,避免历史件数快照被展示为箱数。 */
|
||||
private DeliveryResponses.OutboundRow outboundRow(OutboundOrder o) {
|
||||
Integer boxes = "DISCARD_OUTBOUND".equals(o.getOutboundType()) ? outboundQuantities.boxes(o) : o.getPackageCount();
|
||||
return new DeliveryResponses.OutboundRow(o.getId(), o.getOutboundNo(), o.getDispatchNo(), o.getOverseasWarehouseId(), "DISCARD_OUTBOUND".equals(o.getOutboundType()) ? null : o.getLxCodes(), o.getStatus(), o.getPalletCount(), boxes, o.getGrossWeightKg(), o.getVolumeWeightKg(), o.getVolumeCbm(), o.getCreatedAt(), o.getOutboundType());
|
||||
}
|
||||
private DeliveryResponses.OutboundPalletRow outboundPalletRow(OutboundPalletItem item) {
|
||||
return new DeliveryResponses.OutboundPalletRow(item.getId(), item.getPalletNo(), item.getCartonMarks(),
|
||||
item.getInboundCode(), item.getDestinationWarehouseCode(), item.getDestinationWarehouseName(),
|
||||
|
||||
+8
@@ -46,6 +46,14 @@ public class CargoDiscardController {
|
||||
return ApiResponse.success(service.page(scope(user, customerId), query));
|
||||
}
|
||||
|
||||
/** 读取全部筛选结果的数量统计,与分页记录分开返回。 */
|
||||
@GetMapping("/statistics")
|
||||
public ApiResponse<com.baiyue.lastleg.discard.service.CargoDiscardStatisticsService.Statistics> statistics(
|
||||
@AuthenticationPrincipal AuthenticatedUser user, @RequestParam(required = false) String customerId,
|
||||
@Valid CargoDiscardRequests.Query query) {
|
||||
return ApiResponse.success(service.statistics(scope(user, customerId), query));
|
||||
}
|
||||
|
||||
@GetMapping("/{discardNo}")
|
||||
public ApiResponse<CargoDiscardResponses.Detail> detail(@AuthenticationPrincipal AuthenticatedUser user,
|
||||
@RequestParam(required = false) String customerId, @PathVariable String discardNo) {
|
||||
|
||||
+8
@@ -32,6 +32,14 @@ public class MerchantCargoDiscardController {
|
||||
@PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_DISCARD_LIST + "')")
|
||||
public ApiResponse<PageResult<CargoDiscardResponses.Summary>> page(@AuthenticationPrincipal AuthenticatedUser user,
|
||||
@Valid CargoDiscardRequests.Query query) { return ApiResponse.success(service.page(customer(user), query)); }
|
||||
/** 客户统计只读取当前认证客户,不接受客户端客户归属。 */
|
||||
@GetMapping("/statistics")
|
||||
@PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_DISCARD_LIST + "')")
|
||||
public ApiResponse<com.baiyue.lastleg.discard.service.CargoDiscardStatisticsService.Statistics> statistics(
|
||||
@AuthenticationPrincipal AuthenticatedUser user, @Valid CargoDiscardRequests.Query query) {
|
||||
return ApiResponse.success(service.statistics(customer(user), query));
|
||||
}
|
||||
|
||||
@GetMapping("/{discardNo}")
|
||||
@PreAuthorize("hasAuthority('" + OverseasPermissions.MERCHANT_DISCARD_LIST + "')")
|
||||
public ApiResponse<CargoDiscardResponses.Detail> detail(@AuthenticationPrincipal AuthenticatedUser user,
|
||||
|
||||
+2
-1
@@ -33,5 +33,6 @@ public final class CargoDiscardRequests {
|
||||
|
||||
public record Query(@Min(1) long page, @Min(1) @Max(200) long size,
|
||||
String discardNo, String inboundCode, String overseasWarehouseId,
|
||||
String status, LocalDateTime createdFrom, LocalDateTime createdTo) {}
|
||||
String status, LocalDateTime createdFrom, LocalDateTime createdTo,
|
||||
LocalDateTime completedFrom, LocalDateTime completedTo) {}
|
||||
}
|
||||
|
||||
+12
-3
@@ -29,15 +29,24 @@ 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) {
|
||||
String productName, int availablePackagesSnapshot, int discardPackages, List<String> cartonMarks,
|
||||
String quantityUnit, Integer actualDiscardPackages, String pdaStatus) {
|
||||
/** 无来源事实的调用不猜测数量单位或实际完成数。 */
|
||||
public Item(Long id, Long orderId, String inboundCode, String skuCode, String productName, int availablePackagesSnapshot, int discardPackages, List<String> cartonMarks) {
|
||||
this(id, orderId, inboundCode, skuCode, productName, availablePackagesSnapshot, discardPackages, cartonMarks, null, null, null);
|
||||
}
|
||||
public Item(Long id, Long orderId, String inboundCode, String skuCode, String productName, int availablePackagesSnapshot, int discardPackages) {
|
||||
this(id, orderId, inboundCode, skuCode, productName, availablePackagesSnapshot, discardPackages, List.of());
|
||||
}
|
||||
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package com.baiyue.lastleg.discard.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import java.util.List;
|
||||
|
||||
/** 只读取废弃明细真实关联的本库托盘身份。 */
|
||||
@Mapper
|
||||
public interface CargoDiscardDimensionMapper {
|
||||
/** 无托盘事实以空串保留,避免把不适用维度伪造为零。 */
|
||||
@Select("""
|
||||
SELECT COALESCE(CASE WHEN i.return_carton_id IS NOT NULL THEN r.pallet_code
|
||||
WHEN i.inventory_position_id IS NOT NULL THEN p.pallet_no ELSE d.pallet_no END,'')
|
||||
FROM ll_cargo_discard_item i
|
||||
LEFT JOIN ll_return_inventory_carton r ON r.id=i.return_carton_id AND r.customer_id=i.customer_id
|
||||
LEFT JOIN ll_inventory_position p ON p.id=i.inventory_position_id AND p.customer_id=i.customer_id
|
||||
LEFT JOIN ll_dropship_order_profile d ON d.id=i.profile_id AND d.customer_id=i.customer_id
|
||||
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);
|
||||
}
|
||||
+8
-7
@@ -25,26 +25,27 @@ 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,仍严格限定客户、批次、仓和托盘。 */
|
||||
@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
|
||||
AND t.transfer_no=p.batch_no AND t.operating_warehouse_id=p.overseas_warehouse_id
|
||||
JOIN ll_warehouse_transfer_carton c ON c.customer_id=t.customer_id AND c.transfer_order_id=t.id AND c.status='EXPECTED'
|
||||
JOIN ll_warehouse_transfer_pallet tp ON tp.customer_id=t.customer_id AND tp.transfer_order_id=t.id
|
||||
AND tp.warehouse_pallet_id=p.pallet_id AND tp.status='COMPLETED'
|
||||
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 (b.sku_code='MIXED' OR COALESCE(i.sku_code,'')=COALESCE(b.sku_code,''))
|
||||
WHERE p.customer_id=#{customerId} AND p.id=#{positionId}
|
||||
AND (SELECT COUNT(*) FROM ll_inventory_position current_position
|
||||
WHERE current_position.customer_id=p.customer_id AND current_position.balance_id=p.balance_id
|
||||
AND current_position.batch_no=p.batch_no AND current_position.overseas_warehouse_id=p.overseas_warehouse_id
|
||||
AND current_position.available_packages+current_position.hold_packages+current_position.allocated_packages+current_position.picked_packages>0)=1
|
||||
ORDER BY id
|
||||
""")
|
||||
List<com.baiyue.lastleg.discard.model.CargoDiscardStockCartonRow> genericCartons(@Param("customerId") String customerId, @Param("positionId") Long positionId);
|
||||
|
||||
+8
-1
@@ -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());
|
||||
}
|
||||
}
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baiyue.lastleg.discard.model;
|
||||
|
||||
import com.baiyue.lastleg.returnreceipt.entity.ReturnInventoryCarton;
|
||||
|
||||
/** 废弃作业沿用签收时实物标签,兼容历史包裹内部 RP 编号。 */
|
||||
public final class CargoDiscardReturnMark {
|
||||
/** 工具类不允许实例化。 */
|
||||
private CargoDiscardReturnMark() { }
|
||||
|
||||
/** 包裹取签收单元编码;箱子及缺少来源编码的历史数据保留原箱唛。 */
|
||||
public static String of(ReturnInventoryCarton carton) {
|
||||
if (carton == null) return null;
|
||||
if ("PARCEL".equals(carton.getSourceUnitType()) && carton.getSourceUnitCode() != null
|
||||
&& !carton.getSourceUnitCode().isBlank()) return carton.getSourceUnitCode().trim();
|
||||
return carton.getCartonMark();
|
||||
}
|
||||
}
|
||||
+1
@@ -9,4 +9,5 @@ public class CargoDiscardStockCartonRow {
|
||||
private String cartonMark;
|
||||
private String skuCode;
|
||||
private String sourceType;
|
||||
private String skuItemsJson;
|
||||
}
|
||||
|
||||
+2
-1
@@ -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) { }
|
||||
|
||||
+46
-36
@@ -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,30 +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());
|
||||
return carton.getCartonMark() == null ? List.of() : List.of(carton.getCartonMark());
|
||||
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); }
|
||||
}
|
||||
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.baiyue.lastleg.discard.repository;
|
||||
|
||||
import com.baiyue.lastleg.discard.entity.CargoDiscardItem;
|
||||
import com.baiyue.lastleg.discard.mapper.CargoDiscardItemMapper;
|
||||
import com.baiyue.lastleg.discard.mapper.CargoDiscardDimensionMapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.List;
|
||||
|
||||
/** 封装数量统计的明细与来源托盘读取。 */
|
||||
@Repository
|
||||
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;
|
||||
}
|
||||
}
|
||||
+46
@@ -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); }
|
||||
}
|
||||
+3
-2
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.baiyue.lastleg.discard.repository;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baiyue.lastleg.discard.dto.CargoDiscardRequests;
|
||||
import com.baiyue.lastleg.discard.entity.CargoDiscardApplication;
|
||||
import com.baiyue.lastleg.discard.mapper.CargoDiscardApplicationMapper;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.util.StringUtils;
|
||||
import java.util.List;
|
||||
|
||||
/** 列表和全筛选统计共用同一客户及时间过滤条件。 */
|
||||
@Repository
|
||||
public class CargoDiscardQueryRepository {
|
||||
@Resource private CargoDiscardApplicationMapper applications;
|
||||
|
||||
/** 返回全部筛选单据,不受页面大小影响。 */
|
||||
public List<CargoDiscardApplication> list(String customerId, CargoDiscardRequests.Query query) {
|
||||
return applications.selectList(filter(customerId, query));
|
||||
}
|
||||
|
||||
/** 完成时间使用客户确认时间,与客户端完成时间展示保持一致。 */
|
||||
public static LambdaQueryWrapper<CargoDiscardApplication> filter(String customerId, CargoDiscardRequests.Query query) {
|
||||
return new LambdaQueryWrapper<CargoDiscardApplication>()
|
||||
.eq(StringUtils.hasText(customerId), CargoDiscardApplication::getCustomerId, customerId)
|
||||
.like(StringUtils.hasText(query.discardNo()), CargoDiscardApplication::getDiscardNo, query.discardNo())
|
||||
.like(StringUtils.hasText(query.inboundCode()), CargoDiscardApplication::getInboundCodes, query.inboundCode())
|
||||
.eq(StringUtils.hasText(query.overseasWarehouseId()), CargoDiscardApplication::getOverseasWarehouseId, query.overseasWarehouseId())
|
||||
.eq(StringUtils.hasText(query.status()), CargoDiscardApplication::getStatus, query.status())
|
||||
.ge(query.createdFrom() != null, CargoDiscardApplication::getCreatedAt, query.createdFrom())
|
||||
.le(query.createdTo() != null, CargoDiscardApplication::getCreatedAt, query.createdTo())
|
||||
.ge(query.completedFrom() != null, CargoDiscardApplication::getCustomerConfirmedAt, query.completedFrom())
|
||||
.le(query.completedTo() != null, CargoDiscardApplication::getCustomerConfirmedAt, query.completedTo())
|
||||
.orderByDesc(CargoDiscardApplication::getCreatedAt).orderByDesc(CargoDiscardApplication::getId);
|
||||
}
|
||||
}
|
||||
+47
@@ -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); }
|
||||
}
|
||||
+19
-4
@@ -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;
|
||||
@@ -73,7 +74,7 @@ public class CargoDiscardOutboundService {
|
||||
|| !application.getOverseasWarehouseId().equals(carton.getOverseasWarehouseId()))
|
||||
throw conflict("废弃明细关联退货箱不存在或仓库不匹配");
|
||||
palletNo = carton.getPalletCode() == null || carton.getPalletCode().isBlank() ? null : carton.getPalletCode();
|
||||
cartonMarks = carton.getCartonMark();
|
||||
cartonMarks = com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton);
|
||||
} else {
|
||||
var profile = profiles.selectById(line.getProfileId());
|
||||
if (profile == null || !application.getCustomerId().equals(profile.getCustomerId()))
|
||||
@@ -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,20 +100,28 @@ 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("废弃出库明细关联失效"));
|
||||
boolean returned = line.getReturnCartonId() != null;
|
||||
int boxes = returned ? (returnBoxIds.add(line.getReturnCartonId()) ? 1 : 0) : line.getDiscardPackages();
|
||||
if (returned) {
|
||||
var carton = returnCartons.selectById(line.getReturnCartonId());
|
||||
if (carton == null || !application.getCustomerId().equals(carton.getCustomerId()))
|
||||
throw conflict("废弃明细关联退货箱不存在");
|
||||
snapshot.setCartonMarks(com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton));
|
||||
}
|
||||
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");
|
||||
@@ -128,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); }
|
||||
}
|
||||
|
||||
+31
-18
@@ -50,6 +50,7 @@ import java.util.Set;
|
||||
|
||||
@Service
|
||||
public class CargoDiscardService {
|
||||
@Resource private CargoDiscardStatisticsService statisticsService;
|
||||
@Resource private com.baiyue.lastleg.discard.repository.CargoDiscardQuantityRepository quantities;
|
||||
@Resource private com.baiyue.lastleg.service.LastlegOrderNoGenerator orderNoGenerator;
|
||||
public static final String APPROVAL_PERMISSION = "platform:overseas-warehouse:discard:approve";
|
||||
@@ -97,14 +98,14 @@ public class CargoDiscardService {
|
||||
if (returnCartons == null || returnCartonItems == null) return result;
|
||||
for (ReturnInventoryCarton carton : returnCartons.findAvailable(customerId, null)) {
|
||||
if (StringUtils.hasText(keyword) && !containsIgnoreCase(carton.getSourceReturnNo(), keyword)
|
||||
&& !containsIgnoreCase(carton.getCartonMark(), keyword)) continue;
|
||||
&& !containsIgnoreCase(com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton), keyword)) continue;
|
||||
List<CargoDiscardResponses.CandidateSku> skus = returnCartonItems.listCarton(carton.getId()).stream()
|
||||
.filter(item -> value(item.getQuantity()) > 0)
|
||||
.map(item -> new CargoDiscardResponses.CandidateSku(item.getSkuCode(), item.getProductNameZh(), value(item.getQuantity())))
|
||||
.toList();
|
||||
long available = skus.stream().mapToLong(CargoDiscardResponses.CandidateSku::availablePackages).sum();
|
||||
if (available <= 0) continue;
|
||||
result.add(new CargoDiscardResponses.Candidate(null, "RETURN_CARTON", carton.getId(), carton.getCartonMark(),
|
||||
result.add(new CargoDiscardResponses.Candidate(null, "RETURN_CARTON", carton.getId(), com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton),
|
||||
carton.getSourceReturnNo(), carton.getSourceReturnNo(), carton.getOverseasWarehouseId(), null,
|
||||
null, available, skus));
|
||||
}
|
||||
@@ -164,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) {
|
||||
@@ -201,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()) {
|
||||
@@ -213,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();
|
||||
@@ -235,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);
|
||||
@@ -253,7 +259,8 @@ public class CargoDiscardService {
|
||||
if ("INVENTORY".equals(line.getSourceType())) return stockService.cartonMarks(line);
|
||||
if (isReturnItem(line)) {
|
||||
var carton = returnCartons.selectById(line.getReturnCartonId());
|
||||
return carton == null || carton.getCartonMark() == null ? List.of() : List.of(carton.getCartonMark());
|
||||
String mark = com.baiyue.lastleg.discard.model.CargoDiscardReturnMark.of(carton);
|
||||
return mark == null ? List.of() : List.of(mark);
|
||||
}
|
||||
return discardCartons.listApplication(customer, application.getId()).stream().filter(link -> link.getItemId().equals(line.getId()))
|
||||
.map(CargoDiscardCarton::getCartonMark).distinct().sorted().toList();
|
||||
@@ -261,16 +268,7 @@ public class CargoDiscardService {
|
||||
|
||||
public PageResult<CargoDiscardResponses.Summary> page(String customerId, CargoDiscardRequests.Query query) {
|
||||
validateQuery(query);
|
||||
LambdaQueryWrapper<CargoDiscardApplication> wrapper = new LambdaQueryWrapper<CargoDiscardApplication>()
|
||||
.eq(StringUtils.hasText(customerId), CargoDiscardApplication::getCustomerId, customerId)
|
||||
.like(StringUtils.hasText(query.discardNo()), CargoDiscardApplication::getDiscardNo, query.discardNo())
|
||||
.like(StringUtils.hasText(query.inboundCode()), CargoDiscardApplication::getInboundCodes, query.inboundCode())
|
||||
.eq(StringUtils.hasText(query.overseasWarehouseId()), CargoDiscardApplication::getOverseasWarehouseId,
|
||||
query.overseasWarehouseId())
|
||||
.eq(StringUtils.hasText(query.status()), CargoDiscardApplication::getStatus, query.status())
|
||||
.ge(query.createdFrom() != null, CargoDiscardApplication::getCreatedAt, query.createdFrom())
|
||||
.le(query.createdTo() != null, CargoDiscardApplication::getCreatedAt, query.createdTo())
|
||||
.orderByDesc(CargoDiscardApplication::getCreatedAt).orderByDesc(CargoDiscardApplication::getId);
|
||||
var wrapper = com.baiyue.lastleg.discard.repository.CargoDiscardQueryRepository.filter(customerId, query);
|
||||
Page<CargoDiscardApplication> result = applications.selectPage(Page.of(query.page(), query.size()), wrapper);
|
||||
Map<String, String> names = result.getRecords().stream().anyMatch(a -> !StringUtils.hasText(a.getOverseasWarehouseName()))
|
||||
? warehouseNames() : Map.of();
|
||||
@@ -278,12 +276,19 @@ public class CargoDiscardService {
|
||||
return new PageResult<>(records, query.page(), query.size(), result.getTotal(), result.getPages());
|
||||
}
|
||||
|
||||
/** 全筛选汇总与列表使用同一输入校验,不受当前分页影响。 */
|
||||
public CargoDiscardStatisticsService.Statistics statistics(String customerId, CargoDiscardRequests.Query query) {
|
||||
validateQuery(query);
|
||||
return statisticsService.statistics(customerId, query);
|
||||
}
|
||||
|
||||
public CargoDiscardResponses.Detail detail(String customerId, String discardNo) {
|
||||
CargoDiscardApplication application = applications.findNo(customerId, discardNo);
|
||||
if (application == null) throw notFound("Cargo discard application not found");
|
||||
List<CargoDiscardResponses.Item> itemViews = items.listApplication(customerId, application.getId()).stream()
|
||||
.map(value -> new CargoDiscardResponses.Item(value.getId(), value.getOrderId(), value.getInboundCode(),
|
||||
value.getSkuCode(), value.getProductName(), value.getAvailablePackagesSnapshot(), value.getDiscardPackages(), selectedMarks(customerId, application, value)))
|
||||
value.getSkuCode(), value.getProductName(), value.getAvailablePackagesSnapshot(), value.getDiscardPackages(), selectedMarks(customerId, application, value),
|
||||
value.getReturnCartonId() != null ? "件" : "箱", value.getActualDiscardPackages(), value.getPdaStatus()))
|
||||
.toList();
|
||||
List<CargoDiscardResponses.History> historyViews = histories.listApplication(customerId, application.getId()).stream()
|
||||
.map(value -> new CargoDiscardResponses.History(value.getFromStatus(), value.getToStatus(),
|
||||
@@ -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,
|
||||
@@ -528,6 +538,9 @@ public class CargoDiscardService {
|
||||
}
|
||||
|
||||
private void validateQuery(CargoDiscardRequests.Query query) {
|
||||
if (query.completedFrom() != null && query.completedTo() != null && query.completedFrom().isAfter(query.completedTo())) {
|
||||
throw badRequest("completedFrom must not be after completedTo");
|
||||
}
|
||||
if (StringUtils.hasText(query.status()) && !STATUSES.contains(query.status())) throw badRequest("Unsupported discard status");
|
||||
if (query.createdFrom() != null && query.createdTo() != null && query.createdFrom().isAfter(query.createdTo())) {
|
||||
throw badRequest("createdFrom must not be after createdTo");
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.baiyue.lastleg.discard.service;
|
||||
|
||||
import com.baiyue.lastleg.discard.dto.CargoDiscardRequests;
|
||||
import com.baiyue.lastleg.discard.model.CargoDiscardQuantities;
|
||||
import com.baiyue.lastleg.discard.repository.CargoDiscardQueryRepository;
|
||||
import com.baiyue.lastleg.discard.repository.CargoDiscardDimensionRepository;
|
||||
import jakarta.annotation.Resource;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.HashSet;
|
||||
|
||||
/** 按全部筛选单据统计票、SKU、件、箱和真实来源托盘。 */
|
||||
@Service
|
||||
public class CargoDiscardStatisticsService {
|
||||
@Resource private CargoDiscardQueryRepository queries;
|
||||
@Resource private CargoDiscardDimensionRepository dimensions;
|
||||
|
||||
public record Statistics(long orderCount, int skuCount, long requestedPackages, Long actualPackages,
|
||||
Long requestedPieces, Long actualPieces, Integer palletCount) {}
|
||||
|
||||
/** 已确认实际数独立汇总;缺失件数或托盘事实返回空值,不从箱数换算。 */
|
||||
public Statistics statistics(String customer, CargoDiscardRequests.Query query) {
|
||||
var applications = queries.list(customer, query);
|
||||
var skus = new HashSet<String>(); var pallets = new HashSet<String>();
|
||||
long boxes = 0, actualBoxes = 0, pieces = 0, actualPieces = 0;
|
||||
boolean piecesKnown = true, actualPiecesKnown = true, actualKnown = false, palletsKnown = true;
|
||||
for (var application : applications) {
|
||||
var lines = dimensions.items(application.getCustomerId(), application.getId());
|
||||
boxes += lines.isEmpty() ? application.getTotalPackages() : CargoDiscardQuantities.boxes(lines, false);
|
||||
if (lines.isEmpty()) { piecesKnown = false; palletsKnown = false; }
|
||||
var confirmed = lines.stream().filter(i -> i.getActualDiscardPackages() != null).toList();
|
||||
if (!confirmed.isEmpty()) { actualKnown = true; actualBoxes += CargoDiscardQuantities.boxes(confirmed, true); }
|
||||
for (var line : lines) {
|
||||
if (line.getSkuCode() != null && !line.getSkuCode().isBlank()) skus.add(line.getSkuCode());
|
||||
if (line.getReturnCartonId() == null) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
var sourcePallets = dimensions.pallets(application.getCustomerId(), application.getId());
|
||||
if (sourcePallets.isEmpty()) palletsKnown = false;
|
||||
for (var pallet : sourcePallets) {
|
||||
if (pallet == null || pallet.isBlank() || "散箱".equals(pallet)) palletsKnown = false;
|
||||
else pallets.add(application.getCustomerId() + ":" + application.getOverseasWarehouseId() + ":" + pallet);
|
||||
}
|
||||
}
|
||||
return new Statistics(applications.size(), skus.size(), boxes, actualKnown ? actualBoxes : null,
|
||||
!applications.isEmpty() && piecesKnown ? pieces : null,
|
||||
actualKnown && actualPiecesKnown ? actualPieces : null,
|
||||
!applications.isEmpty() && palletsKnown ? pallets.size() : null);
|
||||
}
|
||||
}
|
||||
+146
-42
@@ -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,127 +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 (changeBox(customer, carton.getId(), carton.getSourceType(), "TRANSFER".equals(carton.getSourceType()) ? "EXPECTED" : "AVAILABLE", "DISCARD_PENDING") != 1) throw conflict("箱子已被其他作业占用,请刷新后重选");
|
||||
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())) {
|
||||
if (Objects.equals(link.getItemId(), line.getId()) && changeBox(customer, link.getCartonId(), link.getSourceType(), "DISCARD_PENDING", "TRANSFER".equals(link.getSourceType()) && "AVAILABLE".equals(status) ? "EXPECTED" : status) != 1)
|
||||
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); }
|
||||
}
|
||||
|
||||
+24
@@ -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);
|
||||
}
|
||||
}
|
||||
+59
-24
@@ -1,30 +1,65 @@
|
||||
package com.baiyue.lastleg.dispatch.mapper;
|
||||
import com.baiyue.lastleg.dispatch.model.DispatchBolData;
|
||||
|
||||
import org.apache.ibatis.annotations.*;
|
||||
import java.util.List;
|
||||
/** BOL按真实明细客户逐行读取整车,不依赖已移除的主单客户头。 */
|
||||
|
||||
/** BOL读取原调度逐来源数量及真实预约分配,扫码进度和订单商品JOIN均不放大或缩小箱数。 */
|
||||
@Mapper
|
||||
public interface DispatchBolMapper {
|
||||
@Select("SELECT di.customer_id AS customerId,di.destination_type AS destinationType,di.delivery_address AS deliveryAddress,di.postal_code AS postalCode," +
|
||||
"COALESCE(MAX(NULLIF(o.container_no,'')),MAX(NULLIF(ip.container_no,''))) AS containerNo," +
|
||||
"MAX(NULLIF(di.pallet_no,'')) AS palletNo," +
|
||||
"COALESCE(MAX(NULLIF(l.destination_warehouse_code,'')),MAX(NULLIF(di.fba_warehouse_code,''))," +
|
||||
"MAX(NULLIF(di.destination_warehouse_code,''))) AS fbaWarehouseCode," +
|
||||
"COALESCE(MAX(NULLIF(l.destination_warehouse_name,'')),MAX(NULLIF(di.destination_warehouse_name,''))) AS destinationWarehouseName," +
|
||||
"COALESCE(MAX(NULLIF(l.inbound_code,'')),MAX(NULLIF(di.inbound_code,''))) AS warehouseNo," +
|
||||
"GROUP_CONCAT(DISTINCT NULLIF(od.shipment_no,'') ORDER BY od.shipment_no SEPARATOR ', ') AS fbaShipmentId," +
|
||||
"GROUP_CONCAT(DISTINCT NULLIF(od.fba_tracking_no,'') ORDER BY od.fba_tracking_no SEPARATOR ', ') AS poReferenceNo," +
|
||||
"CASE WHEN MAX(l.id) IS NULL THEN COALESCE(MAX(di.package_count),0) " +
|
||||
"WHEN COALESCE(MAX(a.picked_package_count),0)>0 THEN MAX(a.picked_package_count) " +
|
||||
"ELSE COALESCE(MAX(a.planned_package_count),0) END AS packageCount " +
|
||||
"FROM ll_dispatch_item di " +
|
||||
"LEFT JOIN ll_inbound_plan_pallet p ON p.id=di.plan_pallet_id " +
|
||||
"LEFT JOIN ll_inbound_plan ip ON ip.id=p.plan_id AND ip.customer_id=di.customer_id " +
|
||||
"LEFT JOIN ll_inbound_plan_pallet_allocation a ON a.pallet_id=p.id AND di.return_receipt_id IS NULL AND COALESCE(di.source_business_type,'')<>'RELABEL_ORDER' " +
|
||||
"LEFT JOIN ll_inbound_plan_line l ON l.id=a.line_id AND l.customer_id=di.customer_id " +
|
||||
"LEFT JOIN ll_order o ON o.id=l.order_id AND o.customer_id=di.customer_id " +
|
||||
"LEFT JOIN ll_order_detail od ON od.order_id=l.order_id AND od.customer_id=di.customer_id " +
|
||||
"WHERE di.dispatch_order_id=#{dispatchOrderId} " +
|
||||
"GROUP BY di.id,di.customer_id,di.destination_type,di.delivery_address,di.postal_code,l.id ORDER BY di.id,l.id")
|
||||
List<DispatchBolData.Line> findWholeDispatch(@Param("dispatchOrderId") Long dispatchOrderId);
|
||||
record Cargo(Long dispatchItemId,Long orderId,Long planPalletId,String customerId,String destinationType,
|
||||
String deliveryAddress,String postalCode,String containerNo,String palletNo,String fbaWarehouseCode,
|
||||
String destinationWarehouseName,String warehouseNo,String fbaShipmentId,String poReferenceNo,
|
||||
Integer packageCount,Integer itemPackageCount,boolean originalPlan) { }
|
||||
record Allocation(Long dispatchItemId,Long planPalletId,String batchKey,String customerId,String sourceKey,
|
||||
String destinationKey,Integer packageCount,Long appointmentId,Long orderId,String confirmationNo) { }
|
||||
|
||||
/** 一行对应本车一个真实计划来源行;商品明细只聚合展示字段,原调度数量不取部分已拣数。 */
|
||||
@Select("""
|
||||
SELECT di.id AS dispatchItemId,
|
||||
CASE WHEN di.plan_pallet_id IS NOT NULL AND di.return_receipt_id IS NULL
|
||||
AND COALESCE(di.source_business_type,'')<>'RELABEL_ORDER' THEN l.order_id ELSE di.order_id END AS orderId,
|
||||
di.plan_pallet_id AS planPalletId,di.customer_id AS customerId,di.destination_type AS destinationType,
|
||||
di.delivery_address AS deliveryAddress,di.postal_code AS postalCode,
|
||||
COALESCE(MAX(NULLIF(o.container_no,'')),MAX(NULLIF(ip.container_no,''))) AS containerNo,
|
||||
MAX(NULLIF(di.pallet_no,'')) AS palletNo,
|
||||
COALESCE(MAX(NULLIF(l.fba_warehouse_code,'')),MAX(NULLIF(l.destination_warehouse_code,'')),
|
||||
MAX(NULLIF(di.fba_warehouse_code,'')),MAX(NULLIF(di.destination_warehouse_code,''))) AS fbaWarehouseCode,
|
||||
COALESCE(MAX(NULLIF(l.destination_warehouse_name,'')),MAX(NULLIF(di.destination_warehouse_name,''))) AS destinationWarehouseName,
|
||||
COALESCE(MAX(NULLIF(l.inbound_code,'')),MAX(NULLIF(di.inbound_code,''))) AS warehouseNo,
|
||||
GROUP_CONCAT(DISTINCT NULLIF(od.shipment_no,'') ORDER BY od.shipment_no SEPARATOR ', ') AS fbaShipmentId,
|
||||
GROUP_CONCAT(DISTINCT NULLIF(od.fba_tracking_no,'') ORDER BY od.fba_tracking_no SEPARATOR ', ') AS poReferenceNo,
|
||||
CASE WHEN l.id IS NULL THEN MAX(di.package_count)
|
||||
WHEN di.source_stage='RECEIVED' THEN MAX(a.counted_package_count)
|
||||
ELSE MAX(a.planned_package_count) END AS packageCount,
|
||||
MAX(di.package_count) AS itemPackageCount,
|
||||
CASE WHEN di.plan_pallet_id IS NOT NULL AND di.return_receipt_id IS NULL
|
||||
AND COALESCE(di.source_business_type,'')<>'RELABEL_ORDER' THEN TRUE ELSE FALSE END AS originalPlan
|
||||
FROM ll_dispatch_item di
|
||||
LEFT JOIN ll_inbound_plan_pallet p ON p.id=di.plan_pallet_id
|
||||
LEFT JOIN ll_inbound_plan ip ON ip.id=p.plan_id AND ip.customer_id=di.customer_id
|
||||
LEFT JOIN ll_inbound_plan_pallet_allocation a ON a.pallet_id=p.id AND a.customer_id=di.customer_id
|
||||
AND di.return_receipt_id IS NULL AND COALESCE(di.source_business_type,'')<>'RELABEL_ORDER'
|
||||
LEFT JOIN ll_inbound_plan_line l ON l.id=a.line_id AND l.customer_id=di.customer_id AND l.plan_id=p.plan_id
|
||||
LEFT JOIN ll_order o ON o.id=l.order_id AND o.customer_id=di.customer_id
|
||||
LEFT JOIN ll_order_detail od ON od.order_id=l.order_id AND od.customer_id=l.customer_id
|
||||
WHERE di.dispatch_order_id=#{dispatchOrderId}
|
||||
GROUP BY di.id,di.order_id,di.plan_pallet_id,di.customer_id,di.destination_type,di.delivery_address,
|
||||
di.postal_code,di.source_stage,di.return_receipt_id,di.source_business_type,l.id,l.order_id,a.id
|
||||
ORDER BY di.id,l.id,a.id
|
||||
""")
|
||||
List<Cargo> findWholeDispatch(@Param("dispatchOrderId") long dispatchOrderId);
|
||||
|
||||
/** 原batch+客户+稳定来源+目的地定位预约货物;BOOKING使用持久化order_id,绝不自行拼ORDER键。 */
|
||||
@Select("""
|
||||
SELECT a.dispatch_item_id AS dispatchItemId,a.plan_pallet_id AS planPalletId,a.batch_key AS batchKey,
|
||||
a.customer_id AS customerId,a.source_key AS sourceKey,a.destination_key AS destinationKey,
|
||||
a.package_count AS packageCount,p.id AS appointmentId,i.order_id AS orderId,p.confirmation_no AS confirmationNo
|
||||
FROM ll_dispatch_appointment_allocation a
|
||||
LEFT JOIN ll_inbound_fba_appointment p ON a.batch_key=CONCAT('FBA_APPOINTMENT:',p.id)
|
||||
LEFT JOIN ll_inbound_fba_appointment_item i ON i.appointment_id=p.id AND i.customer_id=a.customer_id
|
||||
AND i.source_key=a.source_key AND CONCAT('FBA:',i.fba_warehouse_code)=a.destination_key
|
||||
WHERE a.dispatch_id=#{dispatchOrderId} AND a.batch_key LIKE 'FBA_APPOINTMENT:%'
|
||||
ORDER BY a.dispatch_item_id,a.customer_id,a.source_key,a.destination_key,a.batch_key
|
||||
""")
|
||||
List<Allocation> findAppointmentAllocations(@Param("dispatchOrderId") long dispatchOrderId);
|
||||
}
|
||||
|
||||
+2
-1
@@ -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 > 0 " +
|
||||
// 未绑定实托的位置不是可选运输来源;完整申请中的缺失组成仍由提供者返回阻断原因。
|
||||
"AND pos.hold_packages > 0 AND pos.pallet_id > 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 " +
|
||||
|
||||
+9
-5
@@ -3,13 +3,17 @@ import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
/** 打印服务内部一致快照,不恢复旧排车JSON协议。 */
|
||||
public record DispatchBolData(String dispatchNo,String overseasWarehouseId,String overseasWarehouseName,String carrierName,
|
||||
String vehiclePlate,LocalDateTime estimatedArrivalAt,List<Line> bolLines,Map<String,String> appointmentNumbers) {
|
||||
public record Line(String customerId,String destinationType,String deliveryAddress,String postalCode,String containerNo,
|
||||
String vehiclePlate,LocalDateTime estimatedArrivalAt,List<Line> bolLines) {
|
||||
public record Line(Long dispatchItemId,Long orderId,String customerId,String destinationType,String deliveryAddress,String postalCode,String containerNo,
|
||||
String palletNo,String fbaWarehouseCode,String destinationWarehouseName,String warehouseNo,String fbaShipmentId,
|
||||
String poReferenceNo,int packageCount) {
|
||||
String poReferenceNo,int packageCount,String appointmentNo) {
|
||||
/** 外部确认号只去首尾空白,未取得真实约号时保留空。 */
|
||||
public Line { appointmentNo=appointmentNo==null || appointmentNo.isBlank()?null:appointmentNo.strip(); }
|
||||
/** 目的地身份不使用客户作为分组条件。 */
|
||||
public String destinationKey(){return com.baiyue.lastleg.fleet.trip.FleetDispatchGateway.destinationKey(destinationType,fbaWarehouseCode,null,deliveryAddress,postalCode);}
|
||||
/** 打印展示使用业务名称或真实地址。 */
|
||||
public String destinationLabel(){return "PRIVATE".equals(destinationType)?deliveryAddress:destinationWarehouseName;}
|
||||
public String groupKey(){return customerId+"\u0000"+destinationKey();}
|
||||
/** 同目的地同约号跨客户合并,无号也可组成同目的地文档。 */
|
||||
public String groupKey(){return destinationKey()+"\u0000"+Objects.requireNonNullElse(appointmentNo,"");}
|
||||
}
|
||||
public String appointmentFor(Line line){return appointmentNumbers.get(line.groupKey());}
|
||||
}
|
||||
|
||||
+2
-2
@@ -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());
|
||||
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.baiyue.lastleg.dispatch.port;
|
||||
|
||||
/** 原排车详情的只读应用端口,供运营视图组合真实履约事实。 */
|
||||
public interface DispatchDetailReader {
|
||||
/** 沿原排车读取及身份守卫,不创建单据、不推进状态。 */
|
||||
DispatchViews.Detail detail(DispatchContracts.Actor actor, String dispatchNo);
|
||||
}
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
package com.baiyue.lastleg.dispatch.port;
|
||||
|
||||
/** 一次真实拣货消费的冻结来源额度;件数未知时保留空,不接受请求伪造来源身份。 */
|
||||
public record DispatchSourceAllocation(Long dispatchItemSourceId, long packages, Long productQuantity) { }
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.baiyue.lastleg.dispatch.repository;
|
||||
|
||||
import com.baiyue.lastleg.dispatch.mapper.DispatchBolMapper;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import java.util.List;
|
||||
|
||||
/** BOL专用只读事实入口,应用服务不直接持有Mapper。 */
|
||||
@Repository
|
||||
public class DispatchBolRepository {
|
||||
private final DispatchBolMapper mapper;
|
||||
/** 装配同一次事务使用的来源及分配读取。 */
|
||||
public DispatchBolRepository(DispatchBolMapper mapper){this.mapper=mapper;}
|
||||
/** 返回完整明细身份、原调度箱数及逐来源打印资料。 */
|
||||
public List<DispatchBolMapper.Cargo> cargo(long dispatchId){return mapper.findWholeDispatch(dispatchId);}
|
||||
/** 仅正式FBA预约分配有外部预约号;客户仓内部DISPATCH批次不伪造约号。 */
|
||||
public List<DispatchBolMapper.Allocation> allocations(long dispatchId){return mapper.findAppointmentAllocations(dispatchId);}
|
||||
}
|
||||
+15
-2
@@ -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,
|
||||
@@ -369,7 +371,7 @@ public class DispatchAggregateService implements DispatchExecutionPort,DispatchA
|
||||
var row=lockPlatform(actor,number);var identity=identity(actor,number,Action.SUBMIT_REVIEW,request.recordVersion(),request.idempotencyKey(),request);
|
||||
var original=commands.replay(actor,number,identity);if(original.isPresent())return original.get();
|
||||
requireEditing(row,request.recordVersion());
|
||||
if(!Set.of(ReviewState.DRAFT.name(),ReviewState.DISPATCH_REJECTED.name(),ReviewState.LOADING_REJECTED.name()).contains(row.getReviewState()))throw conflict("当前审核已提交,请刷新核对");
|
||||
if(!canSubmitReview(row.getReviewState()))throw conflict("当前审核已提交,请刷新核对");
|
||||
verifyReviewResources(row);
|
||||
if(n(row.getPackageCount())<=0 || repository.cargo(row.getId()).isEmpty())throw bad("空排车不能提交审核");
|
||||
long round=row.getReviewRound()+1;String basis=basis(row);
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -739,6 +745,12 @@ public class DispatchAggregateService implements DispatchExecutionPort,DispatchA
|
||||
if(!Status.ACTIVE.name().equals(row.getStatus()) || !Stage.BEFORE_LOADING.name().equals(row.getStage()) || n(row.getPickedPackageCount())>0 || n(row.getShippedPackageCount())>0) throw conflict("仅装车前且未扫码的有效排车可以调整货物");
|
||||
}
|
||||
|
||||
/** 提交资格和写入共用可重提状态,已进入两级待审的整车不得再次显示提交入口。 */
|
||||
private static boolean canSubmitReview(String reviewState) {
|
||||
return ReviewState.DRAFT.name().equals(reviewState) || ReviewState.DISPATCH_REJECTED.name().equals(reviewState)
|
||||
|| ReviewState.LOADING_REJECTED.name().equals(reviewState);
|
||||
}
|
||||
|
||||
/** 动作快照只反映实际当前资格,写入仍须再次加锁校验。 */
|
||||
Map<Action,Gate> actions(Actor actor,DispatchAggregate row) {
|
||||
var gates=new EnumMap<Action,Gate>(Action.class); boolean active=Status.ACTIVE.name().equals(row.getStatus());
|
||||
@@ -746,7 +758,8 @@ public class DispatchAggregateService implements DispatchExecutionPort,DispatchA
|
||||
for(var action:Action.values()) {
|
||||
boolean state=switch(action) {
|
||||
case CREATE -> actor.mode()==ActorMode.PLATFORM;
|
||||
case EDIT,ADD_CARGO,REMOVE_CARGO,CANCEL,SUBMIT_REVIEW -> active && stage==Stage.BEFORE_LOADING && n(row.getPickedPackageCount())==0;
|
||||
case EDIT,ADD_CARGO,REMOVE_CARGO,CANCEL -> active && stage==Stage.BEFORE_LOADING && n(row.getPickedPackageCount())==0;
|
||||
case SUBMIT_REVIEW -> active && stage==Stage.BEFORE_LOADING && n(row.getPickedPackageCount())==0 && canSubmitReview(row.getReviewState());
|
||||
case DISPATCH_REVIEW -> active && review==ReviewState.DISPATCH_PENDING;
|
||||
case LOADING_REVIEW -> active && review==ReviewState.LOADING_PENDING;
|
||||
case RETURN_TO_REVIEW -> active && stage==Stage.LOADING && n(row.getPickedPackageCount())==0;
|
||||
|
||||
+3
-1
@@ -32,6 +32,7 @@ public class DispatchBolPrintService {
|
||||
@Resource private DomesticWarehouseDirectoryClient warehouses;
|
||||
@Value("${baiyue.security.internal-service-token:}") private String internalToken;
|
||||
|
||||
/** 按本车一致快照组装全部BOL,一次调用打印服务并保持一个PDF下载。 */
|
||||
public GeneratedPdf generate(String dispatchNo, String requestId) {
|
||||
DispatchBolData detail = dispatches.read(dispatchNo);
|
||||
if (detail.bolLines() == null || detail.bolLines().isEmpty()) {
|
||||
@@ -54,6 +55,7 @@ public class DispatchBolPrintService {
|
||||
}
|
||||
}
|
||||
|
||||
/** 将同目的地同预约号的跨客户货物组装为独立分页BOL,无预约号时ISA保持空白。 */
|
||||
private List<PrintPdfClient.Document> documents(DispatchBolData detail) {
|
||||
String shipFromAddress = warehouseAddress(detail.overseasWarehouseId());
|
||||
Map<String, List<DispatchBolData.Line>> groups = new LinkedHashMap<>();
|
||||
@@ -72,7 +74,7 @@ public class DispatchBolPrintService {
|
||||
.map(line -> new PrintPdfClient.CargoRow(text(line.containerNo()), text(line.palletNo()), text(line.fbaWarehouseCode()),
|
||||
text(line.warehouseNo()), text(line.fbaShipmentId()), text(line.poReferenceNo()), line.packageCount())).toList();
|
||||
documents.add(new PrintPdfClient.Document(text(detail.overseasWarehouseName()), shipFromAddress, text(detail.carrierName()),
|
||||
text(detail.appointmentFor(lines.get(0))), dateTime(detail.estimatedArrivalAt()), text(detail.vehiclePlate()), "—",
|
||||
lines.get(0).appointmentNo() == null ? "" : lines.get(0).appointmentNo().strip(), dateTime(detail.estimatedArrivalAt()), text(detail.vehiclePlate()), "—",
|
||||
text(lines.get(0).fbaWarehouseCode()), destination, "—", text(detail.dispatchNo()), unique(lines, true), unique(lines, false),
|
||||
total, page + 1, pages, rows));
|
||||
offset = end;
|
||||
|
||||
+71
-10
@@ -1,31 +1,92 @@
|
||||
package com.baiyue.lastleg.dispatch.service;
|
||||
|
||||
import com.baiyue.common.core.api.ResultCode;
|
||||
import com.baiyue.common.core.exception.BizException;
|
||||
import com.baiyue.lastleg.dispatch.model.DispatchBolData;
|
||||
import com.baiyue.lastleg.dispatch.mapper.DispatchBolMapper;
|
||||
import com.baiyue.lastleg.dispatch.repository.DispatchAggregateRepository;
|
||||
import com.baiyue.lastleg.dispatch.repository.DispatchBolRepository;
|
||||
import com.baiyue.lastleg.dispatch.port.DispatchContracts.Resources;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.*;
|
||||
import java.time.*;
|
||||
import java.util.*;
|
||||
import java.util.stream.Collectors;
|
||||
/** 先在本地一致事务读全车打印事实,事务结束后才调用远程打印。 */
|
||||
|
||||
/** 同一只读事务内核实本车逐来源数量,再按真实预约份额拆行;事务结束后才调用远程打印。 */
|
||||
@Service
|
||||
public class DispatchBolReadService {
|
||||
private final DispatchAggregateRepository roots;private final DispatchBolMapper lines;private final ObjectMapper json;
|
||||
public DispatchBolReadService(DispatchAggregateRepository roots,DispatchBolMapper lines,ObjectMapper json){this.roots=roots;this.lines=lines;this.json=json;}
|
||||
private final DispatchAggregateRepository roots;private final DispatchBolRepository facts;private final ObjectMapper json;
|
||||
private record Source(Long itemId,String customerId,Long orderId,String destinationKey) { }
|
||||
private record AllocationKey(Long itemId,String batchKey,String customerId,String sourceKey,String destinationKey) { }
|
||||
/** 打印读取只经Repository,不写预约、调度或库存事实。 */
|
||||
public DispatchBolReadService(DispatchAggregateRepository roots,DispatchBolRepository facts,ObjectMapper json){this.roots=roots;this.facts=facts;this.json=json;}
|
||||
|
||||
/** 保留原调度总量,未约部分以空约号打印,不按部分拣货进度缩量。 */
|
||||
@Transactional(readOnly=true,isolation=Isolation.REPEATABLE_READ)
|
||||
public DispatchBolData read(String number) {
|
||||
var row=roots.find(number);if(row==null)throw new BizException(ResultCode.NOT_FOUND,"排车单不存在");
|
||||
Resources resources;try{resources=json.readValue(row.getResourcesJson(),Resources.class);}catch(com.fasterxml.jackson.core.JsonProcessingException e){throw new IllegalStateException("本车资源快照损坏",e);}
|
||||
var cargo=lines.findWholeDispatch(row.getId());
|
||||
if(cargo.stream().anyMatch(l->l.customerId()==null || l.destinationKey()==null || l.packageCount()<=0))throw new BizException(ResultCode.VALIDATION_FAILED,"BOL货物客户、目的地或箱数尚未核实");
|
||||
var confirmations=new LinkedHashMap<String,LinkedHashSet<String>>();
|
||||
for(var batch:roots.batches(row.getId()))if(batch.confirmationNo()!=null && !batch.confirmationNo().isBlank())confirmations.computeIfAbsent(batch.customerId()+"\u0000"+batch.destinationKey(),k->new LinkedHashSet<>()).add(batch.confirmationNo());
|
||||
var numbers=confirmations.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,e->String.join(", ",e.getValue())));
|
||||
var cargo=new LinkedHashMap<Source,DispatchBolData.Line>();var totals=new HashMap<Long,Integer>();var pallets=new HashMap<Long,Long>();
|
||||
for(var raw:facts.cargo(row.getId())) {
|
||||
int packages=nonnegative(raw.packageCount());var line=line(raw,null,packages);
|
||||
if(raw.dispatchItemId()==null || blank(raw.customerId()) || line.destinationKey()==null
|
||||
|| raw.originalPlan() && raw.orderId()==null)throw invalid();
|
||||
int total=positive(raw.itemPackageCount());var prior=totals.putIfAbsent(raw.dispatchItemId(),total);
|
||||
if(prior!=null && prior!=total)throw invalid();
|
||||
if(pallets.containsKey(raw.dispatchItemId()) && !Objects.equals(pallets.get(raw.dispatchItemId()),raw.planPalletId()))throw invalid();
|
||||
pallets.put(raw.dispatchItemId(),raw.planPalletId());
|
||||
if(packages==0)continue;
|
||||
var key=new Source(raw.dispatchItemId(),raw.customerId(),raw.orderId(),line.destinationKey());
|
||||
cargo.merge(key,line,DispatchBolReadService::merge);
|
||||
}
|
||||
var sourceTotals=new HashMap<Long,Integer>();
|
||||
cargo.forEach((key,line)->sourceTotals.merge(key.itemId(),line.packageCount(),Math::addExact));
|
||||
if(!sourceTotals.equals(totals))throw invalid();
|
||||
var remaining=new LinkedHashMap<Source,Integer>();cargo.forEach((key,line)->remaining.put(key,line.packageCount()));
|
||||
var seen=new HashSet<AllocationKey>();var result=new ArrayList<DispatchBolData.Line>();
|
||||
for(var allocation:facts.allocations(row.getId())) {
|
||||
if(allocation.appointmentId()==null || allocation.orderId()==null || blank(allocation.sourceKey())
|
||||
|| !Objects.equals(pallets.get(allocation.dispatchItemId()),allocation.planPalletId()))throw invalid();
|
||||
var key=new Source(allocation.dispatchItemId(),allocation.customerId(),allocation.orderId(),allocation.destinationKey());
|
||||
var source=cargo.get(key);int count=positive(allocation.packageCount());
|
||||
if(source==null || !seen.add(new AllocationKey(allocation.dispatchItemId(),allocation.batchKey(),allocation.customerId(),allocation.sourceKey(),allocation.destinationKey()))
|
||||
|| count>remaining.get(key))throw invalid();
|
||||
remaining.put(key,remaining.get(key)-count);result.add(copy(source,count,allocation.confirmationNo()));
|
||||
}
|
||||
// 每个来源只消费实际分配份额,余额有明确实物依据,保持空ISA而非重复整托。
|
||||
remaining.forEach((key,count)->{if(count>0)result.add(copy(cargo.get(key),count,null));});
|
||||
var printedTotals=new HashMap<Long,Integer>();result.forEach(line->printedTotals.merge(line.dispatchItemId(),line.packageCount(),Math::addExact));
|
||||
if(!printedTotals.equals(totals))throw invalid();
|
||||
return new DispatchBolData(row.getDispatchNo(),row.getOverseasWarehouseId(),row.getOverseasWarehouseName(),resources.vehicle()==null?null:resources.vehicle().carrierName(),resources.vehicle()==null?null:resources.vehicle().plate(),
|
||||
row.getEstimatedArrivalAt()==null?null:LocalDateTime.ofInstant(row.getEstimatedArrivalAt().toInstant(ZoneOffset.UTC),ZoneId.systemDefault()),List.copyOf(cargo),Map.copyOf(numbers));
|
||||
row.getEstimatedArrivalAt()==null?null:LocalDateTime.ofInstant(row.getEstimatedArrivalAt().toInstant(ZoneOffset.UTC),ZoneId.systemDefault()),List.copyOf(result));
|
||||
}
|
||||
/** 将数据库原始来源行转换为带真实身份的内部打印行。 */
|
||||
private static DispatchBolData.Line line(DispatchBolMapper.Cargo c,String appointment,int packages) {
|
||||
return new DispatchBolData.Line(c.dispatchItemId(),c.orderId(),c.customerId(),c.destinationType(),c.deliveryAddress(),c.postalCode(),c.containerNo(),c.palletNo(),
|
||||
c.fbaWarehouseCode(),c.destinationWarehouseName(),c.warehouseNo(),c.fbaShipmentId(),c.poReferenceNo(),packages,appointment);
|
||||
}
|
||||
/** 拆份只改变份额和预约号,真实客户、源订单和排车明细身份不变。 */
|
||||
private static DispatchBolData.Line copy(DispatchBolData.Line c,int packages,String appointment) {
|
||||
return new DispatchBolData.Line(c.dispatchItemId(),c.orderId(),c.customerId(),c.destinationType(),c.deliveryAddress(),c.postalCode(),c.containerNo(),c.palletNo(),
|
||||
c.fbaWarehouseCode(),c.destinationWarehouseName(),c.warehouseNo(),c.fbaShipmentId(),c.poReferenceNo(),packages,appointment);
|
||||
}
|
||||
/** 同订单多来源行先守恒合并,再让每条预约分配消费一次;展示字符串只去重合并。 */
|
||||
private static DispatchBolData.Line merge(DispatchBolData.Line a,DispatchBolData.Line b) {
|
||||
return new DispatchBolData.Line(a.dispatchItemId(),a.orderId(),a.customerId(),a.destinationType(),a.deliveryAddress(),a.postalCode(),join(a.containerNo(),b.containerNo()),a.palletNo(),
|
||||
a.fbaWarehouseCode(),a.destinationWarehouseName(),join(a.warehouseNo(),b.warehouseNo()),join(a.fbaShipmentId(),b.fbaShipmentId()),join(a.poReferenceNo(),b.poReferenceNo()),Math.addExact(a.packageCount(),b.packageCount()),null);
|
||||
}
|
||||
/** 仅打印展示字段去重,不用逗号字符串表示预约身份。 */
|
||||
private static String join(String a,String b) {
|
||||
var values=new LinkedHashSet<String>();for(var text:Arrays.asList(a,b))if(text!=null)for(var part:text.split(","))if(!part.isBlank())values.add(part.strip());
|
||||
return values.isEmpty()?null:String.join(", ",values);
|
||||
}
|
||||
/** 数量未知或非正不得伪造打印份额。 */
|
||||
private static int positive(Integer value){if(value==null || value<=0)throw invalid();return value;}
|
||||
/** 已核实为零的源行没有待打印货物,但不以零替代未知数量。 */
|
||||
private static int nonnegative(Integer value){if(value==null || value<0)throw invalid();return value;}
|
||||
/** 来源身份必须来自真实持久事实。 */
|
||||
private static boolean blank(String value){return value==null || value.isBlank();}
|
||||
/** 不完整、跨客户或超额分配不能生成看似守恒的BOL。 */
|
||||
private static BizException invalid(){return new BizException(ResultCode.VALIDATION_FAILED,"BOL货物来源、预约归属或分配箱数尚未核实");}
|
||||
}
|
||||
|
||||
+5
-7
@@ -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);
|
||||
}
|
||||
|
||||
+1
-1
@@ -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();
|
||||
|
||||
+3
-1
@@ -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) { }
|
||||
|
||||
+78
@@ -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));
|
||||
}
|
||||
}
|
||||
+86
@@ -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) {}
|
||||
}
|
||||
+15
@@ -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);
|
||||
}
|
||||
+88
@@ -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);
|
||||
}
|
||||
+57
@@ -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 >= #{q.from}</if>
|
||||
<if test='q.to != null'> AND d.planned_departure_at < #{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);
|
||||
}
|
||||
+64
@@ -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) {}
|
||||
}
|
||||
+57
@@ -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; }
|
||||
}
|
||||
+10
@@ -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);
|
||||
}
|
||||
+53
@@ -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);}
|
||||
}
|
||||
+62
@@ -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);
|
||||
}
|
||||
}
|
||||
+52
@@ -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("原装车车辆归属证据不同");
|
||||
}
|
||||
}
|
||||
+95
@@ -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);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user