20261109 #20
39
README.md
39
README.md
@ -160,7 +160,41 @@ public async Task<PlatformStoreOrderBatchCreateLogisticsOutput> BatchCreateFulfi
|
||||
|
||||
新增增量迁移文件命名:`migrate_<主题>_YYYYMMDD.sql`(日期在末尾,例如 `migrate_xxx_20261016.sql`)。详细约定见 `sql/README.md`。
|
||||
|
||||
### 3. 上传代码前先同步远端
|
||||
### 3. 新建表 / 迁移 DDL 必须对齐审计字段(定死)
|
||||
|
||||
`db.sql`、`sql/migrate_*.sql` 新建业务表时,**必须**带齐与现网一致的审计列,写法以 `t_outbound_record`、`t_order_operation_log` 为准。缺字段、类型不对或可空性写错会导致框架/ORM 读写报错,**禁止自创变体**。
|
||||
|
||||
| 字段 | 定死写法 | 禁止 |
|
||||
|------|----------|------|
|
||||
| `Id` | `INT NOT NULL AUTO_INCREMENT`,`PRIMARY KEY`,COMMENT 主键 | — |
|
||||
| `IsDeleted` | `TINYINT NOT NULL DEFAULT 0` | `TINYINT(1)`、`BIT`、缺省可空 |
|
||||
| `ConcurrencyStamp` | `CHAR(36) NOT NULL DEFAULT (UUID())` | `DEFAULT ''`、`VARCHAR`、缺省列 |
|
||||
| `CreateUserId` | `INT NOT NULL DEFAULT 0` | 可空 |
|
||||
| `CreateTime` | `DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP` | — |
|
||||
| `UpdateUserId` | `INT NULL`(无 DEFAULT) | `NOT NULL DEFAULT 0` |
|
||||
| `UpdateTime` | `DATETIME NULL`(无 DEFAULT / 无 `ON UPDATE`) | `NOT NULL … ON UPDATE CURRENT_TIMESTAMP` |
|
||||
|
||||
标准片段(新建表末尾照抄):
|
||||
|
||||
```sql
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`UpdateUserId` INT NULL COMMENT '更新人',
|
||||
`UpdateTime` DATETIME NULL COMMENT '更新时间',
|
||||
PRIMARY KEY (`Id`)
|
||||
-- 业务索引只用 KEY / INDEX,禁止 UNIQUE KEY(PRIMARY KEY 除外)
|
||||
```
|
||||
|
||||
其它定死规则:
|
||||
|
||||
- 列、表须有 `COMMENT`;参考同模块已有表命名与索引风格,不要少列硬凑。
|
||||
- **禁止** `UNIQUE KEY` / 库级唯一约束:业务唯一性在 Application 校验;见 `.cursor/rules/no-unique-indexes.mdc`。
|
||||
- 增量脚本尽量可重复执行(先判断表/列是否存在);纠偏已有错误列用 `MODIFY COLUMN` 对齐上表,不要另起一套定义。
|
||||
- 实体 / SqlSugar 映射字段名、可空性须与 DDL 一致。
|
||||
|
||||
### 4. 上传代码前先同步远端
|
||||
|
||||
`test`、`master` 等共享分支会有其他人提交。**推送前必须先拉取远端,再上传**,避免覆盖或漏掉别人的提交。
|
||||
|
||||
@ -174,9 +208,10 @@ git push origin <当前分支>
|
||||
- 本地已有未推送提交、远端也有新提交时,先 rebase 或 merge 并解决冲突,确认与远端对齐后再 `push`。
|
||||
- 禁止在未同步远端的情况下直接 `push` 共享分支。
|
||||
|
||||
### 4. 相关约定速查
|
||||
### 5. 相关约定速查
|
||||
|
||||
- **禁止**新建库级唯一索引(`UNIQUE KEY`):见 `.cursor/rules/no-unique-indexes.mdc`,业务唯一性在 Application 校验。
|
||||
- 新建表审计列按 §3 定死写法;参考 `t_outbound_record`。
|
||||
- 路由显式声明;分页统一 `totalCount` + `items`;勿把 Entity 直接返回前端。
|
||||
|
||||
## Fake 框架特性
|
||||
|
||||
@ -17,3 +17,24 @@ OMS / 共用库的建表脚本已统一到仓库根目录 `db.sql`。
|
||||
- 单次增量迁移命名:`migrate_<主题>_YYYYMMDD.sql`(日期放在文件名**末尾**,如 `migrate_sales_store_order_provider_fulfillment_20261016.sql`)
|
||||
- 尽量可重复执行(先判断列/表/字典是否已存在)
|
||||
- **后续新增脚本一律带日期后缀**;历史未带日期的脚本不强制改名
|
||||
|
||||
## 新建表审计字段(定死,与根 README §3 一致)
|
||||
|
||||
参考现网:`t_outbound_record`、`t_order_operation_log`。缺列或写法不对会报错,禁止自创变体。
|
||||
|
||||
```sql
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT '并发戳',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`UpdateUserId` INT NULL COMMENT '更新人',
|
||||
`UpdateTime` DATETIME NULL COMMENT '更新时间',
|
||||
```
|
||||
|
||||
| 禁止 | 正确 |
|
||||
|------|------|
|
||||
| `IsDeleted TINYINT(1)` | `TINYINT NOT NULL DEFAULT 0` |
|
||||
| `ConcurrencyStamp … DEFAULT ''` | `DEFAULT (UUID())` |
|
||||
| `UpdateUserId INT NOT NULL DEFAULT 0` | `INT NULL` |
|
||||
| `UpdateTime … ON UPDATE CURRENT_TIMESTAMP` | `DATETIME NULL` |
|
||||
| `UNIQUE KEY` | 普通 `KEY`;唯一性业务侧校验 |
|
||||
|
||||
151
sql/migrate_approval_engine_20261107.sql
Normal file
151
sql/migrate_approval_engine_20261107.sql
Normal file
@ -0,0 +1,151 @@
|
||||
-- =============================================================================
|
||||
-- migrate_approval_engine_20261107.sql
|
||||
-- 单级可配置审批引擎:定义 / 实例 / 任务 / 事件
|
||||
-- 审计字段对齐 t_outbound_record(定死):
|
||||
-- IsDeleted TINYINT NOT NULL DEFAULT 0
|
||||
-- ConcurrencyStamp CHAR(36) NOT NULL DEFAULT (UUID())
|
||||
-- CreateUserId INT NOT NULL DEFAULT 0
|
||||
-- CreateTime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
-- UpdateUserId INT NULL
|
||||
-- UpdateTime DATETIME NULL
|
||||
-- 禁止 UNIQUE KEY;业务唯一性(OperationCode)在 Application 校验。可重复执行。
|
||||
-- =============================================================================
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- ---------- t_approval_definition ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_definition'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_definition` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`OperationCode` VARCHAR(128) NOT NULL COMMENT ''操作编码,如 Finance.Recharge.Credit'',
|
||||
`OperationName` VARCHAR(128) NOT NULL DEFAULT '''' COMMENT ''操作显示名快照'',
|
||||
`IsEnabled` TINYINT NOT NULL DEFAULT 1 COMMENT ''是否启用:0-否,1-是'',
|
||||
`ConditionFormula` VARCHAR(2000) NULL COMMENT ''触发条件公式,空表示启用即始终需审'',
|
||||
`ApproverType` VARCHAR(16) NOT NULL DEFAULT ''User'' COMMENT ''审批人类型:User/Role'',
|
||||
`ApproverIds` VARCHAR(2000) NOT NULL DEFAULT '''' COMMENT ''候选人 ID,逗号分隔(User=Guid,Role=Guid)'',
|
||||
`ForbidSelfApprove` TINYINT NOT NULL DEFAULT 1 COMMENT ''禁止申请人自审:0-否,1-是'',
|
||||
`Remark` VARCHAR(512) NULL COMMENT ''备注'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_def_op` (`OperationCode`),
|
||||
KEY `ix_approval_def_enabled` (`IsEnabled`)
|
||||
) COMMENT=''审批定义(单级,按操作编码配置)''',
|
||||
'SELECT ''t_approval_definition already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_instance ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_instance'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_instance` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceNo` VARCHAR(32) NOT NULL COMMENT ''实例单号'',
|
||||
`OperationCode` VARCHAR(128) NOT NULL COMMENT ''操作编码'',
|
||||
`BizKey` VARCHAR(128) NOT NULL COMMENT ''业务幂等键'',
|
||||
`Title` VARCHAR(256) NOT NULL DEFAULT '''' COMMENT ''摘要标题'',
|
||||
`Status` TINYINT NOT NULL DEFAULT 1 COMMENT ''1Pending/2Approved/3Rejected/4Withdrawn/5Executing/6Executed/7ExecuteFailed'',
|
||||
`ApplicantUserId` INT NOT NULL DEFAULT 0 COMMENT ''申请人 mapId'',
|
||||
`ApplicantUserGuid` CHAR(36) NOT NULL DEFAULT '''' COMMENT ''申请人 RBAC Guid'',
|
||||
`ApplicantUserName` VARCHAR(64) NULL COMMENT ''申请人显示名'',
|
||||
`PayloadJson` MEDIUMTEXT NULL COMMENT ''冻结业务载荷 JSON'',
|
||||
`PayloadHash` VARCHAR(64) NULL COMMENT ''载荷哈希'',
|
||||
`SummaryJson` VARCHAR(2000) NULL COMMENT ''展示用摘要 JSON'',
|
||||
`DefinitionSnapshot` MEDIUMTEXT NULL COMMENT ''提交时定义快照 JSON'',
|
||||
`CurrentTaskId` INT NULL COMMENT ''当前任务 Id'',
|
||||
`CompletedTime` DATETIME NULL COMMENT ''终审完成时间'',
|
||||
`ExecutedTime` DATETIME NULL COMMENT ''业务执行完成时间'',
|
||||
`ExecuteMessage` VARCHAR(1000) NULL COMMENT ''执行结果/失败信息'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_inst_no` (`InstanceNo`),
|
||||
KEY `ix_approval_inst_op_biz` (`OperationCode`, `BizKey`),
|
||||
KEY `ix_approval_inst_status` (`Status`),
|
||||
KEY `ix_approval_inst_applicant` (`ApplicantUserId`)
|
||||
) COMMENT=''审批实例''',
|
||||
'SELECT ''t_approval_instance already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_task ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_task'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_task` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceId` INT NOT NULL COMMENT ''审批实例 Id'',
|
||||
`StepNo` INT NOT NULL DEFAULT 1 COMMENT ''步骤号,一期固定 1'',
|
||||
`Status` TINYINT NOT NULL DEFAULT 1 COMMENT ''1Pending/2Approved/3Rejected/4Cancelled'',
|
||||
`ApproverType` VARCHAR(16) NOT NULL DEFAULT ''User'' COMMENT ''审批人类型快照'',
|
||||
`ApproverIds` VARCHAR(2000) NOT NULL DEFAULT '''' COMMENT ''配置候选人快照'',
|
||||
`CandidateUserIds` VARCHAR(4000) NOT NULL DEFAULT '''' COMMENT ''展开后的可审用户 Guid,逗号分隔'',
|
||||
`ActionUserId` INT NULL COMMENT ''实际处理人 mapId'',
|
||||
`ActionUserGuid` CHAR(36) NULL COMMENT ''实际处理人 Guid'',
|
||||
`ActionUserName` VARCHAR(64) NULL COMMENT ''实际处理人显示名'',
|
||||
`ActionTime` DATETIME NULL COMMENT ''处理时间'',
|
||||
`Comment` VARCHAR(1000) NULL COMMENT ''审批意见'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_task_inst` (`InstanceId`),
|
||||
KEY `ix_approval_task_status` (`Status`)
|
||||
) COMMENT=''审批任务(单级)''',
|
||||
'SELECT ''t_approval_task already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_approval_event ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_approval_event'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_approval_event` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`InstanceId` INT NOT NULL COMMENT ''审批实例 Id'',
|
||||
`TaskId` INT NULL COMMENT ''关联任务 Id'',
|
||||
`EventType` VARCHAR(32) NOT NULL COMMENT ''Submitted/Approved/Rejected/Withdrawn/Executing/Executed/ExecuteFailed'',
|
||||
`FromStatus` TINYINT NULL COMMENT ''变更前实例状态'',
|
||||
`ToStatus` TINYINT NULL COMMENT ''变更后实例状态'',
|
||||
`OperatorUserId` INT NOT NULL DEFAULT 0 COMMENT ''操作人 mapId'',
|
||||
`OperatorUserGuid` CHAR(36) NULL COMMENT ''操作人 Guid'',
|
||||
`OperatorUserName` VARCHAR(64) NULL COMMENT ''操作人显示名'',
|
||||
`Message` VARCHAR(1000) NULL COMMENT ''事件说明/意见'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_approval_event_inst` (`InstanceId`),
|
||||
KEY `ix_approval_event_type` (`EventType`)
|
||||
) COMMENT=''审批事件(追加写)''',
|
||||
'SELECT ''t_approval_event already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
266
sql/migrate_ship_bag_master_20261107.sql
Normal file
266
sql/migrate_ship_bag_master_20261107.sql
Normal file
@ -0,0 +1,266 @@
|
||||
-- =============================================================================
|
||||
-- migrate_ship_bag_master_20261107.sql
|
||||
-- 出库容器:大包 + 内部主单(可绑外部 MAWB)
|
||||
-- 审计字段对齐 t_outbound_record / migrate_order_operation_log(定死):
|
||||
-- IsDeleted TINYINT NOT NULL DEFAULT 0
|
||||
-- ConcurrencyStamp CHAR(36) NOT NULL DEFAULT (UUID())
|
||||
-- CreateUserId INT NOT NULL DEFAULT 0
|
||||
-- CreateTime DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
-- UpdateUserId INT NULL
|
||||
-- UpdateTime DATETIME NULL
|
||||
-- 禁止 UNIQUE KEY;小包可不入袋、不上主单。可重复执行。
|
||||
-- 大包/主单件重尺与口岸:
|
||||
-- Length/Width/Height DECIMAL(10,2) NULL -- cm
|
||||
-- Weight DECIMAL(10,2) NULL -- kg
|
||||
-- DestinationPort VARCHAR(64) NULL -- 目的口岸
|
||||
-- =============================================================================
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- ---------- t_ship_bag ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_ship_bag'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_ship_bag` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`BagNo` VARCHAR(32) NOT NULL COMMENT ''大包号'',
|
||||
`BagType` VARCHAR(16) NOT NULL DEFAULT ''sack'' COMMENT ''sack麻袋/box箱子'',
|
||||
`Status` VARCHAR(16) NOT NULL DEFAULT ''open'' COMMENT ''open/sealed/shipped/voided'',
|
||||
`WarehouseId` INT NULL COMMENT ''仓库ID'',
|
||||
`DestinationCountry` VARCHAR(8) NULL COMMENT ''目的国'',
|
||||
`DestinationPort` VARCHAR(64) NULL COMMENT ''目的口岸'',
|
||||
`ChannelCode` VARCHAR(64) NULL COMMENT ''渠道编码'',
|
||||
`Length` DECIMAL(10,2) NULL COMMENT ''长(cm)'',
|
||||
`Width` DECIMAL(10,2) NULL COMMENT ''宽(cm)'',
|
||||
`Height` DECIMAL(10,2) NULL COMMENT ''高(cm)'',
|
||||
`Weight` DECIMAL(10,2) NULL COMMENT ''重量(kg)'',
|
||||
`ParcelCount` INT NOT NULL DEFAULT 0 COMMENT ''袋内小包数'',
|
||||
`SealTime` DATETIME NULL COMMENT ''封袋时间'',
|
||||
`ShipTime` DATETIME NULL COMMENT ''出库时间'',
|
||||
`MasterId` INT NULL COMMENT ''归属内部主单Id,可空'',
|
||||
`Remark` VARCHAR(512) NULL COMMENT ''备注'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_ship_bag_no` (`BagNo`),
|
||||
KEY `ix_ship_bag_status` (`Status`),
|
||||
KEY `ix_ship_bag_master` (`MasterId`),
|
||||
KEY `ix_ship_bag_wh` (`WarehouseId`)
|
||||
) COMMENT=''出库大包(麻袋/箱子)''',
|
||||
'SELECT ''t_ship_bag already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_ship_bag_item ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_ship_bag_item'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_ship_bag_item` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`BagId` INT NOT NULL COMMENT ''大包Id'',
|
||||
`OrderId` INT NOT NULL COMMENT ''小包订单Id'',
|
||||
`WaybillNo` VARCHAR(64) NOT NULL COMMENT ''运单号'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_ship_bag_item_bag` (`BagId`),
|
||||
KEY `ix_ship_bag_item_order` (`OrderId`),
|
||||
KEY `ix_ship_bag_item_waybill` (`WaybillNo`)
|
||||
) COMMENT=''大包内小包明细''',
|
||||
'SELECT ''t_ship_bag_item already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_ship_master ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_ship_master'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_ship_master` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`MasterNo` VARCHAR(32) NOT NULL COMMENT ''内部主单号'',
|
||||
`ExternalMawb` VARCHAR(64) NULL COMMENT ''外部MAWB/提单号,可后补'',
|
||||
`Status` VARCHAR(16) NOT NULL DEFAULT ''open'' COMMENT ''open/sealed/handed/voided'',
|
||||
`WarehouseId` INT NULL COMMENT ''仓库ID'',
|
||||
`DestinationCountry` VARCHAR(8) NULL COMMENT ''目的国'',
|
||||
`DestinationPort` VARCHAR(64) NULL COMMENT ''目的口岸'',
|
||||
`FlightOrVoyage` VARCHAR(64) NULL COMMENT ''航班/船名航次'',
|
||||
`Length` DECIMAL(10,2) NULL COMMENT ''长(cm)'',
|
||||
`Width` DECIMAL(10,2) NULL COMMENT ''宽(cm)'',
|
||||
`Height` DECIMAL(10,2) NULL COMMENT ''高(cm)'',
|
||||
`Weight` DECIMAL(10,2) NULL COMMENT ''重量(kg)'',
|
||||
`BagCount` INT NOT NULL DEFAULT 0 COMMENT ''大包数'',
|
||||
`ParcelCount` INT NOT NULL DEFAULT 0 COMMENT ''小包合计(含袋内)'',
|
||||
`SealTime` DATETIME NULL COMMENT ''封板时间'',
|
||||
`HandTime` DATETIME NULL COMMENT ''交运时间'',
|
||||
`Remark` VARCHAR(512) NULL COMMENT ''备注'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_ship_master_no` (`MasterNo`),
|
||||
KEY `ix_ship_master_mawb` (`ExternalMawb`),
|
||||
KEY `ix_ship_master_status` (`Status`),
|
||||
KEY `ix_ship_master_wh` (`WarehouseId`)
|
||||
) COMMENT=''内部主单(可绑定外部MAWB)''',
|
||||
'SELECT ''t_ship_master already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_ship_master_item ----------
|
||||
SET @tbl := (
|
||||
SELECT COUNT(1) FROM information_schema.TABLES
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_ship_master_item'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@tbl = 0,
|
||||
'CREATE TABLE `t_ship_master_item` (
|
||||
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
|
||||
`MasterId` INT NOT NULL COMMENT ''内部主单Id'',
|
||||
`ItemType` VARCHAR(16) NOT NULL COMMENT ''bag/parcel'',
|
||||
`BagId` INT NULL COMMENT ''大包Id(ItemType=bag)'',
|
||||
`BagNo` VARCHAR(32) NULL COMMENT ''大包号冗余'',
|
||||
`OrderId` INT NULL COMMENT ''小包订单Id(ItemType=parcel)'',
|
||||
`WaybillNo` VARCHAR(64) NULL COMMENT ''运单号冗余'',
|
||||
`IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是'',
|
||||
`ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳'',
|
||||
`CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''创建人'',
|
||||
`CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''创建时间'',
|
||||
`UpdateUserId` INT NULL COMMENT ''更新人'',
|
||||
`UpdateTime` DATETIME NULL COMMENT ''更新时间'',
|
||||
PRIMARY KEY (`Id`),
|
||||
KEY `ix_ship_master_item_master` (`MasterId`),
|
||||
KEY `ix_ship_master_item_bag` (`BagId`),
|
||||
KEY `ix_ship_master_item_order` (`OrderId`)
|
||||
) COMMENT=''主单明细:大包或散货小包''',
|
||||
'SELECT ''t_ship_master_item already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 纠偏:若已用错误审计列建过表,改成标准可空/UUID(可重复) ----------
|
||||
-- t_ship_bag
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='UpdateUserId');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag` MODIFY COLUMN `UpdateUserId` INT NULL COMMENT ''更新人''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='UpdateTime');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag` MODIFY COLUMN `UpdateTime` DATETIME NULL COMMENT ''更新时间''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='IsDeleted');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag` MODIFY COLUMN `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='ConcurrencyStamp');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag` MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- t_ship_bag_item
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag_item' AND COLUMN_NAME='UpdateUserId');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag_item` MODIFY COLUMN `UpdateUserId` INT NULL COMMENT ''更新人''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag_item' AND COLUMN_NAME='UpdateTime');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag_item` MODIFY COLUMN `UpdateTime` DATETIME NULL COMMENT ''更新时间''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag_item' AND COLUMN_NAME='IsDeleted');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag_item` MODIFY COLUMN `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag_item' AND COLUMN_NAME='ConcurrencyStamp');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_bag_item` MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- t_ship_master
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='UpdateUserId');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master` MODIFY COLUMN `UpdateUserId` INT NULL COMMENT ''更新人''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='UpdateTime');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master` MODIFY COLUMN `UpdateTime` DATETIME NULL COMMENT ''更新时间''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='IsDeleted');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master` MODIFY COLUMN `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='ConcurrencyStamp');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master` MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- t_ship_master_item
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master_item' AND COLUMN_NAME='UpdateUserId');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master_item` MODIFY COLUMN `UpdateUserId` INT NULL COMMENT ''更新人''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master_item' AND COLUMN_NAME='UpdateTime');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master_item` MODIFY COLUMN `UpdateTime` DATETIME NULL COMMENT ''更新时间''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master_item' AND COLUMN_NAME='IsDeleted');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master_item` MODIFY COLUMN `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''软删除:0-否,1-是''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master_item' AND COLUMN_NAME='ConcurrencyStamp');
|
||||
SET @sql := IF(@exists>0, 'ALTER TABLE `t_ship_master_item` MODIFY COLUMN `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''并发戳''', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- 存量补列:件重尺 + 目的口岸(可重复) ----------
|
||||
-- t_ship_bag
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='DestinationPort');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_bag` ADD COLUMN `DestinationPort` VARCHAR(64) NULL COMMENT ''目的口岸'' AFTER `DestinationCountry`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='Length');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_bag` ADD COLUMN `Length` DECIMAL(10,2) NULL COMMENT ''长(cm)'' AFTER `ChannelCode`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='Width');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_bag` ADD COLUMN `Width` DECIMAL(10,2) NULL COMMENT ''宽(cm)'' AFTER `Length`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='Height');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_bag` ADD COLUMN `Height` DECIMAL(10,2) NULL COMMENT ''高(cm)'' AFTER `Width`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_bag' AND COLUMN_NAME='Weight');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_bag` ADD COLUMN `Weight` DECIMAL(10,2) NULL COMMENT ''重量(kg)'' AFTER `Height`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- t_ship_master
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='DestinationPort');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_master` ADD COLUMN `DestinationPort` VARCHAR(64) NULL COMMENT ''目的口岸'' AFTER `DestinationCountry`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='Length');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_master` ADD COLUMN `Length` DECIMAL(10,2) NULL COMMENT ''长(cm)'' AFTER `FlightOrVoyage`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='Width');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_master` ADD COLUMN `Width` DECIMAL(10,2) NULL COMMENT ''宽(cm)'' AFTER `Length`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='Height');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_master` ADD COLUMN `Height` DECIMAL(10,2) NULL COMMENT ''高(cm)'' AFTER `Width`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
SET @exists := (SELECT COUNT(1) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA=@db AND TABLE_NAME='t_ship_master' AND COLUMN_NAME='Weight');
|
||||
SET @sql := IF(@exists=0, 'ALTER TABLE `t_ship_master` ADD COLUMN `Weight` DECIMAL(10,2) NULL COMMENT ''重量(kg)'' AFTER `Height`', 'SELECT 1');
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- ---------- t_order 归属冗余(可空,不强制) ----------
|
||||
SET @exists := (
|
||||
SELECT COUNT(1) FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_order' AND COLUMN_NAME = 'ShipBagId'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@exists = 0,
|
||||
'ALTER TABLE `t_order`
|
||||
ADD COLUMN `ShipBagId` INT NULL COMMENT ''当前大包Id可空'' AFTER `WarehouseId`,
|
||||
ADD COLUMN `ShipBagNo` VARCHAR(32) NULL COMMENT ''当前大包号可空'' AFTER `ShipBagId`,
|
||||
ADD COLUMN `ShipMasterId` INT NULL COMMENT ''当前主单Id可空'' AFTER `ShipBagNo`,
|
||||
ADD COLUMN `ShipMasterNo` VARCHAR(32) NULL COMMENT ''当前内部主单号可空'' AFTER `ShipMasterId`,
|
||||
ADD KEY `ix_order_ship_bag` (`ShipBagId`),
|
||||
ADD KEY `ix_order_ship_master` (`ShipMasterId`)',
|
||||
'SELECT ''t_order ship bag/master columns already exist'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
|
||||
20
sql/smoke_approval_engine_checklist.md
Normal file
20
sql/smoke_approval_engine_checklist.md
Normal file
@ -0,0 +1,20 @@
|
||||
# 审批引擎一期联调清单
|
||||
|
||||
1. 在 OMS 库执行 `migrate_approval_engine_20261107.sql`。
|
||||
2. 重启 SimpleAdmin.Api(触发 `ApprovalRolePermissionSeedContributor` 合并 Admin 权限码)。
|
||||
3. 前端打开 **系统管理 → 审批配置**:
|
||||
- 新增:`System.Approval.Simulate`,审批人选**另一位用户**(若选自己请关闭「禁止自审」),启用。
|
||||
- 点击「模拟提交」,应返回 `PendingApproval` + 实例单号。
|
||||
4. 用审批人账号打开 **审批待办**:
|
||||
- 「待我审批」可见该单 → 通过 / 驳回。
|
||||
- 详情抽屉可见事件:`Submitted` → `Approved`/`Rejected` →(通过时)`Executing` → `Executed`。
|
||||
5. 申请人账号在「我发起的」可撤回 Pending 单。
|
||||
|
||||
业务接入见 `src/Oms.Application/Services/Approval/README.md`。
|
||||
|
||||
## 充值入账(Finance.Recharge.Credit)
|
||||
|
||||
1. 审批配置新增并启用 `Finance.Recharge.Credit`,指定审批人。
|
||||
2. 客户提交充值 → 列表状态「待审批」+ 审批号;审批人收到站内信。
|
||||
3. 审批待办通过 → 余额入账、记录「审核通过」;驳回 → 记录「审核驳回」。
|
||||
4. 未配置该操作定义时:提交后 Bypass 直接入账(与价格发布一致)。
|
||||
257
src/Oms.Application/Dtos/Approval/ApprovalDtos.cs
Normal file
257
src/Oms.Application/Dtos/Approval/ApprovalDtos.cs
Normal file
@ -0,0 +1,257 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
|
||||
namespace Oms.Application.Dtos.Approval;
|
||||
|
||||
/// <summary>审批定义列表查询。</summary>
|
||||
public class ApprovalDefinitionListInput
|
||||
{
|
||||
/// <summary>页码,从 1 开始。</summary>
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
/// <summary>每页条数。</summary>
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>关键词(操作编码/名称)。</summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>是否启用筛选。</summary>
|
||||
public bool? IsEnabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批定义保存入参。</summary>
|
||||
public class ApprovalDefinitionSaveInput
|
||||
{
|
||||
/// <summary>主键;空或 0 表示新增。</summary>
|
||||
public int? Id { get; set; }
|
||||
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>触发条件公式;空表示始终需审。</summary>
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>审批人类型:User / Role。</summary>
|
||||
[Required]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>候选人 Guid 列表。</summary>
|
||||
public List<string> ApproverIds { get; set; } = [];
|
||||
|
||||
/// <summary>禁止申请人自审。</summary>
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>启停入参。</summary>
|
||||
public class ApprovalDefinitionEnableInput
|
||||
{
|
||||
/// <summary>定义主键。</summary>
|
||||
[Required]
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批定义输出。</summary>
|
||||
public class ApprovalDefinitionOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string OperationName { get; set; } = string.Empty;
|
||||
|
||||
public bool IsEnabled { get; set; }
|
||||
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
public List<string> ApproverIds { get; set; } = [];
|
||||
|
||||
public bool ForbidSelfApprove { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public DateTime? UpdateTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>操作目录项输出。</summary>
|
||||
public class ApprovalOperationCatalogItemOutput
|
||||
{
|
||||
public string Code { get; set; } = string.Empty;
|
||||
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
public string Module { get; set; } = string.Empty;
|
||||
|
||||
public bool SupportsCondition { get; set; }
|
||||
|
||||
public string ConditionHint { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>条件试算入参。</summary>
|
||||
public class ApprovalConditionTestInput
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>条件公式。</summary>
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>上下文字典。</summary>
|
||||
public Dictionary<string, object?>? Context { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>条件试算结果。</summary>
|
||||
public class ApprovalConditionTestOutput
|
||||
{
|
||||
public bool Ok { get; set; }
|
||||
|
||||
public bool Matched { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>实例列表查询。</summary>
|
||||
public class ApprovalInstanceListInput
|
||||
{
|
||||
public int Page { get; set; } = 1;
|
||||
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
/// <summary>关键词(单号/标题/操作码)。</summary>
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
/// <summary>状态筛选。</summary>
|
||||
public ApprovalInstanceStatus? Status { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>提交/模拟提交入参。</summary>
|
||||
public class ApprovalSubmitInput
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[Required]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键;空则自动生成。</summary>
|
||||
public string? BizKey { get; set; }
|
||||
|
||||
/// <summary>标题。</summary>
|
||||
public string? Title { get; set; }
|
||||
|
||||
/// <summary>载荷 JSON 字符串或对象。</summary>
|
||||
public object? Payload { get; set; }
|
||||
|
||||
/// <summary>摘要对象。</summary>
|
||||
public object? Summary { get; set; }
|
||||
|
||||
/// <summary>条件上下文。</summary>
|
||||
public Dictionary<string, object?>? ConditionContext { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>审批动作入参。</summary>
|
||||
public class ApprovalActionInput
|
||||
{
|
||||
/// <summary>实例 Id。</summary>
|
||||
[Required]
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>意见;驳回必填。</summary>
|
||||
public string? Comment { get; set; }
|
||||
|
||||
/// <summary>并发戳(可选)。</summary>
|
||||
public string? ConcurrencyStamp { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>实例列表/详情输出。</summary>
|
||||
public class ApprovalInstanceOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
public ApprovalInstanceStatus Status { get; set; }
|
||||
|
||||
public string StatusName { get; set; } = string.Empty;
|
||||
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
public string? ApplicantUserName { get; set; }
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public string? SummaryJson { get; set; }
|
||||
|
||||
public string? DefinitionSnapshot { get; set; }
|
||||
|
||||
public int? CurrentTaskId { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public DateTime? CompletedTime { get; set; }
|
||||
|
||||
public DateTime? ExecutedTime { get; set; }
|
||||
|
||||
public string? ExecuteMessage { get; set; }
|
||||
|
||||
public string? ConcurrencyStamp { get; set; }
|
||||
|
||||
/// <summary>当前用户是否可审批该待办。</summary>
|
||||
public bool CanApprove { get; set; }
|
||||
|
||||
/// <summary>当前用户是否可撤回。</summary>
|
||||
public bool CanWithdraw { get; set; }
|
||||
|
||||
public List<ApprovalEventOutput> Events { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>事件输出。</summary>
|
||||
public class ApprovalEventOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string EventType { get; set; } = string.Empty;
|
||||
|
||||
public ApprovalInstanceStatus? FromStatus { get; set; }
|
||||
|
||||
public ApprovalInstanceStatus? ToStatus { get; set; }
|
||||
|
||||
public string? OperatorUserName { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>提交结果。</summary>
|
||||
public class ApprovalSubmitOutput
|
||||
{
|
||||
/// <summary>Bypass / PendingApproval。</summary>
|
||||
public string Decision { get; set; } = string.Empty;
|
||||
|
||||
public int? InstanceId { get; set; }
|
||||
|
||||
public string? InstanceNo { get; set; }
|
||||
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
@ -0,0 +1,21 @@
|
||||
namespace Oms.Application.Dtos.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 销售产品发布结果(可能 Bypass 直接发布,或进入审批)。
|
||||
/// </summary>
|
||||
public class SalesProductPublishResultOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// Bypass=未启用审批已直接发布;PendingApproval=已提交审批;Executed=审批后执行成功(一般不由发布接口返回)。
|
||||
/// </summary>
|
||||
public string Decision { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>审批实例 Id(PendingApproval 时有值)。</summary>
|
||||
public int? ApprovalInstanceId { get; set; }
|
||||
|
||||
/// <summary>审批单号。</summary>
|
||||
public string? ApprovalInstanceNo { get; set; }
|
||||
|
||||
/// <summary>说明。</summary>
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
@ -19,4 +19,27 @@ public class SalesProductPublishSyncStatusOutput
|
||||
|
||||
/// <summary>线上快照内容哈希。</summary>
|
||||
public string? OnlineContentHash { get; set; }
|
||||
|
||||
/// <summary>是否已启用价格发布审批定义(前端发布弹窗文案切换用)。</summary>
|
||||
public bool ApprovalRequired { get; set; }
|
||||
|
||||
/// <summary>是否存在在途价格审批(Pending)。</summary>
|
||||
public bool ApprovalPending { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 无在途单时,最近一次终态是否为失败可重提(驳回 / 撤回 / 执行失败)。
|
||||
/// </summary>
|
||||
public bool ApprovalFailed { get; set; }
|
||||
|
||||
/// <summary>关联审批实例 Id(在途或最近失败单)。</summary>
|
||||
public int? ApprovalInstanceId { get; set; }
|
||||
|
||||
/// <summary>关联审批单号。</summary>
|
||||
public string? ApprovalInstanceNo { get; set; }
|
||||
|
||||
/// <summary>审批状态名(待审批 / 已驳回 / 已撤回 / 执行失败)。</summary>
|
||||
public string? ApprovalStatusName { get; set; }
|
||||
|
||||
/// <summary>驳回意见或执行失败信息(失败态时)。</summary>
|
||||
public string? ApprovalComment { get; set; }
|
||||
}
|
||||
|
||||
@ -45,6 +45,12 @@ public class CustomerPaginatedInput
|
||||
/// <summary>按绑定代理 Id 筛选。</summary>
|
||||
public int? AgentId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 监控页客户 KPI 下钻口径:total / newToday / online / inactive7d。
|
||||
/// 与 /monitor/overview 客户统计一致;传入时默认仅 Normal 客户。
|
||||
/// </summary>
|
||||
public string? MonitorScope { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 排序字段:createTime / updateTime / customerCode / customerName / balance。
|
||||
/// </summary>
|
||||
|
||||
388
src/Oms.Application/Dtos/Operations/ShipContainerDtos.cs
Normal file
388
src/Oms.Application/Dtos/Operations/ShipContainerDtos.cs
Normal file
@ -0,0 +1,388 @@
|
||||
namespace Oms.Application.Dtos.Operations;
|
||||
|
||||
/// <summary>创建大包入参。</summary>
|
||||
public class CreateShipBagInput
|
||||
{
|
||||
/// <summary>sack / box,默认 sack。</summary>
|
||||
public string? BagType { get; set; }
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>长(cm)。</summary>
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
/// <summary>宽(cm)。</summary>
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
/// <summary>高(cm)。</summary>
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
/// <summary>重量(kg)。</summary>
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>更新大包件重尺 / 目的口岸等属性(交运前)。</summary>
|
||||
public class UpdateShipBagMetaInput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>大包扫入/移出小包。</summary>
|
||||
public class ShipBagParcelInput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public string WaybillNo { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>按大包号操作。</summary>
|
||||
public class ShipBagNoInput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>大包分页查询。</summary>
|
||||
public class ShipBagPageInput
|
||||
{
|
||||
public int PageIndex { get; set; } = 1;
|
||||
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
public string? Status { get; set; }
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>大包输出。</summary>
|
||||
public class ShipBagOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public string BagType { get; set; } = string.Empty;
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
public string? StatusName { get; set; }
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>长(cm)。</summary>
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
/// <summary>宽(cm)。</summary>
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
/// <summary>高(cm)。</summary>
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
/// <summary>重量(kg)。</summary>
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public int ParcelCount { get; set; }
|
||||
|
||||
public DateTime? SealTime { get; set; }
|
||||
|
||||
public DateTime? ShipTime { get; set; }
|
||||
|
||||
public int? MasterId { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public List<ShipBagItemOutput>? Items { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>大包明细输出。</summary>
|
||||
public class ShipBagItemOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
public string WaybillNo { get; set; } = string.Empty;
|
||||
|
||||
public string? OrderStatus { get; set; }
|
||||
|
||||
public string? OrderStatusName { get; set; }
|
||||
|
||||
public string? ConsigneeCountry { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>大包出库入参。</summary>
|
||||
public class CreateBagOutboundInput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>大包出库结果。</summary>
|
||||
public class BagOutboundResultOutput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public int SuccessCount { get; set; }
|
||||
|
||||
public List<string> WaybillNos { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>创建内部主单。</summary>
|
||||
public class CreateShipMasterInput
|
||||
{
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? FlightOrVoyage { get; set; }
|
||||
|
||||
public string? ExternalMawb { get; set; }
|
||||
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>更新主单件重尺 / 目的口岸等属性(交运前)。</summary>
|
||||
public class UpdateShipMasterMetaInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? FlightOrVoyage { get; set; }
|
||||
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>主单号入参。</summary>
|
||||
public class ShipMasterNoInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>主单扫入大包。</summary>
|
||||
public class ShipMasterAddBagInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>主单扫入散货小包。</summary>
|
||||
public class ShipMasterAddParcelInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string WaybillNo { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>主单移除明细。</summary>
|
||||
public class ShipMasterRemoveItemInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public int ItemId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>绑定外部 MAWB。</summary>
|
||||
public class ShipMasterBindMawbInput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string ExternalMawb { get; set; } = string.Empty;
|
||||
|
||||
public string? FlightOrVoyage { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>主单分页。</summary>
|
||||
public class ShipMasterPageInput
|
||||
{
|
||||
public int PageIndex { get; set; } = 1;
|
||||
|
||||
public int PageSize { get; set; } = 50;
|
||||
|
||||
public string? Keyword { get; set; }
|
||||
|
||||
public string? Status { get; set; }
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>主单输出。</summary>
|
||||
public class ShipMasterOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string? ExternalMawb { get; set; }
|
||||
|
||||
public string Status { get; set; } = string.Empty;
|
||||
|
||||
public string? StatusName { get; set; }
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
public string? FlightOrVoyage { get; set; }
|
||||
|
||||
/// <summary>长(cm)。</summary>
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
/// <summary>宽(cm)。</summary>
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
/// <summary>高(cm)。</summary>
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
/// <summary>重量(kg)。</summary>
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public int BagCount { get; set; }
|
||||
|
||||
public int ParcelCount { get; set; }
|
||||
|
||||
public DateTime? SealTime { get; set; }
|
||||
|
||||
public DateTime? HandTime { get; set; }
|
||||
|
||||
public string? Remark { get; set; }
|
||||
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
public List<ShipMasterItemOutput>? Items { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>主单明细输出。</summary>
|
||||
public class ShipMasterItemOutput
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
public string ItemType { get; set; } = string.Empty;
|
||||
|
||||
public int? BagId { get; set; }
|
||||
|
||||
public string? BagNo { get; set; }
|
||||
|
||||
public int? OrderId { get; set; }
|
||||
|
||||
public string? WaybillNo { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>批量打印大包标签入参。</summary>
|
||||
public class ShipBagPrintLabelsInput
|
||||
{
|
||||
/// <summary>大包号列表。</summary>
|
||||
public List<string> BagNos { get; set; } = [];
|
||||
|
||||
/// <summary>标签模板 ID;不传则取类型 shipBag 最新模板。</summary>
|
||||
public int? LabelTemplateId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>批量打印大包标签出参。</summary>
|
||||
public class ShipBagPrintLabelsOutput
|
||||
{
|
||||
/// <summary>使用的模板名称。</summary>
|
||||
public string? TemplateName { get; set; }
|
||||
|
||||
/// <summary>各包打印结果。</summary>
|
||||
public List<ShipBagPrintLabelItemOutput> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>单个大包打印结果。</summary>
|
||||
public class ShipBagPrintLabelItemOutput
|
||||
{
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
public string PrintUrl { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>批量打印主单标签入参。</summary>
|
||||
public class ShipMasterPrintLabelsInput
|
||||
{
|
||||
/// <summary>内部主单号列表。</summary>
|
||||
public List<string> MasterNos { get; set; } = [];
|
||||
|
||||
/// <summary>标签模板 ID;不传则取类型 shipMaster 最新模板。</summary>
|
||||
public int? LabelTemplateId { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>批量打印主单标签出参。</summary>
|
||||
public class ShipMasterPrintLabelsOutput
|
||||
{
|
||||
/// <summary>使用的模板名称。</summary>
|
||||
public string? TemplateName { get; set; }
|
||||
|
||||
/// <summary>各主单打印结果。</summary>
|
||||
public List<ShipMasterPrintLabelItemOutput> Items { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>单个主单打印结果。</summary>
|
||||
public class ShipMasterPrintLabelItemOutput
|
||||
{
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
public string PrintUrl { get; set; } = string.Empty;
|
||||
}
|
||||
@ -100,6 +100,12 @@ public class OrderOutput
|
||||
/// </summary>
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>当前大包号,可空。</summary>
|
||||
public string? ShipBagNo { get; set; }
|
||||
|
||||
/// <summary>当前内部主单号,可空。</summary>
|
||||
public string? ShipMasterNo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 仓库名称。
|
||||
/// </summary>
|
||||
|
||||
@ -65,6 +65,12 @@ public class OrderPaginatedOutput
|
||||
/// </summary>
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>当前大包号,可空(不强制装袋)。</summary>
|
||||
public string? ShipBagNo { get; set; }
|
||||
|
||||
/// <summary>当前内部主单号,可空(不强制上主单)。</summary>
|
||||
public string? ShipMasterNo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 仓库名称。
|
||||
/// </summary>
|
||||
|
||||
@ -56,4 +56,24 @@ public class RechargeRecordOutput
|
||||
/// 创建时间。
|
||||
/// </summary>
|
||||
public DateTime CreateTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 审批门面判定:Bypass / PendingApproval。
|
||||
/// </summary>
|
||||
public string? Decision { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 在途审批实例 Id。
|
||||
/// </summary>
|
||||
public int? ApprovalInstanceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 在途审批单号。
|
||||
/// </summary>
|
||||
public string? ApprovalInstanceNo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 提交结果说明。
|
||||
/// </summary>
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
@ -22,6 +22,11 @@ public class RechargeRecordPaginatedOutput
|
||||
/// </summary>
|
||||
public string? CustomerCode { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客户名称。
|
||||
/// </summary>
|
||||
public string? CustomerName { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 客户手机号。
|
||||
/// </summary>
|
||||
@ -82,6 +87,21 @@ public class RechargeRecordPaginatedOutput
|
||||
/// </summary>
|
||||
public string? AuditBy { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否存在在途审批。
|
||||
/// </summary>
|
||||
public bool ApprovalPending { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 在途审批实例 Id。
|
||||
/// </summary>
|
||||
public int? ApprovalInstanceId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 在途审批单号。
|
||||
/// </summary>
|
||||
public string? ApprovalInstanceNo { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间。
|
||||
/// </summary>
|
||||
|
||||
17
src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs
Normal file
17
src/Oms.Application/Dtos/System/PaymentReceiveQrOutput.cs
Normal file
@ -0,0 +1,17 @@
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>
|
||||
/// 充值收款码展示输出。
|
||||
/// </summary>
|
||||
public class PaymentReceiveQrOutput
|
||||
{
|
||||
/// <summary>
|
||||
/// 支付宝收款码可访问 URL;未配置时为空。
|
||||
/// </summary>
|
||||
public string AlipayUrl { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 微信收款码可访问 URL;未配置时为空。
|
||||
/// </summary>
|
||||
public string WechatUrl { get; set; } = string.Empty;
|
||||
}
|
||||
@ -0,0 +1,19 @@
|
||||
using Microsoft.AspNetCore.Http;
|
||||
|
||||
namespace Oms.Application.Dtos.System;
|
||||
|
||||
/// <summary>
|
||||
/// 上传充值收款码入参(multipart/form-data:channel + file)。
|
||||
/// </summary>
|
||||
public class PaymentReceiveQrUploadInput
|
||||
{
|
||||
/// <summary>
|
||||
/// 渠道:alipay / wechat。
|
||||
/// </summary>
|
||||
public string Channel { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 收款码图片。
|
||||
/// </summary>
|
||||
public IFormFile File { get; set; } = null!;
|
||||
}
|
||||
@ -121,6 +121,61 @@ public static class LabelFieldDictionary
|
||||
]
|
||||
},
|
||||
new LabelFieldGroup
|
||||
{
|
||||
Code = "shipBag",
|
||||
Title = "出库大包",
|
||||
Fields =
|
||||
[
|
||||
Field("bagNo", "大包号"),
|
||||
Field("bagType", "袋型编码"),
|
||||
Field("bagTypeName", "袋型名称"),
|
||||
Field("status", "状态"),
|
||||
Field("barcode", "条码内容"),
|
||||
Field("destinationCountry", "目的国"),
|
||||
Field("destinationPort", "目的口岸"),
|
||||
Field("channelCode", "渠道编码"),
|
||||
Field("parcelCount", "件数"),
|
||||
Field("weight", "重量(kg)"),
|
||||
Field("length", "长(cm)"),
|
||||
Field("width", "宽(cm)"),
|
||||
Field("height", "高(cm)"),
|
||||
Field("weightUnit", "重量单位"),
|
||||
Field("dimUnit", "尺寸单位"),
|
||||
Field("dimensions", "尺寸摘要"),
|
||||
Field("warehouseName", "仓库"),
|
||||
Field("sealTime", "封袋时间"),
|
||||
Field("remark", "备注")
|
||||
]
|
||||
},
|
||||
new LabelFieldGroup
|
||||
{
|
||||
Code = "shipMaster",
|
||||
Title = "内部主单",
|
||||
Fields =
|
||||
[
|
||||
Field("masterNo", "内部主单号"),
|
||||
Field("externalMawb", "外部MAWB"),
|
||||
Field("barcode", "条码内容"),
|
||||
Field("status", "状态"),
|
||||
Field("destinationCountry", "目的国"),
|
||||
Field("destinationPort", "目的口岸"),
|
||||
Field("flightOrVoyage", "航班/航次"),
|
||||
Field("bagCount", "大包数"),
|
||||
Field("parcelCount", "小包数"),
|
||||
Field("weight", "重量(kg)"),
|
||||
Field("length", "长(cm)"),
|
||||
Field("width", "宽(cm)"),
|
||||
Field("height", "高(cm)"),
|
||||
Field("weightUnit", "重量单位"),
|
||||
Field("dimUnit", "尺寸单位"),
|
||||
Field("dimensions", "尺寸摘要"),
|
||||
Field("warehouseName", "仓库"),
|
||||
Field("sealTime", "封板时间"),
|
||||
Field("handTime", "交运时间"),
|
||||
Field("remark", "备注")
|
||||
]
|
||||
},
|
||||
new LabelFieldGroup
|
||||
{
|
||||
Code = "system",
|
||||
Title = "系统",
|
||||
|
||||
80
src/Oms.Application/Labeling/ShipBagLabelPrintDataBuilder.cs
Normal file
80
src/Oms.Application/Labeling/ShipBagLabelPrintDataBuilder.cs
Normal file
@ -0,0 +1,80 @@
|
||||
using System.Globalization;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
namespace Oms.Application.Labeling;
|
||||
|
||||
/// <summary>
|
||||
/// 出库大包标签 PrintData(camelCase,与 hiprint 字段对齐)。
|
||||
/// </summary>
|
||||
public static class ShipBagLabelPrintDataBuilder
|
||||
{
|
||||
public static IReadOnlyDictionary<string, object?> Build(
|
||||
ShipBag bag,
|
||||
string? warehouseName = null,
|
||||
string? operatorName = null,
|
||||
DateTime? printTime = null,
|
||||
int pageIndex = 1,
|
||||
int pageCount = 1)
|
||||
{
|
||||
return new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["bagNo"] = bag.BagNo,
|
||||
["bagType"] = bag.BagType,
|
||||
["bagTypeName"] = string.Equals(bag.BagType, "box", StringComparison.OrdinalIgnoreCase) ? "箱子" : "麻袋",
|
||||
["status"] = bag.Status,
|
||||
["barcode"] = bag.BagNo,
|
||||
["destinationCountry"] = bag.DestinationCountry,
|
||||
["destinationPort"] = bag.DestinationPort,
|
||||
["channelCode"] = bag.ChannelCode,
|
||||
["parcelCount"] = bag.ParcelCount,
|
||||
["weight"] = bag.Weight,
|
||||
["length"] = bag.Length,
|
||||
["width"] = bag.Width,
|
||||
["height"] = bag.Height,
|
||||
["weightUnit"] = "KG",
|
||||
["dimUnit"] = "CM",
|
||||
["dimensions"] = FormatDims(bag.Length, bag.Width, bag.Height),
|
||||
["remark"] = bag.Remark,
|
||||
["warehouseName"] = warehouseName,
|
||||
["sealTime"] = bag.SealTime?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["pageIndex"] = pageIndex,
|
||||
["pageCount"] = pageCount,
|
||||
["printTime"] = (printTime ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["operatorName"] = operatorName
|
||||
};
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<string, object?> BuildMock() =>
|
||||
new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["bagNo"] = "BAG2511071200001234",
|
||||
["bagType"] = "sack",
|
||||
["bagTypeName"] = "麻袋",
|
||||
["status"] = "sealed",
|
||||
["barcode"] = "BAG2511071200001234",
|
||||
["destinationCountry"] = "US",
|
||||
["destinationPort"] = "LAX",
|
||||
["channelCode"] = "DEMO",
|
||||
["parcelCount"] = 12,
|
||||
["weight"] = 18.5m,
|
||||
["length"] = 60m,
|
||||
["width"] = 40m,
|
||||
["height"] = 40m,
|
||||
["weightUnit"] = "KG",
|
||||
["dimUnit"] = "CM",
|
||||
["dimensions"] = "60×40×40",
|
||||
["remark"] = null,
|
||||
["warehouseName"] = "深圳仓库",
|
||||
["sealTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["pageIndex"] = 1,
|
||||
["pageCount"] = 1,
|
||||
["printTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["operatorName"] = "demo"
|
||||
};
|
||||
|
||||
private static string? FormatDims(decimal? length, decimal? width, decimal? height)
|
||||
{
|
||||
if (length is null && width is null && height is null) return null;
|
||||
return $"{length ?? 0}×{width ?? 0}×{height ?? 0}";
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,85 @@
|
||||
using System.Globalization;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
namespace Oms.Application.Labeling;
|
||||
|
||||
/// <summary>
|
||||
/// 内部主单标签 PrintData(camelCase,与 hiprint 字段对齐)。
|
||||
/// </summary>
|
||||
public static class ShipMasterLabelPrintDataBuilder
|
||||
{
|
||||
public static IReadOnlyDictionary<string, object?> Build(
|
||||
ShipMaster master,
|
||||
string? warehouseName = null,
|
||||
string? operatorName = null,
|
||||
DateTime? printTime = null,
|
||||
int pageIndex = 1,
|
||||
int pageCount = 1)
|
||||
{
|
||||
return new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["masterNo"] = master.MasterNo,
|
||||
["externalMawb"] = master.ExternalMawb,
|
||||
["barcode"] = FirstNonEmpty(master.ExternalMawb, master.MasterNo),
|
||||
["status"] = master.Status,
|
||||
["destinationCountry"] = master.DestinationCountry,
|
||||
["destinationPort"] = master.DestinationPort,
|
||||
["flightOrVoyage"] = master.FlightOrVoyage,
|
||||
["bagCount"] = master.BagCount,
|
||||
["parcelCount"] = master.ParcelCount,
|
||||
["weight"] = master.Weight,
|
||||
["length"] = master.Length,
|
||||
["width"] = master.Width,
|
||||
["height"] = master.Height,
|
||||
["weightUnit"] = "KG",
|
||||
["dimUnit"] = "CM",
|
||||
["dimensions"] = FormatDims(master.Length, master.Width, master.Height),
|
||||
["remark"] = master.Remark,
|
||||
["warehouseName"] = warehouseName,
|
||||
["sealTime"] = master.SealTime?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["handTime"] = master.HandTime?.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["pageIndex"] = pageIndex,
|
||||
["pageCount"] = pageCount,
|
||||
["printTime"] = (printTime ?? DateTime.Now).ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["operatorName"] = operatorName
|
||||
};
|
||||
}
|
||||
|
||||
public static IReadOnlyDictionary<string, object?> BuildMock() =>
|
||||
new Dictionary<string, object?>(StringComparer.OrdinalIgnoreCase)
|
||||
{
|
||||
["masterNo"] = "MBL2511071200005678",
|
||||
["externalMawb"] = "176-12345678",
|
||||
["barcode"] = "176-12345678",
|
||||
["status"] = "sealed",
|
||||
["destinationCountry"] = "US",
|
||||
["destinationPort"] = "JFK",
|
||||
["flightOrVoyage"] = "CA981",
|
||||
["bagCount"] = 8,
|
||||
["parcelCount"] = 96,
|
||||
["weight"] = 320.5m,
|
||||
["length"] = 120m,
|
||||
["width"] = 100m,
|
||||
["height"] = 160m,
|
||||
["weightUnit"] = "KG",
|
||||
["dimUnit"] = "CM",
|
||||
["dimensions"] = "120×100×160",
|
||||
["remark"] = null,
|
||||
["warehouseName"] = "深圳仓库",
|
||||
["sealTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["handTime"] = null,
|
||||
["pageIndex"] = 1,
|
||||
["pageCount"] = 1,
|
||||
["printTime"] = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture),
|
||||
["operatorName"] = "demo"
|
||||
};
|
||||
|
||||
private static string? FormatDims(decimal? length, decimal? width, decimal? height)
|
||||
{
|
||||
if (length is null && width is null && height is null) return null;
|
||||
return $"{length ?? 0}×{width ?? 0}×{height ?? 0}";
|
||||
}
|
||||
|
||||
private static string? FirstNonEmpty(params string?[] values) =>
|
||||
values.FirstOrDefault(x => !string.IsNullOrWhiteSpace(x));
|
||||
}
|
||||
@ -12,6 +12,10 @@ using Oms.Application.Integrations.Itfx;
|
||||
using Oms.Application.Integrations.PlatformShop;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Labeling.Hiprint;
|
||||
using Oms.Application.Services.Approval;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Services.Channels;
|
||||
using Oms.Application.Services.Recharge;
|
||||
using Oms.Application.Services.Storage;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Workers;
|
||||
@ -53,6 +57,12 @@ public class OmsApplicationModule : FakeModule
|
||||
context.Services.AddTransient<ILabelPdfRenderer, QuestPdfLabelRenderer>();
|
||||
context.Services.AddTransient<LabelPdfGenerationService>();
|
||||
|
||||
// 审批终审 Handler:约定注册只暴露 I{类名},须显式挂到 IApprovalOperationHandler,
|
||||
// 否则 Approve 会空跑成 Executed、不落发布/入账。
|
||||
context.Services.AddTransient<IApprovalOperationHandler, SalesProductPricePublishApprovalHandler>();
|
||||
context.Services.AddTransient<IApprovalOperationHandler, RechargeCreditApprovalHandler>();
|
||||
context.Services.AddTransient<IApprovalOperationHandler, NoopApprovalHandler>();
|
||||
|
||||
context.Services.AddHttpClient(FileStorageService.UrlFetchClientName, client =>
|
||||
{
|
||||
client.Timeout = TimeSpan.FromSeconds(60);
|
||||
|
||||
@ -0,0 +1,68 @@
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Oms.Application.DataPerm;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 将定义中的角色/用户候选人展开为可审用户 Guid 列表。
|
||||
/// </summary>
|
||||
public class ApprovalCandidateResolver(DataPermRepository dataPermRepository) : IScopedDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 展开候选人;User 类型直接返回 Guid;Role 类型展开成员。
|
||||
/// </summary>
|
||||
public async Task<List<string>> ExpandCandidateUserIdsAsync(
|
||||
string approverType,
|
||||
string approverIds,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var ids = ApprovalIdHelper.SplitIds(approverIds);
|
||||
if (ids.Count == 0)
|
||||
{
|
||||
throw new BusinessException("审批候选人不能为空");
|
||||
}
|
||||
|
||||
if (string.Equals(approverType, ApprovalCodes.ApproverTypeUser, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
foreach (var id in ids)
|
||||
{
|
||||
if (!Guid.TryParse(id, out _))
|
||||
{
|
||||
throw new BusinessException($"用户候选人 Id 无效:{id}");
|
||||
}
|
||||
}
|
||||
|
||||
return ids;
|
||||
}
|
||||
|
||||
if (!string.Equals(approverType, ApprovalCodes.ApproverTypeRole, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("审批人类型仅支持 User 或 Role");
|
||||
}
|
||||
|
||||
var userIds = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var roleIdText in ids)
|
||||
{
|
||||
if (!Guid.TryParse(roleIdText, out var roleId))
|
||||
{
|
||||
throw new BusinessException($"角色候选人 Id 无效:{roleIdText}");
|
||||
}
|
||||
|
||||
var members = await dataPermRepository.GetUserIdsByRoleAsync(roleId, cancellationToken);
|
||||
foreach (var uid in members)
|
||||
{
|
||||
userIds.Add(uid.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
if (userIds.Count == 0)
|
||||
{
|
||||
throw new BusinessException("所选角色下没有可审批用户");
|
||||
}
|
||||
|
||||
return userIds.ToList();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,348 @@
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批条件求值:空公式视为命中;非空需操作支持条件,并用简易比较表达式求值。
|
||||
/// 一期支持:标签 比较符 数字/字符串,以及 && || ! 与括号;与自动触发公式子集对齐。
|
||||
/// </summary>
|
||||
public class ApprovalConditionEvaluator(IEnumerable<IApprovalConditionContextFactory> factories) : IScopedDependency
|
||||
{
|
||||
private readonly Dictionary<string, IApprovalConditionContextFactory> _factories = factories
|
||||
.GroupBy(x => x.OperationCode, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 校验公式是否允许保存。
|
||||
/// </summary>
|
||||
public void EnsureFormulaAllowed(string operationCode, string? formula)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var item = ApprovalOperationCatalog.Find(operationCode);
|
||||
if (item is { SupportsCondition: false } && !_factories.ContainsKey(operationCode))
|
||||
{
|
||||
throw new BusinessException($"操作 {operationCode} 暂不支持条件公式,请留空");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 求值是否命中需审条件。空公式返回 true。
|
||||
/// </summary>
|
||||
public bool Evaluate(
|
||||
string operationCode,
|
||||
string? formula,
|
||||
IReadOnlyDictionary<string, object?>? rawContext)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(formula))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
IReadOnlyDictionary<string, object?> context = rawContext ?? new Dictionary<string, object?>();
|
||||
if (_factories.TryGetValue(operationCode, out var factory))
|
||||
{
|
||||
context = factory.Build(rawContext);
|
||||
}
|
||||
|
||||
if (!TryEvaluate(formula, context, out var matched, out var error))
|
||||
{
|
||||
throw new BusinessException(error ?? "条件公式求值失败");
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 试算(不抛业务异常,返回消息)。
|
||||
/// </summary>
|
||||
public (bool Ok, bool Matched, string? Message) TryTest(
|
||||
string operationCode,
|
||||
string? formula,
|
||||
IReadOnlyDictionary<string, object?>? rawContext)
|
||||
{
|
||||
try
|
||||
{
|
||||
EnsureFormulaAllowed(operationCode, formula);
|
||||
var matched = Evaluate(operationCode, formula, rawContext);
|
||||
return (true, matched, matched ? "条件命中(需审批)" : "条件未命中(可不审批)");
|
||||
}
|
||||
catch (BusinessException ex)
|
||||
{
|
||||
return (false, false, ex.Message);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return (false, false, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TryEvaluate(
|
||||
string expression,
|
||||
IReadOnlyDictionary<string, object?> context,
|
||||
out bool result,
|
||||
out string? error)
|
||||
{
|
||||
result = false;
|
||||
error = null;
|
||||
try
|
||||
{
|
||||
var parser = new SimpleParser(expression.Trim(), context);
|
||||
result = parser.ParseExpression();
|
||||
parser.ExpectEnd();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
error = ex.Message;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class SimpleParser(string source, IReadOnlyDictionary<string, object?> context)
|
||||
{
|
||||
private int _pos;
|
||||
|
||||
public bool ParseExpression() => ParseOr();
|
||||
|
||||
public void ExpectEnd()
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length)
|
||||
{
|
||||
throw new InvalidOperationException($"条件公式存在无法解析内容:{source[_pos..]}");
|
||||
}
|
||||
}
|
||||
|
||||
private bool ParseOr()
|
||||
{
|
||||
var left = ParseAnd();
|
||||
while (MatchKeyword("||") || MatchKeyword("或"))
|
||||
{
|
||||
var right = ParseAnd();
|
||||
left = left || right;
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private bool ParseAnd()
|
||||
{
|
||||
var left = ParseUnary();
|
||||
while (MatchKeyword("&&") || MatchKeyword("且"))
|
||||
{
|
||||
var right = ParseUnary();
|
||||
left = left && right;
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private bool ParseUnary()
|
||||
{
|
||||
if (MatchKeyword("!") || MatchKeyword("非"))
|
||||
{
|
||||
return !ParseUnary();
|
||||
}
|
||||
|
||||
return ParsePrimary();
|
||||
}
|
||||
|
||||
private bool ParsePrimary()
|
||||
{
|
||||
SkipWs();
|
||||
if (Match('('))
|
||||
{
|
||||
var inner = ParseExpression();
|
||||
if (!Match(')'))
|
||||
{
|
||||
throw new InvalidOperationException("条件公式缺少右括号");
|
||||
}
|
||||
|
||||
return inner;
|
||||
}
|
||||
|
||||
var label = ReadLabel();
|
||||
SkipWs();
|
||||
if (MatchKeyword("有值"))
|
||||
{
|
||||
return HasValue(Resolve(label));
|
||||
}
|
||||
|
||||
if (MatchKeyword("为空"))
|
||||
{
|
||||
return !HasValue(Resolve(label));
|
||||
}
|
||||
|
||||
if (MatchKeyword("包含"))
|
||||
{
|
||||
if (!Match('('))
|
||||
{
|
||||
throw new InvalidOperationException("包含(...) 语法错误");
|
||||
}
|
||||
|
||||
var needle = ReadStringOrNumber();
|
||||
if (!Match(')'))
|
||||
{
|
||||
throw new InvalidOperationException("包含(...) 缺少右括号");
|
||||
}
|
||||
|
||||
var hay = Resolve(label)?.ToString() ?? string.Empty;
|
||||
return hay.Contains(needle, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
string op;
|
||||
if (MatchKeyword(">=")) op = ">=";
|
||||
else if (MatchKeyword("<=")) op = "<=";
|
||||
else if (MatchKeyword("!=") || MatchKeyword("<>")) op = "!=";
|
||||
else if (MatchKeyword("==") || MatchKeyword("=")) op = "==";
|
||||
else if (Match('>')) op = ">";
|
||||
else if (Match('<')) op = "<";
|
||||
else throw new InvalidOperationException($"条件公式缺少比较符:{label}");
|
||||
|
||||
var rightRaw = ReadStringOrNumber();
|
||||
return Compare(Resolve(label), op, rightRaw);
|
||||
}
|
||||
|
||||
private object? Resolve(string label)
|
||||
{
|
||||
if (context.TryGetValue(label, out var value))
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
var hit = context.FirstOrDefault(x =>
|
||||
string.Equals(x.Key, label, StringComparison.OrdinalIgnoreCase));
|
||||
return hit.Key == null ? null : hit.Value;
|
||||
}
|
||||
|
||||
private string ReadLabel()
|
||||
{
|
||||
SkipWs();
|
||||
var start = _pos;
|
||||
while (_pos < source.Length)
|
||||
{
|
||||
var ch = source[_pos];
|
||||
if (char.IsLetterOrDigit(ch) || ch is '_' or '.' || ch > 127)
|
||||
{
|
||||
_pos++;
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (_pos == start)
|
||||
{
|
||||
throw new InvalidOperationException("条件公式缺少字段名");
|
||||
}
|
||||
|
||||
return source[start.._pos];
|
||||
}
|
||||
|
||||
private string ReadStringOrNumber()
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length && (source[_pos] == '"' || source[_pos] == '\''))
|
||||
{
|
||||
var quote = source[_pos++];
|
||||
var start = _pos;
|
||||
while (_pos < source.Length && source[_pos] != quote)
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
var text = source[start.._pos];
|
||||
if (_pos < source.Length)
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
return text;
|
||||
}
|
||||
|
||||
var m = Regex.Match(source[_pos..], @"^[+-]?\d+(\.\d+)?");
|
||||
if (m.Success)
|
||||
{
|
||||
_pos += m.Length;
|
||||
return m.Value;
|
||||
}
|
||||
|
||||
return ReadLabel();
|
||||
}
|
||||
|
||||
private static bool HasValue(object? value) =>
|
||||
value != null && !string.IsNullOrWhiteSpace(Convert.ToString(value, CultureInfo.InvariantCulture));
|
||||
|
||||
private static bool Compare(object? left, string op, string rightText)
|
||||
{
|
||||
if (decimal.TryParse(Convert.ToString(left, CultureInfo.InvariantCulture), NumberStyles.Any, CultureInfo.InvariantCulture, out var ln)
|
||||
&& decimal.TryParse(rightText, NumberStyles.Any, CultureInfo.InvariantCulture, out var rn))
|
||||
{
|
||||
return op switch
|
||||
{
|
||||
">" => ln > rn,
|
||||
">=" => ln >= rn,
|
||||
"<" => ln < rn,
|
||||
"<=" => ln <= rn,
|
||||
"==" => ln == rn,
|
||||
"!=" => ln != rn,
|
||||
_ => false
|
||||
};
|
||||
}
|
||||
|
||||
var ls = Convert.ToString(left, CultureInfo.InvariantCulture) ?? string.Empty;
|
||||
return op switch
|
||||
{
|
||||
"==" => string.Equals(ls, rightText, StringComparison.OrdinalIgnoreCase),
|
||||
"!=" => !string.Equals(ls, rightText, StringComparison.OrdinalIgnoreCase),
|
||||
_ => throw new InvalidOperationException("非数值字段仅支持 = / !=")
|
||||
};
|
||||
}
|
||||
|
||||
private void SkipWs()
|
||||
{
|
||||
while (_pos < source.Length && char.IsWhiteSpace(source[_pos]))
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
}
|
||||
|
||||
private bool Match(char ch)
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos < source.Length && source[_pos] == ch)
|
||||
{
|
||||
_pos++;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private bool MatchKeyword(string keyword)
|
||||
{
|
||||
SkipWs();
|
||||
if (_pos + keyword.Length > source.Length)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!string.Equals(source.Substring(_pos, keyword.Length), keyword, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_pos += keyword.Length;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,266 @@
|
||||
using System.Linq.Expressions;
|
||||
using Fake.Application;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Approval;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批定义配置 API。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Approval")]
|
||||
public class ApprovalDefinitionService : ApplicationService
|
||||
{
|
||||
private IApprovalDefinitionRepository DefinitionRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalDefinitionRepository>();
|
||||
|
||||
private ApprovalPermissionGuard PermissionGuard =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalPermissionGuard>();
|
||||
|
||||
private ApprovalConditionEvaluator ConditionEvaluator =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalConditionEvaluator>();
|
||||
|
||||
private ApprovalCandidateResolver CandidateResolver =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalCandidateResolver>();
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询审批定义。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/definition/list")]
|
||||
public async Task<OmsPageResult<ApprovalDefinitionOutput>> GetListAsync(
|
||||
[FromQuery] ApprovalDefinitionListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery);
|
||||
|
||||
var keyword = input.Keyword?.Trim();
|
||||
Expression<Func<ApprovalDefinition, bool>> predicate = x =>
|
||||
(string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.OperationCode.Contains(keyword)
|
||||
|| x.OperationName.Contains(keyword))
|
||||
&& (input.IsEnabled == null || x.IsEnabled == input.IsEnabled.Value);
|
||||
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize <= 0 ? 50 : input.PageSize);
|
||||
var (items, total) = await RepositoryPageHelper.GetPageAsync(
|
||||
DefinitionRepository,
|
||||
predicate,
|
||||
pageIndex,
|
||||
pageSize,
|
||||
q => q.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id));
|
||||
|
||||
return new OmsPageResult<ApprovalDefinitionOutput>
|
||||
{
|
||||
Items = items.Select(MapOutput).ToList(),
|
||||
Total = total
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询审批定义详情。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/definition/get")]
|
||||
public async Task<ApprovalDefinitionOutput> GetAsync([FromQuery] int id)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionQuery);
|
||||
var entity = await GetOrThrowAsync(id);
|
||||
return MapOutput(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取可配置操作目录。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/operation-catalog")]
|
||||
public async Task<List<ApprovalOperationCatalogItemOutput>> GetCatalogAsync()
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.DefinitionQuery,
|
||||
ApprovalPermissionCodes.DefinitionCreate,
|
||||
ApprovalPermissionCodes.DefinitionUpdate);
|
||||
|
||||
return ApprovalOperationCatalog.All.Select(x => new ApprovalOperationCatalogItemOutput
|
||||
{
|
||||
Code = x.Code,
|
||||
Name = x.Name,
|
||||
Module = x.Module,
|
||||
SupportsCondition = x.SupportsCondition,
|
||||
ConditionHint = x.ConditionHint
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 新增或更新审批定义。同一 OperationCode 仅允许一条有效定义。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/save")]
|
||||
public async Task<ApprovalDefinitionOutput> SaveAsync(ApprovalDefinitionSaveInput input)
|
||||
{
|
||||
var isCreate = !input.Id.HasValue || input.Id.Value <= 0;
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
isCreate ? ApprovalPermissionCodes.DefinitionCreate : ApprovalPermissionCodes.DefinitionUpdate);
|
||||
|
||||
var operationCode = input.OperationCode?.Trim() ?? string.Empty;
|
||||
if (string.IsNullOrWhiteSpace(operationCode))
|
||||
{
|
||||
throw new BusinessException("操作编码不能为空");
|
||||
}
|
||||
|
||||
if (!ApprovalOperationCatalog.IsKnown(operationCode))
|
||||
{
|
||||
throw new BusinessException($"未知操作编码:{operationCode}");
|
||||
}
|
||||
|
||||
var approverType = NormalizeApproverType(input.ApproverType);
|
||||
var approverIds = ApprovalIdHelper.JoinIds(input.ApproverIds);
|
||||
if (string.IsNullOrWhiteSpace(approverIds))
|
||||
{
|
||||
throw new BusinessException("审批候选人不能为空");
|
||||
}
|
||||
|
||||
// 保存时展开校验,避免角色下无人
|
||||
await CandidateResolver.ExpandCandidateUserIdsAsync(approverType, approverIds);
|
||||
|
||||
var formula = string.IsNullOrWhiteSpace(input.ConditionFormula)
|
||||
? null
|
||||
: input.ConditionFormula.Trim();
|
||||
ConditionEvaluator.EnsureFormulaAllowed(operationCode, formula);
|
||||
|
||||
var catalogItem = ApprovalOperationCatalog.Find(operationCode)!;
|
||||
var remark = string.IsNullOrWhiteSpace(input.Remark) ? null : input.Remark.Trim();
|
||||
if (isCreate)
|
||||
{
|
||||
await EnsureOperationUniqueAsync(operationCode, null);
|
||||
var created = await DefinitionRepository.InsertAsync(new ApprovalDefinition
|
||||
{
|
||||
OperationCode = operationCode,
|
||||
OperationName = catalogItem.Name,
|
||||
IsEnabled = input.IsEnabled,
|
||||
ConditionFormula = formula,
|
||||
ApproverType = approverType,
|
||||
ApproverIds = approverIds,
|
||||
ForbidSelfApprove = input.ForbidSelfApprove,
|
||||
Remark = remark
|
||||
});
|
||||
return MapOutput(created);
|
||||
}
|
||||
|
||||
var entity = await GetOrThrowAsync(input.Id!.Value);
|
||||
if (!string.Equals(entity.OperationCode, operationCode, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
await EnsureOperationUniqueAsync(operationCode, entity.Id);
|
||||
}
|
||||
|
||||
entity.OperationCode = operationCode;
|
||||
entity.OperationName = catalogItem.Name;
|
||||
entity.IsEnabled = input.IsEnabled;
|
||||
entity.ConditionFormula = formula;
|
||||
entity.ApproverType = approverType;
|
||||
entity.ApproverIds = approverIds;
|
||||
entity.ForbidSelfApprove = input.ForbidSelfApprove;
|
||||
entity.Remark = remark;
|
||||
await DefinitionRepository.UpdateAsync(entity);
|
||||
return MapOutput(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启用或停用审批定义。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/enable")]
|
||||
public async Task EnableAsync(ApprovalDefinitionEnableInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionEnable);
|
||||
var entity = await GetOrThrowAsync(input.Id);
|
||||
entity.IsEnabled = input.IsEnabled;
|
||||
await DefinitionRepository.UpdateAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除审批定义(软删)。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/delete")]
|
||||
public async Task DeleteAsync(IdInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.DefinitionDelete);
|
||||
var entity = await GetOrThrowAsync(input.Id);
|
||||
await DefinitionRepository.DeleteAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 条件公式试算。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/definition/test-condition")]
|
||||
public async Task<ApprovalConditionTestOutput> TestConditionAsync(ApprovalConditionTestInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.DefinitionQuery,
|
||||
ApprovalPermissionCodes.DefinitionUpdate);
|
||||
|
||||
var (ok, matched, message) = ConditionEvaluator.TryTest(
|
||||
input.OperationCode?.Trim() ?? string.Empty,
|
||||
input.ConditionFormula,
|
||||
input.Context);
|
||||
return new ApprovalConditionTestOutput
|
||||
{
|
||||
Ok = ok,
|
||||
Matched = matched,
|
||||
Message = message
|
||||
};
|
||||
}
|
||||
|
||||
private async Task EnsureOperationUniqueAsync(string operationCode, int? excludeId)
|
||||
{
|
||||
var existed = await DefinitionRepository.FirstOrDefaultAsync(x => x.OperationCode == operationCode);
|
||||
if (existed != null && existed.Id != excludeId)
|
||||
{
|
||||
throw new BusinessException($"操作 {operationCode} 已存在审批定义");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<ApprovalDefinition> GetOrThrowAsync(int id)
|
||||
{
|
||||
var entity = await DefinitionRepository.FirstOrDefaultAsync(x => x.Id == id);
|
||||
if (entity == null)
|
||||
{
|
||||
throw new BusinessException("审批定义不存在");
|
||||
}
|
||||
|
||||
return entity;
|
||||
}
|
||||
|
||||
private static string NormalizeApproverType(string? type)
|
||||
{
|
||||
if (string.Equals(type, ApprovalCodes.ApproverTypeRole, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ApprovalCodes.ApproverTypeRole;
|
||||
}
|
||||
|
||||
if (string.Equals(type, ApprovalCodes.ApproverTypeUser, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return ApprovalCodes.ApproverTypeUser;
|
||||
}
|
||||
|
||||
throw new BusinessException("审批人类型仅支持 User 或 Role");
|
||||
}
|
||||
|
||||
private static ApprovalDefinitionOutput MapOutput(ApprovalDefinition entity) => new()
|
||||
{
|
||||
Id = entity.Id,
|
||||
OperationCode = entity.OperationCode,
|
||||
OperationName = entity.OperationName,
|
||||
IsEnabled = entity.IsEnabled,
|
||||
ConditionFormula = entity.ConditionFormula,
|
||||
ApproverType = entity.ApproverType,
|
||||
ApproverIds = ApprovalIdHelper.SplitIds(entity.ApproverIds),
|
||||
ForbidSelfApprove = entity.ForbidSelfApprove,
|
||||
Remark = entity.Remark,
|
||||
CreateTime = entity.CreateTime,
|
||||
UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime)
|
||||
};
|
||||
}
|
||||
620
src/Oms.Application/Services/Approval/ApprovalEngineCore.cs
Normal file
620
src/Oms.Application/Services/Approval/ApprovalEngineCore.cs
Normal file
@ -0,0 +1,620 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Fake.Users;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批引擎核心逻辑(供 Gate 与 ApplicationService 共用)。
|
||||
/// </summary>
|
||||
public class ApprovalEngineCore(
|
||||
IApprovalDefinitionRepository definitionRepository,
|
||||
IApprovalInstanceRepository instanceRepository,
|
||||
IApprovalTaskRepository taskRepository,
|
||||
IApprovalEventRepository eventRepository,
|
||||
ApprovalConditionEvaluator conditionEvaluator,
|
||||
ApprovalCandidateResolver candidateResolver,
|
||||
ApprovalNotifier approvalNotifier,
|
||||
ICurrentUser currentUser,
|
||||
IEnumerable<IApprovalOperationHandler> handlers) : IScopedDependency
|
||||
{
|
||||
private readonly Dictionary<string, IApprovalOperationHandler> _handlers = handlers
|
||||
.GroupBy(x => x.OperationCode, StringComparer.OrdinalIgnoreCase)
|
||||
.ToDictionary(g => g.Key, g => g.First(), StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>
|
||||
/// 检查并提交或 Bypass。
|
||||
/// </summary>
|
||||
public async Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(request.OperationCode))
|
||||
{
|
||||
throw new BusinessException("操作编码不能为空");
|
||||
}
|
||||
|
||||
var operationCode = request.OperationCode.Trim();
|
||||
var bizKey = string.IsNullOrWhiteSpace(request.BizKey)
|
||||
? Guid.NewGuid().ToString("N")
|
||||
: request.BizKey.Trim();
|
||||
|
||||
var definition = await definitionRepository.FirstOrDefaultAsync(
|
||||
x => x.OperationCode == operationCode && x.IsEnabled);
|
||||
if (definition == null)
|
||||
{
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.Bypass,
|
||||
Message = "未启用审批定义,直接执行"
|
||||
};
|
||||
}
|
||||
|
||||
var matched = conditionEvaluator.Evaluate(
|
||||
operationCode,
|
||||
definition.ConditionFormula,
|
||||
request.ConditionContext);
|
||||
if (!matched)
|
||||
{
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.Bypass,
|
||||
Message = "条件未命中,无需审批"
|
||||
};
|
||||
}
|
||||
|
||||
var pending = await instanceRepository.FirstOrDefaultAsync(x =>
|
||||
x.OperationCode == operationCode
|
||||
&& x.BizKey == bizKey
|
||||
&& x.Status == ApprovalInstanceStatus.Pending);
|
||||
if (pending != null)
|
||||
{
|
||||
throw new BusinessException($"已存在待审批实例:{pending.InstanceNo}");
|
||||
}
|
||||
|
||||
var applicantMapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var applicantGuid = ResolveCurrentUserGuid();
|
||||
var applicantName = currentUser.UserName;
|
||||
|
||||
var candidateUserIds = await candidateResolver.ExpandCandidateUserIdsAsync(
|
||||
definition.ApproverType,
|
||||
definition.ApproverIds,
|
||||
cancellationToken);
|
||||
|
||||
if (definition.ForbidSelfApprove
|
||||
&& !string.IsNullOrWhiteSpace(applicantGuid)
|
||||
&& candidateUserIds.Contains(applicantGuid, StringComparer.OrdinalIgnoreCase)
|
||||
&& candidateUserIds.Count == 1)
|
||||
{
|
||||
throw new BusinessException("已禁止自审,且审批候选人仅含申请人本人,无法提交");
|
||||
}
|
||||
|
||||
var payloadJson = NormalizePayloadJson(request.PayloadJson);
|
||||
var instance = new ApprovalInstance
|
||||
{
|
||||
InstanceNo = await NextInstanceNoAsync(),
|
||||
OperationCode = operationCode,
|
||||
BizKey = bizKey,
|
||||
Title = string.IsNullOrWhiteSpace(request.Title)
|
||||
? (string.IsNullOrWhiteSpace(definition.OperationName) ? operationCode : definition.OperationName)
|
||||
: request.Title.Trim(),
|
||||
Status = ApprovalInstanceStatus.Pending,
|
||||
ApplicantUserId = applicantMapId,
|
||||
ApplicantUserGuid = applicantGuid,
|
||||
ApplicantUserName = applicantName,
|
||||
PayloadJson = payloadJson,
|
||||
PayloadHash = ComputeHash(payloadJson),
|
||||
SummaryJson = OmsDocHelper.SerializeJson(request.Summary),
|
||||
DefinitionSnapshot = OmsDocHelper.SerializeJson(new
|
||||
{
|
||||
definition.Id,
|
||||
definition.OperationCode,
|
||||
definition.OperationName,
|
||||
definition.ConditionFormula,
|
||||
definition.ApproverType,
|
||||
definition.ApproverIds,
|
||||
definition.ForbidSelfApprove
|
||||
})
|
||||
};
|
||||
|
||||
var saved = await instanceRepository.InsertAsync(instance);
|
||||
|
||||
var task = new ApprovalTask
|
||||
{
|
||||
InstanceId = saved.Id,
|
||||
StepNo = 1,
|
||||
Status = ApprovalTaskStatus.Pending,
|
||||
ApproverType = definition.ApproverType,
|
||||
ApproverIds = definition.ApproverIds,
|
||||
CandidateUserIds = ApprovalIdHelper.JoinIds(candidateUserIds)
|
||||
};
|
||||
var savedTask = await taskRepository.InsertAsync(task);
|
||||
|
||||
saved.CurrentTaskId = savedTask.Id;
|
||||
await instanceRepository.UpdateAsync(saved);
|
||||
|
||||
await AppendEventAsync(
|
||||
saved.Id,
|
||||
savedTask.Id,
|
||||
ApprovalCodes.EventSubmitted,
|
||||
null,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
applicantMapId,
|
||||
applicantGuid,
|
||||
applicantName,
|
||||
"提交审批");
|
||||
|
||||
try
|
||||
{
|
||||
await approvalNotifier.NotifyCandidatesSubmittedAsync(
|
||||
saved,
|
||||
candidateUserIds,
|
||||
cancellationToken);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 通知失败不影响建单
|
||||
}
|
||||
|
||||
return new ApprovalGateResult
|
||||
{
|
||||
Decision = ApprovalGateDecision.PendingApproval,
|
||||
InstanceId = saved.Id,
|
||||
InstanceNo = saved.InstanceNo,
|
||||
Message = "已创建审批实例,并已通知审批人"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批通过并尝试执行业务 Handler。
|
||||
/// </summary>
|
||||
public async Task ApproveAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
EnsureCanAct(instance, task, isApprove: true);
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Approved;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment?.Trim();
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Approved;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventApproved,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Approved,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment?.Trim() ?? "通过");
|
||||
|
||||
try
|
||||
{
|
||||
await approvalNotifier.NotifyApplicantResultAsync(
|
||||
instance,
|
||||
"通过",
|
||||
comment);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 通知失败不影响审批
|
||||
}
|
||||
|
||||
await ExecuteHandlerAsync(instance, mapId, guid);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 驳回。
|
||||
/// </summary>
|
||||
public async Task RejectAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(comment))
|
||||
{
|
||||
throw new BusinessException("驳回意见不能为空");
|
||||
}
|
||||
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
EnsureCanAct(instance, task, isApprove: false);
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Rejected;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment.Trim();
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Rejected;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventRejected,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Rejected,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment.Trim());
|
||||
|
||||
try
|
||||
{
|
||||
await approvalNotifier.NotifyApplicantResultAsync(
|
||||
instance,
|
||||
"驳回",
|
||||
comment);
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 通知失败不影响审批
|
||||
}
|
||||
|
||||
await InvokeRejectOrWithdrawHandlerAsync(instance, mapId, guid, name, isReject: true, comment.Trim());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 申请人撤回。
|
||||
/// </summary>
|
||||
public async Task WithdrawAsync(int instanceId, string? comment, string? concurrencyStamp)
|
||||
{
|
||||
var (instance, task) = await LoadPendingAsync(instanceId);
|
||||
EnsureConcurrency(instance, concurrencyStamp);
|
||||
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
if (!string.Equals(instance.ApplicantUserGuid, guid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("仅申请人可撤回");
|
||||
}
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var name = currentUser.UserName;
|
||||
var now = DateTime.Now;
|
||||
|
||||
task.Status = ApprovalTaskStatus.Cancelled;
|
||||
task.ActionUserId = mapId;
|
||||
task.ActionUserGuid = guid;
|
||||
task.ActionUserName = name;
|
||||
task.ActionTime = now;
|
||||
task.Comment = comment?.Trim() ?? "撤回";
|
||||
await taskRepository.UpdateAsync(task);
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Withdrawn;
|
||||
instance.CompletedTime = now;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
task.Id,
|
||||
ApprovalCodes.EventWithdrawn,
|
||||
ApprovalInstanceStatus.Pending,
|
||||
ApprovalInstanceStatus.Withdrawn,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
comment?.Trim() ?? "撤回");
|
||||
|
||||
await InvokeRejectOrWithdrawHandlerAsync(
|
||||
instance,
|
||||
mapId,
|
||||
guid,
|
||||
name,
|
||||
isReject: false,
|
||||
comment?.Trim() ?? "撤回");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行失败后的重试。
|
||||
/// </summary>
|
||||
public async Task RetryExecuteAsync(int instanceId)
|
||||
{
|
||||
var instance = await instanceRepository.FirstOrDefaultAsync(x => x.Id == instanceId)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
// Executed 也允许重试:兼容 Handler 未注册时空跑成 Executed、业务未落库的历史单
|
||||
if (instance.Status is not (
|
||||
ApprovalInstanceStatus.Approved
|
||||
or ApprovalInstanceStatus.ExecuteFailed
|
||||
or ApprovalInstanceStatus.Executed))
|
||||
{
|
||||
throw new BusinessException("仅已通过、已执行或执行失败的实例可重试执行");
|
||||
}
|
||||
|
||||
var mapId = OmsSessionHelper.ResolveMapUserId(currentUser);
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
await ExecuteHandlerAsync(instance, mapId, guid);
|
||||
}
|
||||
|
||||
private async Task ExecuteHandlerAsync(ApprovalInstance instance, int operatorMapId, string operatorGuid)
|
||||
{
|
||||
instance.Status = ApprovalInstanceStatus.Executing;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuting,
|
||||
ApprovalInstanceStatus.Approved,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
"开始执行业务");
|
||||
|
||||
try
|
||||
{
|
||||
if (!_handlers.TryGetValue(instance.OperationCode, out var handler))
|
||||
{
|
||||
throw new BusinessException($"未注册业务执行器:{instance.OperationCode}");
|
||||
}
|
||||
|
||||
await handler.ExecuteAsync(BuildExecutionContext(
|
||||
instance,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName));
|
||||
|
||||
instance.Status = ApprovalInstanceStatus.Executed;
|
||||
instance.ExecutedTime = DateTime.Now;
|
||||
instance.ExecuteMessage = "执行成功";
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuted,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
ApprovalInstanceStatus.Executed,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
"执行成功");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
instance.Status = ApprovalInstanceStatus.ExecuteFailed;
|
||||
instance.ExecuteMessage = ex.Message;
|
||||
await instanceRepository.UpdateAsync(instance);
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
ApprovalCodes.EventExecuteFailed,
|
||||
ApprovalInstanceStatus.Executing,
|
||||
ApprovalInstanceStatus.ExecuteFailed,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
currentUser.UserName,
|
||||
ex.Message);
|
||||
throw new BusinessException($"审批通过,但业务执行失败:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<(ApprovalInstance Instance, ApprovalTask Task)> LoadPendingAsync(int instanceId)
|
||||
{
|
||||
var instance = await instanceRepository.FirstOrDefaultAsync(x => x.Id == instanceId)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
if (instance.Status != ApprovalInstanceStatus.Pending)
|
||||
{
|
||||
throw new BusinessException("仅待审批实例可操作");
|
||||
}
|
||||
|
||||
var taskId = instance.CurrentTaskId
|
||||
?? throw new BusinessException("审批任务不存在");
|
||||
var task = await taskRepository.FirstOrDefaultAsync(x => x.Id == taskId)
|
||||
?? throw new BusinessException("审批任务不存在");
|
||||
if (task.Status != ApprovalTaskStatus.Pending)
|
||||
{
|
||||
throw new BusinessException("审批任务已处理");
|
||||
}
|
||||
|
||||
return (instance, task);
|
||||
}
|
||||
|
||||
private async Task InvokeRejectOrWithdrawHandlerAsync(
|
||||
ApprovalInstance instance,
|
||||
int operatorMapId,
|
||||
string operatorGuid,
|
||||
string? operatorName,
|
||||
bool isReject,
|
||||
string? comment)
|
||||
{
|
||||
if (!_handlers.TryGetValue(instance.OperationCode, out var handler))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var context = BuildExecutionContext(instance, operatorMapId, operatorGuid, operatorName);
|
||||
try
|
||||
{
|
||||
if (isReject)
|
||||
{
|
||||
await handler.OnRejectedAsync(context, comment);
|
||||
}
|
||||
else
|
||||
{
|
||||
await handler.OnWithdrawnAsync(context, comment);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// 业务补偿失败不回滚审批终态,记事件便于排查
|
||||
await AppendEventAsync(
|
||||
instance.Id,
|
||||
instance.CurrentTaskId,
|
||||
isReject ? "RejectCompensateFailed" : "WithdrawCompensateFailed",
|
||||
instance.Status,
|
||||
instance.Status,
|
||||
operatorMapId,
|
||||
operatorGuid,
|
||||
operatorName,
|
||||
ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
private static ApprovalExecutionContext BuildExecutionContext(
|
||||
ApprovalInstance instance,
|
||||
int operatorMapId,
|
||||
string operatorGuid,
|
||||
string? operatorName) =>
|
||||
new()
|
||||
{
|
||||
InstanceId = instance.Id,
|
||||
InstanceNo = instance.InstanceNo,
|
||||
OperationCode = instance.OperationCode,
|
||||
BizKey = instance.BizKey,
|
||||
PayloadJson = instance.PayloadJson,
|
||||
ApplicantUserId = instance.ApplicantUserId,
|
||||
ApplicantUserGuid = instance.ApplicantUserGuid,
|
||||
ApproverUserId = operatorMapId,
|
||||
ApproverUserGuid = operatorGuid,
|
||||
ApproverUserName = operatorName
|
||||
};
|
||||
|
||||
private void EnsureCanAct(ApprovalInstance instance, ApprovalTask task, bool isApprove)
|
||||
{
|
||||
var guid = ResolveCurrentUserGuid();
|
||||
if (string.IsNullOrWhiteSpace(guid))
|
||||
{
|
||||
throw new BusinessException("无法识别当前用户");
|
||||
}
|
||||
|
||||
var snapshot = OmsDocHelper.DeserializeJson<DefinitionSnap>(instance.DefinitionSnapshot);
|
||||
var forbidSelf = snapshot?.ForbidSelfApprove ?? true;
|
||||
if (forbidSelf && string.Equals(instance.ApplicantUserGuid, guid, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("禁止申请人审批自己的申请");
|
||||
}
|
||||
|
||||
if (!ApprovalIdHelper.ContainsId(task.CandidateUserIds, guid.ToString()))
|
||||
{
|
||||
throw new BusinessException("当前用户不在审批候选人中");
|
||||
}
|
||||
}
|
||||
|
||||
private static void EnsureConcurrency(ApprovalInstance instance, string? concurrencyStamp)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(concurrencyStamp))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var expected = concurrencyStamp.Trim();
|
||||
var actual = instance.ConcurrencyStamp.ToString();
|
||||
if (!string.Equals(actual, expected, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("数据已变更,请刷新后重试");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task AppendEventAsync(
|
||||
int instanceId,
|
||||
int? taskId,
|
||||
string eventType,
|
||||
ApprovalInstanceStatus? from,
|
||||
ApprovalInstanceStatus? to,
|
||||
int operatorUserId,
|
||||
string? operatorGuid,
|
||||
string? operatorName,
|
||||
string? message)
|
||||
{
|
||||
await eventRepository.InsertAsync(new ApprovalEvent
|
||||
{
|
||||
InstanceId = instanceId,
|
||||
TaskId = taskId,
|
||||
EventType = eventType,
|
||||
FromStatus = from,
|
||||
ToStatus = to,
|
||||
OperatorUserId = operatorUserId,
|
||||
OperatorUserGuid = operatorGuid,
|
||||
OperatorUserName = operatorName,
|
||||
Message = message
|
||||
});
|
||||
}
|
||||
|
||||
private async Task<string> NextInstanceNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"AP{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(100, 999)}";
|
||||
var exists = await instanceRepository.AnyAsync(x => x.InstanceNo == no);
|
||||
if (!exists)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
return $"AP{Guid.NewGuid():N}"[..20];
|
||||
}
|
||||
|
||||
private string ResolveCurrentUserGuid()
|
||||
{
|
||||
if (ApprovalPermissionGuard.TryGetUserGuid(currentUser, out var guid))
|
||||
{
|
||||
return guid.ToString();
|
||||
}
|
||||
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
private static string? NormalizePayloadJson(string? payloadJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payloadJson))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using var doc = JsonDocument.Parse(payloadJson);
|
||||
return JsonSerializer.Serialize(doc.RootElement);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return payloadJson;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ComputeHash(string? payloadJson)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(payloadJson))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var bytes = SHA256.HashData(Encoding.UTF8.GetBytes(payloadJson));
|
||||
return Convert.ToHexString(bytes);
|
||||
}
|
||||
|
||||
private sealed class DefinitionSnap
|
||||
{
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
}
|
||||
}
|
||||
347
src/Oms.Application/Services/Approval/ApprovalEngineService.cs
Normal file
347
src/Oms.Application/Services/Approval/ApprovalEngineService.cs
Normal file
@ -0,0 +1,347 @@
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Approval;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批引擎 API:提交、待办、通过/驳回/撤回、详情。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Approval")]
|
||||
public class ApprovalEngineService : ApplicationService
|
||||
{
|
||||
private IApprovalInstanceRepository InstanceRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalInstanceRepository>();
|
||||
|
||||
private IApprovalTaskRepository TaskRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalTaskRepository>();
|
||||
|
||||
private IApprovalEventRepository EventRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalEventRepository>();
|
||||
|
||||
private ApprovalEngineCore EngineCore =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalEngineCore>();
|
||||
|
||||
private ApprovalPermissionGuard PermissionGuard =>
|
||||
LazyServiceProvider.GetRequiredService<ApprovalPermissionGuard>();
|
||||
|
||||
/// <summary>
|
||||
/// 模拟提交审批(走 Gate;需定义管理权限)。用于一期联调。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/simulate-submit")]
|
||||
public async Task<ApprovalSubmitOutput> SimulateSubmitAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.DefinitionCreate,
|
||||
ApprovalPermissionCodes.DefinitionUpdate,
|
||||
ApprovalPermissionCodes.DefinitionEnable);
|
||||
|
||||
input.OperationCode = string.IsNullOrWhiteSpace(input.OperationCode)
|
||||
? ApprovalCodes.SimOperationCode
|
||||
: input.OperationCode.Trim();
|
||||
|
||||
return await SubmitInternalAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 提交审批(供后续业务或联调调用)。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/submit")]
|
||||
public async Task<ApprovalSubmitOutput> SubmitAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.TaskQuery,
|
||||
ApprovalPermissionCodes.DefinitionQuery);
|
||||
return await SubmitInternalAsync(input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 我的待办(待审批且当前用户在候选人中)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/my-todo")]
|
||||
public async Task<OmsPageResult<ApprovalInstanceOutput>> GetMyTodoAsync(
|
||||
[FromQuery] ApprovalInstanceListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var userGuid))
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var guidText = userGuid.ToString();
|
||||
var pendingTasks = await TaskRepository.GetListAsync(x => x.Status == ApprovalTaskStatus.Pending);
|
||||
var myTaskInstanceIds = pendingTasks
|
||||
.Where(t => ApprovalIdHelper.ContainsId(t.CandidateUserIds, guidText))
|
||||
.Select(t => t.InstanceId)
|
||||
.Distinct()
|
||||
.ToHashSet();
|
||||
|
||||
if (myTaskInstanceIds.Count == 0)
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var instances = await InstanceRepository.GetListAsync(x =>
|
||||
x.Status == ApprovalInstanceStatus.Pending && myTaskInstanceIds.Contains(x.Id));
|
||||
var filtered = instances
|
||||
.Where(x => string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.InstanceNo.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.OperationCode.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(x => x.CreateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.ToList();
|
||||
|
||||
return await PageMapAsync(filtered, input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 我发起的审批。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/my-submitted")]
|
||||
public async Task<OmsPageResult<ApprovalInstanceOutput>> GetMySubmittedAsync(
|
||||
[FromQuery] ApprovalInstanceListInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var userGuid))
|
||||
{
|
||||
return new OmsPageResult<ApprovalInstanceOutput> { Items = [], Total = 0 };
|
||||
}
|
||||
|
||||
var guidText = userGuid.ToString();
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var list = await InstanceRepository.GetListAsync(x => x.ApplicantUserGuid == guidText);
|
||||
var filtered = list
|
||||
.Where(x => input.Status == null || x.Status == input.Status.Value)
|
||||
.Where(x => string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.InstanceNo.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.Title.Contains(keyword, StringComparison.OrdinalIgnoreCase)
|
||||
|| x.OperationCode.Contains(keyword, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(x => x.CreateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.ToList();
|
||||
|
||||
return await PageMapAsync(filtered, input);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 实例详情(含事件时间线)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/approval/engine/detail")]
|
||||
public async Task<ApprovalInstanceOutput> GetDetailAsync([FromQuery] int id)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
var instance = await InstanceRepository.FirstOrDefaultAsync(x => x.Id == id)
|
||||
?? throw new BusinessException("审批实例不存在");
|
||||
var events = await EventRepository.GetListAsync(x => x.InstanceId == id);
|
||||
var output = MapInstance(instance, events.OrderBy(x => x.Id).ToList());
|
||||
await FillActionFlagsAsync(output, instance);
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批通过。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/approve")]
|
||||
public async Task ApproveAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskApprove);
|
||||
await EngineCore.ApproveAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批驳回。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/reject")]
|
||||
public async Task RejectAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskReject);
|
||||
await EngineCore.RejectAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 申请人撤回。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/withdraw")]
|
||||
public async Task WithdrawAsync(ApprovalActionInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(CurrentUser, ApprovalPermissionCodes.TaskQuery);
|
||||
await EngineCore.WithdrawAsync(input.InstanceId, input.Comment, input.ConcurrencyStamp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 业务执行失败后重试。
|
||||
/// </summary>
|
||||
[HttpPost("/system/approval/engine/retry-execute")]
|
||||
public async Task RetryExecuteAsync(IdInput input)
|
||||
{
|
||||
await PermissionGuard.EnsureAsync(
|
||||
CurrentUser,
|
||||
ApprovalPermissionCodes.TaskApprove,
|
||||
ApprovalPermissionCodes.DefinitionEnable);
|
||||
await EngineCore.RetryExecuteAsync(input.Id);
|
||||
}
|
||||
|
||||
private async Task<ApprovalSubmitOutput> SubmitInternalAsync(ApprovalSubmitInput input)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(input.OperationCode))
|
||||
{
|
||||
throw new BusinessException("操作编码不能为空");
|
||||
}
|
||||
|
||||
var payloadJson = input.Payload switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
JsonElement el => el.GetRawText(),
|
||||
_ => OmsDocHelper.SerializeJson(input.Payload)
|
||||
};
|
||||
|
||||
var result = await EngineCore.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest
|
||||
{
|
||||
OperationCode = input.OperationCode.Trim(),
|
||||
BizKey = input.BizKey,
|
||||
Title = input.Title ?? string.Empty,
|
||||
PayloadJson = payloadJson,
|
||||
Summary = input.Summary,
|
||||
ConditionContext = input.ConditionContext
|
||||
});
|
||||
|
||||
return new ApprovalSubmitOutput
|
||||
{
|
||||
Decision = result.Decision.ToString(),
|
||||
InstanceId = result.InstanceId,
|
||||
InstanceNo = result.InstanceNo,
|
||||
Message = result.Message
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<OmsPageResult<ApprovalInstanceOutput>> PageMapAsync(
|
||||
List<ApprovalInstance> filtered,
|
||||
ApprovalInstanceListInput input)
|
||||
{
|
||||
var pageIndex = OmsDocHelper.NormalizePage(input.Page);
|
||||
var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize <= 0 ? 50 : input.PageSize);
|
||||
var total = filtered.Count;
|
||||
var slice = filtered
|
||||
.Skip((pageIndex - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.ToList();
|
||||
|
||||
var pageItems = new List<ApprovalInstanceOutput>(slice.Count);
|
||||
foreach (var x in slice)
|
||||
{
|
||||
var output = MapInstance(x, []);
|
||||
await FillActionFlagsAsync(output, x);
|
||||
pageItems.Add(output);
|
||||
}
|
||||
|
||||
return new OmsPageResult<ApprovalInstanceOutput>
|
||||
{
|
||||
Items = pageItems,
|
||||
Total = total
|
||||
};
|
||||
}
|
||||
|
||||
private async Task FillActionFlagsAsync(ApprovalInstanceOutput output, ApprovalInstance instance)
|
||||
{
|
||||
if (!ApprovalPermissionGuard.TryGetUserGuid(CurrentUser, out var guid))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var guidText = guid.ToString();
|
||||
output.CanWithdraw = instance.Status == ApprovalInstanceStatus.Pending
|
||||
&& string.Equals(instance.ApplicantUserGuid, guidText, StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
if (instance.Status != ApprovalInstanceStatus.Pending || instance.CurrentTaskId == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var task = await TaskRepository.FirstOrDefaultAsync(x => x.Id == instance.CurrentTaskId.Value);
|
||||
if (task == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var forbidSelf = true;
|
||||
var snap = OmsDocHelper.DeserializeJson<ForbidSnap>(instance.DefinitionSnapshot);
|
||||
if (snap != null)
|
||||
{
|
||||
forbidSelf = snap.ForbidSelfApprove;
|
||||
}
|
||||
|
||||
if (forbidSelf && string.Equals(instance.ApplicantUserGuid, guidText, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
output.CanApprove = false;
|
||||
return;
|
||||
}
|
||||
|
||||
output.CanApprove = ApprovalIdHelper.ContainsId(task.CandidateUserIds, guidText);
|
||||
}
|
||||
|
||||
private static ApprovalInstanceOutput MapInstance(
|
||||
ApprovalInstance entity,
|
||||
List<ApprovalEvent> events) => new()
|
||||
{
|
||||
Id = entity.Id,
|
||||
InstanceNo = entity.InstanceNo,
|
||||
OperationCode = entity.OperationCode,
|
||||
BizKey = entity.BizKey,
|
||||
Title = entity.Title,
|
||||
Status = entity.Status,
|
||||
StatusName = StatusName(entity.Status),
|
||||
ApplicantUserId = entity.ApplicantUserId,
|
||||
ApplicantUserGuid = entity.ApplicantUserGuid,
|
||||
ApplicantUserName = entity.ApplicantUserName,
|
||||
PayloadJson = entity.PayloadJson,
|
||||
SummaryJson = entity.SummaryJson,
|
||||
DefinitionSnapshot = entity.DefinitionSnapshot,
|
||||
CurrentTaskId = entity.CurrentTaskId,
|
||||
CreateTime = entity.CreateTime,
|
||||
CompletedTime = entity.CompletedTime,
|
||||
ExecutedTime = entity.ExecutedTime,
|
||||
ExecuteMessage = entity.ExecuteMessage,
|
||||
ConcurrencyStamp = entity.ConcurrencyStamp.ToString(),
|
||||
Events = events.Select(e => new ApprovalEventOutput
|
||||
{
|
||||
Id = e.Id,
|
||||
EventType = e.EventType,
|
||||
FromStatus = e.FromStatus,
|
||||
ToStatus = e.ToStatus,
|
||||
OperatorUserName = e.OperatorUserName,
|
||||
Message = e.Message,
|
||||
CreateTime = e.CreateTime
|
||||
}).ToList()
|
||||
};
|
||||
|
||||
private static string StatusName(ApprovalInstanceStatus status) => status switch
|
||||
{
|
||||
ApprovalInstanceStatus.Pending => "待审批",
|
||||
ApprovalInstanceStatus.Approved => "已通过",
|
||||
ApprovalInstanceStatus.Rejected => "已驳回",
|
||||
ApprovalInstanceStatus.Withdrawn => "已撤回",
|
||||
ApprovalInstanceStatus.Executing => "执行中",
|
||||
ApprovalInstanceStatus.Executed => "已执行",
|
||||
ApprovalInstanceStatus.ExecuteFailed => "执行失败",
|
||||
_ => status.ToString()
|
||||
};
|
||||
|
||||
private sealed class ForbidSnap
|
||||
{
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
}
|
||||
}
|
||||
16
src/Oms.Application/Services/Approval/ApprovalGate.cs
Normal file
16
src/Oms.Application/Services/Approval/ApprovalGate.cs
Normal file
@ -0,0 +1,16 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批门面实现:供后续业务接入。一期也可由引擎模拟提交调用。
|
||||
/// </summary>
|
||||
public class ApprovalGate(ApprovalEngineCore engineCore) : IApprovalGate, IScopedDependency
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default) =>
|
||||
engineCore.CheckAndSubmitOrBypassAsync(request, cancellationToken);
|
||||
}
|
||||
49
src/Oms.Application/Services/Approval/ApprovalIdHelper.cs
Normal file
49
src/Oms.Application/Services/Approval/ApprovalIdHelper.cs
Normal file
@ -0,0 +1,49 @@
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批候选人 ID 解析辅助。
|
||||
/// </summary>
|
||||
public static class ApprovalIdHelper
|
||||
{
|
||||
private static readonly char[] Separators = [',', ';', ',', ' '];
|
||||
|
||||
/// <summary>拆分为去重后的非空片段。</summary>
|
||||
public static List<string> SplitIds(string? raw)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(raw))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
return raw
|
||||
.Split(Separators, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>规范化存储(逗号分隔)。</summary>
|
||||
public static string JoinIds(IEnumerable<string>? ids)
|
||||
{
|
||||
if (ids == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return string.Join(",",
|
||||
ids.Select(x => x.Trim())
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>判断候选串是否包含指定 Guid。</summary>
|
||||
public static bool ContainsId(string? raw, string? id)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(id))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return SplitIds(raw).Contains(id.Trim(), StringComparer.OrdinalIgnoreCase);
|
||||
}
|
||||
}
|
||||
140
src/Oms.Application/Services/Approval/ApprovalNotifier.cs
Normal file
140
src/Oms.Application/Services/Approval/ApprovalNotifier.cs
Normal file
@ -0,0 +1,140 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Rbac.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批站内信通知(提交时通知候选人;终审结果通知申请人)。
|
||||
/// </summary>
|
||||
public class ApprovalNotifier(
|
||||
INoticeRepository noticeRepository,
|
||||
FakeRbacDbContext rbacDbContext,
|
||||
ILogger<ApprovalNotifier> logger) : IScopedDependency
|
||||
{
|
||||
private const string NoticeTypeMessage = "message";
|
||||
private const string ReceiverTypeUser = "user";
|
||||
|
||||
/// <summary>
|
||||
/// 通知审批候选人:有待办需处理。
|
||||
/// </summary>
|
||||
public async Task NotifyCandidatesSubmittedAsync(
|
||||
ApprovalInstance instance,
|
||||
IReadOnlyCollection<string> candidateUserGuids,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var receiverMapIds = await ResolveMapUserIdsAsync(candidateUserGuids, cancellationToken);
|
||||
if (receiverMapIds.Count == 0)
|
||||
{
|
||||
logger.LogInformation(
|
||||
"审批单 {InstanceNo} 提交通知跳过:无有效候选人 mapId",
|
||||
instance.InstanceNo);
|
||||
return;
|
||||
}
|
||||
|
||||
var title = $"待审批:{instance.Title}";
|
||||
var content =
|
||||
$"审批单 {instance.InstanceNo} 待你处理。\n" +
|
||||
$"操作:{instance.OperationCode}\n" +
|
||||
$"申请人:{instance.ApplicantUserName ?? instance.ApplicantUserGuid}\n" +
|
||||
$"请到「系统管理 / 审批待办」处理。\n" +
|
||||
$"[OMS_APPROVAL:id={instance.Id}&tab=todo]";
|
||||
|
||||
await noticeRepository.InsertAsync(new Notice
|
||||
{
|
||||
NoticeType = NoticeTypeMessage,
|
||||
Title = title,
|
||||
Content = content,
|
||||
IsPopup = 0,
|
||||
ReceiverType = ReceiverTypeUser,
|
||||
ReceiverIds = OmsDocHelper.SerializeJson(receiverMapIds) ?? "[]"
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 通知申请人:审批结果。
|
||||
/// </summary>
|
||||
public async Task NotifyApplicantResultAsync(
|
||||
ApprovalInstance instance,
|
||||
string resultText,
|
||||
string? comment,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
var receivers = new List<int>();
|
||||
if (instance.ApplicantUserId > 0)
|
||||
{
|
||||
receivers.Add(instance.ApplicantUserId);
|
||||
}
|
||||
else if (!string.IsNullOrWhiteSpace(instance.ApplicantUserGuid))
|
||||
{
|
||||
receivers = await ResolveMapUserIdsAsync([instance.ApplicantUserGuid], cancellationToken);
|
||||
}
|
||||
|
||||
if (receivers.Count == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var title = $"审批{resultText}:{instance.Title}";
|
||||
var content =
|
||||
$"审批单 {instance.InstanceNo} 已{resultText}。\n" +
|
||||
$"操作:{instance.OperationCode}\n" +
|
||||
(string.IsNullOrWhiteSpace(comment) ? string.Empty : $"意见:{comment.Trim()}\n") +
|
||||
$"可在「系统管理 / 审批待办 → 我发起的」查看详情。\n" +
|
||||
$"[OMS_APPROVAL:id={instance.Id}&tab=submitted]";
|
||||
|
||||
await noticeRepository.InsertAsync(new Notice
|
||||
{
|
||||
NoticeType = NoticeTypeMessage,
|
||||
Title = title,
|
||||
Content = content,
|
||||
IsPopup = 0,
|
||||
ReceiverType = ReceiverTypeUser,
|
||||
ReceiverIds = OmsDocHelper.SerializeJson(receivers.Distinct().OrderBy(x => x).ToList()) ?? "[]"
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
private async Task<List<int>> ResolveMapUserIdsAsync(
|
||||
IReadOnlyCollection<string> userGuids,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var guids = userGuids
|
||||
.Select(x => Guid.TryParse(x, out var g) ? g : Guid.Empty)
|
||||
.Where(x => x != Guid.Empty)
|
||||
.Distinct()
|
||||
.ToList();
|
||||
if (guids.Count == 0)
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new List<int>();
|
||||
try
|
||||
{
|
||||
foreach (var guid in guids)
|
||||
{
|
||||
var sql =
|
||||
$"SELECT `userid` AS `Value` FROM `{FakeTables.User}` WHERE `Id` = {{0}} AND `IsDeleted` = 0 AND `userid` > 0";
|
||||
var userId = await rbacDbContext.Database
|
||||
.SqlQueryRaw<int?>(sql, guid)
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
if (userId is > 0)
|
||||
{
|
||||
result.Add(userId.Value);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogWarning(ex, "解析审批通知接收人 mapId 失败");
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.Distinct().OrderBy(x => x).ToList();
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,71 @@
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 可配置审批的操作目录(代码注册,非库表)。
|
||||
/// </summary>
|
||||
public static class ApprovalOperationCatalog
|
||||
{
|
||||
/// <summary>
|
||||
/// 目录项。
|
||||
/// </summary>
|
||||
public sealed record Item(
|
||||
string Code,
|
||||
string Name,
|
||||
string Module,
|
||||
bool SupportsCondition,
|
||||
string ConditionHint);
|
||||
|
||||
private static readonly IReadOnlyList<Item> Items =
|
||||
[
|
||||
new(
|
||||
ApprovalCodes.SimOperationCode,
|
||||
"审批引擎模拟提交",
|
||||
"System",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "一期自测用,不支持条件公式"),
|
||||
new(
|
||||
ApprovalCodes.FinanceRechargeCredit,
|
||||
"充值入账",
|
||||
"Finance",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "已接入提交接口;未配置或未启用不拦截(直接入账),启用后提交审批"),
|
||||
new(
|
||||
"Marketing.Commission.Withdraw",
|
||||
"佣金提现",
|
||||
"Marketing",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按金额等配置条件"),
|
||||
new(
|
||||
ApprovalCodes.SalesProductPublishPrice,
|
||||
"销售产品价格发布",
|
||||
"Channel",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "已接入发布接口;未配置或未启用不拦截,启用后提交审批"),
|
||||
new(
|
||||
"Order.Refund.Apply",
|
||||
"订单退款",
|
||||
"Order",
|
||||
SupportsCondition: false,
|
||||
ConditionHint: "业务接入后可按退款金额等配置条件")
|
||||
];
|
||||
|
||||
/// <summary>全部目录项。</summary>
|
||||
public static IReadOnlyList<Item> All => Items;
|
||||
|
||||
/// <summary>按编码查找。</summary>
|
||||
public static Item? Find(string? operationCode)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(operationCode))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Items.FirstOrDefault(x =>
|
||||
string.Equals(x.Code, operationCode.Trim(), StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
/// <summary>是否已知操作。</summary>
|
||||
public static bool IsKnown(string? operationCode) => Find(operationCode) != null;
|
||||
}
|
||||
110
src/Oms.Application/Services/Approval/ApprovalPermissionGuard.cs
Normal file
110
src/Oms.Application/Services/Approval/ApprovalPermissionGuard.cs
Normal file
@ -0,0 +1,110 @@
|
||||
using System.Security.Claims;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Fake.Domain.Exceptions;
|
||||
using Fake.Rbac.Application.Services;
|
||||
using Fake.Users;
|
||||
using Oms.Application.DataPerm;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 审批服务端权限校验(Admin 放行;否则查角色权限码)。
|
||||
/// </summary>
|
||||
public class ApprovalPermissionGuard(
|
||||
DataPermRepository dataPermRepository,
|
||||
RoleService roleService) : IScopedDependency
|
||||
{
|
||||
/// <summary>
|
||||
/// 要求当前用户具备指定权限码之一(含 Admin)。
|
||||
/// </summary>
|
||||
public async Task EnsureAsync(ICurrentUser currentUser, params string[] permissionCodes)
|
||||
{
|
||||
if (permissionCodes.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (await HasAnyAsync(currentUser, permissionCodes))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
throw new BusinessException("无权限执行该审批操作");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否具备任一权限。
|
||||
/// </summary>
|
||||
public async Task<bool> HasAnyAsync(ICurrentUser currentUser, params string[] permissionCodes)
|
||||
{
|
||||
if (!TryGetUserGuid(currentUser, out var userId))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (HasAdminRoleClaim(currentUser) || await dataPermRepository.IsAdminUserAsync(userId))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var roleIds = await dataPermRepository.GetUserRoleIdsAsync(userId);
|
||||
if (roleIds.Count == 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var wanted = permissionCodes
|
||||
.SelectMany(ExpandCandidates)
|
||||
.ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
foreach (var roleId in roleIds)
|
||||
{
|
||||
var codes = await roleService.GetRolePermissionsAsync(roleId);
|
||||
if (codes.Any(c => !string.IsNullOrWhiteSpace(c) && wanted.Contains(c.Trim())))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>解析当前用户 Guid。</summary>
|
||||
public static bool TryGetUserGuid(ICurrentUser currentUser, out Guid userId)
|
||||
{
|
||||
userId = Guid.Empty;
|
||||
var raw = currentUser.FindClaimOrNull(ClaimTypes.NameIdentifier)?.Value
|
||||
?? currentUser.FindClaimOrNull("sub")?.Value;
|
||||
return Guid.TryParse(raw, out userId) && userId != Guid.Empty;
|
||||
}
|
||||
|
||||
private static bool HasAdminRoleClaim(ICurrentUser currentUser)
|
||||
{
|
||||
return currentUser.FindClaims(ClaimTypes.Role)
|
||||
.Concat(currentUser.FindClaims("role"))
|
||||
.Any(c => string.Equals(c.Value, "Admin", StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
private static IEnumerable<string> ExpandCandidates(string code)
|
||||
{
|
||||
var c = code.Trim();
|
||||
if (string.IsNullOrWhiteSpace(c))
|
||||
{
|
||||
yield break;
|
||||
}
|
||||
|
||||
yield return c;
|
||||
var suffixes = new[] { ".Query", ".Create", ".Update", ".Delete", ".Enable", ".Approve", ".Reject" };
|
||||
foreach (var suffix in suffixes)
|
||||
{
|
||||
if (!c.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
yield return c[..^suffix.Length];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,139 @@
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
/// <summary>
|
||||
/// 审批提交请求(业务侧组装后交给 Gate)。
|
||||
/// </summary>
|
||||
public class ApprovalSubmitRequest
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键(同操作下 Pending 中不可重复)。</summary>
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>摘要标题。</summary>
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>冻结业务载荷 JSON。</summary>
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
/// <summary>展示摘要对象(序列化进 SummaryJson)。</summary>
|
||||
public object? Summary { get; set; }
|
||||
|
||||
/// <summary>条件求值上下文字典(中文标签 → 值);无条件时可空。</summary>
|
||||
public IReadOnlyDictionary<string, object?>? ConditionContext { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gate 判定结果。
|
||||
/// </summary>
|
||||
public enum ApprovalGateDecision
|
||||
{
|
||||
/// <summary>无需审批,业务可立即执行。</summary>
|
||||
Bypass = 0,
|
||||
|
||||
/// <summary>已创建待审批实例。</summary>
|
||||
PendingApproval = 1
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gate 返回。
|
||||
/// </summary>
|
||||
public class ApprovalGateResult
|
||||
{
|
||||
/// <summary>判定。</summary>
|
||||
public ApprovalGateDecision Decision { get; set; }
|
||||
|
||||
/// <summary>实例 Id(PendingApproval 时有值)。</summary>
|
||||
public int? InstanceId { get; set; }
|
||||
|
||||
/// <summary>实例单号。</summary>
|
||||
public string? InstanceNo { get; set; }
|
||||
|
||||
/// <summary>说明。</summary>
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批门面:业务入口调用,判断 Bypass 或建单。
|
||||
/// </summary>
|
||||
public interface IApprovalGate
|
||||
{
|
||||
/// <summary>
|
||||
/// 检查是否需审;需审则创建实例与任务,否则 Bypass。
|
||||
/// </summary>
|
||||
Task<ApprovalGateResult> CheckAndSubmitOrBypassAsync(
|
||||
ApprovalSubmitRequest request,
|
||||
CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 终审通过后的业务执行器(按 OperationCode 注册)。
|
||||
/// </summary>
|
||||
public interface IApprovalOperationHandler
|
||||
{
|
||||
/// <summary>支持的操作编码。</summary>
|
||||
string OperationCode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// 执行业务。成功无异常;失败抛 BusinessException 或普通 Exception,引擎记 ExecuteFailed。
|
||||
/// </summary>
|
||||
Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <summary>
|
||||
/// 审批驳回后的业务补偿(如把充值记录置为驳回)。默认空实现。
|
||||
/// </summary>
|
||||
Task OnRejectedAsync(
|
||||
ApprovalExecutionContext context,
|
||||
string? comment,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.CompletedTask;
|
||||
|
||||
/// <summary>
|
||||
/// 申请人撤回后的业务补偿。默认空实现。
|
||||
/// </summary>
|
||||
Task OnWithdrawnAsync(
|
||||
ApprovalExecutionContext context,
|
||||
string? comment,
|
||||
CancellationToken cancellationToken = default)
|
||||
=> Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行上下文。
|
||||
/// </summary>
|
||||
public class ApprovalExecutionContext
|
||||
{
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
public int ApproverUserId { get; set; }
|
||||
|
||||
public string ApproverUserGuid { get; set; } = string.Empty;
|
||||
|
||||
public string? ApproverUserName { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 条件上下文工厂(按操作提供公式字段;未注册则仅允许空条件)。
|
||||
/// </summary>
|
||||
public interface IApprovalConditionContextFactory
|
||||
{
|
||||
string OperationCode { get; }
|
||||
|
||||
/// <summary>将业务上下文字典转为公式求值用标签字典。</summary>
|
||||
IReadOnlyDictionary<string, object?> Build(IReadOnlyDictionary<string, object?>? raw);
|
||||
}
|
||||
19
src/Oms.Application/Services/Approval/NoopApprovalHandler.cs
Normal file
19
src/Oms.Application/Services/Approval/NoopApprovalHandler.cs
Normal file
@ -0,0 +1,19 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace Oms.Application.Services.Approval;
|
||||
|
||||
/// <summary>
|
||||
/// 模拟操作的空执行器(终审通过后仅记 Executed)。
|
||||
/// </summary>
|
||||
[ExposeServices(typeof(IApprovalOperationHandler))]
|
||||
public class NoopApprovalHandler : IApprovalOperationHandler, ITransientDependency
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string OperationCode => ApprovalCodes.SimOperationCode;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default) =>
|
||||
Task.CompletedTask;
|
||||
}
|
||||
16
src/Oms.Application/Services/Approval/README.md
Normal file
16
src/Oms.Application/Services/Approval/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
# 审批引擎(一期)
|
||||
|
||||
单级可配置审批:定义某 `OperationCode` 是否需审、谁审、可选条件;实例/任务/事件由引擎托管。
|
||||
|
||||
## 业务接入(后续)
|
||||
|
||||
1. 在操作入口组装 `ApprovalSubmitRequest`,调用 `IApprovalGate.CheckAndSubmitOrBypassAsync`。
|
||||
2. `Bypass`:业务立即执行;`PendingApproval`:业务进入自有「待审批」中间态,等待终审。
|
||||
3. 实现 `IApprovalOperationHandler`(`OperationCode` 匹配)并 `[ExposeServices(typeof(IApprovalOperationHandler))]`(或在 `OmsApplicationModule` 显式 `AddTransient<IApprovalOperationHandler, ...>`),终审通过后引擎调用 `ExecuteAsync`;Handler 内须再次校验业务状态后落账/发布。约定注册不会自动挂到该接口,漏注册会导致 Approve 空跑成 Executed、业务不落库。
|
||||
4. 若操作需条件公式,再实现 `IApprovalConditionContextFactory`,并将目录项 `SupportsCondition` 改为 true。
|
||||
|
||||
已接入:
|
||||
- `Channel.SalesProduct.PublishPrice`(`/channel/sales-product/publish`,operatorType=price)。未配置/未启用 Bypass 直接发布;启用后由 `SalesProductPricePublishApprovalHandler` 落发布记录。
|
||||
- `Finance.Recharge.Credit`(`/recharge/recharge/submit`)。未配置/未启用 Bypass 直接入账;启用后建单,终审由 `RechargeCreditApprovalHandler` 入账,驳回/撤回同步充值记录为驳回。
|
||||
|
||||
联调也可用「模拟提交」+ 操作码 `System.Approval.Simulate`。
|
||||
@ -115,6 +115,14 @@ public class LabelTemplateService : ApplicationService
|
||||
{
|
||||
printData = SkuLabelPrintDataBuilder.BuildMock();
|
||||
}
|
||||
else if (string.Equals(templateType, LabelTemplateTypeCodes.ShipBag, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
printData = ShipBagLabelPrintDataBuilder.BuildMock();
|
||||
}
|
||||
else if (string.Equals(templateType, LabelTemplateTypeCodes.ShipMaster, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
printData = ShipMasterLabelPrintDataBuilder.BuildMock();
|
||||
}
|
||||
|
||||
var bytes = await LabelPdfGenerationService.PreviewAsync(templateJson, printData);
|
||||
return new FileContentResult(bytes, "application/pdf")
|
||||
|
||||
@ -0,0 +1,146 @@
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.Shared.Enums;
|
||||
|
||||
namespace Oms.Application.Services.Channels;
|
||||
|
||||
/// <summary>
|
||||
/// 销售产品价格发布审批终审执行器:按冻结快照写入发布记录。
|
||||
/// </summary>
|
||||
[ExposeServices(typeof(IApprovalOperationHandler))]
|
||||
public class SalesProductPricePublishApprovalHandler(
|
||||
ISalesProductRepository salesProductRepository) : IApprovalOperationHandler, ITransientDependency
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public string OperationCode => ApprovalCodes.SalesProductPublishPrice;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(context.PayloadJson))
|
||||
{
|
||||
throw new BusinessException("价格发布审批载荷为空");
|
||||
}
|
||||
|
||||
using var document = JsonDocument.Parse(context.PayloadJson);
|
||||
var root = document.RootElement;
|
||||
var salesProductId = ReadInt32(root, "salesProductId", "SalesProductId");
|
||||
var content = ReadJsonPayload(root, "content", "Content");
|
||||
if (salesProductId <= 0 || string.IsNullOrWhiteSpace(content))
|
||||
{
|
||||
throw new BusinessException("价格发布审批载荷缺少产品或快照");
|
||||
}
|
||||
|
||||
var product = await salesProductRepository.FirstOrDefaultAsync(
|
||||
x => x.Id == salesProductId,
|
||||
cancellationToken);
|
||||
if (product == null)
|
||||
{
|
||||
throw new BusinessException("销售产品不存在");
|
||||
}
|
||||
|
||||
var applicantUserName = ReadString(root, "applicantUserName", "ApplicantUserName");
|
||||
var publishUser = string.IsNullOrWhiteSpace(applicantUserName)
|
||||
? (string.IsNullOrWhiteSpace(context.ApplicantUserGuid)
|
||||
? context.ApplicantUserId.ToString()
|
||||
: context.ApplicantUserGuid)
|
||||
: applicantUserName.Trim();
|
||||
|
||||
var descriptionRaw = ReadString(root, "description", "Description");
|
||||
var description = string.IsNullOrWhiteSpace(descriptionRaw)
|
||||
? $"审批通过发布 {context.InstanceNo}"
|
||||
: $"{descriptionRaw.Trim()}(审批单 {context.InstanceNo})";
|
||||
|
||||
var aiReport = ReadString(root, "aiAnalysisReport", "AiAnalysisReport");
|
||||
|
||||
await salesProductRepository.InsertPublishRecordAsync(new SalesProductPublishRecord
|
||||
{
|
||||
SalesProductId = salesProductId,
|
||||
Version = DateTime.Now.ToString("yyyyMMddHHmmss"),
|
||||
OperatorType = "price",
|
||||
Status = EsSnapshotStatus.Active,
|
||||
PublishUser = publishUser,
|
||||
PublishTime = DateTime.Now,
|
||||
Description = description,
|
||||
AiAnalysisReport = string.IsNullOrWhiteSpace(aiReport) ? null : aiReport.Trim(),
|
||||
Content = content
|
||||
}, cancellationToken);
|
||||
}
|
||||
|
||||
private static int ReadInt32(JsonElement root, params string[] names)
|
||||
{
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (!root.TryGetProperty(name, out var el))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (el.ValueKind == JsonValueKind.Number && el.TryGetInt32(out var n))
|
||||
{
|
||||
return n;
|
||||
}
|
||||
|
||||
if (el.ValueKind == JsonValueKind.String && int.TryParse(el.GetString(), out n))
|
||||
{
|
||||
return n;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string? ReadString(JsonElement root, params string[] names)
|
||||
{
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (!root.TryGetProperty(name, out var el))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (el.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
return el.GetString();
|
||||
}
|
||||
|
||||
if (el.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined))
|
||||
{
|
||||
return el.GetRawText();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// content 可能是 JSON 字符串,也可能是对象(历史/异常序列化);统一成快照正文。
|
||||
/// </summary>
|
||||
private static string? ReadJsonPayload(JsonElement root, params string[] names)
|
||||
{
|
||||
foreach (var name in names)
|
||||
{
|
||||
if (!root.TryGetProperty(name, out var el))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (el.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
return el.GetString();
|
||||
}
|
||||
|
||||
if (el.ValueKind is JsonValueKind.Object or JsonValueKind.Array)
|
||||
{
|
||||
return el.GetRawText();
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@ -1,7 +1,9 @@
|
||||
using Oms.Application.Dtos.Channels;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.Shared;
|
||||
@ -418,6 +420,94 @@ public partial class SalesProductService
|
||||
? OmsDocHelper.CanonicalizeSalesProductPriceSnapshotJson(snapshot)
|
||||
: OmsDocHelper.CanonicalizeSalesProductRulesSnapshotJson(snapshot);
|
||||
|
||||
await InsertPublishRecordCoreAsync(
|
||||
salesProductId,
|
||||
operatorType,
|
||||
description,
|
||||
aiAnalysisReport,
|
||||
content,
|
||||
ResolvePublishUserName());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 价格发布:先冻结快照,再经审批门面(未配置则直接落库)。
|
||||
/// </summary>
|
||||
private async Task<SalesProductPublishResultOutput> PublishPriceWithApprovalAsync(
|
||||
int salesProductId,
|
||||
string? description,
|
||||
string? aiAnalysisReport)
|
||||
{
|
||||
var product = await GetProductOrThrowAsync(salesProductId);
|
||||
var priceSnapshot = await BuildPricePublishSnapshotAsync(salesProductId);
|
||||
ValidateBillingPriceItemRules(
|
||||
priceSnapshot.Prices.Select(p => MapPriceSaveInput(p, salesProductId)).ToList());
|
||||
var content = OmsDocHelper.CanonicalizeSalesProductPriceSnapshotJson(priceSnapshot);
|
||||
var contentHash = ComputeContentHash(content);
|
||||
var publishUser = ResolvePublishUserName();
|
||||
|
||||
var payload = new
|
||||
{
|
||||
salesProductId,
|
||||
productCode = product.ProductCode,
|
||||
productName = product.ProductName,
|
||||
operatorType = PriceOperatorType,
|
||||
description,
|
||||
aiAnalysisReport,
|
||||
content,
|
||||
contentHash,
|
||||
applicantUserName = publishUser
|
||||
};
|
||||
|
||||
var gateResult = await ApprovalGate.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest
|
||||
{
|
||||
OperationCode = ApprovalCodes.SalesProductPublishPrice,
|
||||
BizKey = $"SalesProduct.PricePublish:{salesProductId}",
|
||||
Title = $"价格发布 - {product.ProductCode} {product.ProductName}".Trim(),
|
||||
PayloadJson = OmsDocHelper.SerializeJson(payload),
|
||||
Summary = new
|
||||
{
|
||||
productCode = product.ProductCode,
|
||||
productName = product.ProductName,
|
||||
description,
|
||||
hasAiReport = !string.IsNullOrWhiteSpace(aiAnalysisReport),
|
||||
applicantUserName = publishUser
|
||||
}
|
||||
});
|
||||
|
||||
if (gateResult.Decision == ApprovalGateDecision.PendingApproval)
|
||||
{
|
||||
return new SalesProductPublishResultOutput
|
||||
{
|
||||
Decision = nameof(ApprovalGateDecision.PendingApproval),
|
||||
ApprovalInstanceId = gateResult.InstanceId,
|
||||
ApprovalInstanceNo = gateResult.InstanceNo,
|
||||
Message = $"已提交审批({gateResult.InstanceNo}),通过后生效"
|
||||
};
|
||||
}
|
||||
|
||||
await InsertPublishRecordCoreAsync(
|
||||
salesProductId,
|
||||
PriceOperatorType,
|
||||
description,
|
||||
aiAnalysisReport,
|
||||
content,
|
||||
publishUser);
|
||||
|
||||
return new SalesProductPublishResultOutput
|
||||
{
|
||||
Decision = nameof(ApprovalGateDecision.Bypass),
|
||||
Message = gateResult.Message ?? "未启用审批,已直接发布"
|
||||
};
|
||||
}
|
||||
|
||||
private async Task InsertPublishRecordCoreAsync(
|
||||
int salesProductId,
|
||||
string operatorType,
|
||||
string? description,
|
||||
string? aiAnalysisReport,
|
||||
string? content,
|
||||
string publishUser)
|
||||
{
|
||||
// Content 中保存完整快照,回滚时直接从快照恢复,避免依赖当前库内状态。
|
||||
await SalesProductRepository.InsertPublishRecordAsync(new SalesProductPublishRecord
|
||||
{
|
||||
@ -425,7 +515,7 @@ public partial class SalesProductService
|
||||
Version = DateTime.Now.ToString("yyyyMMddHHmmss"),
|
||||
OperatorType = operatorType,
|
||||
Status = EsSnapshotStatus.Active,
|
||||
PublishUser = string.IsNullOrWhiteSpace(CurrentUser.UserName) ? CurrentUser.GetId<int>().ToString() : CurrentUser.UserName!,
|
||||
PublishUser = publishUser,
|
||||
PublishTime = DateTime.Now,
|
||||
Description = description,
|
||||
AiAnalysisReport = string.IsNullOrWhiteSpace(aiAnalysisReport) ? null : aiAnalysisReport.Trim(),
|
||||
@ -433,6 +523,11 @@ public partial class SalesProductService
|
||||
});
|
||||
}
|
||||
|
||||
private string ResolvePublishUserName() =>
|
||||
string.IsNullOrWhiteSpace(CurrentUser.UserName)
|
||||
? CurrentUser.GetId<int>().ToString()
|
||||
: CurrentUser.UserName!;
|
||||
|
||||
/// <summary>
|
||||
/// 按发布记录回滚价格或规则配置。
|
||||
/// </summary>
|
||||
|
||||
@ -3,7 +3,11 @@ using Fake.Application;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Channels;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
|
||||
@ -29,6 +33,14 @@ public partial class SalesProductService : ApplicationService
|
||||
private OmsRbacUserDisplayNameResolver UserDisplayNameResolver =>
|
||||
LazyServiceProvider.GetRequiredService<OmsRbacUserDisplayNameResolver>();
|
||||
|
||||
private IApprovalGate ApprovalGate => LazyServiceProvider.GetRequiredService<IApprovalGate>();
|
||||
private IApprovalInstanceRepository ApprovalInstanceRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalInstanceRepository>();
|
||||
private IApprovalTaskRepository ApprovalTaskRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalTaskRepository>();
|
||||
private IApprovalDefinitionRepository ApprovalDefinitionRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalDefinitionRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 查询销售产品列表。
|
||||
/// </summary>
|
||||
@ -316,9 +328,8 @@ public partial class SalesProductService : ApplicationService
|
||||
throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告");
|
||||
}
|
||||
|
||||
await CreatePublishRecordAsync(
|
||||
await PublishPriceWithApprovalAsync(
|
||||
input.SalesProductId,
|
||||
PriceOperatorType,
|
||||
"保存并发布价格",
|
||||
input.AiAnalysisReport);
|
||||
}
|
||||
@ -429,40 +440,142 @@ public partial class SalesProductService : ApplicationService
|
||||
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(currentSnapshot)
|
||||
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(currentSnapshot));
|
||||
|
||||
// 价格:是否启用审批定义 + 在途/失败终态
|
||||
var approvalRequired = false;
|
||||
var approvalPending = false;
|
||||
var approvalFailed = false;
|
||||
int? approvalInstanceId = null;
|
||||
string? approvalInstanceNo = null;
|
||||
string? approvalStatusName = null;
|
||||
string? approvalComment = null;
|
||||
if (normalized == PriceOperatorType)
|
||||
{
|
||||
var enabledDef = await ApprovalDefinitionRepository.FirstOrDefaultAsync(x =>
|
||||
x.OperationCode == ApprovalCodes.SalesProductPublishPrice && x.IsEnabled);
|
||||
approvalRequired = enabledDef != null;
|
||||
|
||||
var approvalState = await ResolvePricePublishApprovalStateAsync(salesProductId);
|
||||
approvalPending = approvalState.Pending;
|
||||
approvalFailed = approvalState.Failed;
|
||||
approvalInstanceId = approvalState.InstanceId;
|
||||
approvalInstanceNo = approvalState.InstanceNo;
|
||||
approvalStatusName = approvalState.StatusName;
|
||||
approvalComment = approvalState.Comment;
|
||||
}
|
||||
|
||||
// 生效 = 最新 Active 发布记录 Content
|
||||
var onlineRecord = await SalesProductRepository.GetEffectivePublishRecordAsync(
|
||||
salesProductId,
|
||||
normalized,
|
||||
DateTime.Now);
|
||||
bool contentPending;
|
||||
string? onlineVersion = null;
|
||||
DateTime? onlinePublishTime = null;
|
||||
string? onlineContentHash = null;
|
||||
if (onlineRecord == null || string.IsNullOrWhiteSpace(onlineRecord.Content))
|
||||
{
|
||||
return new SalesProductPublishSyncStatusOutput
|
||||
{
|
||||
Pending = true,
|
||||
OnlineVersion = null,
|
||||
OnlinePublishTime = null,
|
||||
PendingContentHash = currentHash,
|
||||
OnlineContentHash = null
|
||||
};
|
||||
contentPending = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
onlineVersion = onlineRecord.Version;
|
||||
onlinePublishTime = onlineRecord.PublishTime;
|
||||
onlineContentHash = ComputeContentHash(
|
||||
normalized == PriceOperatorType
|
||||
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(
|
||||
OmsDocHelper.DeserializePriceSnapshot(onlineRecord.Content))
|
||||
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(
|
||||
OmsDocHelper.DeserializeRulesSnapshot(onlineRecord.Content)));
|
||||
contentPending = !string.Equals(currentHash, onlineContentHash, StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
var onlineHash = ComputeContentHash(
|
||||
normalized == PriceOperatorType
|
||||
? OmsDocHelper.HashSalesProductPriceSnapshotForSync(
|
||||
OmsDocHelper.DeserializePriceSnapshot(onlineRecord.Content))
|
||||
: OmsDocHelper.HashSalesProductRulesSnapshotForSync(
|
||||
OmsDocHelper.DeserializeRulesSnapshot(onlineRecord.Content)));
|
||||
// 内容已与线上一致时,旧驳回/撤回不再当失败引导;执行失败仍展示(可能空跑未落库)
|
||||
if (!contentPending
|
||||
&& approvalFailed
|
||||
&& !string.Equals(approvalStatusName, "执行失败", StringComparison.Ordinal))
|
||||
{
|
||||
approvalFailed = false;
|
||||
approvalInstanceId = null;
|
||||
approvalInstanceNo = null;
|
||||
approvalStatusName = null;
|
||||
approvalComment = null;
|
||||
}
|
||||
|
||||
return new SalesProductPublishSyncStatusOutput
|
||||
{
|
||||
Pending = !string.Equals(currentHash, onlineHash, StringComparison.Ordinal),
|
||||
OnlineVersion = onlineRecord.Version,
|
||||
OnlinePublishTime = onlineRecord.PublishTime,
|
||||
Pending = contentPending,
|
||||
OnlineVersion = onlineVersion,
|
||||
OnlinePublishTime = onlinePublishTime,
|
||||
PendingContentHash = currentHash,
|
||||
OnlineContentHash = onlineHash
|
||||
OnlineContentHash = onlineContentHash,
|
||||
ApprovalRequired = approvalRequired,
|
||||
ApprovalPending = approvalPending,
|
||||
ApprovalFailed = approvalFailed,
|
||||
ApprovalInstanceId = approvalInstanceId,
|
||||
ApprovalInstanceNo = approvalInstanceNo,
|
||||
ApprovalStatusName = approvalStatusName,
|
||||
ApprovalComment = approvalComment
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 解析价格发布审批态:优先 Pending;否则最近一条驳回/撤回/执行失败。
|
||||
/// </summary>
|
||||
private async Task<(
|
||||
bool Pending,
|
||||
bool Failed,
|
||||
int? InstanceId,
|
||||
string? InstanceNo,
|
||||
string? StatusName,
|
||||
string? Comment)> ResolvePricePublishApprovalStateAsync(int salesProductId)
|
||||
{
|
||||
var bizKey = $"SalesProduct.PricePublish:{salesProductId}";
|
||||
var pendingApproval = await ApprovalInstanceRepository.FirstOrDefaultAsync(x =>
|
||||
x.OperationCode == ApprovalCodes.SalesProductPublishPrice
|
||||
&& x.BizKey == bizKey
|
||||
&& x.Status == ApprovalInstanceStatus.Pending);
|
||||
if (pendingApproval != null)
|
||||
{
|
||||
return (true, false, pendingApproval.Id, pendingApproval.InstanceNo, "待审批", null);
|
||||
}
|
||||
|
||||
var failedList = await ApprovalInstanceRepository.GetListAsync(x =>
|
||||
x.OperationCode == ApprovalCodes.SalesProductPublishPrice
|
||||
&& x.BizKey == bizKey
|
||||
&& (x.Status == ApprovalInstanceStatus.Rejected
|
||||
|| x.Status == ApprovalInstanceStatus.Withdrawn
|
||||
|| x.Status == ApprovalInstanceStatus.ExecuteFailed));
|
||||
var failed = failedList
|
||||
.OrderByDescending(x => x.CompletedTime ?? x.CreateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.FirstOrDefault();
|
||||
if (failed == null)
|
||||
{
|
||||
return (false, false, null, null, null, null);
|
||||
}
|
||||
|
||||
var statusName = failed.Status switch
|
||||
{
|
||||
ApprovalInstanceStatus.Rejected => "已驳回",
|
||||
ApprovalInstanceStatus.Withdrawn => "已撤回",
|
||||
ApprovalInstanceStatus.ExecuteFailed => "执行失败",
|
||||
_ => failed.Status.ToString()
|
||||
};
|
||||
|
||||
string? comment = null;
|
||||
if (failed.Status == ApprovalInstanceStatus.ExecuteFailed)
|
||||
{
|
||||
comment = string.IsNullOrWhiteSpace(failed.ExecuteMessage) ? null : failed.ExecuteMessage.Trim();
|
||||
}
|
||||
else if (failed.CurrentTaskId is int taskId)
|
||||
{
|
||||
var task = await ApprovalTaskRepository.FirstOrDefaultAsync(x => x.Id == taskId);
|
||||
comment = string.IsNullOrWhiteSpace(task?.Comment) ? null : task!.Comment!.Trim();
|
||||
}
|
||||
|
||||
return (false, true, failed.Id, failed.InstanceNo, statusName, comment);
|
||||
}
|
||||
|
||||
private static string ComputeContentHash(string content)
|
||||
{
|
||||
var hash = global::System.Security.Cryptography.SHA256.HashData(
|
||||
@ -471,17 +584,25 @@ public partial class SalesProductService : ApplicationService
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行销售产品发布。
|
||||
/// 执行销售产品发布。价格发布会走审批门面:未配置/未命中则直接发布,否则创建审批单。
|
||||
/// </summary>
|
||||
/// <param name="input">入参:销售产品发布参数。</param>
|
||||
/// <returns>无返回体,仅完成销售产品发布处理。</returns>
|
||||
/// <returns>发布结果(直接发布或待审批)。</returns>
|
||||
[HttpPost("/channel/sales-product/publish")]
|
||||
public async Task PublishAsync(SalesProductPublishInput input)
|
||||
public async Task<SalesProductPublishResultOutput> PublishAsync(SalesProductPublishInput input)
|
||||
{
|
||||
var operatorType = NormalizeOperatorType(input.OperatorType);
|
||||
if (operatorType == PriceOperatorType && string.IsNullOrWhiteSpace(input.AiAnalysisReport))
|
||||
if (operatorType == PriceOperatorType)
|
||||
{
|
||||
throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告");
|
||||
if (string.IsNullOrWhiteSpace(input.AiAnalysisReport))
|
||||
{
|
||||
throw new Fake.Application.BusinessException("价格发布前须完成 AI 风险分析并保存报告");
|
||||
}
|
||||
|
||||
return await PublishPriceWithApprovalAsync(
|
||||
input.SalesProductId,
|
||||
input.Description,
|
||||
input.AiAnalysisReport);
|
||||
}
|
||||
|
||||
await CreatePublishRecordAsync(
|
||||
@ -489,6 +610,11 @@ public partial class SalesProductService : ApplicationService
|
||||
operatorType,
|
||||
input.Description,
|
||||
input.AiAnalysisReport);
|
||||
return new SalesProductPublishResultOutput
|
||||
{
|
||||
Decision = "Bypass",
|
||||
Message = "规则发布已完成"
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -518,6 +518,13 @@ public class CustomerService : ApplicationService
|
||||
var customerGroupValue = input.CustomerGroup.GetValueOrDefault();
|
||||
var hasAgentFilter = input.AgentId is > 0;
|
||||
var agentId = input.AgentId.GetValueOrDefault();
|
||||
var monitorScope = NormalizeMonitorScope(input.MonitorScope);
|
||||
var hasMonitorScope = !string.IsNullOrEmpty(monitorScope);
|
||||
// 与 /monitor/overview 客户 KPI 同一时间口径
|
||||
var today = DateTime.Today;
|
||||
var tomorrow = today.AddDays(1);
|
||||
var inactive7dThreshold = today.AddDays(-7);
|
||||
var onlineSince = DateTime.Now.AddMinutes(-30);
|
||||
|
||||
return customer =>
|
||||
(string.IsNullOrWhiteSpace(keyword) ||
|
||||
@ -526,10 +533,32 @@ public class CustomerService : ApplicationService
|
||||
(customer.Phone ?? string.Empty).Contains(keyword) ||
|
||||
(customer.Email ?? string.Empty).Contains(keyword)) &&
|
||||
(!hasStatusFilter || customer.Status == statusValue) &&
|
||||
(!hasMonitorScope || customer.Status == CustomerStatus.Normal) &&
|
||||
(!hasCustomerGroupFilter || customer.CustomerGroup == customerGroupValue) &&
|
||||
(string.IsNullOrWhiteSpace(salesman) || customer.Salesman == salesman) &&
|
||||
(string.IsNullOrWhiteSpace(customerService) || customer.CustomerService == customerService) &&
|
||||
(!hasAgentFilter || customer.AgentId == agentId);
|
||||
(!hasAgentFilter || customer.AgentId == agentId) &&
|
||||
(monitorScope != "newToday" || (customer.CreateTime >= today && customer.CreateTime < tomorrow)) &&
|
||||
(monitorScope != "online" ||
|
||||
(customer.LastLoginTime != null && customer.LastLoginTime >= onlineSince)) &&
|
||||
(monitorScope != "inactive7d" ||
|
||||
(customer.LastLoginTime == null || customer.LastLoginTime < inactive7dThreshold));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 规范化监控下钻口径;非法值视为无筛选。
|
||||
/// </summary>
|
||||
private static string? NormalizeMonitorScope(string? scope)
|
||||
{
|
||||
var value = (scope ?? string.Empty).Trim().ToLowerInvariant();
|
||||
return value switch
|
||||
{
|
||||
"total" => "total",
|
||||
"newtoday" => "newToday",
|
||||
"online" => "online",
|
||||
"inactive7d" => "inactive7d",
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<Dictionary<int, (string Code, string Name)>> ResolveAgentDisplayMapAsync(
|
||||
|
||||
644
src/Oms.Application/Services/Operations/ShipBagService.cs
Normal file
644
src/Oms.Application/Services/Operations/ShipBagService.cs
Normal file
@ -0,0 +1,644 @@
|
||||
using System.Data;
|
||||
using Fake.Application;
|
||||
using Fake.ObjectStorage;
|
||||
using Fake.UnitOfWork;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Operations;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Services.Orders;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.OperationsAggregate.Consts;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
using Oms.Domain.OperationsAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
using OutboundRecord = Oms.Domain.OperationsAggregate.Entities.OutboundRecord;
|
||||
|
||||
namespace Oms.Application.Services.Operations;
|
||||
|
||||
/// <summary>
|
||||
/// 大包装袋与管理。小包可不入袋;入袋仅待发货。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Operation")]
|
||||
public class ShipBagService : ApplicationService
|
||||
{
|
||||
private IShipBagRepository BagRepository => LazyServiceProvider.GetRequiredService<IShipBagRepository>();
|
||||
private IShipBagItemRepository BagItemRepository => LazyServiceProvider.GetRequiredService<IShipBagItemRepository>();
|
||||
private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||||
private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>();
|
||||
private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
|
||||
LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>();
|
||||
private IOutboundRecordRepository OutboundRecordRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IOutboundRecordRepository>();
|
||||
private ILabelTemplateRepository LabelTemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ILabelTemplateRepository>();
|
||||
private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService<ILabelPdfRenderer>();
|
||||
private IObjectStorage FileStorage => LazyServiceProvider.GetRequiredService<IObjectStorage>();
|
||||
private IWarehouseAddressRepository WarehouseAddressRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建空大包(装袋中)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/create")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> CreateAsync(CreateShipBagInput input)
|
||||
{
|
||||
var bagType = string.IsNullOrWhiteSpace(input.BagType)
|
||||
? ShipBagTypeCodes.Sack
|
||||
: input.BagType.Trim().ToLowerInvariant();
|
||||
if (bagType is not (ShipBagTypeCodes.Sack or ShipBagTypeCodes.Box))
|
||||
{
|
||||
throw new BusinessException("袋型仅支持 sack(麻袋)或 box(箱子)");
|
||||
}
|
||||
|
||||
var entity = new ShipBag
|
||||
{
|
||||
BagNo = await NextBagNoAsync(),
|
||||
BagType = bagType,
|
||||
Status = ShipBagStatusCodes.Open,
|
||||
WarehouseId = input.WarehouseId,
|
||||
DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant(),
|
||||
DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim(),
|
||||
ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim(),
|
||||
Length = input.Length,
|
||||
Width = input.Width,
|
||||
Height = input.Height,
|
||||
Weight = input.Weight,
|
||||
Remark = input.Remark?.Trim(),
|
||||
ParcelCount = 0,
|
||||
};
|
||||
|
||||
var saved = await BagRepository.InsertAsync(entity);
|
||||
return MapBag(saved);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新大包件重尺、目的口岸等属性(已出库/作废不可改)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/update-meta")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> UpdateMetaAsync(UpdateShipBagMetaInput input)
|
||||
{
|
||||
var bag = await RequireBagAsync(input.BagNo);
|
||||
if (bag.Status is ShipBagStatusCodes.Shipped or ShipBagStatusCodes.Voided)
|
||||
{
|
||||
throw new BusinessException("已出库或已作废的大包不可改属性");
|
||||
}
|
||||
|
||||
bag.DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant();
|
||||
bag.DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim();
|
||||
bag.ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim();
|
||||
bag.Length = input.Length;
|
||||
bag.Width = input.Width;
|
||||
bag.Height = input.Height;
|
||||
bag.Weight = input.Weight;
|
||||
bag.Remark = input.Remark?.Trim();
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
return await GetDetailAsync(bag.BagNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扫小包入袋(仅待发货;可不使用大包出库路径)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/add-parcel")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> AddParcelAsync(ShipBagParcelInput input)
|
||||
{
|
||||
var bag = await RequireOpenBagAsync(input.BagNo);
|
||||
var order = await RequireOrderByWaybillAsync(input.WaybillNo);
|
||||
|
||||
if (order.OrderStatus != OrderStatusCodes.PendingShip)
|
||||
{
|
||||
throw new BusinessException(
|
||||
$"运单 {order.ServiceNo} 状态为「{OmsDocHelper.GetOrderStatusName(order.OrderStatus)}」,仅待发货可入袋");
|
||||
}
|
||||
|
||||
if (order.IsPaid == 0)
|
||||
{
|
||||
throw new BusinessException($"运单 {order.ServiceNo} 未付款,禁止入袋");
|
||||
}
|
||||
|
||||
var existing = await BagItemRepository.FindActiveByOrderIdAsync(order.Id);
|
||||
if (existing != null)
|
||||
{
|
||||
if (existing.BagId == bag.Id)
|
||||
{
|
||||
throw new BusinessException("该运单已在本袋中");
|
||||
}
|
||||
|
||||
throw new BusinessException($"该运单已在其它大包中(明细Id={existing.BagId})");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(bag.DestinationCountry)
|
||||
&& !string.IsNullOrWhiteSpace(order.ConsigneeCountry)
|
||||
&& !string.Equals(bag.DestinationCountry, order.ConsigneeCountry, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException(
|
||||
$"目的国不一致:袋={bag.DestinationCountry},运单={order.ConsigneeCountry}");
|
||||
}
|
||||
|
||||
await BagItemRepository.InsertAsync(
|
||||
new ShipBagItem
|
||||
{
|
||||
BagId = bag.Id,
|
||||
OrderId = order.Id,
|
||||
WaybillNo = order.ServiceNo,
|
||||
});
|
||||
|
||||
order.ShipBagId = bag.Id;
|
||||
order.ShipBagNo = bag.BagNo;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
|
||||
bag.ParcelCount = (await BagItemRepository.ListByBagIdAsync(bag.Id)).Count;
|
||||
if (string.IsNullOrWhiteSpace(bag.DestinationCountry) && !string.IsNullOrWhiteSpace(order.ConsigneeCountry))
|
||||
{
|
||||
bag.DestinationCountry = order.ConsigneeCountry;
|
||||
}
|
||||
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
return await GetDetailAsync(bag.BagNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从袋中移除小包(仅装袋中)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/remove-parcel")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> RemoveParcelAsync(ShipBagParcelInput input)
|
||||
{
|
||||
var bag = await RequireOpenBagAsync(input.BagNo);
|
||||
var order = await RequireOrderByWaybillAsync(input.WaybillNo);
|
||||
var item = (await BagItemRepository.ListByBagIdAsync(bag.Id))
|
||||
.FirstOrDefault(x => x.OrderId == order.Id);
|
||||
if (item == null)
|
||||
{
|
||||
throw new BusinessException("袋内无此运单");
|
||||
}
|
||||
|
||||
await BagItemRepository.DeleteAsync(item);
|
||||
if (order.ShipBagId == bag.Id)
|
||||
{
|
||||
order.ShipBagId = null;
|
||||
order.ShipBagNo = null;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
}
|
||||
|
||||
bag.ParcelCount = (await BagItemRepository.ListByBagIdAsync(bag.Id)).Count;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
return await GetDetailAsync(bag.BagNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 封袋。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/seal")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> SealAsync(ShipBagNoInput input)
|
||||
{
|
||||
var bag = await RequireBagAsync(input.BagNo);
|
||||
if (bag.Status != ShipBagStatusCodes.Open)
|
||||
{
|
||||
throw new BusinessException("仅装袋中的大包可封袋");
|
||||
}
|
||||
|
||||
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new BusinessException("空袋不能封袋");
|
||||
}
|
||||
|
||||
bag.Status = ShipBagStatusCodes.Sealed;
|
||||
bag.SealTime = DateTime.Now;
|
||||
bag.ParcelCount = items.Count;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
return await GetDetailAsync(bag.BagNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 作废空袋或装袋中大包(有货须先移出)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/void")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipBagOutput> VoidAsync(ShipBagNoInput input)
|
||||
{
|
||||
var bag = await RequireBagAsync(input.BagNo);
|
||||
if (bag.Status is ShipBagStatusCodes.Shipped or ShipBagStatusCodes.Voided)
|
||||
{
|
||||
throw new BusinessException("已出库或已作废的大包不能再作废");
|
||||
}
|
||||
|
||||
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
|
||||
if (items.Count > 0)
|
||||
{
|
||||
throw new BusinessException("请先移出袋内运单再作废");
|
||||
}
|
||||
|
||||
bag.Status = ShipBagStatusCodes.Voided;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
return MapBag(bag);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 大包详情(含明细)。
|
||||
/// </summary>
|
||||
[HttpGet("/operation/bag/get")]
|
||||
public async Task<ShipBagOutput> GetAsync([FromQuery] string bagNo) => await GetDetailAsync(bagNo);
|
||||
|
||||
/// <summary>
|
||||
/// 大包分页列表。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/bag/page")]
|
||||
public async Task<OmsPageResult<ShipBagOutput>> PageAsync([FromBody] ShipBagPageInput input)
|
||||
{
|
||||
var pageIndex = PagingHelper.NormalizePageIndex(input.PageIndex);
|
||||
var pageSize = PagingHelper.NormalizePageSize(input.PageSize);
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var status = input.Status?.Trim();
|
||||
var hasWh = input.WarehouseId.HasValue;
|
||||
var wh = input.WarehouseId.GetValueOrDefault();
|
||||
|
||||
var list = await BagRepository.GetListAsync(x =>
|
||||
(string.IsNullOrEmpty(status) || x.Status == status)
|
||||
&& (!hasWh || x.WarehouseId == wh)
|
||||
&& (string.IsNullOrEmpty(keyword)
|
||||
|| x.BagNo.Contains(keyword)
|
||||
|| (x.ChannelCode != null && x.ChannelCode.Contains(keyword))
|
||||
|| (x.DestinationCountry != null && x.DestinationCountry.Contains(keyword))));
|
||||
|
||||
var ordered = list.OrderByDescending(x => x.Id).ToList();
|
||||
var total = ordered.Count;
|
||||
var page = ordered.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(MapBag).ToList();
|
||||
return new OmsPageResult<ShipBagOutput> { Items = page, Total = total };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按大包出库:袋须已封;袋内待发货小包全部出库(用入库/预报件重尺),整袋成功或整袋失败。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/outbound/bag-create")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<BagOutboundResultOutput> OutboundByBagAsync(CreateBagOutboundInput input)
|
||||
{
|
||||
var bag = await RequireBagAsync(input.BagNo);
|
||||
if (bag.Status != ShipBagStatusCodes.Sealed)
|
||||
{
|
||||
throw new BusinessException("仅已封袋的大包可出库");
|
||||
}
|
||||
|
||||
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new BusinessException("袋内无运单");
|
||||
}
|
||||
|
||||
var orderIds = items.Select(x => x.OrderId).Distinct().ToArray();
|
||||
var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id));
|
||||
var orderMap = orders.ToDictionary(x => x.Id);
|
||||
var weights = await OrderRepository.GetWeightsByOrderIdsAsync(orderIds);
|
||||
var weightGroups = weights.GroupBy(x => x.OrderId).ToDictionary(g => g.Key, g => g.ToList());
|
||||
|
||||
foreach (var item in items)
|
||||
{
|
||||
if (!orderMap.TryGetValue(item.OrderId, out var order))
|
||||
{
|
||||
throw new BusinessException($"袋内运单缺失订单 Id={item.OrderId}");
|
||||
}
|
||||
|
||||
if (order.OrderStatus != OrderStatusCodes.PendingShip || order.IsPaid == 0)
|
||||
{
|
||||
throw new BusinessException(
|
||||
$"运单 {order.ServiceNo} 不可出库(状态={OmsDocHelper.GetOrderStatusName(order.OrderStatus)})");
|
||||
}
|
||||
|
||||
if (!weightGroups.TryGetValue(order.Id, out var rows)
|
||||
|| !TryResolveOutboundDims(rows, out var length, out var width, out var height, out var weight))
|
||||
{
|
||||
throw new BusinessException($"运单 {order.ServiceNo} 缺少可用件重尺,无法大包出库");
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
var operatorId = CurrentUser.GetId<int>();
|
||||
await OrderService.ApplyShipBillingByWaybillAsync(order.ServiceNo, length, width, height, weight);
|
||||
await OutboundRecordRepository.InsertAsync(
|
||||
new OutboundRecord
|
||||
{
|
||||
WaybillNo = order.ServiceNo,
|
||||
Weight = weight,
|
||||
Length = length,
|
||||
Width = width,
|
||||
Height = height,
|
||||
DestinationCountry = order.ConsigneeCountry,
|
||||
WarehouseId = input.WarehouseId ?? bag.WarehouseId ?? order.WarehouseId,
|
||||
OperateTime = now,
|
||||
OperatorId = operatorId,
|
||||
});
|
||||
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId);
|
||||
}
|
||||
|
||||
bag.Status = ShipBagStatusCodes.Shipped;
|
||||
bag.ShipTime = DateTime.Now;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
|
||||
return new BagOutboundResultOutput
|
||||
{
|
||||
BagNo = bag.BagNo,
|
||||
SuccessCount = items.Count,
|
||||
WaybillNos = items.Select(x => x.WaybillNo).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
private static bool TryResolveOutboundDims(
|
||||
List<OrderWeight> rows,
|
||||
out decimal length,
|
||||
out decimal width,
|
||||
out decimal height,
|
||||
out decimal weight)
|
||||
{
|
||||
length = width = height = weight = 0;
|
||||
var receive = rows.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Receive);
|
||||
var forecast = rows.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Forecast);
|
||||
var src = receive ?? forecast;
|
||||
if (src == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (src.Length is not > 0 || src.Width is not > 0 || src.Height is not > 0 || src.ActualWeight is not > 0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
length = src.Length.Value;
|
||||
width = src.Width.Value;
|
||||
height = src.Height.Value;
|
||||
weight = src.ActualWeight.Value;
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task<ShipBagOutput> GetDetailAsync(string bagNo)
|
||||
{
|
||||
var bag = await RequireBagAsync(bagNo);
|
||||
var output = MapBag(bag);
|
||||
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
|
||||
if (items.Count == 0)
|
||||
{
|
||||
output.Items = [];
|
||||
return output;
|
||||
}
|
||||
|
||||
var orderIds = items.Select(x => x.OrderId).Distinct().ToArray();
|
||||
var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id));
|
||||
var orderMap = orders.ToDictionary(x => x.Id);
|
||||
output.Items = items
|
||||
.Select(i =>
|
||||
{
|
||||
orderMap.TryGetValue(i.OrderId, out var order);
|
||||
return new ShipBagItemOutput
|
||||
{
|
||||
Id = i.Id,
|
||||
OrderId = i.OrderId,
|
||||
WaybillNo = i.WaybillNo,
|
||||
OrderStatus = order?.OrderStatus,
|
||||
OrderStatusName = order == null ? null : OmsDocHelper.GetOrderStatusName(order.OrderStatus),
|
||||
ConsigneeCountry = order?.ConsigneeCountry,
|
||||
};
|
||||
})
|
||||
.ToList();
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量打印大包标签:按所选模板(类型 shipBag)渲染 PDF,返回各包可打印 URL。
|
||||
/// </summary>
|
||||
/// <param name="input">大包号列表与可选模板 ID。</param>
|
||||
/// <returns>模板名 + 各包 printUrl。</returns>
|
||||
[HttpPost("/operation/bag/print-labels")]
|
||||
public async Task<ShipBagPrintLabelsOutput> PrintLabelsAsync(ShipBagPrintLabelsInput input)
|
||||
{
|
||||
var bagNos = (input.BagNos ?? [])
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Select(x => x.Trim())
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
if (bagNos.Count == 0)
|
||||
{
|
||||
throw new BusinessException("请选择要打印的大包");
|
||||
}
|
||||
|
||||
var template = await ResolveLabelTemplateAsync(LabelTemplateTypeCodes.ShipBag, input.LabelTemplateId);
|
||||
var bags = await BagRepository.GetListAsync(x => bagNos.Contains(x.BagNo));
|
||||
if (bags.Count == 0)
|
||||
{
|
||||
throw new BusinessException("未找到可打印的大包");
|
||||
}
|
||||
|
||||
var bagMap = bags.ToDictionary(x => x.BagNo, StringComparer.OrdinalIgnoreCase);
|
||||
var warehouseIds = bags.Where(x => x.WarehouseId is > 0).Select(x => x.WarehouseId!.Value).Distinct().ToArray();
|
||||
var warehouses = warehouseIds.Length == 0
|
||||
? []
|
||||
: await WarehouseAddressRepository.GetListAsync(x => warehouseIds.Contains(x.Id));
|
||||
var warehouseMap = warehouses.ToDictionary(x => x.Id);
|
||||
var operatorName = CurrentUser?.UserName;
|
||||
var printTime = DateTime.Now;
|
||||
var pageCount = bagNos.Count(x => bagMap.ContainsKey(x));
|
||||
var pageIndex = 0;
|
||||
var items = new List<ShipBagPrintLabelItemOutput>();
|
||||
|
||||
foreach (var bagNo in bagNos)
|
||||
{
|
||||
if (!bagMap.TryGetValue(bagNo, out var bag))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
pageIndex++;
|
||||
string? warehouseName = null;
|
||||
if (bag.WarehouseId is > 0 && warehouseMap.TryGetValue(bag.WarehouseId.Value, out var wh))
|
||||
{
|
||||
warehouseName = wh.WarehouseName;
|
||||
}
|
||||
|
||||
var printData = ShipBagLabelPrintDataBuilder.Build(
|
||||
bag,
|
||||
warehouseName: warehouseName,
|
||||
operatorName: operatorName,
|
||||
printTime: printTime,
|
||||
pageIndex: pageIndex,
|
||||
pageCount: pageCount);
|
||||
var pdfBytes = await LabelPdfRenderer.RenderAsync(template.TemplateJson!, printData);
|
||||
var printUrl = await SaveBagLabelPdfAsync(bag.BagNo, pdfBytes);
|
||||
items.Add(new ShipBagPrintLabelItemOutput
|
||||
{
|
||||
BagNo = bag.BagNo,
|
||||
PrintUrl = printUrl
|
||||
});
|
||||
}
|
||||
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new BusinessException("未找到可打印的大包");
|
||||
}
|
||||
|
||||
return new ShipBagPrintLabelsOutput
|
||||
{
|
||||
TemplateName = template.Name,
|
||||
Items = items
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<LabelTemplate> ResolveLabelTemplateAsync(string templateType, int? labelTemplateId)
|
||||
{
|
||||
if (labelTemplateId is > 0)
|
||||
{
|
||||
var specified = await LabelTemplateRepository.FirstOrDefaultAsync(x => x.Id == labelTemplateId.Value);
|
||||
if (specified == null)
|
||||
{
|
||||
throw new BusinessException("标签模板不存在");
|
||||
}
|
||||
|
||||
if (!string.Equals(specified.TemplateType, templateType, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException($"请选择类型为 {templateType} 的标签模板");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(specified.TemplateJson))
|
||||
{
|
||||
throw new BusinessException("所选标签模板内容为空,请先在标签设计中保存");
|
||||
}
|
||||
|
||||
return specified;
|
||||
}
|
||||
|
||||
var templates = await LabelTemplateRepository.GetListAsync(x => x.TemplateType == templateType);
|
||||
var latest = templates
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x.TemplateJson))
|
||||
.OrderByDescending(x => x.UpdateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.FirstOrDefault();
|
||||
if (latest == null)
|
||||
{
|
||||
throw new BusinessException($"未配置大包标签模板(类型 {templateType}),请先在标签设计中创建");
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
private async Task<string> SaveBagLabelPdfAsync(string bagNo, byte[] pdfBytes)
|
||||
{
|
||||
var safeNo = string.IsNullOrWhiteSpace(bagNo) ? "bag" : bagNo.Trim();
|
||||
foreach (var c in Path.GetInvalidFileNameChars())
|
||||
{
|
||||
safeNo = safeNo.Replace(c, '_');
|
||||
}
|
||||
|
||||
var fileName = $"{safeNo}-{DateTime.Now:yyyyMMddHHmmssfff}.pdf";
|
||||
var relativeKey = $"uploads/prints/ship-bag-labels/{fileName}";
|
||||
await using var stream = new MemoryStream(pdfBytes);
|
||||
var key = await FileStorage.SaveObjectAsync(stream, relativeKey, "application/pdf");
|
||||
return FileStorage.GetPublicUrl(key);
|
||||
}
|
||||
|
||||
private async Task<ShipBag> RequireBagAsync(string bagNo)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(bagNo))
|
||||
{
|
||||
throw new BusinessException("请输入大包号");
|
||||
}
|
||||
|
||||
var bag = await BagRepository.GetByBagNoAsync(bagNo.Trim());
|
||||
if (bag == null)
|
||||
{
|
||||
throw new BusinessException("未找到大包");
|
||||
}
|
||||
|
||||
return bag;
|
||||
}
|
||||
|
||||
private async Task<ShipBag> RequireOpenBagAsync(string bagNo)
|
||||
{
|
||||
var bag = await RequireBagAsync(bagNo);
|
||||
if (bag.Status != ShipBagStatusCodes.Open)
|
||||
{
|
||||
throw new BusinessException("仅装袋中的大包可继续装/拆");
|
||||
}
|
||||
|
||||
return bag;
|
||||
}
|
||||
|
||||
private async Task<Order> RequireOrderByWaybillAsync(string waybillNo)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(waybillNo))
|
||||
{
|
||||
throw new BusinessException("请扫描运单号");
|
||||
}
|
||||
|
||||
var order = await OrderRepository.GetByWaybillNoAsync(waybillNo.Trim());
|
||||
if (order == null)
|
||||
{
|
||||
throw new BusinessException("未找到对应订单");
|
||||
}
|
||||
|
||||
return order;
|
||||
}
|
||||
|
||||
private async Task<string> NextBagNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"BAG{DateTime.Now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
|
||||
if (await BagRepository.GetByBagNoAsync(no) == null)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("生成大包号失败,请重试");
|
||||
}
|
||||
|
||||
private static ShipBagOutput MapBag(ShipBag bag) =>
|
||||
new()
|
||||
{
|
||||
Id = bag.Id,
|
||||
BagNo = bag.BagNo,
|
||||
BagType = bag.BagType,
|
||||
Status = bag.Status,
|
||||
StatusName = bag.Status switch
|
||||
{
|
||||
ShipBagStatusCodes.Open => "装袋中",
|
||||
ShipBagStatusCodes.Sealed => "已封袋",
|
||||
ShipBagStatusCodes.Shipped => "已出库",
|
||||
ShipBagStatusCodes.Voided => "已作废",
|
||||
_ => bag.Status,
|
||||
},
|
||||
WarehouseId = bag.WarehouseId,
|
||||
DestinationCountry = bag.DestinationCountry,
|
||||
DestinationPort = bag.DestinationPort,
|
||||
ChannelCode = bag.ChannelCode,
|
||||
Length = bag.Length,
|
||||
Width = bag.Width,
|
||||
Height = bag.Height,
|
||||
Weight = bag.Weight,
|
||||
ParcelCount = bag.ParcelCount,
|
||||
SealTime = bag.SealTime,
|
||||
ShipTime = bag.ShipTime,
|
||||
MasterId = bag.MasterId,
|
||||
Remark = bag.Remark,
|
||||
CreateTime = bag.CreateTime,
|
||||
};
|
||||
}
|
||||
625
src/Oms.Application/Services/Operations/ShipMasterService.cs
Normal file
625
src/Oms.Application/Services/Operations/ShipMasterService.cs
Normal file
@ -0,0 +1,625 @@
|
||||
using System.Data;
|
||||
using Fake.Application;
|
||||
using Fake.ObjectStorage;
|
||||
using Fake.UnitOfWork;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Operations;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Labeling;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.OperationsAggregate.Consts;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
using Oms.Domain.OperationsAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
using Oms.Domain.OrdersAggregate.Repositories;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Operations;
|
||||
|
||||
/// <summary>
|
||||
/// 内部主单打板与管理;可绑定外部 MAWB。小包可不进主单。
|
||||
/// </summary>
|
||||
[ApiExplorerSettings(GroupName = "OMS-Operation")]
|
||||
public class ShipMasterService : ApplicationService
|
||||
{
|
||||
private IShipMasterRepository MasterRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IShipMasterRepository>();
|
||||
private IShipMasterItemRepository MasterItemRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IShipMasterItemRepository>();
|
||||
private IShipBagRepository BagRepository => LazyServiceProvider.GetRequiredService<IShipBagRepository>();
|
||||
private IShipBagItemRepository BagItemRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IShipBagItemRepository>();
|
||||
private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService<IOrderRepository>();
|
||||
private ILabelTemplateRepository LabelTemplateRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ILabelTemplateRepository>();
|
||||
private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService<ILabelPdfRenderer>();
|
||||
private IObjectStorage FileStorage => LazyServiceProvider.GetRequiredService<IObjectStorage>();
|
||||
private IWarehouseAddressRepository WarehouseAddressRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 创建内部主单(打板中)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/create")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> CreateAsync(CreateShipMasterInput input)
|
||||
{
|
||||
var entity = new ShipMaster
|
||||
{
|
||||
MasterNo = await NextMasterNoAsync(),
|
||||
Status = ShipMasterStatusCodes.Open,
|
||||
WarehouseId = input.WarehouseId,
|
||||
DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant(),
|
||||
DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim(),
|
||||
FlightOrVoyage = string.IsNullOrWhiteSpace(input.FlightOrVoyage)
|
||||
? null
|
||||
: input.FlightOrVoyage.Trim(),
|
||||
ExternalMawb = string.IsNullOrWhiteSpace(input.ExternalMawb) ? null : input.ExternalMawb.Trim(),
|
||||
Length = input.Length,
|
||||
Width = input.Width,
|
||||
Height = input.Height,
|
||||
Weight = input.Weight,
|
||||
Remark = input.Remark?.Trim(),
|
||||
};
|
||||
var saved = await MasterRepository.InsertAsync(entity);
|
||||
return MapMaster(saved);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新主单件重尺、目的口岸等属性(已交运/作废不可改)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/update-meta")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> UpdateMetaAsync(UpdateShipMasterMetaInput input)
|
||||
{
|
||||
var master = await RequireMasterAsync(input.MasterNo);
|
||||
if (master.Status is ShipMasterStatusCodes.Handed or ShipMasterStatusCodes.Voided)
|
||||
{
|
||||
throw new BusinessException("已交运或已作废的主单不可改属性");
|
||||
}
|
||||
|
||||
master.DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
|
||||
? null
|
||||
: input.DestinationCountry.Trim().ToUpperInvariant();
|
||||
master.DestinationPort = string.IsNullOrWhiteSpace(input.DestinationPort)
|
||||
? null
|
||||
: input.DestinationPort.Trim();
|
||||
master.FlightOrVoyage = string.IsNullOrWhiteSpace(input.FlightOrVoyage)
|
||||
? null
|
||||
: input.FlightOrVoyage.Trim();
|
||||
master.Length = input.Length;
|
||||
master.Width = input.Width;
|
||||
master.Height = input.Height;
|
||||
master.Weight = input.Weight;
|
||||
master.Remark = input.Remark?.Trim();
|
||||
await MasterRepository.UpdateAsync(master);
|
||||
return await GetDetailAsync(master.MasterNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扫已封/已出库大包上板。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/add-bag")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> AddBagAsync(ShipMasterAddBagInput input)
|
||||
{
|
||||
var master = await RequireOpenMasterAsync(input.MasterNo);
|
||||
if (string.IsNullOrWhiteSpace(input.BagNo))
|
||||
{
|
||||
throw new BusinessException("请扫描大包号");
|
||||
}
|
||||
|
||||
var bag = await BagRepository.GetByBagNoAsync(input.BagNo.Trim());
|
||||
if (bag == null)
|
||||
{
|
||||
throw new BusinessException("未找到大包");
|
||||
}
|
||||
|
||||
if (bag.Status is not (ShipBagStatusCodes.Sealed or ShipBagStatusCodes.Shipped))
|
||||
{
|
||||
throw new BusinessException("仅已封袋或已出库的大包可上主单");
|
||||
}
|
||||
|
||||
if (bag.MasterId.HasValue && bag.MasterId != master.Id)
|
||||
{
|
||||
throw new BusinessException("该大包已归属其它主单");
|
||||
}
|
||||
|
||||
var exists = (await MasterItemRepository.ListByMasterIdAsync(master.Id))
|
||||
.Any(x => x.ItemType == ShipMasterItemTypeCodes.Bag && x.BagId == bag.Id);
|
||||
if (exists)
|
||||
{
|
||||
throw new BusinessException("该大包已在本主单中");
|
||||
}
|
||||
|
||||
await MasterItemRepository.InsertAsync(
|
||||
new ShipMasterItem
|
||||
{
|
||||
MasterId = master.Id,
|
||||
ItemType = ShipMasterItemTypeCodes.Bag,
|
||||
BagId = bag.Id,
|
||||
BagNo = bag.BagNo,
|
||||
});
|
||||
|
||||
bag.MasterId = master.Id;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
|
||||
var bagItems = await BagItemRepository.ListByBagIdAsync(bag.Id);
|
||||
foreach (var bi in bagItems)
|
||||
{
|
||||
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == bi.OrderId);
|
||||
if (order == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
order.ShipMasterId = master.Id;
|
||||
order.ShipMasterNo = master.MasterNo;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
}
|
||||
|
||||
await RefreshMasterCountsAsync(master);
|
||||
return await GetDetailAsync(master.MasterNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 扫散货小包上板(跳过大包;建议已出库)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/add-parcel")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> AddParcelAsync(ShipMasterAddParcelInput input)
|
||||
{
|
||||
var master = await RequireOpenMasterAsync(input.MasterNo);
|
||||
if (string.IsNullOrWhiteSpace(input.WaybillNo))
|
||||
{
|
||||
throw new BusinessException("请扫描运单号");
|
||||
}
|
||||
|
||||
var order = await OrderRepository.GetByWaybillNoAsync(input.WaybillNo.Trim());
|
||||
if (order == null)
|
||||
{
|
||||
throw new BusinessException("未找到订单");
|
||||
}
|
||||
|
||||
// 大货:已出库可上主单;仍在待发货也可上(仅归集,不作出库门禁)
|
||||
if (order.OrderStatus is OrderStatusCodes.Draft or OrderStatusCodes.Deleted)
|
||||
{
|
||||
throw new BusinessException("草稿/已删除运单不能上主单");
|
||||
}
|
||||
|
||||
if (order.ShipMasterId.HasValue && order.ShipMasterId != master.Id)
|
||||
{
|
||||
throw new BusinessException("该运单已归属其它主单");
|
||||
}
|
||||
|
||||
var exists = (await MasterItemRepository.ListByMasterIdAsync(master.Id))
|
||||
.Any(x => x.ItemType == ShipMasterItemTypeCodes.Parcel && x.OrderId == order.Id);
|
||||
if (exists)
|
||||
{
|
||||
throw new BusinessException("该运单已在本主单中");
|
||||
}
|
||||
|
||||
await MasterItemRepository.InsertAsync(
|
||||
new ShipMasterItem
|
||||
{
|
||||
MasterId = master.Id,
|
||||
ItemType = ShipMasterItemTypeCodes.Parcel,
|
||||
OrderId = order.Id,
|
||||
WaybillNo = order.ServiceNo,
|
||||
});
|
||||
|
||||
order.ShipMasterId = master.Id;
|
||||
order.ShipMasterNo = master.MasterNo;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
|
||||
await RefreshMasterCountsAsync(master);
|
||||
return await GetDetailAsync(master.MasterNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从主单移除一条明细(仅打板中)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/remove-item")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> RemoveItemAsync(ShipMasterRemoveItemInput input)
|
||||
{
|
||||
var master = await RequireOpenMasterAsync(input.MasterNo);
|
||||
var items = await MasterItemRepository.ListByMasterIdAsync(master.Id);
|
||||
var item = items.FirstOrDefault(x => x.Id == input.ItemId);
|
||||
if (item == null)
|
||||
{
|
||||
throw new BusinessException("明细不存在");
|
||||
}
|
||||
|
||||
if (item.ItemType == ShipMasterItemTypeCodes.Bag && item.BagId.HasValue)
|
||||
{
|
||||
var bag = await BagRepository.FirstOrDefaultAsync(x => x.Id == item.BagId.Value);
|
||||
if (bag != null && bag.MasterId == master.Id)
|
||||
{
|
||||
bag.MasterId = null;
|
||||
await BagRepository.UpdateAsync(bag);
|
||||
}
|
||||
|
||||
var bagItems = await BagItemRepository.ListByBagIdAsync(item.BagId.Value);
|
||||
foreach (var bi in bagItems)
|
||||
{
|
||||
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == bi.OrderId);
|
||||
if (order?.ShipMasterId == master.Id)
|
||||
{
|
||||
order.ShipMasterId = null;
|
||||
order.ShipMasterNo = null;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (item.OrderId.HasValue)
|
||||
{
|
||||
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == item.OrderId.Value);
|
||||
if (order?.ShipMasterId == master.Id)
|
||||
{
|
||||
order.ShipMasterId = null;
|
||||
order.ShipMasterNo = null;
|
||||
await OrderRepository.UpdateAsync(order);
|
||||
}
|
||||
}
|
||||
|
||||
await MasterItemRepository.DeleteAsync(item);
|
||||
await RefreshMasterCountsAsync(master);
|
||||
return await GetDetailAsync(master.MasterNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 封板。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/seal")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> SealAsync(ShipMasterNoInput input)
|
||||
{
|
||||
var master = await RequireMasterAsync(input.MasterNo);
|
||||
if (master.Status != ShipMasterStatusCodes.Open)
|
||||
{
|
||||
throw new BusinessException("仅打板中的主单可封板");
|
||||
}
|
||||
|
||||
var items = await MasterItemRepository.ListByMasterIdAsync(master.Id);
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new BusinessException("空主单不能封板");
|
||||
}
|
||||
|
||||
master.Status = ShipMasterStatusCodes.Sealed;
|
||||
master.SealTime = DateTime.Now;
|
||||
await MasterRepository.UpdateAsync(master);
|
||||
return await GetDetailAsync(master.MasterNo);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 绑定或修改外部 MAWB(交运前)。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/bind-mawb")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> BindMawbAsync(ShipMasterBindMawbInput input)
|
||||
{
|
||||
var master = await RequireMasterAsync(input.MasterNo);
|
||||
if (master.Status == ShipMasterStatusCodes.Handed)
|
||||
{
|
||||
throw new BusinessException("已交运主单不可改 MAWB,请走换绑流程(二期)");
|
||||
}
|
||||
|
||||
if (master.Status == ShipMasterStatusCodes.Voided)
|
||||
{
|
||||
throw new BusinessException("已作废主单不可绑定");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(input.ExternalMawb))
|
||||
{
|
||||
throw new BusinessException("请填写外部 MAWB/提单号");
|
||||
}
|
||||
|
||||
master.ExternalMawb = input.ExternalMawb.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(input.FlightOrVoyage))
|
||||
{
|
||||
master.FlightOrVoyage = input.FlightOrVoyage.Trim();
|
||||
}
|
||||
|
||||
await MasterRepository.UpdateAsync(master);
|
||||
return MapMaster(master);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 交运确认。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/hand-over")]
|
||||
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
|
||||
public async Task<ShipMasterOutput> HandOverAsync(ShipMasterNoInput input)
|
||||
{
|
||||
var master = await RequireMasterAsync(input.MasterNo);
|
||||
if (master.Status != ShipMasterStatusCodes.Sealed)
|
||||
{
|
||||
throw new BusinessException("仅已封板主单可交运");
|
||||
}
|
||||
|
||||
master.Status = ShipMasterStatusCodes.Handed;
|
||||
master.HandTime = DateTime.Now;
|
||||
await MasterRepository.UpdateAsync(master);
|
||||
return MapMaster(master);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主单详情。
|
||||
/// </summary>
|
||||
[HttpGet("/operation/master/get")]
|
||||
public async Task<ShipMasterOutput> GetAsync([FromQuery] string masterNo) =>
|
||||
await GetDetailAsync(masterNo);
|
||||
|
||||
/// <summary>
|
||||
/// 主单分页。
|
||||
/// </summary>
|
||||
[HttpPost("/operation/master/page")]
|
||||
public async Task<OmsPageResult<ShipMasterOutput>> PageAsync([FromBody] ShipMasterPageInput input)
|
||||
{
|
||||
var pageIndex = PagingHelper.NormalizePageIndex(input.PageIndex);
|
||||
var pageSize = PagingHelper.NormalizePageSize(input.PageSize);
|
||||
var keyword = input.Keyword?.Trim();
|
||||
var status = input.Status?.Trim();
|
||||
var hasWh = input.WarehouseId.HasValue;
|
||||
var wh = input.WarehouseId.GetValueOrDefault();
|
||||
|
||||
var list = await MasterRepository.GetListAsync(x =>
|
||||
(string.IsNullOrEmpty(status) || x.Status == status)
|
||||
&& (!hasWh || x.WarehouseId == wh)
|
||||
&& (string.IsNullOrEmpty(keyword)
|
||||
|| x.MasterNo.Contains(keyword)
|
||||
|| (x.ExternalMawb != null && x.ExternalMawb.Contains(keyword))
|
||||
|| (x.DestinationCountry != null && x.DestinationCountry.Contains(keyword))));
|
||||
|
||||
var ordered = list.OrderByDescending(x => x.Id).ToList();
|
||||
var page = ordered.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(MapMaster).ToList();
|
||||
return new OmsPageResult<ShipMasterOutput> { Items = page, Total = ordered.Count };
|
||||
}
|
||||
|
||||
private async Task RefreshMasterCountsAsync(ShipMaster master)
|
||||
{
|
||||
var items = await MasterItemRepository.ListByMasterIdAsync(master.Id);
|
||||
master.BagCount = items.Count(x => x.ItemType == ShipMasterItemTypeCodes.Bag);
|
||||
var directParcels = items.Count(x => x.ItemType == ShipMasterItemTypeCodes.Parcel);
|
||||
var bagParcelCount = 0;
|
||||
foreach (var bagItem in items.Where(x => x.ItemType == ShipMasterItemTypeCodes.Bag && x.BagId.HasValue))
|
||||
{
|
||||
bagParcelCount += (await BagItemRepository.ListByBagIdAsync(bagItem.BagId!.Value)).Count;
|
||||
}
|
||||
|
||||
master.ParcelCount = directParcels + bagParcelCount;
|
||||
await MasterRepository.UpdateAsync(master);
|
||||
}
|
||||
|
||||
private async Task<ShipMasterOutput> GetDetailAsync(string masterNo)
|
||||
{
|
||||
var master = await RequireMasterAsync(masterNo);
|
||||
var output = MapMaster(master);
|
||||
var items = await MasterItemRepository.ListByMasterIdAsync(master.Id);
|
||||
output.Items = items
|
||||
.Select(x => new ShipMasterItemOutput
|
||||
{
|
||||
Id = x.Id,
|
||||
ItemType = x.ItemType,
|
||||
BagId = x.BagId,
|
||||
BagNo = x.BagNo,
|
||||
OrderId = x.OrderId,
|
||||
WaybillNo = x.WaybillNo,
|
||||
})
|
||||
.ToList();
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 批量打印主单标签:按所选模板(类型 shipMaster)渲染 PDF,返回各主单可打印 URL。
|
||||
/// </summary>
|
||||
/// <param name="input">主单号列表与可选模板 ID。</param>
|
||||
/// <returns>模板名 + 各主单 printUrl。</returns>
|
||||
[HttpPost("/operation/master/print-labels")]
|
||||
public async Task<ShipMasterPrintLabelsOutput> PrintLabelsAsync(ShipMasterPrintLabelsInput input)
|
||||
{
|
||||
var masterNos = (input.MasterNos ?? [])
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x))
|
||||
.Select(x => x.Trim())
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
if (masterNos.Count == 0)
|
||||
{
|
||||
throw new BusinessException("请选择要打印的主单");
|
||||
}
|
||||
|
||||
var template = await ResolveLabelTemplateAsync(LabelTemplateTypeCodes.ShipMaster, input.LabelTemplateId);
|
||||
var masters = await MasterRepository.GetListAsync(x => masterNos.Contains(x.MasterNo));
|
||||
if (masters.Count == 0)
|
||||
{
|
||||
throw new BusinessException("未找到可打印的主单");
|
||||
}
|
||||
|
||||
var masterMap = masters.ToDictionary(x => x.MasterNo, StringComparer.OrdinalIgnoreCase);
|
||||
var warehouseIds = masters.Where(x => x.WarehouseId is > 0).Select(x => x.WarehouseId!.Value).Distinct().ToArray();
|
||||
var warehouses = warehouseIds.Length == 0
|
||||
? []
|
||||
: await WarehouseAddressRepository.GetListAsync(x => warehouseIds.Contains(x.Id));
|
||||
var warehouseMap = warehouses.ToDictionary(x => x.Id);
|
||||
var operatorName = CurrentUser?.UserName;
|
||||
var printTime = DateTime.Now;
|
||||
var pageCount = masterNos.Count(x => masterMap.ContainsKey(x));
|
||||
var pageIndex = 0;
|
||||
var items = new List<ShipMasterPrintLabelItemOutput>();
|
||||
|
||||
foreach (var masterNo in masterNos)
|
||||
{
|
||||
if (!masterMap.TryGetValue(masterNo, out var master))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
pageIndex++;
|
||||
string? warehouseName = null;
|
||||
if (master.WarehouseId is > 0 && warehouseMap.TryGetValue(master.WarehouseId.Value, out var wh))
|
||||
{
|
||||
warehouseName = wh.WarehouseName;
|
||||
}
|
||||
|
||||
var printData = ShipMasterLabelPrintDataBuilder.Build(
|
||||
master,
|
||||
warehouseName: warehouseName,
|
||||
operatorName: operatorName,
|
||||
printTime: printTime,
|
||||
pageIndex: pageIndex,
|
||||
pageCount: pageCount);
|
||||
var pdfBytes = await LabelPdfRenderer.RenderAsync(template.TemplateJson!, printData);
|
||||
var printUrl = await SaveMasterLabelPdfAsync(master.MasterNo, pdfBytes);
|
||||
items.Add(new ShipMasterPrintLabelItemOutput
|
||||
{
|
||||
MasterNo = master.MasterNo,
|
||||
PrintUrl = printUrl
|
||||
});
|
||||
}
|
||||
|
||||
if (items.Count == 0)
|
||||
{
|
||||
throw new BusinessException("未找到可打印的主单");
|
||||
}
|
||||
|
||||
return new ShipMasterPrintLabelsOutput
|
||||
{
|
||||
TemplateName = template.Name,
|
||||
Items = items
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<LabelTemplate> ResolveLabelTemplateAsync(string templateType, int? labelTemplateId)
|
||||
{
|
||||
if (labelTemplateId is > 0)
|
||||
{
|
||||
var specified = await LabelTemplateRepository.FirstOrDefaultAsync(x => x.Id == labelTemplateId.Value);
|
||||
if (specified == null)
|
||||
{
|
||||
throw new BusinessException("标签模板不存在");
|
||||
}
|
||||
|
||||
if (!string.Equals(specified.TemplateType, templateType, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException($"请选择类型为 {templateType} 的标签模板");
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(specified.TemplateJson))
|
||||
{
|
||||
throw new BusinessException("所选标签模板内容为空,请先在标签设计中保存");
|
||||
}
|
||||
|
||||
return specified;
|
||||
}
|
||||
|
||||
var templates = await LabelTemplateRepository.GetListAsync(x => x.TemplateType == templateType);
|
||||
var latest = templates
|
||||
.Where(x => !string.IsNullOrWhiteSpace(x.TemplateJson))
|
||||
.OrderByDescending(x => x.UpdateTime)
|
||||
.ThenByDescending(x => x.Id)
|
||||
.FirstOrDefault();
|
||||
if (latest == null)
|
||||
{
|
||||
throw new BusinessException($"未配置主单标签模板(类型 {templateType}),请先在标签设计中创建");
|
||||
}
|
||||
|
||||
return latest;
|
||||
}
|
||||
|
||||
private async Task<string> SaveMasterLabelPdfAsync(string masterNo, byte[] pdfBytes)
|
||||
{
|
||||
var safeNo = string.IsNullOrWhiteSpace(masterNo) ? "master" : masterNo.Trim();
|
||||
foreach (var c in Path.GetInvalidFileNameChars())
|
||||
{
|
||||
safeNo = safeNo.Replace(c, '_');
|
||||
}
|
||||
|
||||
var fileName = $"{safeNo}-{DateTime.Now:yyyyMMddHHmmssfff}.pdf";
|
||||
var relativeKey = $"uploads/prints/ship-master-labels/{fileName}";
|
||||
await using var stream = new MemoryStream(pdfBytes);
|
||||
var key = await FileStorage.SaveObjectAsync(stream, relativeKey, "application/pdf");
|
||||
return FileStorage.GetPublicUrl(key);
|
||||
}
|
||||
|
||||
private async Task<ShipMaster> RequireMasterAsync(string masterNo)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(masterNo))
|
||||
{
|
||||
throw new BusinessException("请输入主单号");
|
||||
}
|
||||
|
||||
var master = await MasterRepository.GetByMasterNoAsync(masterNo.Trim());
|
||||
if (master == null)
|
||||
{
|
||||
throw new BusinessException("未找到主单");
|
||||
}
|
||||
|
||||
return master;
|
||||
}
|
||||
|
||||
private async Task<ShipMaster> RequireOpenMasterAsync(string masterNo)
|
||||
{
|
||||
var master = await RequireMasterAsync(masterNo);
|
||||
if (master.Status != ShipMasterStatusCodes.Open)
|
||||
{
|
||||
throw new BusinessException("仅打板中的主单可继续装板/拆板");
|
||||
}
|
||||
|
||||
return master;
|
||||
}
|
||||
|
||||
private async Task<string> NextMasterNoAsync()
|
||||
{
|
||||
for (var i = 0; i < 8; i++)
|
||||
{
|
||||
var no = $"MBL{DateTime.Now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
|
||||
if (await MasterRepository.GetByMasterNoAsync(no) == null)
|
||||
{
|
||||
return no;
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("生成主单号失败,请重试");
|
||||
}
|
||||
|
||||
private static ShipMasterOutput MapMaster(ShipMaster m) =>
|
||||
new()
|
||||
{
|
||||
Id = m.Id,
|
||||
MasterNo = m.MasterNo,
|
||||
ExternalMawb = m.ExternalMawb,
|
||||
Status = m.Status,
|
||||
StatusName = m.Status switch
|
||||
{
|
||||
ShipMasterStatusCodes.Open => "打板中",
|
||||
ShipMasterStatusCodes.Sealed => "已封板",
|
||||
ShipMasterStatusCodes.Handed => "已交运",
|
||||
ShipMasterStatusCodes.Voided => "已作废",
|
||||
_ => m.Status,
|
||||
},
|
||||
WarehouseId = m.WarehouseId,
|
||||
DestinationCountry = m.DestinationCountry,
|
||||
DestinationPort = m.DestinationPort,
|
||||
FlightOrVoyage = m.FlightOrVoyage,
|
||||
Length = m.Length,
|
||||
Width = m.Width,
|
||||
Height = m.Height,
|
||||
Weight = m.Weight,
|
||||
BagCount = m.BagCount,
|
||||
ParcelCount = m.ParcelCount,
|
||||
SealTime = m.SealTime,
|
||||
HandTime = m.HandTime,
|
||||
Remark = m.Remark,
|
||||
CreateTime = m.CreateTime,
|
||||
};
|
||||
}
|
||||
@ -0,0 +1,156 @@
|
||||
using System.Text.Json;
|
||||
using Fake.Application;
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.RechargeAggregate.Enums;
|
||||
using Oms.Domain.RechargeAggregate.Repositories;
|
||||
|
||||
namespace Oms.Application.Services.Recharge;
|
||||
|
||||
/// <summary>
|
||||
/// 充值入账审批:通过后入账;驳回/撤回同步充值记录状态。
|
||||
/// </summary>
|
||||
[ExposeServices(typeof(IApprovalOperationHandler))]
|
||||
public class RechargeCreditApprovalHandler(
|
||||
IRechargeRecordRepository rechargeRecordRepository,
|
||||
ICustomerRepository customerRepository,
|
||||
CustomerBalanceMutator balanceMutator) : IApprovalOperationHandler, ITransientDependency
|
||||
{
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public string OperationCode => ApprovalCodes.FinanceRechargeCredit;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task ExecuteAsync(ApprovalExecutionContext context, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var recordId = ResolveRecordId(context);
|
||||
var record = await rechargeRecordRepository.FirstOrDefaultAsync(x => x.Id == recordId, cancellationToken)
|
||||
?? throw new BusinessException("充值记录不存在");
|
||||
|
||||
if (record.RechargeStatus == RechargeStatus.Approved)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (record.RechargeStatus != RechargeStatus.Pending)
|
||||
{
|
||||
throw new BusinessException("只有待审核充值记录才能入账");
|
||||
}
|
||||
|
||||
var customer = await customerRepository.FirstOrDefaultAsync(x => x.Id == record.CustomerId, cancellationToken)
|
||||
?? throw new BusinessException("客户不存在");
|
||||
|
||||
var now = DateTime.Now;
|
||||
var auditor = string.IsNullOrWhiteSpace(context.ApproverUserName)
|
||||
? (string.IsNullOrWhiteSpace(context.ApproverUserGuid)
|
||||
? context.ApproverUserId.ToString()
|
||||
: context.ApproverUserGuid)
|
||||
: context.ApproverUserName.Trim();
|
||||
|
||||
record.RechargeStatus = RechargeStatus.Approved;
|
||||
record.AuditTime = now;
|
||||
record.AuditBy = auditor;
|
||||
if (string.IsNullOrWhiteSpace(record.Remark))
|
||||
{
|
||||
record.Remark = $"审批通过 {context.InstanceNo}";
|
||||
}
|
||||
|
||||
await balanceMutator.CreditRechargeAsync(
|
||||
customer,
|
||||
record.RechargeAmount,
|
||||
record.Id,
|
||||
record.SerialNumber,
|
||||
record.Remark ?? "充值审核通过",
|
||||
cancellationToken);
|
||||
|
||||
await rechargeRecordRepository.UpdateAsync(record, cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task OnRejectedAsync(
|
||||
ApprovalExecutionContext context,
|
||||
string? comment,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await MarkTerminalAsync(context, comment, "审批驳回", cancellationToken);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task OnWithdrawnAsync(
|
||||
ApprovalExecutionContext context,
|
||||
string? comment,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
await MarkTerminalAsync(context, comment, "申请人撤回", cancellationToken);
|
||||
}
|
||||
|
||||
private async Task MarkTerminalAsync(
|
||||
ApprovalExecutionContext context,
|
||||
string? comment,
|
||||
string defaultRemark,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var recordId = ResolveRecordId(context);
|
||||
var record = await rechargeRecordRepository.FirstOrDefaultAsync(x => x.Id == recordId, cancellationToken);
|
||||
if (record == null || record.RechargeStatus != RechargeStatus.Pending)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var auditor = string.IsNullOrWhiteSpace(context.ApproverUserName)
|
||||
? (string.IsNullOrWhiteSpace(context.ApproverUserGuid)
|
||||
? context.ApproverUserId.ToString()
|
||||
: context.ApproverUserGuid)
|
||||
: context.ApproverUserName.Trim();
|
||||
|
||||
record.RechargeStatus = RechargeStatus.Rejected;
|
||||
record.AuditTime = DateTime.Now;
|
||||
record.AuditBy = auditor;
|
||||
record.Remark = string.IsNullOrWhiteSpace(comment)
|
||||
? $"{defaultRemark} {context.InstanceNo}".Trim()
|
||||
: comment.Trim();
|
||||
await rechargeRecordRepository.UpdateAsync(record, cancellationToken);
|
||||
}
|
||||
|
||||
private static int ResolveRecordId(ApprovalExecutionContext context)
|
||||
{
|
||||
if (!string.IsNullOrWhiteSpace(context.PayloadJson))
|
||||
{
|
||||
try
|
||||
{
|
||||
var payload = JsonSerializer.Deserialize<RechargeCreditPayload>(context.PayloadJson, JsonOptions);
|
||||
if (payload is { RechargeRecordId: > 0 })
|
||||
{
|
||||
return payload.RechargeRecordId;
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
// fall through BizKey
|
||||
}
|
||||
}
|
||||
|
||||
var bizKey = context.BizKey ?? string.Empty;
|
||||
var prefix = $"{ApprovalCodes.FinanceRechargeCredit}:";
|
||||
if (bizKey.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)
|
||||
&& int.TryParse(bizKey[prefix.Length..], out var id)
|
||||
&& id > 0)
|
||||
{
|
||||
return id;
|
||||
}
|
||||
|
||||
throw new BusinessException("充值审批载荷缺少记录 Id");
|
||||
}
|
||||
|
||||
private sealed class RechargeCreditPayload
|
||||
{
|
||||
public int RechargeRecordId { get; set; }
|
||||
}
|
||||
}
|
||||
@ -6,8 +6,12 @@ using MiniExcelLibs;
|
||||
using Oms.Application.Dtos.Recharge;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Fake.ObjectStorage;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
using Oms.Domain.CustomersAggregate.Repositories;
|
||||
using Oms.Domain.RechargeAggregate.Entities;
|
||||
using Oms.Domain.RechargeAggregate.Enums;
|
||||
@ -24,12 +28,15 @@ public class RechargeService : ApplicationService
|
||||
private IRechargeRecordRepository RechargeRecordRepository => LazyServiceProvider.GetRequiredService<IRechargeRecordRepository>();
|
||||
private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService<ICustomerRepository>();
|
||||
private IObjectStorage FileStorage => LazyServiceProvider.GetRequiredService<IObjectStorage>();
|
||||
private IApprovalGate ApprovalGate => LazyServiceProvider.GetRequiredService<IApprovalGate>();
|
||||
private IApprovalInstanceRepository ApprovalInstanceRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalInstanceRepository>();
|
||||
|
||||
/// <summary>
|
||||
/// 提交充值申请。
|
||||
/// 提交充值申请(经审批门面:未配置则直接入账,启用后待审批)。
|
||||
/// </summary>
|
||||
/// <param name="input">入参:multipart 表单,截图字段 rechargeScreenshot。</param>
|
||||
/// <returns>充值记录结果。</returns>
|
||||
/// <returns>充值记录结果(含审批判定与单号)。</returns>
|
||||
[HttpPost("/recharge/recharge/submit")]
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<RechargeRecordOutput> SubmitAsync([FromForm] SubmitRechargeFormInput input)
|
||||
@ -61,13 +68,56 @@ public class RechargeService : ApplicationService
|
||||
};
|
||||
|
||||
var savedEntity = await RechargeRecordRepository.InsertAsync(entity);
|
||||
|
||||
var gateResult = await ApprovalGate.CheckAndSubmitOrBypassAsync(new ApprovalSubmitRequest
|
||||
{
|
||||
OperationCode = ApprovalCodes.FinanceRechargeCredit,
|
||||
BizKey = BuildRechargeBizKey(savedEntity.Id),
|
||||
Title = $"充值入账 - {customer.CustomerCode} {customer.CustomerName}".Trim(),
|
||||
PayloadJson = OmsDocHelper.SerializeJson(new
|
||||
{
|
||||
rechargeRecordId = savedEntity.Id,
|
||||
customerId = customer.Id,
|
||||
customerCode = customer.CustomerCode,
|
||||
customerName = customer.CustomerName,
|
||||
serialNumber = savedEntity.SerialNumber,
|
||||
rechargeAmount = savedEntity.RechargeAmount,
|
||||
payType = (int)savedEntity.PayType,
|
||||
payTypeName = GetPayTypeName(savedEntity.PayType),
|
||||
remark = savedEntity.Remark,
|
||||
// 审批人查看用公网 URL;相对路径便于前端二次 resolve
|
||||
rechargeScreenshot = FileStorage.GetPublicUrl(savedEntity.RechargeScreenshot),
|
||||
rechargeScreenshotPath = savedEntity.RechargeScreenshot
|
||||
}),
|
||||
Summary = new
|
||||
{
|
||||
customer.CustomerCode,
|
||||
customer.CustomerName,
|
||||
savedEntity.SerialNumber,
|
||||
savedEntity.RechargeAmount,
|
||||
payTypeName = GetPayTypeName(savedEntity.PayType)
|
||||
}
|
||||
});
|
||||
|
||||
if (gateResult.Decision == ApprovalGateDecision.Bypass)
|
||||
{
|
||||
await ApplyApproveCoreAsync(savedEntity, input.Remark ?? "未启用审批,已直接入账");
|
||||
savedEntity = await GetRechargeRecordOrThrowAsync(savedEntity.Id);
|
||||
}
|
||||
|
||||
var output = ObjectMapper.Map<RechargeRecord, RechargeRecordOutput>(savedEntity);
|
||||
output.RechargeScreenshot = FileStorage.GetPublicUrl(savedEntity.RechargeScreenshot);
|
||||
output.Decision = gateResult.Decision.ToString();
|
||||
output.ApprovalInstanceId = gateResult.InstanceId;
|
||||
output.ApprovalInstanceNo = gateResult.InstanceNo;
|
||||
output.Message = gateResult.Decision == ApprovalGateDecision.PendingApproval
|
||||
? $"已提交审批({gateResult.InstanceNo}),通过后入账"
|
||||
: (gateResult.Message ?? "未启用审批,已直接入账");
|
||||
return output;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审核通过充值记录。
|
||||
/// 审核通过充值记录(无在途审批实例的存量待审单;有审批单请走审批待办)。
|
||||
/// </summary>
|
||||
/// <param name="input">入参:充值审核通过参数。</param>
|
||||
/// <returns>无返回体,仅完成审核通过充值记录。</returns>
|
||||
@ -80,32 +130,12 @@ public class RechargeService : ApplicationService
|
||||
throw new BusinessException("只有待审核记录才能审核通过");
|
||||
}
|
||||
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == record.CustomerId);
|
||||
if (customer == null)
|
||||
{
|
||||
throw new BusinessException("客户不存在");
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
|
||||
record.RechargeStatus = RechargeStatus.Approved;
|
||||
record.Remark = input.Remark;
|
||||
record.AuditTime = now;
|
||||
record.AuditBy = CurrentUser.UserName;
|
||||
|
||||
var balanceMutator = LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>();
|
||||
await balanceMutator.CreditRechargeAsync(
|
||||
customer,
|
||||
record.RechargeAmount,
|
||||
record.Id,
|
||||
record.SerialNumber,
|
||||
input.Remark ?? "充值审核通过");
|
||||
|
||||
await RechargeRecordRepository.UpdateAsync(record);
|
||||
await EnsureNoPendingApprovalOrThrowAsync(record.Id);
|
||||
await ApplyApproveCoreAsync(record, input.Remark);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 驳回充值记录。
|
||||
/// 驳回充值记录(无在途审批实例的存量待审单;有审批单请走审批待办)。
|
||||
/// </summary>
|
||||
/// <param name="input">入参:充值审核驳回参数。</param>
|
||||
/// <returns>无返回体,仅完成驳回充值记录。</returns>
|
||||
@ -118,6 +148,8 @@ public class RechargeService : ApplicationService
|
||||
throw new BusinessException("只有待审核记录才能驳回");
|
||||
}
|
||||
|
||||
await EnsureNoPendingApprovalOrThrowAsync(record.Id);
|
||||
|
||||
record.RechargeStatus = RechargeStatus.Rejected;
|
||||
record.Remark = input.Remark;
|
||||
record.AuditTime = DateTime.Now;
|
||||
@ -156,7 +188,25 @@ public class RechargeService : ApplicationService
|
||||
: await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id));
|
||||
var customerMap = customers.ToDictionary(x => x.Id);
|
||||
|
||||
// 列表返回时补齐客户信息,避免前端为了展示字段额外发起关联查询。
|
||||
var pendingBizKeys = entities
|
||||
.Where(x => x.RechargeStatus == RechargeStatus.Pending)
|
||||
.Select(x => BuildRechargeBizKey(x.Id))
|
||||
.Distinct()
|
||||
.ToList();
|
||||
var approvalMap = new Dictionary<string, (int Id, string InstanceNo)>(StringComparer.OrdinalIgnoreCase);
|
||||
if (pendingBizKeys.Count > 0)
|
||||
{
|
||||
var approvals = await ApprovalInstanceRepository.GetListAsync(x =>
|
||||
x.OperationCode == ApprovalCodes.FinanceRechargeCredit
|
||||
&& pendingBizKeys.Contains(x.BizKey)
|
||||
&& x.Status == ApprovalInstanceStatus.Pending);
|
||||
foreach (var approval in approvals)
|
||||
{
|
||||
approvalMap[approval.BizKey] = (approval.Id, approval.InstanceNo);
|
||||
}
|
||||
}
|
||||
|
||||
// 列表返回时补齐客户信息与在途审批,避免前端额外关联查询。
|
||||
foreach (var entity in entities)
|
||||
{
|
||||
var output = ObjectMapper.Map<RechargeRecord, RechargeRecordPaginatedOutput>(entity);
|
||||
@ -166,9 +216,22 @@ public class RechargeService : ApplicationService
|
||||
if (customerMap.TryGetValue(entity.CustomerId, out var customer))
|
||||
{
|
||||
output.CustomerCode = customer.CustomerCode;
|
||||
output.CustomerName = customer.CustomerName;
|
||||
output.CustomerPhone = customer.Phone;
|
||||
}
|
||||
|
||||
var bizKey = BuildRechargeBizKey(entity.Id);
|
||||
if (approvalMap.TryGetValue(bizKey, out var approvalInfo))
|
||||
{
|
||||
output.ApprovalPending = true;
|
||||
output.ApprovalInstanceId = approvalInfo.Id;
|
||||
output.ApprovalInstanceNo = approvalInfo.InstanceNo;
|
||||
if (entity.RechargeStatus == RechargeStatus.Pending)
|
||||
{
|
||||
output.RechargeStatusName = "待审批";
|
||||
}
|
||||
}
|
||||
|
||||
output.UpdateTime = OmsDocHelper.NullIfDefault(entity.UpdateTime);
|
||||
items.Add(output);
|
||||
}
|
||||
@ -204,6 +267,7 @@ public class RechargeService : ApplicationService
|
||||
record.SerialNumber,
|
||||
record.CustomerId,
|
||||
CustomerCode = customerMap.TryGetValue(record.CustomerId, out var customer) ? customer.CustomerCode : null,
|
||||
CustomerName = customerMap.TryGetValue(record.CustomerId, out customer) ? customer.CustomerName : null,
|
||||
CustomerPhone = customerMap.TryGetValue(record.CustomerId, out customer) ? customer.Phone : null,
|
||||
record.RechargeTime,
|
||||
record.PayType,
|
||||
@ -254,6 +318,51 @@ public class RechargeService : ApplicationService
|
||||
return record;
|
||||
}
|
||||
|
||||
private static string BuildRechargeBizKey(int rechargeRecordId) =>
|
||||
$"{ApprovalCodes.FinanceRechargeCredit}:{rechargeRecordId}";
|
||||
|
||||
private async Task EnsureNoPendingApprovalOrThrowAsync(int rechargeRecordId)
|
||||
{
|
||||
var bizKey = BuildRechargeBizKey(rechargeRecordId);
|
||||
var pending = await ApprovalInstanceRepository.FirstOrDefaultAsync(x =>
|
||||
x.OperationCode == ApprovalCodes.FinanceRechargeCredit
|
||||
&& x.BizKey == bizKey
|
||||
&& x.Status == ApprovalInstanceStatus.Pending);
|
||||
if (pending != null)
|
||||
{
|
||||
throw new BusinessException($"该充值已进入审批({pending.InstanceNo}),请到「审批待办」处理");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyApproveCoreAsync(RechargeRecord record, string? remark)
|
||||
{
|
||||
var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == record.CustomerId);
|
||||
if (customer == null)
|
||||
{
|
||||
throw new BusinessException("客户不存在");
|
||||
}
|
||||
|
||||
var now = DateTime.Now;
|
||||
record.RechargeStatus = RechargeStatus.Approved;
|
||||
if (!string.IsNullOrWhiteSpace(remark))
|
||||
{
|
||||
record.Remark = remark.Trim();
|
||||
}
|
||||
|
||||
record.AuditTime = now;
|
||||
record.AuditBy = CurrentUser.UserName;
|
||||
|
||||
var balanceMutator = LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>();
|
||||
await balanceMutator.CreditRechargeAsync(
|
||||
customer,
|
||||
record.RechargeAmount,
|
||||
record.Id,
|
||||
record.SerialNumber,
|
||||
record.Remark ?? "充值审核通过");
|
||||
|
||||
await RechargeRecordRepository.UpdateAsync(record);
|
||||
}
|
||||
|
||||
private async Task<string> GenerateSerialNumberAsync()
|
||||
{
|
||||
for (var i = 0; i < 5; i++)
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
using System.Linq.Expressions;
|
||||
using Fake.Application;
|
||||
using Fake.ObjectStorage;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Dtos.System;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.SystemAggregate.Consts;
|
||||
using Oms.Domain.SystemAggregate.Entities;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
@ -17,10 +19,14 @@ namespace Oms.Application.Services.System;
|
||||
public class SystemOtherConfigService : ApplicationService
|
||||
{
|
||||
private const string SecretMask = "******";
|
||||
private const string PaymentQrChannelAlipay = "alipay";
|
||||
private const string PaymentQrChannelWechat = "wechat";
|
||||
|
||||
private ISystemOtherConfigRepository SystemOtherConfigRepository =>
|
||||
LazyServiceProvider.GetRequiredService<ISystemOtherConfigRepository>();
|
||||
|
||||
private IObjectStorage FileStorage => LazyServiceProvider.GetRequiredService<IObjectStorage>();
|
||||
|
||||
/// <summary>
|
||||
/// 查询系统其他配置列表。
|
||||
/// </summary>
|
||||
@ -140,13 +146,92 @@ public class SystemOtherConfigService : ApplicationService
|
||||
await SystemOtherConfigRepository.DeleteAsync(entity);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取客户充值用支付宝/微信收款码图片地址。未配置时对应 URL 为空(前端可回退本地默认图)。
|
||||
/// </summary>
|
||||
[HttpGet("/system/other-config/payment-qr")]
|
||||
public async Task<PaymentReceiveQrOutput> GetPaymentReceiveQrAsync()
|
||||
{
|
||||
var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr);
|
||||
return new PaymentReceiveQrOutput
|
||||
{
|
||||
AlipayUrl = FileStorage.GetPublicUrl(entity?.AppKey),
|
||||
WechatUrl = FileStorage.GetPublicUrl(entity?.Remark)
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传并替换充值收款码图片。Channel=alipay|wechat;返回最新支付宝/微信可访问 URL。
|
||||
/// </summary>
|
||||
/// <param name="input">入参:渠道 + 图片文件。</param>
|
||||
[HttpPost("/system/other-config/payment-qr/upload")]
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<PaymentReceiveQrOutput> UploadPaymentReceiveQrAsync([FromForm] PaymentReceiveQrUploadInput input)
|
||||
{
|
||||
var channel = (input.Channel ?? string.Empty).Trim().ToLowerInvariant();
|
||||
if (channel is not (PaymentQrChannelAlipay or PaymentQrChannelWechat))
|
||||
{
|
||||
throw new BusinessException("渠道仅支持 alipay 或 wechat");
|
||||
}
|
||||
|
||||
var key = await OmsFileUploadHelper.SavePaymentReceiveQrAsync(input.File, FileStorage);
|
||||
var entity = await EnsurePaymentReceiveQrConfigAsync();
|
||||
if (channel == PaymentQrChannelAlipay)
|
||||
{
|
||||
entity.AppKey = key;
|
||||
}
|
||||
else
|
||||
{
|
||||
entity.Remark = key;
|
||||
}
|
||||
|
||||
await SystemOtherConfigRepository.UpdateAsync(entity);
|
||||
return new PaymentReceiveQrOutput
|
||||
{
|
||||
AlipayUrl = FileStorage.GetPublicUrl(entity.AppKey),
|
||||
WechatUrl = FileStorage.GetPublicUrl(entity.Remark)
|
||||
};
|
||||
}
|
||||
|
||||
private async Task<SystemOtherConfig> EnsurePaymentReceiveQrConfigAsync()
|
||||
{
|
||||
var entity = await SystemOtherConfigRepository.GetByConfigCodeAsync(SystemOtherConfigCodes.PaymentReceiveQr);
|
||||
if (entity != null)
|
||||
{
|
||||
return entity;
|
||||
}
|
||||
|
||||
var deleted = await SystemOtherConfigRepository.GetByConfigCodeIncludingDeletedAsync(
|
||||
SystemOtherConfigCodes.PaymentReceiveQr);
|
||||
if (deleted != null)
|
||||
{
|
||||
deleted.IsDeleted = false;
|
||||
deleted.ConfigName = "充值收款码";
|
||||
deleted.Enabled = true;
|
||||
deleted.TimeoutSeconds = 30;
|
||||
deleted.BaseUrl = null;
|
||||
deleted.AppSecret = null;
|
||||
await SystemOtherConfigRepository.UpdateAsync(deleted);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
return await SystemOtherConfigRepository.InsertAsync(new SystemOtherConfig
|
||||
{
|
||||
ConfigCode = SystemOtherConfigCodes.PaymentReceiveQr,
|
||||
ConfigName = "充值收款码",
|
||||
Enabled = true,
|
||||
TimeoutSeconds = 30
|
||||
});
|
||||
}
|
||||
|
||||
private static Expression<Func<SystemOtherConfig, bool>> BuildListPredicate(SystemOtherConfigListInput input)
|
||||
{
|
||||
var keyword = input.Keyword?.Trim();
|
||||
return x =>
|
||||
string.IsNullOrWhiteSpace(keyword) ||
|
||||
x.ConfigCode.Contains(keyword) ||
|
||||
x.ConfigName.Contains(keyword);
|
||||
x.ConfigCode != SystemOtherConfigCodes.PaymentReceiveQr
|
||||
&& (string.IsNullOrWhiteSpace(keyword)
|
||||
|| x.ConfigCode.Contains(keyword)
|
||||
|| x.ConfigName.Contains(keyword));
|
||||
}
|
||||
|
||||
private async Task<SystemOtherConfig> GetConfigOrThrowAsync(int id)
|
||||
|
||||
@ -316,7 +316,9 @@ public static class OmsDocHelper
|
||||
|
||||
private static object? ConvertJsonElement(JsonElement element) => element.ValueKind switch
|
||||
{
|
||||
// MySQL JSON 列会重排 object key;按名字排序后再入 Dictionary,避免 sync-status 误报待发布
|
||||
JsonValueKind.Object => element.EnumerateObject()
|
||||
.OrderBy(property => property.Name, StringComparer.Ordinal)
|
||||
.ToDictionary(property => property.Name, property => ConvertJsonElement(property.Value)),
|
||||
JsonValueKind.Array => element.EnumerateArray()
|
||||
.Select(ConvertJsonElement)
|
||||
|
||||
@ -26,6 +26,9 @@ public static class OmsFileUploadHelper
|
||||
public static Task<string> SaveWarehouseParcelImageAsync(IFormFile file, IObjectStorage storage) =>
|
||||
SaveImageAsync(file, storage, "parcel", "包裹商品图片");
|
||||
|
||||
public static Task<string> SavePaymentReceiveQrAsync(IFormFile file, IObjectStorage storage) =>
|
||||
SaveImageAsync(file, storage, "payment-qr", "收款码图片");
|
||||
|
||||
private static async Task<string> SaveImageAsync(
|
||||
IFormFile? file,
|
||||
IObjectStorage storage,
|
||||
|
||||
59
src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs
Normal file
59
src/Oms.Domain/ApprovalAggregate/Consts/ApprovalCodes.cs
Normal file
@ -0,0 +1,59 @@
|
||||
namespace Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 审批相关常量。
|
||||
/// </summary>
|
||||
public static class ApprovalCodes
|
||||
{
|
||||
/// <summary>审批人类型:用户。</summary>
|
||||
public const string ApproverTypeUser = "User";
|
||||
|
||||
/// <summary>审批人类型:角色。</summary>
|
||||
public const string ApproverTypeRole = "Role";
|
||||
|
||||
/// <summary>事件:提交。</summary>
|
||||
public const string EventSubmitted = "Submitted";
|
||||
|
||||
/// <summary>事件:通过。</summary>
|
||||
public const string EventApproved = "Approved";
|
||||
|
||||
/// <summary>事件:驳回。</summary>
|
||||
public const string EventRejected = "Rejected";
|
||||
|
||||
/// <summary>事件:撤回。</summary>
|
||||
public const string EventWithdrawn = "Withdrawn";
|
||||
|
||||
/// <summary>事件:开始执行。</summary>
|
||||
public const string EventExecuting = "Executing";
|
||||
|
||||
/// <summary>事件:执行成功。</summary>
|
||||
public const string EventExecuted = "Executed";
|
||||
|
||||
/// <summary>事件:执行失败。</summary>
|
||||
public const string EventExecuteFailed = "ExecuteFailed";
|
||||
|
||||
/// <summary>模拟提交操作编码(引擎自测)。</summary>
|
||||
public const string SimOperationCode = "System.Approval.Simulate";
|
||||
|
||||
/// <summary>销售产品价格发布。</summary>
|
||||
public const string SalesProductPublishPrice = "Channel.SalesProduct.PublishPrice";
|
||||
|
||||
/// <summary>客户充值入账。</summary>
|
||||
public const string FinanceRechargeCredit = "Finance.Recharge.Credit";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批权限码。
|
||||
/// </summary>
|
||||
public static class ApprovalPermissionCodes
|
||||
{
|
||||
public const string DefinitionQuery = "System.ApprovalDefinition.Query";
|
||||
public const string DefinitionCreate = "System.ApprovalDefinition.Create";
|
||||
public const string DefinitionUpdate = "System.ApprovalDefinition.Update";
|
||||
public const string DefinitionDelete = "System.ApprovalDefinition.Delete";
|
||||
public const string DefinitionEnable = "System.ApprovalDefinition.Enable";
|
||||
|
||||
public const string TaskQuery = "System.ApprovalTask.Query";
|
||||
public const string TaskApprove = "System.ApprovalTask.Approve";
|
||||
public const string TaskReject = "System.ApprovalTask.Reject";
|
||||
}
|
||||
@ -0,0 +1,41 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批定义:按操作编码配置是否需审、条件与审批人。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_definition")]
|
||||
public class ApprovalDefinition : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>操作编码。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>操作显示名快照。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationName { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>是否启用。</summary>
|
||||
public bool IsEnabled { get; set; } = true;
|
||||
|
||||
/// <summary>触发条件公式;空表示启用即始终需审。</summary>
|
||||
[SugarColumn(Length = 2000, IsNullable = true)]
|
||||
public string? ConditionFormula { get; set; }
|
||||
|
||||
/// <summary>审批人类型:User / Role。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>候选人 ID,逗号分隔。</summary>
|
||||
[SugarColumn(Length = 2000)]
|
||||
public string ApproverIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>禁止申请人自审。</summary>
|
||||
public bool ForbidSelfApprove { get; set; } = true;
|
||||
|
||||
/// <summary>备注。</summary>
|
||||
[SugarColumn(Length = 512, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
46
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalEvent.cs
Normal file
46
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalEvent.cs
Normal file
@ -0,0 +1,46 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批事件(追加写)。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_event")]
|
||||
public class ApprovalEvent : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>审批实例 Id。</summary>
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>关联任务 Id。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? TaskId { get; set; }
|
||||
|
||||
/// <summary>事件类型。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string EventType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>变更前实例状态。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public ApprovalInstanceStatus? FromStatus { get; set; }
|
||||
|
||||
/// <summary>变更后实例状态。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public ApprovalInstanceStatus? ToStatus { get; set; }
|
||||
|
||||
/// <summary>操作人 mapId。</summary>
|
||||
public int OperatorUserId { get; set; }
|
||||
|
||||
/// <summary>操作人 Guid。</summary>
|
||||
[SugarColumn(Length = 36, IsNullable = true)]
|
||||
public string? OperatorUserGuid { get; set; }
|
||||
|
||||
/// <summary>操作人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? OperatorUserName { get; set; }
|
||||
|
||||
/// <summary>事件说明/意见。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? Message { get; set; }
|
||||
}
|
||||
@ -0,0 +1,74 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批实例。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_instance")]
|
||||
public class ApprovalInstance : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>实例单号。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string InstanceNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>操作编码。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string OperationCode { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>业务幂等键。</summary>
|
||||
[SugarColumn(Length = 128)]
|
||||
public string BizKey { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>摘要标题。</summary>
|
||||
[SugarColumn(Length = 256)]
|
||||
public string Title { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>实例状态。</summary>
|
||||
public ApprovalInstanceStatus Status { get; set; } = ApprovalInstanceStatus.Pending;
|
||||
|
||||
/// <summary>申请人 mapId。</summary>
|
||||
public int ApplicantUserId { get; set; }
|
||||
|
||||
/// <summary>申请人 RBAC Guid。</summary>
|
||||
[SugarColumn(Length = 36)]
|
||||
public string ApplicantUserGuid { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>申请人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ApplicantUserName { get; set; }
|
||||
|
||||
/// <summary>冻结业务载荷。</summary>
|
||||
[SugarColumn(ColumnDataType = "mediumtext", IsNullable = true)]
|
||||
public string? PayloadJson { get; set; }
|
||||
|
||||
/// <summary>载荷哈希。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? PayloadHash { get; set; }
|
||||
|
||||
/// <summary>展示摘要 JSON。</summary>
|
||||
[SugarColumn(Length = 2000, IsNullable = true)]
|
||||
public string? SummaryJson { get; set; }
|
||||
|
||||
/// <summary>提交时定义快照。</summary>
|
||||
[SugarColumn(ColumnDataType = "mediumtext", IsNullable = true)]
|
||||
public string? DefinitionSnapshot { get; set; }
|
||||
|
||||
/// <summary>当前任务 Id。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? CurrentTaskId { get; set; }
|
||||
|
||||
/// <summary>终审完成时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? CompletedTime { get; set; }
|
||||
|
||||
/// <summary>业务执行完成时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? ExecutedTime { get; set; }
|
||||
|
||||
/// <summary>执行结果/失败信息。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? ExecuteMessage { get; set; }
|
||||
}
|
||||
53
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalTask.cs
Normal file
53
src/Oms.Domain/ApprovalAggregate/Entities/ApprovalTask.cs
Normal file
@ -0,0 +1,53 @@
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 审批任务(一期单级仅一条进行中任务)。
|
||||
/// </summary>
|
||||
[SugarTable("t_approval_task")]
|
||||
public class ApprovalTask : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>审批实例 Id。</summary>
|
||||
public int InstanceId { get; set; }
|
||||
|
||||
/// <summary>步骤号,一期固定 1。</summary>
|
||||
public int StepNo { get; set; } = 1;
|
||||
|
||||
/// <summary>任务状态。</summary>
|
||||
public ApprovalTaskStatus Status { get; set; } = ApprovalTaskStatus.Pending;
|
||||
|
||||
/// <summary>审批人类型快照。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string ApproverType { get; set; } = "User";
|
||||
|
||||
/// <summary>配置候选人快照。</summary>
|
||||
[SugarColumn(Length = 2000)]
|
||||
public string ApproverIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>展开后的可审用户 Guid。</summary>
|
||||
[SugarColumn(Length = 4000)]
|
||||
public string CandidateUserIds { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>实际处理人 mapId。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? ActionUserId { get; set; }
|
||||
|
||||
/// <summary>实际处理人 Guid。</summary>
|
||||
[SugarColumn(Length = 36, IsNullable = true)]
|
||||
public string? ActionUserGuid { get; set; }
|
||||
|
||||
/// <summary>实际处理人显示名。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ActionUserName { get; set; }
|
||||
|
||||
/// <summary>处理时间。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public DateTime? ActionTime { get; set; }
|
||||
|
||||
/// <summary>审批意见。</summary>
|
||||
[SugarColumn(Length = 1000, IsNullable = true)]
|
||||
public string? Comment { get; set; }
|
||||
}
|
||||
58
src/Oms.Domain/ApprovalAggregate/Enums/ApprovalEnums.cs
Normal file
58
src/Oms.Domain/ApprovalAggregate/Enums/ApprovalEnums.cs
Normal file
@ -0,0 +1,58 @@
|
||||
namespace Oms.Domain.ApprovalAggregate.Enums;
|
||||
|
||||
/// <summary>
|
||||
/// 审批实例状态。
|
||||
/// </summary>
|
||||
public enum ApprovalInstanceStatus
|
||||
{
|
||||
/// <summary>待审批。</summary>
|
||||
Pending = 1,
|
||||
|
||||
/// <summary>已通过(待/正在执行业务)。</summary>
|
||||
Approved = 2,
|
||||
|
||||
/// <summary>已驳回。</summary>
|
||||
Rejected = 3,
|
||||
|
||||
/// <summary>已撤回。</summary>
|
||||
Withdrawn = 4,
|
||||
|
||||
/// <summary>业务执行中。</summary>
|
||||
Executing = 5,
|
||||
|
||||
/// <summary>业务已执行成功。</summary>
|
||||
Executed = 6,
|
||||
|
||||
/// <summary>业务执行失败。</summary>
|
||||
ExecuteFailed = 7
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批任务状态。
|
||||
/// </summary>
|
||||
public enum ApprovalTaskStatus
|
||||
{
|
||||
/// <summary>待处理。</summary>
|
||||
Pending = 1,
|
||||
|
||||
/// <summary>已通过。</summary>
|
||||
Approved = 2,
|
||||
|
||||
/// <summary>已驳回。</summary>
|
||||
Rejected = 3,
|
||||
|
||||
/// <summary>已取消(撤回等)。</summary>
|
||||
Cancelled = 4
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 审批人类型。
|
||||
/// </summary>
|
||||
public enum ApprovalApproverType
|
||||
{
|
||||
/// <summary>指定用户(RBAC Guid)。</summary>
|
||||
User = 1,
|
||||
|
||||
/// <summary>指定角色(RBAC Role Guid)。</summary>
|
||||
Role = 2
|
||||
}
|
||||
@ -0,0 +1,20 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.ApprovalAggregate.Repositories;
|
||||
|
||||
public interface IApprovalDefinitionRepository : IRepository<ApprovalDefinition>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalInstanceRepository : IRepository<ApprovalInstance>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalTaskRepository : IRepository<ApprovalTask>
|
||||
{
|
||||
}
|
||||
|
||||
public interface IApprovalEventRepository : IRepository<ApprovalEvent>
|
||||
{
|
||||
}
|
||||
@ -22,4 +22,10 @@ public static class LabelTemplateTypeCodes
|
||||
|
||||
/// <summary>箱唛标签(入库预报按箱打印)。</summary>
|
||||
public const string Box = "box";
|
||||
|
||||
/// <summary>出库大包标签。</summary>
|
||||
public const string ShipBag = "shipBag";
|
||||
|
||||
/// <summary>内部主单标签。</summary>
|
||||
public const string ShipMaster = "shipMaster";
|
||||
}
|
||||
|
||||
@ -0,0 +1,28 @@
|
||||
namespace Oms.Domain.OperationsAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 大包状态。
|
||||
/// </summary>
|
||||
public static class ShipBagStatusCodes
|
||||
{
|
||||
/// <summary>装袋中。</summary>
|
||||
public const string Open = "open";
|
||||
|
||||
/// <summary>已封袋。</summary>
|
||||
public const string Sealed = "sealed";
|
||||
|
||||
/// <summary>已出库(袋内小包已出库)。</summary>
|
||||
public const string Shipped = "shipped";
|
||||
|
||||
/// <summary>作废。</summary>
|
||||
public const string Voided = "voided";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 大包类型。
|
||||
/// </summary>
|
||||
public static class ShipBagTypeCodes
|
||||
{
|
||||
public const string Sack = "sack";
|
||||
public const string Box = "box";
|
||||
}
|
||||
@ -0,0 +1,28 @@
|
||||
namespace Oms.Domain.OperationsAggregate.Consts;
|
||||
|
||||
/// <summary>
|
||||
/// 内部主单状态。
|
||||
/// </summary>
|
||||
public static class ShipMasterStatusCodes
|
||||
{
|
||||
/// <summary>打板中。</summary>
|
||||
public const string Open = "open";
|
||||
|
||||
/// <summary>已封板。</summary>
|
||||
public const string Sealed = "sealed";
|
||||
|
||||
/// <summary>已交运。</summary>
|
||||
public const string Handed = "handed";
|
||||
|
||||
/// <summary>作废。</summary>
|
||||
public const string Voided = "voided";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主单明细类型。
|
||||
/// </summary>
|
||||
public static class ShipMasterItemTypeCodes
|
||||
{
|
||||
public const string Bag = "bag";
|
||||
public const string Parcel = "parcel";
|
||||
}
|
||||
63
src/Oms.Domain/OperationsAggregate/Entities/ShipBag.cs
Normal file
63
src/Oms.Domain/OperationsAggregate/Entities/ShipBag.cs
Normal file
@ -0,0 +1,63 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 出库大包(麻袋/箱子)。小包可无大包。
|
||||
/// </summary>
|
||||
[SugarTable("t_ship_bag")]
|
||||
public class ShipBag : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>大包号。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string BagNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>sack / box。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string BagType { get; set; } = "sack";
|
||||
|
||||
/// <summary>open / sealed / shipped / voided。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string Status { get; set; } = "open";
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 8, IsNullable = true)]
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ChannelCode { get; set; }
|
||||
|
||||
/// <summary>长(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
/// <summary>宽(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
/// <summary>高(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
/// <summary>重量(kg)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public int ParcelCount { get; set; }
|
||||
|
||||
public DateTime? SealTime { get; set; }
|
||||
|
||||
public DateTime? ShipTime { get; set; }
|
||||
|
||||
/// <summary>归属内部主单,可空。</summary>
|
||||
public int? MasterId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 512, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
18
src/Oms.Domain/OperationsAggregate/Entities/ShipBagItem.cs
Normal file
18
src/Oms.Domain/OperationsAggregate/Entities/ShipBagItem.cs
Normal file
@ -0,0 +1,18 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 大包内小包明细。
|
||||
/// </summary>
|
||||
[SugarTable("t_ship_bag_item")]
|
||||
public class ShipBagItem : OmsAuditedAggregateRoot
|
||||
{
|
||||
public int BagId { get; set; }
|
||||
|
||||
public int OrderId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64)]
|
||||
public string WaybillNo { get; set; } = string.Empty;
|
||||
}
|
||||
62
src/Oms.Domain/OperationsAggregate/Entities/ShipMaster.cs
Normal file
62
src/Oms.Domain/OperationsAggregate/Entities/ShipMaster.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 内部主单;可绑定外部 MAWB。小包可无主单。
|
||||
/// </summary>
|
||||
[SugarTable("t_ship_master")]
|
||||
public class ShipMaster : OmsAuditedAggregateRoot
|
||||
{
|
||||
/// <summary>内部主单号。</summary>
|
||||
[SugarColumn(Length = 32)]
|
||||
public string MasterNo { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>外部 MAWB/提单号,可后补。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? ExternalMawb { get; set; }
|
||||
|
||||
/// <summary>open / sealed / handed / voided。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string Status { get; set; } = "open";
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 8, IsNullable = true)]
|
||||
public string? DestinationCountry { get; set; }
|
||||
|
||||
/// <summary>目的口岸。</summary>
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? DestinationPort { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? FlightOrVoyage { get; set; }
|
||||
|
||||
/// <summary>长(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Length { get; set; }
|
||||
|
||||
/// <summary>宽(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Width { get; set; }
|
||||
|
||||
/// <summary>高(cm)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Height { get; set; }
|
||||
|
||||
/// <summary>重量(kg)。</summary>
|
||||
[SugarColumn(DecimalDigits = 2, IsNullable = true)]
|
||||
public decimal? Weight { get; set; }
|
||||
|
||||
public int BagCount { get; set; }
|
||||
|
||||
public int ParcelCount { get; set; }
|
||||
|
||||
public DateTime? SealTime { get; set; }
|
||||
|
||||
public DateTime? HandTime { get; set; }
|
||||
|
||||
[SugarColumn(Length = 512, IsNullable = true)]
|
||||
public string? Remark { get; set; }
|
||||
}
|
||||
@ -0,0 +1,27 @@
|
||||
using Oms.Domain.Shared;
|
||||
using SqlSugar;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
/// <summary>
|
||||
/// 主单明细:大包或散货小包。
|
||||
/// </summary>
|
||||
[SugarTable("t_ship_master_item")]
|
||||
public class ShipMasterItem : OmsAuditedAggregateRoot
|
||||
{
|
||||
public int MasterId { get; set; }
|
||||
|
||||
/// <summary>bag / parcel。</summary>
|
||||
[SugarColumn(Length = 16)]
|
||||
public string ItemType { get; set; } = string.Empty;
|
||||
|
||||
public int? BagId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 32, IsNullable = true)]
|
||||
public string? BagNo { get; set; }
|
||||
|
||||
public int? OrderId { get; set; }
|
||||
|
||||
[SugarColumn(Length = 64, IsNullable = true)]
|
||||
public string? WaybillNo { get; set; }
|
||||
}
|
||||
@ -0,0 +1,16 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Repositories;
|
||||
|
||||
public interface IShipBagRepository : IRepository<ShipBag>
|
||||
{
|
||||
Task<ShipBag?> GetByBagNoAsync(string bagNo, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface IShipBagItemRepository : IRepository<ShipBagItem>
|
||||
{
|
||||
Task<List<ShipBagItem>> ListByBagIdAsync(int bagId, CancellationToken cancellationToken = default);
|
||||
|
||||
Task<ShipBagItem?> FindActiveByOrderIdAsync(int orderId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -0,0 +1,14 @@
|
||||
using Fake.Domain.Repositories;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
|
||||
namespace Oms.Domain.OperationsAggregate.Repositories;
|
||||
|
||||
public interface IShipMasterRepository : IRepository<ShipMaster>
|
||||
{
|
||||
Task<ShipMaster?> GetByMasterNoAsync(string masterNo, CancellationToken cancellationToken = default);
|
||||
}
|
||||
|
||||
public interface IShipMasterItemRepository : IRepository<ShipMasterItem>
|
||||
{
|
||||
Task<List<ShipMasterItem>> ListByMasterIdAsync(int masterId, CancellationToken cancellationToken = default);
|
||||
}
|
||||
@ -127,6 +127,22 @@ public class Order : OmsAuditedAggregateRoot
|
||||
|
||||
public int? WarehouseId { get; set; }
|
||||
|
||||
/// <summary>当前大包 Id,可空(不强制装袋)。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? ShipBagId { get; set; }
|
||||
|
||||
/// <summary>当前大包号,可空。</summary>
|
||||
[SugarColumn(Length = 32, IsNullable = true)]
|
||||
public string? ShipBagNo { get; set; }
|
||||
|
||||
/// <summary>当前内部主单 Id,可空(不强制上主单)。</summary>
|
||||
[SugarColumn(IsNullable = true)]
|
||||
public int? ShipMasterId { get; set; }
|
||||
|
||||
/// <summary>当前内部主单号,可空。</summary>
|
||||
[SugarColumn(Length = 32, IsNullable = true)]
|
||||
public string? ShipMasterNo { get; set; }
|
||||
|
||||
public int? CustomerId { get; set; }
|
||||
|
||||
/// <summary>下单时代理快照(跟主客户 AgentId)。</summary>
|
||||
|
||||
@ -59,4 +59,9 @@ public static class SystemOtherConfigCodes
|
||||
/// 国内揽收服务商推送件重尺/费用(历史配置;鉴权已改由 itfx 上游应用完成,OMS 不再校验 AppKey)。
|
||||
/// </summary>
|
||||
public const string PickupOpenApi = "pickup_open_api";
|
||||
|
||||
/// <summary>
|
||||
/// 客户充值收款码(AppKey=支付宝收款码 object key,Remark=微信收款码 object key)。
|
||||
/// </summary>
|
||||
public const string PaymentReceiveQr = "payment_receive_qr";
|
||||
}
|
||||
|
||||
30
src/Oms.SqlSugarCore/Approval/ApprovalRepositories.cs
Normal file
30
src/Oms.SqlSugarCore/Approval/ApprovalRepositories.cs
Normal file
@ -0,0 +1,30 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.ApprovalAggregate.Entities;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Approval;
|
||||
|
||||
public class ApprovalDefinitionRepository : OmsSqlSugarRepository<ApprovalDefinition>,
|
||||
IApprovalDefinitionRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalInstanceRepository : OmsSqlSugarRepository<ApprovalInstance>,
|
||||
IApprovalInstanceRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalTaskRepository : OmsSqlSugarRepository<ApprovalTask>,
|
||||
IApprovalTaskRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
|
||||
public class ApprovalEventRepository : OmsSqlSugarRepository<ApprovalEvent>,
|
||||
IApprovalEventRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
}
|
||||
24
src/Oms.SqlSugarCore/Operations/ShipBagRepository.cs
Normal file
24
src/Oms.SqlSugarCore/Operations/ShipBagRepository.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
using Oms.Domain.OperationsAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Operations;
|
||||
|
||||
public class ShipBagRepository : OmsSqlSugarRepository<ShipBag>, IShipBagRepository, IScopedDependency
|
||||
{
|
||||
public Task<ShipBag?> GetByBagNoAsync(string bagNo, CancellationToken cancellationToken = default) =>
|
||||
FirstOrDefaultAsync(x => x.BagNo == bagNo, cancellationToken);
|
||||
}
|
||||
|
||||
public class ShipBagItemRepository : OmsSqlSugarRepository<ShipBagItem>, IShipBagItemRepository, IScopedDependency
|
||||
{
|
||||
public async Task<List<ShipBagItem>> ListByBagIdAsync(int bagId, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var list = await GetListAsync(x => x.BagId == bagId);
|
||||
return list.OrderBy(x => x.Id).ToList();
|
||||
}
|
||||
|
||||
public Task<ShipBagItem?> FindActiveByOrderIdAsync(int orderId, CancellationToken cancellationToken = default) =>
|
||||
FirstOrDefaultAsync(x => x.OrderId == orderId, cancellationToken);
|
||||
}
|
||||
27
src/Oms.SqlSugarCore/Operations/ShipMasterRepository.cs
Normal file
27
src/Oms.SqlSugarCore/Operations/ShipMasterRepository.cs
Normal file
@ -0,0 +1,27 @@
|
||||
using Fake.DependencyInjection;
|
||||
using Oms.Domain.OperationsAggregate.Entities;
|
||||
using Oms.Domain.OperationsAggregate.Repositories;
|
||||
using Oms.SqlSugarCore.Repositories;
|
||||
|
||||
namespace Oms.SqlSugarCore.Operations;
|
||||
|
||||
public class ShipMasterRepository : OmsSqlSugarRepository<ShipMaster>, IShipMasterRepository, IScopedDependency
|
||||
{
|
||||
public Task<ShipMaster?> GetByMasterNoAsync(string masterNo, CancellationToken cancellationToken = default) =>
|
||||
FirstOrDefaultAsync(x => x.MasterNo == masterNo, cancellationToken);
|
||||
}
|
||||
|
||||
public class ShipMasterItemRepository
|
||||
: OmsSqlSugarRepository<ShipMasterItem>,
|
||||
IShipMasterItemRepository,
|
||||
IScopedDependency
|
||||
{
|
||||
public async Task<List<ShipMasterItem>> ListByMasterIdAsync(
|
||||
int masterId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = cancellationToken;
|
||||
var list = await GetListAsync(x => x.MasterId == masterId);
|
||||
return list.OrderBy(x => x.Id).ToList();
|
||||
}
|
||||
}
|
||||
@ -201,6 +201,75 @@ public class OmsDocHelperTests
|
||||
liveHash.Should().NotContain("0.0000");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void HashSalesProductPriceSnapshotForSync_ShouldIgnoreJsonObjectKeyOrder()
|
||||
{
|
||||
// LIVE 明细原文 key 顺序 vs MySQL JSON 列重排后的顺序
|
||||
var live = """
|
||||
{
|
||||
"salesProductId": 8,
|
||||
"priceAreaRefs": [],
|
||||
"prices": [
|
||||
{
|
||||
"id": 13,
|
||||
"serialNumber": 1,
|
||||
"status": 2,
|
||||
"priceName": "运费",
|
||||
"costItem": "freight",
|
||||
"costUnit": "kg",
|
||||
"currency": "CNY",
|
||||
"factors": [],
|
||||
"details": [
|
||||
{
|
||||
"id": 1511,
|
||||
"priceId": 13,
|
||||
"factorValuesJson": { "仓库": "2", "重量": "(0-0.5]" },
|
||||
"calculationFormula": "total",
|
||||
"calculatedValue": 10,
|
||||
"customerGroupValues": { "全部客户": 10, "VIP": 12 }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
var onlineFromMysqlJson = """
|
||||
{
|
||||
"salesProductId": 8,
|
||||
"priceAreaRefs": [],
|
||||
"prices": [
|
||||
{
|
||||
"id": 13,
|
||||
"serialNumber": 1,
|
||||
"status": 2,
|
||||
"priceName": "运费",
|
||||
"costItem": "freight",
|
||||
"costUnit": "kg",
|
||||
"currency": "CNY",
|
||||
"factors": [],
|
||||
"details": [
|
||||
{
|
||||
"id": 1511,
|
||||
"priceId": 13,
|
||||
"factorValuesJson": { "重量": "(0-0.5]", "仓库": "2" },
|
||||
"calculationFormula": "total",
|
||||
"calculatedValue": 10,
|
||||
"customerGroupValues": { "VIP": 12, "全部客户": 10 }
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
""";
|
||||
|
||||
var liveHash = OmsDocHelper.HashSalesProductPriceSnapshotForSync(
|
||||
OmsDocHelper.DeserializePriceSnapshot(live));
|
||||
var onlineHash = OmsDocHelper.HashSalesProductPriceSnapshotForSync(
|
||||
OmsDocHelper.DeserializePriceSnapshot(onlineFromMysqlJson));
|
||||
|
||||
liveHash.Should().Be(onlineHash);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DeserializeJsonObject_ShouldCoerceIntegerValuedDecimalsToLong()
|
||||
{
|
||||
|
||||
@ -0,0 +1,50 @@
|
||||
using Fake.Data.Seeding;
|
||||
using Fake.Rbac.Application.Services;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
|
||||
namespace SimpleAdmin.Api.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// 将审批权限码合并进 Admin 角色(Admin 本就全量菜单,此处便于角色管理可见/非 Admin 复用)。
|
||||
/// </summary>
|
||||
public class ApprovalRolePermissionSeedContributor(RoleService roleService) : IDataSeedContributor
|
||||
{
|
||||
public static readonly string[] Permissions =
|
||||
[
|
||||
ApprovalPermissionCodes.DefinitionQuery,
|
||||
ApprovalPermissionCodes.DefinitionCreate,
|
||||
ApprovalPermissionCodes.DefinitionUpdate,
|
||||
ApprovalPermissionCodes.DefinitionDelete,
|
||||
ApprovalPermissionCodes.DefinitionEnable,
|
||||
ApprovalPermissionCodes.TaskQuery,
|
||||
ApprovalPermissionCodes.TaskApprove,
|
||||
ApprovalPermissionCodes.TaskReject,
|
||||
"System.ApprovalDefinition",
|
||||
"System.ApprovalTask"
|
||||
];
|
||||
|
||||
public async Task SeedAsync()
|
||||
{
|
||||
var roles = await roleService.GetAllRolesAsync();
|
||||
var admin = roles.FirstOrDefault(x =>
|
||||
string.Equals(x.Code, XhsRolePermissionSeedContributor.AdminRoleCode, StringComparison.OrdinalIgnoreCase));
|
||||
if (admin == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var existing = await roleService.GetRolePermissionsAsync(admin.Id);
|
||||
var merged = existing
|
||||
.Concat(Permissions)
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
|
||||
if (merged.Count == existing.Count &&
|
||||
Permissions.All(p => existing.Contains(p, StringComparer.OrdinalIgnoreCase)))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await roleService.AssignPermissionsAsync(admin.Id, merged);
|
||||
}
|
||||
}
|
||||
11
tools/ApprovalSmoke/ApprovalSmoke.csproj
Normal file
11
tools/ApprovalSmoke/ApprovalSmoke.csproj
Normal file
@ -0,0 +1,11 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\..\src\Oms.Application\Oms.Application.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
25
tools/ApprovalSmoke/Program.cs
Normal file
25
tools/ApprovalSmoke/Program.cs
Normal file
@ -0,0 +1,25 @@
|
||||
using Fake.Application;
|
||||
using Oms.Application.Services.Approval;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
|
||||
// 无库烟测:ID 解析 + 条件求值(空工厂)
|
||||
var ids = ApprovalIdHelper.SplitIds("a, b; c,d");
|
||||
if (ids.Count != 4) throw new Exception($"SplitIds failed: {ids.Count}");
|
||||
if (!ApprovalIdHelper.ContainsId("a,b,c", "B")) throw new Exception("ContainsId case failed");
|
||||
|
||||
var evaluator = new ApprovalConditionEvaluator(Array.Empty<IApprovalConditionContextFactory>());
|
||||
evaluator.EnsureFormulaAllowed("System.Approval.Simulate", null);
|
||||
try
|
||||
{
|
||||
evaluator.EnsureFormulaAllowed("System.Approval.Simulate", "金额 > 1");
|
||||
throw new Exception("Simulate should reject non-empty formula");
|
||||
}
|
||||
catch (BusinessException)
|
||||
{
|
||||
// expected
|
||||
}
|
||||
|
||||
var (ok, matched, msg) = evaluator.TryTest("Finance.Recharge.Credit", null, null);
|
||||
if (!ok || !matched) throw new Exception($"empty formula should match: {msg}");
|
||||
|
||||
Console.WriteLine("ApprovalSmoke OK");
|
||||
Loading…
Reference in New Issue
Block a user