diff --git a/db.sql b/db.sql
index 074a7ba..385d306 100644
--- a/db.sql
+++ b/db.sql
@@ -1210,7 +1210,7 @@ CREATE TABLE `t_system_other_config` (
CREATE TABLE `t_wechat_notify_template` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
- `EventCode` VARCHAR(32) NOT NULL COMMENT '事件码:inbound/outbound/deliverySuccess/deliveryFailed/problematic',
+ `EventCode` VARCHAR(32) NOT NULL COMMENT '事件码:pendingPayment/inbound/outbound/deliverySuccess/deliveryFailed/problematic',
`EventName` VARCHAR(64) NOT NULL COMMENT '事件显示名',
`TemplateId` VARCHAR(128) NULL COMMENT '微信公众号模板 ID',
`UrlTemplate` VARCHAR(512) NULL COMMENT '跳转 URL 模板,支持 {baseUrl}/{orderId}/{serviceNo}',
@@ -1713,6 +1713,127 @@ CREATE TABLE `c_sku_platform_map` (
KEY `idx_c_sku_map_customer` (`CustomerId`, `SkuId`)
) COMMENT='仓储-平台SKU映射';
+CREATE TABLE `c_warehouse_rent_rate` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `RateName` VARCHAR(128) NOT NULL COMMENT '费率名称',
+ `Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' COMMENT '币种',
+ `CostUnit` VARCHAR(32) NOT NULL DEFAULT 'cbmDay' COMMENT '计费单位:cbmDay=元/CBM/天',
+ `Status` TINYINT NOT NULL DEFAULT 2 COMMENT '状态:1-禁用 2-启用',
+ `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_wh_rent_rate_status` (`Status`, `Id`)
+) COMMENT='仓租费率头';
+
+CREATE TABLE `c_warehouse_rent_rate_factor` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `RateId` INT NOT NULL COMMENT '费率头 ID → c_warehouse_rent_rate.Id',
+ `SerialNumber` INT NOT NULL DEFAULT 0 COMMENT '序号',
+ `Factor` VARCHAR(64) NOT NULL COMMENT '因素:warehouse/days/volume/customer',
+ `FactorValues` JSON NULL COMMENT '因素取值 JSON 数组',
+ `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_wh_rent_rate_factor_rate` (`RateId`, `SerialNumber`)
+) COMMENT='仓租费率计费因素';
+
+CREATE TABLE `c_warehouse_rent_rate_detail` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `RateId` INT NOT NULL COMMENT '费率头 ID → c_warehouse_rent_rate.Id',
+ `FactorValuesJson` JSON NULL COMMENT '行维度因素取值',
+ `CalculationFormula` VARCHAR(64) NOT NULL DEFAULT 'total' COMMENT '计算公式',
+ `CalculatedValue` DECIMAL(18,4) NULL COMMENT '默认单价',
+ `CustomerGroupValues` JSON 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_wh_rent_rate_detail_rate` (`RateId`, `Id`)
+) COMMENT='仓租费率价格明细';
+
+CREATE TABLE `c_warehouse_rent_lot` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `CustomerId` INT NOT NULL COMMENT '客户 ID',
+ `WarehouseId` INT NOT NULL COMMENT '仓库 ID',
+ `SkuId` INT NOT NULL COMMENT 'SKU ID',
+ `BinLocationId` INT NULL COMMENT '库位 ID',
+ `InboundTime` DATETIME NOT NULL COMMENT '入库时间(库龄起点)',
+ `RemainQty` INT NOT NULL DEFAULT 0 COMMENT '剩余数量',
+ `UnitCbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '单件体积 CBM(入库时固化)',
+ `SourceType` VARCHAR(32) NOT NULL COMMENT '来源:inbound/parcel',
+ `SourceId` INT NOT NULL DEFAULT 0 COMMENT '来源单据 ID',
+ `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_wh_rent_lot_owner` (`CustomerId`, `WarehouseId`, `SkuId`, `RemainQty`),
+ KEY `ix_wh_rent_lot_inbound` (`InboundTime`, `Id`),
+ KEY `ix_wh_rent_lot_bin` (`WarehouseId`, `BinLocationId`, `SkuId`)
+) COMMENT='仓租库龄批次';
+
+CREATE TABLE `c_warehouse_rent_bill` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `BillNo` VARCHAR(32) NOT NULL COMMENT '账单号',
+ `CustomerId` INT NOT NULL COMMENT '客户 ID',
+ `WarehouseId` INT NOT NULL COMMENT '仓库 ID',
+ `BillDate` DATE NOT NULL COMMENT '计费业务日',
+ `TotalCbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '计费总体积 CBM',
+ `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '应付金额',
+ `Currency` VARCHAR(8) NOT NULL DEFAULT 'CNY' COMMENT '币种',
+ `UnitPrice` DECIMAL(18,4) NULL COMMENT '命中单价',
+ `Status` VARCHAR(16) NOT NULL DEFAULT 'pending' COMMENT 'pending/paid/unpaid/zero',
+ `FlowId` INT NULL COMMENT '账户流水 ID',
+ `PaidTime` 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_wh_rent_bill_biz` (`CustomerId`, `WarehouseId`, `BillDate`),
+ KEY `ix_wh_rent_bill_status` (`Status`, `BillDate`),
+ KEY `ix_wh_rent_bill_no` (`BillNo`)
+) COMMENT='仓租日账单';
+
+CREATE TABLE `c_warehouse_rent_bill_line` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT '主键,自增,步长 1',
+ `BillId` INT NOT NULL COMMENT '账单 ID → c_warehouse_rent_bill.Id',
+ `LotId` INT NULL COMMENT '批次 ID',
+ `SkuId` INT NOT NULL COMMENT 'SKU ID',
+ `AgeDays` INT NOT NULL DEFAULT 0 COMMENT '库龄天数',
+ `Qty` INT NOT NULL DEFAULT 0 COMMENT '数量',
+ `Cbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT '体积 CBM',
+ `UnitPrice` DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT '单价',
+ `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT '金额(分摊)',
+ `MissingDimension` TINYINT NOT NULL DEFAULT 0 COMMENT '缺尺寸:0-否,1-是',
+ `Remark` VARCHAR(256) 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_wh_rent_bill_line_bill` (`BillId`, `Id`)
+) COMMENT='仓租日账单明细';
+
-- ---------------------------------------------------------------------------
-- 订单域 — 店铺(t_sales_*,接口阶段使用)
-- ---------------------------------------------------------------------------
diff --git a/sql/migrate_warehouse_storage_rent_20261115.sql b/sql/migrate_warehouse_storage_rent_20261115.sql
new file mode 100644
index 0000000..8465013
--- /dev/null
+++ b/sql/migrate_warehouse_storage_rent_20261115.sql
@@ -0,0 +1,204 @@
+# migrate_warehouse_storage_rent_20261115.sql
+# warehouse rent: rate / lot / daily bill (idempotent)
+# no UNIQUE KEY; uniqueness checked in application code
+
+SET @db := DATABASE();
+
+# c_warehouse_rent_rate
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_rate'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_rate` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `RateName` VARCHAR(128) NOT NULL COMMENT ''rate name'',
+ `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''currency'',
+ `CostUnit` VARCHAR(32) NOT NULL DEFAULT ''cbmDay'' COMMENT ''unit cbmDay'',
+ `Status` TINYINT NOT NULL DEFAULT 2 COMMENT ''1 disabled 2 enabled'',
+ `Remark` VARCHAR(512) NULL COMMENT ''remark'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_rate_status` (`Status`, `Id`)
+ ) COMMENT=''warehouse rent rate header''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# c_warehouse_rent_rate_factor
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_rate_factor'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_rate_factor` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `RateId` INT NOT NULL COMMENT ''rate id'',
+ `SerialNumber` INT NOT NULL DEFAULT 0 COMMENT ''serial'',
+ `Factor` VARCHAR(64) NOT NULL COMMENT ''warehouse/days/volume/customer'',
+ `FactorValues` JSON NULL COMMENT ''factor values json'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_rate_factor_rate` (`RateId`, `SerialNumber`)
+ ) COMMENT=''warehouse rent rate factors''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# c_warehouse_rent_rate_detail
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_rate_detail'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_rate_detail` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `RateId` INT NOT NULL COMMENT ''rate id'',
+ `FactorValuesJson` JSON NULL COMMENT ''row factor values'',
+ `CalculationFormula` VARCHAR(64) NOT NULL DEFAULT ''total'' COMMENT ''formula'',
+ `CalculatedValue` DECIMAL(18,4) NULL COMMENT ''default unit price'',
+ `CustomerGroupValues` JSON NULL COMMENT ''customer group prices'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_rate_detail_rate` (`RateId`, `Id`)
+ ) COMMENT=''warehouse rent rate details''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# c_warehouse_rent_lot
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_lot'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_lot` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `CustomerId` INT NOT NULL COMMENT ''customer id'',
+ `WarehouseId` INT NOT NULL COMMENT ''warehouse id'',
+ `SkuId` INT NOT NULL COMMENT ''sku id'',
+ `BinLocationId` INT NULL COMMENT ''bin location id'',
+ `InboundTime` DATETIME NOT NULL COMMENT ''inbound time'',
+ `RemainQty` INT NOT NULL DEFAULT 0 COMMENT ''remain qty'',
+ `UnitCbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT ''unit cbm'',
+ `SourceType` VARCHAR(32) NOT NULL COMMENT ''inbound/parcel'',
+ `SourceId` INT NOT NULL DEFAULT 0 COMMENT ''source id'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_lot_owner` (`CustomerId`, `WarehouseId`, `SkuId`, `RemainQty`),
+ KEY `ix_wh_rent_lot_inbound` (`InboundTime`, `Id`),
+ KEY `ix_wh_rent_lot_bin` (`WarehouseId`, `BinLocationId`, `SkuId`)
+ ) COMMENT=''warehouse rent aging lot''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# c_warehouse_rent_bill
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_bill'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_bill` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `BillNo` VARCHAR(32) NOT NULL COMMENT ''bill no'',
+ `CustomerId` INT NOT NULL COMMENT ''customer id'',
+ `WarehouseId` INT NOT NULL COMMENT ''warehouse id'',
+ `BillDate` DATE NOT NULL COMMENT ''bill date'',
+ `TotalCbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT ''total cbm'',
+ `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT ''amount'',
+ `Currency` VARCHAR(8) NOT NULL DEFAULT ''CNY'' COMMENT ''currency'',
+ `UnitPrice` DECIMAL(18,4) NULL COMMENT ''unit price'',
+ `Status` VARCHAR(16) NOT NULL DEFAULT ''pending'' COMMENT ''pending/paid/unpaid/zero'',
+ `FlowId` INT NULL COMMENT ''account flow id'',
+ `PaidTime` DATETIME NULL COMMENT ''paid time'',
+ `Remark` VARCHAR(512) NULL COMMENT ''remark'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_bill_biz` (`CustomerId`, `WarehouseId`, `BillDate`),
+ KEY `ix_wh_rent_bill_status` (`Status`, `BillDate`),
+ KEY `ix_wh_rent_bill_no` (`BillNo`)
+ ) COMMENT=''warehouse rent daily bill''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# c_warehouse_rent_bill_line
+SET @tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_bill_line'
+);
+SET @sql := IF(
+ @tbl = 0,
+ 'CREATE TABLE `c_warehouse_rent_bill_line` (
+ `Id` INT NOT NULL AUTO_INCREMENT COMMENT ''PK'',
+ `BillId` INT NOT NULL COMMENT ''bill id'',
+ `LotId` INT NULL COMMENT ''lot id'',
+ `SkuId` INT NOT NULL COMMENT ''sku id'',
+ `AgeDays` INT NOT NULL DEFAULT 0 COMMENT ''age days'',
+ `Qty` INT NOT NULL DEFAULT 0 COMMENT ''qty'',
+ `Cbm` DECIMAL(18,6) NOT NULL DEFAULT 0 COMMENT ''cbm'',
+ `UnitPrice` DECIMAL(18,4) NOT NULL DEFAULT 0 COMMENT ''unit price'',
+ `Amount` DECIMAL(18,2) NOT NULL DEFAULT 0 COMMENT ''amount'',
+ `MissingDimension` TINYINT NOT NULL DEFAULT 0 COMMENT ''missing dimension'',
+ `Remark` VARCHAR(256) NULL COMMENT ''remark'',
+ `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT ''soft delete'',
+ `ConcurrencyStamp` CHAR(36) NOT NULL DEFAULT (UUID()) COMMENT ''concurrency'',
+ `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT ''create user'',
+ `CreateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT ''create time'',
+ `UpdateUserId` INT NULL COMMENT ''update user'',
+ `UpdateTime` DATETIME NULL COMMENT ''update time'',
+ PRIMARY KEY (`Id`),
+ KEY `ix_wh_rent_bill_line_bill` (`BillId`, `Id`)
+ ) COMMENT=''warehouse rent bill lines''',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
+
+# fee_item dict seed
+SET @dict_tbl := (
+ SELECT COUNT(1) FROM information_schema.TABLES
+ WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 't_dict'
+);
+SET @sql := IF(
+ @dict_tbl > 0,
+ 'INSERT INTO `t_dict` (`DictType`, `DictSort`, `DictCode`, `DictName`, `IsDeleted`, `CreateUserId`, `CreateTime`)
+ SELECT ''fee_item'', 90, ''storageRent'', ''仓租'', 0, 0, NOW()
+ FROM DUAL
+ WHERE NOT EXISTS (
+ SELECT 1 FROM `t_dict`
+ WHERE `DictType` = ''fee_item'' AND `DictCode` = ''storageRent'' AND `IsDeleted` = 0
+ )',
+ 'SELECT 1'
+);
+PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
diff --git a/sql/migrate_wechat_order_notify_20261115.sql b/sql/migrate_wechat_order_notify_20261115.sql
index d9c1df8..9dd0e44 100644
--- a/sql/migrate_wechat_order_notify_20261115.sql
+++ b/sql/migrate_wechat_order_notify_20261115.sql
@@ -21,7 +21,7 @@ SET @sql := IF(
@tbl = 0,
'CREATE TABLE `t_wechat_notify_template` (
`Id` INT NOT NULL AUTO_INCREMENT COMMENT ''主键,自增,步长 1'',
- `EventCode` VARCHAR(32) NOT NULL COMMENT ''事件码:inbound/outbound/deliverySuccess/deliveryFailed/problematic'',
+ `EventCode` VARCHAR(32) NOT NULL COMMENT ''事件码:pendingPayment/inbound/outbound/deliverySuccess/deliveryFailed/problematic'',
`EventName` VARCHAR(64) NOT NULL COMMENT ''事件显示名'',
`TemplateId` VARCHAR(128) NULL COMMENT ''微信公众号模板 ID'',
`UrlTemplate` VARCHAR(512) NULL COMMENT ''跳转 URL 模板,支持 {baseUrl}/{orderId}/{serviceNo}'',
diff --git a/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs b/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs
new file mode 100644
index 0000000..dcac6b7
--- /dev/null
+++ b/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs
@@ -0,0 +1,153 @@
+using Oms.Application.Dtos.Channels;
+using Oms.Domain.Shared.Enums;
+
+namespace Oms.Application.Dtos.Warehouse;
+
+///
+/// 仓租费率列表查询。
+///
+public class WarehouseRentRateListInput
+{
+ /// 关键词(费率名称)。
+ public string? Keyword { get; set; }
+
+ /// 状态。
+ public EnableStatus? Status { get; set; }
+
+ /// 页码。
+ public int PageIndex { get; set; } = 1;
+
+ /// 每页条数。
+ public int PageSize { get; set; } = 50;
+}
+
+///
+/// 仓租费率保存入参。
+///
+public class WarehouseRentRateSaveInput
+{
+ /// 主键。
+ public int? Id { get; set; }
+
+ /// 费率名称。
+ public string RateName { get; set; } = string.Empty;
+
+ /// 币种,固定 CNY。
+ public string Currency { get; set; } = "CNY";
+
+ /// 计费单位。
+ public string CostUnit { get; set; } = "cbmDay";
+
+ /// 状态。
+ public EnableStatus Status { get; set; } = EnableStatus.Enabled;
+
+ /// 备注。
+ public string? Remark { get; set; }
+
+ /// 计费因素。
+ public List Factors { get; set; } = [];
+
+ /// 价格明细。
+ public List Details { get; set; } = [];
+}
+
+///
+/// 仓租费率输出。
+///
+public class WarehouseRentRateOutput
+{
+ public int Id { get; set; }
+ public string RateName { get; set; } = string.Empty;
+ public string Currency { get; set; } = "CNY";
+ public string CostUnit { get; set; } = "cbmDay";
+ public EnableStatus Status { get; set; }
+ public string? Remark { get; set; }
+ public DateTime CreateTime { get; set; }
+ public DateTime? UpdateTime { get; set; }
+ public List Factors { get; set; } = [];
+ public List Details { get; set; } = [];
+}
+
+///
+/// 仓租费率启停。
+///
+public class WarehouseRentRateToggleInput
+{
+ public int Id { get; set; }
+ public EnableStatus Status { get; set; }
+}
+
+///
+/// 仓租账单列表查询。
+///
+public class WarehouseRentBillListInput
+{
+ public int? CustomerId { get; set; }
+ public int? WarehouseId { get; set; }
+ public string? Status { get; set; }
+ public DateTime? BillDateFrom { get; set; }
+ public DateTime? BillDateTo { get; set; }
+ public string? Keyword { get; set; }
+ public int PageIndex { get; set; } = 1;
+ public int PageSize { get; set; } = 50;
+}
+
+///
+/// 仓租账单输出。
+///
+public class WarehouseRentBillOutput
+{
+ public int Id { get; set; }
+ public string BillNo { get; set; } = string.Empty;
+ public int CustomerId { get; set; }
+ public string? CustomerCode { get; set; }
+ public string? CustomerName { get; set; }
+ public int WarehouseId { get; set; }
+ public string? WarehouseName { get; set; }
+ public DateTime BillDate { get; set; }
+ public decimal TotalCbm { get; set; }
+ public decimal Amount { get; set; }
+ public string Currency { get; set; } = "CNY";
+ public decimal? UnitPrice { get; set; }
+ public string Status { get; set; } = string.Empty;
+ public int? FlowId { get; set; }
+ public DateTime? PaidTime { get; set; }
+ public string? Remark { get; set; }
+ public DateTime CreateTime { get; set; }
+ public List Lines { get; set; } = [];
+}
+
+///
+/// 仓租账单明细输出。
+///
+public class WarehouseRentBillLineOutput
+{
+ public int Id { get; set; }
+ public int? LotId { get; set; }
+ public int SkuId { get; set; }
+ public string? SkuCode { get; set; }
+ public int AgeDays { get; set; }
+ public int Qty { get; set; }
+ public decimal Cbm { get; set; }
+ public decimal UnitPrice { get; set; }
+ public decimal Amount { get; set; }
+ public bool MissingDimension { get; set; }
+ public string? Remark { get; set; }
+}
+
+///
+/// 仓租账单补扣入参。
+///
+public class WarehouseRentBillRetryPayInput
+{
+ public int Id { get; set; }
+}
+
+///
+/// 仓租日结任务触发入参(运维/手工)。
+///
+public class WarehouseRentRunBillingInput
+{
+ /// 业务日,默认昨日。
+ public DateTime? BillDate { get; set; }
+}
diff --git a/src/Oms.Application/OmsApplicationModule.cs b/src/Oms.Application/OmsApplicationModule.cs
index 2abbe0d..09bd753 100644
--- a/src/Oms.Application/OmsApplicationModule.cs
+++ b/src/Oms.Application/OmsApplicationModule.cs
@@ -77,5 +77,6 @@ public class OmsApplicationModule : FakeModule
context.Services.AddAiLlmClient();
context.Services.AddHostedService();
context.Services.AddHostedService();
+ context.Services.AddHostedService();
}
}
diff --git a/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs b/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs
index 98953bb..20a8f10 100644
--- a/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs
+++ b/src/Oms.Application/Services/Customers/CustomerAccountFlowService.cs
@@ -146,6 +146,7 @@ public class CustomerAccountFlowService : ApplicationService
CustomerAccountFlowBizTypes.CommissionWithdraw => "佣金提现",
CustomerAccountFlowBizTypes.MarketingAdjust => "营销调整",
CustomerAccountFlowBizTypes.ManualAdjust => "人工调整",
+ CustomerAccountFlowBizTypes.StorageRent => "仓租扣费",
_ => bizType
};
}
diff --git a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
index b840f5a..475d4fb 100644
--- a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs
@@ -14,6 +14,7 @@ using Oms.Domain.CustomersAggregate.Enums;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.Shared.Enums;
+using Oms.Domain.SystemAggregate.Consts;
namespace Oms.Application.Services.Orders;
@@ -1343,13 +1344,20 @@ public partial class OrderService
order.SalesProductRulesVersion = snapshotBinding.RulesVersion;
}
+ var becamePendingPayment = false;
if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase))
{
order.OrderStatus = OrderStatusCodes.PendingPayment;
+ becamePendingPayment = true;
}
order.UpdateTime = DateTime.Now;
await OrderRepository.UpdateAsync(order);
+
+ if (becamePendingPayment)
+ {
+ await WechatOrderNotifyDispatcher.TryNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
+ }
}
private static void EnsureReallocateAllowed(Order order)
diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
index 1695865..30c5b45 100644
--- a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs
@@ -30,6 +30,7 @@ using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.OrdersAggregate.Repositories;
using Oms.Domain.Shared.Enums;
+using Oms.Domain.SystemAggregate.Consts;
using Oms.Domain.SystemAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
@@ -2745,6 +2746,11 @@ public partial class OrderService
order.UpdateTime = DateTime.Now;
await OrderRepository.UpdateAsync(order);
+ if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingPayment, StringComparison.OrdinalIgnoreCase))
+ {
+ await WechatOrderNotifyDispatcher.TryNotifyAsync(order, WechatOrderNotifyEventCodes.PendingPayment);
+ }
+
if (allocated)
{
var customer = order.CustomerId.HasValue
diff --git a/src/Oms.Application/Services/Orders/OrderService.StockBind.cs b/src/Oms.Application/Services/Orders/OrderService.StockBind.cs
index 04b0668..a9abbc2 100644
--- a/src/Oms.Application/Services/Orders/OrderService.StockBind.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.StockBind.cs
@@ -35,6 +35,9 @@ public partial class OrderService
private ICBinLocationRepository StockBindBinLocationRepository =>
LazyServiceProvider.GetRequiredService();
+ private WarehouseRentLotManager StockBindRentLotManager =>
+ LazyServiceProvider.GetRequiredService();
+
///
/// 查询物流单当前仓储绑定明细。
///
@@ -475,6 +478,12 @@ public partial class OrderService
inv.FrozenQty -= bind.BindQty;
SyncInventoryAvailable(inv);
await StockBindInventoryRepository.UpdateAsync(inv);
+ await StockBindRentLotManager.DeductFifoAsync(
+ bind.CustomerId,
+ bind.WarehouseId,
+ inv.SkuId,
+ bind.BindQty,
+ inv.BinLocationId);
}
else if (bind.SkuId is > 0)
{
@@ -638,6 +647,12 @@ public partial class OrderService
row.FrozenQty -= take;
SyncInventoryAvailable(row);
await StockBindInventoryRepository.UpdateAsync(row);
+ await StockBindRentLotManager.DeductFifoAsync(
+ customerId,
+ warehouseId,
+ skuId,
+ take,
+ row.BinLocationId);
remaining -= take;
}
diff --git a/src/Oms.Application/Services/Orders/OrderService.cs b/src/Oms.Application/Services/Orders/OrderService.cs
index edb4ef4..9088641 100644
--- a/src/Oms.Application/Services/Orders/OrderService.cs
+++ b/src/Oms.Application/Services/Orders/OrderService.cs
@@ -19,7 +19,9 @@ using Newtonsoft.Json;
using Oms.Application.Messaging;
using Oms.Application.Messaging.ParcelCreate;
using Oms.Application.Services.Orders.Batch;
+using Oms.Application.Services.WeChatNotify;
using Oms.Domain.ChannelsAggregate.Repositories;
+using Oms.Domain.SystemAggregate.Consts;
using Oms.Domain.CustomersAggregate.Repositories;
using Oms.Domain.OrdersAggregate;
using Oms.Domain.OrdersAggregate.Consts;
@@ -58,6 +60,9 @@ public partial class OrderService : ApplicationService
private DataPermAccessAuditor DataPermAccessAuditor =>
LazyServiceProvider.GetRequiredService();
+ private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
+ LazyServiceProvider.GetRequiredService();
+
///
/// 查询订单列表。
///
diff --git a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs
index a6ed453..f6003f9 100644
--- a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs
+++ b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs
@@ -38,6 +38,8 @@ public class PlatformStoreOrderService : ApplicationService
private OrderService OrderService => LazyServiceProvider.GetRequiredService();
private PlatformStoreOrderFulfillmentService FulfillmentService =>
LazyServiceProvider.GetRequiredService();
+ private WarehouseRentLotManager RentLotManager =>
+ LazyServiceProvider.GetRequiredService();
///
/// 查询店铺订单列表。
@@ -922,6 +924,7 @@ public class PlatformStoreOrderService : ApplicationService
row.AvailableQty = Math.Max(0, row.Qty - row.FrozenQty);
remaining -= deduct;
await InventoryRepository.UpdateAsync(row);
+ await RentLotManager.DeductFifoAsync(customerId, warehouseId, skuId, deduct, row.BinLocationId);
deductions.Add(new InventoryDeduction(skuId, row.BinLocationId, deduct));
}
@@ -955,12 +958,22 @@ public class PlatformStoreOrderService : ApplicationService
AvailableQty = item.Qty
};
await InventoryRepository.InsertAsync(inventory);
- continue;
+ }
+ else
+ {
+ inventory.Qty += item.Qty;
+ inventory.AvailableQty = Math.Max(0, inventory.Qty - inventory.FrozenQty);
+ await InventoryRepository.UpdateAsync(inventory);
}
- inventory.Qty += item.Qty;
- inventory.AvailableQty = Math.Max(0, inventory.Qty - inventory.FrozenQty);
- await InventoryRepository.UpdateAsync(inventory);
+ await RentLotManager.AddLotAsync(
+ customerId,
+ warehouseId,
+ item.SkuId,
+ item.BinLocationId,
+ item.Qty,
+ WarehouseRentLotSourceCodes.Inbound,
+ 0);
}
}
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs b/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs
new file mode 100644
index 0000000..5bf1ef8
--- /dev/null
+++ b/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs
@@ -0,0 +1,660 @@
+using System.Linq.Expressions;
+using Fake.Application;
+using Microsoft.AspNetCore.Mvc;
+using Oms.Application.Dtos.Channels;
+using Oms.Application.Dtos.Shared;
+using Oms.Application.Dtos.Warehouse;
+using Oms.Application.Shared;
+using Oms.Domain.CustomersAggregate.Entities;
+using Oms.Domain.CustomersAggregate.Repositories;
+using Oms.Domain.Shared.Enums;
+using Oms.Domain.SystemAggregate.Repositories;
+using Oms.Domain.WarehouseAggregate.Consts;
+using Oms.Domain.WarehouseAggregate.Entities;
+using Oms.Domain.WarehouseAggregate.Repositories;
+
+namespace Oms.Application.Services.Warehouse;
+
+///
+/// 仓租费率配置与日账单 API。
+///
+[ApiExplorerSettings(GroupName = "OMS-Warehouse")]
+public class WarehouseRentService : ApplicationService
+{
+ private ICWarehouseRentRateRepository RateRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICWarehouseRentRateFactorRepository FactorRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICWarehouseRentRateDetailRepository DetailRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICWarehouseRentLotRepository LotRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICWarehouseRentBillRepository BillRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICWarehouseRentBillLineRepository BillLineRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService();
+ private ICustomerRepository CustomerRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private IWarehouseAddressRepository WarehouseAddressRepository =>
+ LazyServiceProvider.GetRequiredService();
+ private CustomerBalanceMutator BalanceMutator =>
+ LazyServiceProvider.GetRequiredService();
+
+ ///
+ /// 分页查询仓租费率。
+ ///
+ [HttpPost("/warehouse/storage-rent/rate/list")]
+ public async Task> GetRateListAsync(WarehouseRentRateListInput input)
+ {
+ var keyword = input.Keyword?.Trim();
+ var hasKeyword = !string.IsNullOrWhiteSpace(keyword);
+ var hasStatus = input.Status.HasValue && input.Status.Value != EnableStatus.None;
+ Expression> predicate = x =>
+ (!hasKeyword || x.RateName.Contains(keyword!))
+ && (!hasStatus || x.Status == input.Status!.Value);
+
+ var pageIndex = OmsDocHelper.NormalizePage(input.PageIndex);
+ var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
+ var entities = await RateRepository.GetPagedListAsync(
+ predicate,
+ pageIndex,
+ pageSize,
+ new Dictionary
+ {
+ [nameof(CWarehouseRentRate.UpdateTime)] = false,
+ [nameof(CWarehouseRentRate.Id)] = false
+ });
+ var total = await RateRepository.CountAsync(predicate);
+ return new OmsPageResult
+ {
+ Items = entities.Select(MapRateListItem).ToList(),
+ Total = total
+ };
+ }
+
+ ///
+ /// 获取仓租费率详情(含因素与价格明细)。
+ ///
+ [HttpGet("/warehouse/storage-rent/rate/get")]
+ public async Task GetRateAsync([FromQuery] int id)
+ {
+ var entity = await RateRepository.FirstOrDefaultAsync(x => x.Id == id)
+ ?? throw new BusinessException("仓租费率不存在");
+ return await MapRateDetailAsync(entity);
+ }
+
+ ///
+ /// 保存仓租费率(新增或更新)。
+ ///
+ [HttpPost("/warehouse/storage-rent/rate/save")]
+ public async Task SaveRateAsync(WarehouseRentRateSaveInput input)
+ {
+ var rateName = input.RateName?.Trim() ?? string.Empty;
+ if (string.IsNullOrWhiteSpace(rateName))
+ {
+ throw new BusinessException("费率名称不能为空");
+ }
+
+ await EnsureRateNameUniqueAsync(rateName, input.Id);
+
+ CWarehouseRentRate entity;
+ if (input.Id is > 0)
+ {
+ entity = await RateRepository.FirstOrDefaultAsync(x => x.Id == input.Id.Value)
+ ?? throw new BusinessException("仓租费率不存在");
+ }
+ else
+ {
+ entity = new CWarehouseRentRate();
+ }
+
+ entity.RateName = rateName;
+ entity.Currency = string.IsNullOrWhiteSpace(input.Currency) ? "CNY" : input.Currency.Trim().ToUpperInvariant();
+ entity.CostUnit = string.IsNullOrWhiteSpace(input.CostUnit) ? "cbmDay" : input.CostUnit.Trim();
+ entity.Status = input.Status == EnableStatus.None ? EnableStatus.Enabled : input.Status;
+ entity.Remark = string.IsNullOrWhiteSpace(input.Remark) ? null : input.Remark.Trim();
+
+ if (entity.Id > 0)
+ {
+ await RateRepository.UpdateAsync(entity);
+ await ReplaceFactorsAndDetailsAsync(entity.Id, input.Factors, input.Details);
+ }
+ else
+ {
+ await RateRepository.InsertAsync(entity);
+ await ReplaceFactorsAndDetailsAsync(entity.Id, input.Factors, input.Details);
+ }
+
+ return await MapRateDetailAsync(entity);
+ }
+
+ ///
+ /// 启停仓租费率。
+ ///
+ [HttpPost("/warehouse/storage-rent/rate/toggleStatus")]
+ public async Task ToggleRateStatusAsync(WarehouseRentRateToggleInput input)
+ {
+ var entity = await RateRepository.FirstOrDefaultAsync(x => x.Id == input.Id)
+ ?? throw new BusinessException("仓租费率不存在");
+ entity.Status = input.Status == EnableStatus.None ? EnableStatus.Disabled : input.Status;
+ await RateRepository.UpdateAsync(entity);
+ }
+
+ ///
+ /// 删除仓租费率。
+ ///
+ /// 入参:费率 Id。
+ [HttpPost("/warehouse/storage-rent/rate/delete")]
+ public async Task DeleteRateAsync(WarehouseRentRateToggleInput input)
+ {
+ var id = input.Id;
+ var entity = await RateRepository.FirstOrDefaultAsync(x => x.Id == id)
+ ?? throw new BusinessException("仓租费率不存在");
+ await RateRepository.DeleteAsync(entity);
+
+ var factors = await FactorRepository.GetListAsync(x => x.RateId == id);
+ foreach (var factor in factors)
+ {
+ await FactorRepository.DeleteAsync(factor);
+ }
+
+ var details = await DetailRepository.GetListAsync(x => x.RateId == id);
+ foreach (var detail in details)
+ {
+ await DetailRepository.DeleteAsync(detail);
+ }
+ }
+
+ ///
+ /// 分页查询仓租日账单。
+ ///
+ [HttpPost("/warehouse/storage-rent/bill/list")]
+ public async Task> GetBillListAsync(WarehouseRentBillListInput input)
+ {
+ var keyword = input.Keyword?.Trim();
+ var hasKeyword = !string.IsNullOrWhiteSpace(keyword);
+ var status = input.Status?.Trim();
+ var hasStatus = !string.IsNullOrWhiteSpace(status);
+ var from = input.BillDateFrom?.Date;
+ var to = input.BillDateTo?.Date;
+
+ Expression> predicate = x =>
+ (!input.CustomerId.HasValue || x.CustomerId == input.CustomerId.Value)
+ && (!input.WarehouseId.HasValue || x.WarehouseId == input.WarehouseId.Value)
+ && (!hasStatus || x.Status == status)
+ && (!from.HasValue || x.BillDate >= from.Value)
+ && (!to.HasValue || x.BillDate <= to.Value)
+ && (!hasKeyword || x.BillNo.Contains(keyword!));
+
+ var pageIndex = OmsDocHelper.NormalizePage(input.PageIndex);
+ var pageSize = OmsDocHelper.NormalizePageSize(input.PageSize);
+ var entities = await BillRepository.GetPagedListAsync(
+ predicate,
+ pageIndex,
+ pageSize,
+ new Dictionary
+ {
+ [nameof(CWarehouseRentBill.BillDate)] = false,
+ [nameof(CWarehouseRentBill.Id)] = false
+ });
+ var total = await BillRepository.CountAsync(predicate);
+ var items = await MapBillsAsync(entities, includeLines: false);
+ return new OmsPageResult { Items = items, Total = total };
+ }
+
+ ///
+ /// 仓租日账单详情(含明细)。
+ ///
+ [HttpGet("/warehouse/storage-rent/bill/detail")]
+ public async Task GetBillDetailAsync([FromQuery] int id)
+ {
+ var entity = await BillRepository.FirstOrDefaultAsync(x => x.Id == id)
+ ?? throw new BusinessException("仓租账单不存在");
+ var items = await MapBillsAsync([entity], includeLines: true);
+ return items[0];
+ }
+
+ ///
+ /// 对 unpaid 账单补扣余额并写流水。
+ ///
+ [HttpPost("/warehouse/storage-rent/bill/retry-pay")]
+ public async Task RetryPayBillAsync(WarehouseRentBillRetryPayInput input)
+ {
+ var bill = await BillRepository.FirstOrDefaultAsync(x => x.Id == input.Id)
+ ?? throw new BusinessException("仓租账单不存在");
+ if (bill.Status == WarehouseRentBillStatusCodes.Paid
+ || bill.Status == WarehouseRentBillStatusCodes.Zero)
+ {
+ return (await MapBillsAsync([bill], includeLines: true))[0];
+ }
+
+ await TryDebitBillAsync(bill);
+ return (await MapBillsAsync([bill], includeLines: true))[0];
+ }
+
+ ///
+ /// 手工触发指定业务日仓租日结(默认昨日)。
+ ///
+ [HttpPost("/warehouse/storage-rent/bill/run")]
+ public async Task> RunBillingAsync(WarehouseRentRunBillingInput input)
+ {
+ var billDate = (input.BillDate ?? DateTime.Now.Date.AddDays(-1)).Date;
+ var count = await RunDailyBillingAsync(billDate);
+ return new OmsItemsResult
+ {
+ Items = [$"业务日 {billDate:yyyy-MM-dd} 处理完成,生成/重试账单组数:{count}"]
+ };
+ }
+
+ ///
+ /// 日终结算入口:按客户+仓库生成昨日账单并尝试扣款。
+ ///
+ public async Task RunDailyBillingAsync(DateTime billDate, CancellationToken cancellationToken = default)
+ {
+ billDate = billDate.Date;
+ var lots = await LotRepository.GetListAsync(x => x.RemainQty > 0);
+ var groups = lots
+ .Select(x => (x.CustomerId, x.WarehouseId))
+ .Distinct()
+ .ToList();
+
+ var unpaid = await BillRepository.GetListAsync(x =>
+ x.BillDate == billDate && x.Status == WarehouseRentBillStatusCodes.Unpaid);
+ foreach (var bill in unpaid)
+ {
+ groups.Add((bill.CustomerId, bill.WarehouseId));
+ }
+
+ groups = groups.Distinct().ToList();
+ var processed = 0;
+ foreach (var group in groups)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ await RunDailyBillingForOwnerAsync(group.CustomerId, group.WarehouseId, billDate, cancellationToken);
+ processed++;
+ }
+
+ return processed;
+ }
+
+ ///
+ /// 对单个客户+仓库执行指定业务日仓租结算(幂等)。
+ ///
+ public async Task RunDailyBillingForOwnerAsync(
+ int customerId,
+ int warehouseId,
+ DateTime billDate,
+ CancellationToken cancellationToken = default)
+ {
+ billDate = billDate.Date;
+ var existing = await BillRepository.FirstOrDefaultAsync(x =>
+ x.CustomerId == customerId
+ && x.WarehouseId == warehouseId
+ && x.BillDate == billDate);
+
+ if (existing != null)
+ {
+ if (existing.Status == WarehouseRentBillStatusCodes.Unpaid)
+ {
+ await TryDebitBillAsync(existing, cancellationToken);
+ }
+
+ return;
+ }
+
+ var lots = await LotRepository.GetListAsync(x =>
+ x.CustomerId == customerId
+ && x.WarehouseId == warehouseId
+ && x.RemainQty > 0);
+ if (lots.Count == 0)
+ {
+ return;
+ }
+
+ await CreateAndPayBillAsync(customerId, warehouseId, billDate, lots, cancellationToken);
+ }
+
+ private async Task CreateAndPayBillAsync(
+ int customerId,
+ int warehouseId,
+ DateTime billDate,
+ List lots,
+ CancellationToken cancellationToken = default)
+ {
+ var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == customerId);
+ var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == warehouseId);
+ var warehouseName = warehouse?.WarehouseName;
+
+ var lineDrafts = new List<(CWarehouseRentLot Lot, int AgeDays, decimal Cbm, bool MissingDim)>();
+ decimal totalCbm = 0;
+ foreach (var lot in lots)
+ {
+ var ageDays = Math.Max(0, (billDate - lot.InboundTime.Date).Days);
+ var cbm = Math.Round(lot.RemainQty * lot.UnitCbm, 6, MidpointRounding.AwayFromZero);
+ var missing = lot.UnitCbm <= 0;
+ lineDrafts.Add((lot, ageDays, cbm, missing));
+ totalCbm += cbm;
+ }
+
+ totalCbm = Math.Round(totalCbm, 6, MidpointRounding.AwayFromZero);
+
+ // 体积段按客户当日该仓总 CBM 匹配;天数按各 lot 库龄分别取价后对明细分摊
+ // 简化:同一客户仓使用「最大库龄」匹配天数段(保守,偏高龄段),再 × 总 CBM
+ // 更精确:按 lot 分别匹配后汇总。采用按 lot 匹配并累加。
+ var rateBundles = await LoadEnabledRateBundlesAsync();
+ decimal amount = 0;
+ decimal? sampleUnitPrice = null;
+ var lineEntities = new List();
+
+ foreach (var draft in lineDrafts)
+ {
+ var unitPrice = WarehouseRentCalculator.MatchUnitPrice(
+ rateBundles,
+ warehouseId,
+ warehouseName,
+ draft.AgeDays,
+ totalCbm,
+ customer?.PriceTierKey) ?? 0M;
+ sampleUnitPrice ??= unitPrice;
+ var lineAmount = Math.Round(draft.Cbm * unitPrice, 2, MidpointRounding.AwayFromZero);
+ amount += lineAmount;
+ lineEntities.Add(new CWarehouseRentBillLine
+ {
+ LotId = draft.Lot.Id,
+ SkuId = draft.Lot.SkuId,
+ AgeDays = draft.AgeDays,
+ Qty = draft.Lot.RemainQty,
+ Cbm = draft.Cbm,
+ UnitPrice = unitPrice,
+ Amount = lineAmount,
+ MissingDimension = draft.MissingDim,
+ Remark = draft.MissingDim ? "SKU 缺尺寸,体积计 0" : null
+ });
+ }
+
+ amount = Math.Round(amount, 2, MidpointRounding.AwayFromZero);
+ var bill = new CWarehouseRentBill
+ {
+ BillNo = await GenerateBillNoAsync(cancellationToken),
+ CustomerId = customerId,
+ WarehouseId = warehouseId,
+ BillDate = billDate,
+ TotalCbm = totalCbm,
+ Amount = amount,
+ Currency = "CNY",
+ UnitPrice = sampleUnitPrice,
+ Status = amount <= 0 ? WarehouseRentBillStatusCodes.Zero : WarehouseRentBillStatusCodes.Pending,
+ Remark = amount <= 0 ? "应付为 0" : null
+ };
+ await BillRepository.InsertAsync(bill, cancellationToken);
+
+ foreach (var line in lineEntities)
+ {
+ line.BillId = bill.Id;
+ await BillLineRepository.InsertAsync(line, cancellationToken);
+ }
+
+ if (bill.Status == WarehouseRentBillStatusCodes.Zero)
+ {
+ return;
+ }
+
+ await TryDebitBillAsync(bill, cancellationToken);
+ }
+
+ private async Task TryDebitBillAsync(CWarehouseRentBill bill, CancellationToken cancellationToken = default)
+ {
+ if (bill.Amount <= 0)
+ {
+ bill.Status = WarehouseRentBillStatusCodes.Zero;
+ bill.Remark = "应付为 0";
+ await BillRepository.UpdateAsync(bill, cancellationToken);
+ return;
+ }
+
+ if (bill.Status == WarehouseRentBillStatusCodes.Paid)
+ {
+ return;
+ }
+
+ var customer = await CustomerRepository.FirstOrDefaultAsync(x => x.Id == bill.CustomerId)
+ ?? throw new BusinessException("客户不存在");
+
+ try
+ {
+ var flow = await BalanceMutator.DebitStorageRentAsync(
+ customer,
+ bill.Amount,
+ bill.Id,
+ bill.BillNo,
+ $"仓租 {bill.BillDate:yyyy-MM-dd} 仓{bill.WarehouseId}",
+ cancellationToken);
+ bill.Status = WarehouseRentBillStatusCodes.Paid;
+ bill.FlowId = flow.Id;
+ bill.PaidTime = DateTime.Now;
+ bill.Remark = null;
+ await BillRepository.UpdateAsync(bill, cancellationToken);
+ }
+ catch (BusinessException ex) when (ex.Message.Contains("余额不足"))
+ {
+ bill.Status = WarehouseRentBillStatusCodes.Unpaid;
+ bill.Remark = "账户余额不足";
+ await BillRepository.UpdateAsync(bill, cancellationToken);
+ }
+ }
+
+ private async Task> LoadEnabledRateBundlesAsync()
+ {
+ var rates = await RateRepository.GetListAsync(x => x.Status == EnableStatus.Enabled);
+ if (rates.Count == 0)
+ {
+ return [];
+ }
+
+ var rateIds = rates.Select(x => x.Id).ToArray();
+ var factors = await FactorRepository.GetListAsync(x => rateIds.Contains(x.RateId));
+ var details = await DetailRepository.GetListAsync(x => rateIds.Contains(x.RateId));
+
+ return rates.Select(rate => new WarehouseRentCalculator.RateBundle(
+ rate,
+ factors.Where(f => f.RateId == rate.Id).OrderBy(f => f.SerialNumber).ToList(),
+ details.Where(d => d.RateId == rate.Id).Select(MapDetailOutput).ToList()
+ )).ToList();
+ }
+
+ private async Task ReplaceFactorsAndDetailsAsync(
+ int rateId,
+ List factors,
+ List details)
+ {
+ var oldFactors = await FactorRepository.GetListAsync(x => x.RateId == rateId);
+ foreach (var old in oldFactors)
+ {
+ await FactorRepository.DeleteAsync(old);
+ }
+
+ var oldDetails = await DetailRepository.GetListAsync(x => x.RateId == rateId);
+ foreach (var old in oldDetails)
+ {
+ await DetailRepository.DeleteAsync(old);
+ }
+
+ var factorEntities = factors
+ .Select((f, index) => new CWarehouseRentRateFactor
+ {
+ RateId = rateId,
+ SerialNumber = f.SerialNumber > 0 ? f.SerialNumber : index + 1,
+ Factor = f.Factor?.Trim() ?? string.Empty,
+ FactorValues = OmsDocHelper.SerializeJson(f.FactorValues ?? [])
+ })
+ .Where(f => !string.IsNullOrWhiteSpace(f.Factor))
+ .ToList();
+ foreach (var factor in factorEntities)
+ {
+ await FactorRepository.InsertAsync(factor);
+ }
+
+ foreach (var detail in details)
+ {
+ await DetailRepository.InsertAsync(new CWarehouseRentRateDetail
+ {
+ RateId = rateId,
+ FactorValuesJson = OmsDocHelper.SerializeJson(detail.FactorValuesJson),
+ CalculationFormula = string.IsNullOrWhiteSpace(detail.CalculationFormula)
+ ? "total"
+ : detail.CalculationFormula.Trim(),
+ CalculatedValue = detail.CalculatedValue,
+ CustomerGroupValues = OmsDocHelper.SerializeJson(detail.CustomerGroupValues)
+ });
+ }
+ }
+
+ private async Task EnsureRateNameUniqueAsync(string rateName, int? excludeId)
+ {
+ var exists = await RateRepository.FirstOrDefaultAsync(x =>
+ x.RateName == rateName && (!excludeId.HasValue || x.Id != excludeId.Value));
+ if (exists != null)
+ {
+ throw new BusinessException("费率名称已存在");
+ }
+ }
+
+ private async Task GenerateBillNoAsync(CancellationToken cancellationToken)
+ {
+ for (var i = 0; i < 5; i++)
+ {
+ var billNo = $"WR{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
+ if (!await BillRepository.AnyAsync(x => x.BillNo == billNo))
+ {
+ return billNo;
+ }
+ }
+
+ throw new BusinessException("仓租账单号生成失败");
+ }
+
+ private static WarehouseRentRateOutput MapRateListItem(CWarehouseRentRate entity) => new()
+ {
+ Id = entity.Id,
+ RateName = entity.RateName,
+ Currency = entity.Currency,
+ CostUnit = entity.CostUnit,
+ Status = entity.Status,
+ Remark = entity.Remark,
+ CreateTime = entity.CreateTime,
+ UpdateTime = entity.UpdateTime == default ? null : entity.UpdateTime
+ };
+
+ private async Task MapRateDetailAsync(CWarehouseRentRate entity)
+ {
+ var output = MapRateListItem(entity);
+ var factors = await FactorRepository.GetListAsync(x => x.RateId == entity.Id);
+ var details = await DetailRepository.GetListAsync(x => x.RateId == entity.Id);
+ output.Factors = factors
+ .OrderBy(x => x.SerialNumber)
+ .Select(f => new ChannelPriceFactorOutput
+ {
+ Id = f.Id,
+ PriceId = f.RateId,
+ SerialNumber = f.SerialNumber,
+ Factor = f.Factor,
+ FactorValues = OmsDocHelper.DeserializeJson>(f.FactorValues) ?? []
+ })
+ .ToList();
+ output.Details = details.Select(MapDetailOutput).ToList();
+ return output;
+ }
+
+ private static ChannelPriceDetailOutput MapDetailOutput(CWarehouseRentRateDetail entity) => new()
+ {
+ Id = entity.Id,
+ PriceId = entity.RateId,
+ FactorValuesJson = OmsDocHelper.DeserializeJsonObject(entity.FactorValuesJson),
+ CalculationFormula = entity.CalculationFormula,
+ CalculatedValue = entity.CalculatedValue,
+ CustomerGroupValues = OmsDocHelper.DeserializeJsonObject(entity.CustomerGroupValues)
+ };
+
+ private async Task> MapBillsAsync(
+ List bills,
+ bool includeLines)
+ {
+ if (bills.Count == 0)
+ {
+ return [];
+ }
+
+ var customerIds = bills.Select(x => x.CustomerId).Distinct().ToArray();
+ var warehouseIds = bills.Select(x => x.WarehouseId).Distinct().ToArray();
+ var customers = await CustomerRepository.GetListAsync(x => customerIds.Contains(x.Id));
+ var warehouses = await WarehouseAddressRepository.GetListAsync(x => warehouseIds.Contains(x.Id));
+ var customerMap = customers.ToDictionary(x => x.Id);
+ var warehouseMap = warehouses.ToDictionary(x => x.Id);
+
+ Dictionary> lineMap = new();
+ Dictionary skuMap = new();
+ if (includeLines)
+ {
+ var billIds = bills.Select(x => x.Id).ToArray();
+ var lines = await BillLineRepository.GetListAsync(x => billIds.Contains(x.BillId));
+ lineMap = lines.GroupBy(x => x.BillId).ToDictionary(g => g.Key, g => g.ToList());
+ var skuIds = lines.Select(x => x.SkuId).Distinct().ToArray();
+ if (skuIds.Length > 0)
+ {
+ var skus = await SkuRepository.GetListAsync(x => skuIds.Contains(x.Id));
+ skuMap = skus.ToDictionary(x => x.Id);
+ }
+ }
+
+ return bills.Select(bill =>
+ {
+ customerMap.TryGetValue(bill.CustomerId, out var customer);
+ warehouseMap.TryGetValue(bill.WarehouseId, out var warehouse);
+ var output = new WarehouseRentBillOutput
+ {
+ Id = bill.Id,
+ BillNo = bill.BillNo,
+ CustomerId = bill.CustomerId,
+ CustomerCode = customer?.CustomerCode,
+ CustomerName = customer?.CustomerName,
+ WarehouseId = bill.WarehouseId,
+ WarehouseName = warehouse?.WarehouseName,
+ BillDate = bill.BillDate,
+ TotalCbm = bill.TotalCbm,
+ Amount = bill.Amount,
+ Currency = bill.Currency,
+ UnitPrice = bill.UnitPrice,
+ Status = bill.Status,
+ FlowId = bill.FlowId,
+ PaidTime = bill.PaidTime,
+ Remark = bill.Remark,
+ CreateTime = bill.CreateTime
+ };
+
+ if (includeLines && lineMap.TryGetValue(bill.Id, out var lines))
+ {
+ output.Lines = lines.Select(line =>
+ {
+ skuMap.TryGetValue(line.SkuId, out var sku);
+ return new WarehouseRentBillLineOutput
+ {
+ Id = line.Id,
+ LotId = line.LotId,
+ SkuId = line.SkuId,
+ SkuCode = sku?.SkuCode,
+ AgeDays = line.AgeDays,
+ Qty = line.Qty,
+ Cbm = line.Cbm,
+ UnitPrice = line.UnitPrice,
+ Amount = line.Amount,
+ MissingDimension = line.MissingDimension,
+ Remark = line.Remark
+ };
+ }).ToList();
+ }
+
+ return output;
+ }).ToList();
+ }
+}
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs
index 7b8869d..ea44a61 100644
--- a/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs
+++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs
@@ -125,6 +125,12 @@ public partial class WarehouseService
row.AvailableQty = Math.Max(0, row.Qty - row.FrozenQty);
remaining -= deduct;
await InventoryRepository.UpdateAsync(row);
+ await RentLotManager.DeductFifoAsync(
+ customerId,
+ warehouseId,
+ skuId,
+ deduct,
+ row.BinLocationId);
}
if (remaining > 0)
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs
index 75e8fbb..ef53b63 100644
--- a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs
+++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs
@@ -330,6 +330,14 @@ public partial class WarehouseService
line.SkuId,
lineInput.BinLocationId,
deltaQty);
+ await RentLotManager.AddLotAsync(
+ customerId,
+ notice.WarehouseId,
+ line.SkuId,
+ lineInput.BinLocationId,
+ deltaQty,
+ WarehouseRentLotSourceCodes.Inbound,
+ notice.Id);
}
}
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Inventory.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Inventory.cs
index 0aca173..aaca035 100644
--- a/src/Oms.Application/Services/Warehouse/WarehouseService.Inventory.cs
+++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Inventory.cs
@@ -173,6 +173,13 @@ public partial class WarehouseService
await UpsertInventoryQtyAsync(customerId, input.WarehouseId, input.SkuId, input.SourceBinLocationId, -input.Qty);
await UpsertInventoryQtyAsync(customerId, input.WarehouseId, input.SkuId, input.TargetBinLocationId, input.Qty);
+ await RentLotManager.RelocateAsync(
+ customerId,
+ input.WarehouseId,
+ input.SkuId,
+ input.SourceBinLocationId,
+ input.TargetBinLocationId,
+ input.Qty);
}
///
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs
index ab110da..14cd4aa 100644
--- a/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs
+++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs
@@ -318,6 +318,14 @@ public partial class WarehouseService
sku.Id,
putawayItem.BinLocationId,
item.Quantity);
+ await RentLotManager.AddLotAsync(
+ customerId,
+ parcel.WarehouseId,
+ sku.Id,
+ putawayItem.BinLocationId,
+ item.Quantity,
+ WarehouseRentLotSourceCodes.Parcel,
+ parcel.Id);
}
parcel.LifecycleStatus = WarehouseParcelLifecycleCodes.Stored;
diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.cs
index f969e65..c07e256 100644
--- a/src/Oms.Application/Services/Warehouse/WarehouseService.cs
+++ b/src/Oms.Application/Services/Warehouse/WarehouseService.cs
@@ -1,6 +1,7 @@
using Fake.Application;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Labeling;
+using Oms.Application.Shared;
using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.CustomersAggregate.Repositories;
using Oms.Domain.SystemAggregate.Repositories;
@@ -29,4 +30,6 @@ public partial class WarehouseService : ApplicationService
private ILabelTemplateRepository LabelTemplateRepository =>
LazyServiceProvider.GetRequiredService();
private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService();
+ private WarehouseRentLotManager RentLotManager =>
+ LazyServiceProvider.GetRequiredService();
}
diff --git a/src/Oms.Application/Shared/CustomerBalanceMutator.cs b/src/Oms.Application/Shared/CustomerBalanceMutator.cs
index 4eb0372..9501297 100644
--- a/src/Oms.Application/Shared/CustomerBalanceMutator.cs
+++ b/src/Oms.Application/Shared/CustomerBalanceMutator.cs
@@ -167,7 +167,33 @@ public class CustomerBalanceMutator : IScopedDependency
cancellationToken);
}
- private async Task ApplyAsync(
+ ///
+ /// 仓租日结扣费,写入账户流水并返回流水实体。
+ ///
+ public Task DebitStorageRentAsync(
+ Customer customer,
+ decimal amount,
+ int billId,
+ string billNo,
+ string? remark,
+ CancellationToken cancellationToken = default)
+ {
+ if (amount <= 0)
+ {
+ throw new BusinessException("仓租扣费金额必须大于 0");
+ }
+
+ return ApplyAsync(
+ customer,
+ -amount,
+ CustomerAccountFlowBizTypes.StorageRent,
+ billId,
+ billNo,
+ remark,
+ cancellationToken);
+ }
+
+ private async Task ApplyAsync(
Customer customer,
decimal signedAmount,
string bizType,
@@ -205,6 +231,7 @@ public class CustomerBalanceMutator : IScopedDependency
Remark = remark
};
await _flowRepository.InsertAsync(flow, cancellationToken);
+ return flow;
}
private async Task GenerateSerialNumberAsync(CancellationToken cancellationToken)
diff --git a/src/Oms.Application/Shared/WarehouseRentCalculator.cs b/src/Oms.Application/Shared/WarehouseRentCalculator.cs
new file mode 100644
index 0000000..0078520
--- /dev/null
+++ b/src/Oms.Application/Shared/WarehouseRentCalculator.cs
@@ -0,0 +1,262 @@
+using System.Globalization;
+using System.Text.Json;
+using Oms.Application.Dtos.Channels;
+using Oms.Application.Services.Orders;
+using Oms.Domain.WarehouseAggregate.Consts;
+using Oms.Domain.WarehouseAggregate.Entities;
+
+namespace Oms.Application.Shared;
+
+///
+/// 仓租费率匹配:仓库 × 天数区间 × 体积区间 × 客户组。
+///
+public static class WarehouseRentCalculator
+{
+ private static readonly JsonSerializerOptions JsonOptions = new()
+ {
+ PropertyNameCaseInsensitive = true
+ };
+
+ public sealed record RateBundle(
+ CWarehouseRentRate Rate,
+ IReadOnlyList Factors,
+ IReadOnlyList Details);
+
+ ///
+ /// 在启用费率中匹配单价;无命中返回 null。
+ ///
+ public static decimal? MatchUnitPrice(
+ IReadOnlyList rates,
+ int warehouseId,
+ string? warehouseName,
+ int ageDays,
+ decimal totalCbm,
+ string? priceTierKey)
+ {
+ decimal? bestPrice = null;
+ var bestScore = int.MaxValue;
+
+ foreach (var bundle in rates)
+ {
+ if (!RateCoversWarehouse(bundle, warehouseId, warehouseName))
+ {
+ continue;
+ }
+
+ foreach (var detail in bundle.Details)
+ {
+ var factors = ParseFactorDictionary(detail.FactorValuesJson);
+ if (!MatchWarehouseInDetail(factors, warehouseId, warehouseName))
+ {
+ continue;
+ }
+
+ if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Days, "天数", ageDays, out var daysWidth))
+ {
+ continue;
+ }
+
+ if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Volume, "体积", totalCbm, out var volumeWidth))
+ {
+ continue;
+ }
+
+ var price = ResolvePriceTierKeyPrice(detail, priceTierKey) ?? detail.CalculatedValue;
+ if (!price.HasValue)
+ {
+ continue;
+ }
+
+ // 更窄区间优先;同分取更小单价(保守)
+ var score = daysWidth + volumeWidth;
+ if (bestPrice is null || score < bestScore || (score == bestScore && price.Value < bestPrice.Value))
+ {
+ bestPrice = price.Value;
+ bestScore = score;
+ }
+ }
+ }
+
+ return bestPrice;
+ }
+
+ private static bool RateCoversWarehouse(RateBundle bundle, int warehouseId, string? warehouseName)
+ {
+ var warehouseFactor = bundle.Factors.FirstOrDefault(f =>
+ IsFactor(f.Factor, WarehouseRentFactorCodes.Warehouse, "仓库"));
+ if (warehouseFactor == null)
+ {
+ return true;
+ }
+
+ var values = OmsDocHelper.DeserializeJson>(warehouseFactor.FactorValues) ?? [];
+ if (values.Count == 0)
+ {
+ return true;
+ }
+
+ return values.Any(v => MatchWarehouseValue(v, warehouseId, warehouseName));
+ }
+
+ private static bool MatchWarehouseInDetail(
+ Dictionary factors,
+ int warehouseId,
+ string? warehouseName)
+ {
+ if (!TryGetFactorText(factors, out var value, WarehouseRentFactorCodes.Warehouse, "仓库"))
+ {
+ return true;
+ }
+
+ return MatchWarehouseValue(value, warehouseId, warehouseName);
+ }
+
+ private static bool MatchWarehouseValue(string raw, int warehouseId, string? warehouseName)
+ {
+ var text = raw.Trim();
+ if (string.IsNullOrEmpty(text))
+ {
+ return true;
+ }
+
+ if (int.TryParse(text, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
+ {
+ return id == warehouseId;
+ }
+
+ return !string.IsNullOrWhiteSpace(warehouseName)
+ && string.Equals(text, warehouseName.Trim(), StringComparison.OrdinalIgnoreCase);
+ }
+
+ private static bool MatchIntervalFactor(
+ Dictionary factors,
+ string code,
+ string label,
+ decimal value,
+ out int widthScore)
+ {
+ widthScore = 0;
+ if (!TryGetFactorText(factors, out var text, code, label))
+ {
+ return true;
+ }
+
+ if (!ParcelBillingCalculator.TryParseWeightInterval(text, out var start, out var end))
+ {
+ return false;
+ }
+
+ if (!ParcelBillingCalculator.WeightInLeftOpenRightClosedInterval(value, start, end))
+ {
+ // 天数允许 0:左开右闭时 0 不会命中 (0-N],对 ageDays=0 特判落入起点为 0 的区间
+ if (!(value == 0 && start == 0 && end > 0 && value <= end))
+ {
+ return false;
+ }
+ }
+
+ widthScore = (int)Math.Min(int.MaxValue, Math.Round((end - start) * 1000M));
+ return true;
+ }
+
+ private static bool TryGetFactorText(Dictionary factors, out string value, params string[] keys)
+ {
+ foreach (var key in keys)
+ {
+ foreach (var pair in factors)
+ {
+ if (IsFactor(pair.Key, key) && !string.IsNullOrWhiteSpace(pair.Value))
+ {
+ value = pair.Value.Trim();
+ return true;
+ }
+ }
+ }
+
+ value = string.Empty;
+ return false;
+ }
+
+ private static bool IsFactor(string? actual, params string[] expected)
+ {
+ var a = actual?.Trim() ?? string.Empty;
+ return expected.Any(e => string.Equals(a, e, StringComparison.OrdinalIgnoreCase));
+ }
+
+ private static Dictionary ParseFactorDictionary(object? factorValuesJson)
+ {
+ if (factorValuesJson == null)
+ {
+ return new Dictionary(StringComparer.OrdinalIgnoreCase);
+ }
+
+ try
+ {
+ var json = factorValuesJson is string s
+ ? s
+ : JsonSerializer.Serialize(factorValuesJson, JsonOptions);
+ var map = JsonSerializer.Deserialize>(json, JsonOptions);
+ if (map == null)
+ {
+ return new Dictionary(StringComparer.OrdinalIgnoreCase);
+ }
+
+ var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ foreach (var (key, element) in map)
+ {
+ result[key] = element.ValueKind switch
+ {
+ JsonValueKind.String => element.GetString() ?? string.Empty,
+ JsonValueKind.Number => element.GetRawText(),
+ _ => element.ToString()
+ };
+ }
+
+ return result;
+ }
+ catch
+ {
+ return new Dictionary(StringComparer.OrdinalIgnoreCase);
+ }
+ }
+
+ private static decimal? ResolvePriceTierKeyPrice(ChannelPriceDetailOutput detail, string? priceTierKey)
+ {
+ if (detail.CustomerGroupValues == null)
+ {
+ return null;
+ }
+
+ try
+ {
+ var json = JsonSerializer.Serialize(detail.CustomerGroupValues, JsonOptions);
+ var map = JsonSerializer.Deserialize>(json, JsonOptions);
+ if (map == null || map.Count == 0)
+ {
+ return null;
+ }
+
+ if (map.TryGetValue("全部客户", out var all) || map.TryGetValue("all", out all))
+ {
+ return all;
+ }
+
+ if (!string.IsNullOrWhiteSpace(priceTierKey)
+ && map.TryGetValue(priceTierKey.Trim(), out var tier))
+ {
+ return tier;
+ }
+
+ if (map.TryGetValue("普通客户", out var normal))
+ {
+ return normal;
+ }
+ }
+ catch
+ {
+ // ignore
+ }
+
+ return null;
+ }
+}
diff --git a/src/Oms.Application/Shared/WarehouseRentLotManager.cs b/src/Oms.Application/Shared/WarehouseRentLotManager.cs
new file mode 100644
index 0000000..35eb2bb
--- /dev/null
+++ b/src/Oms.Application/Shared/WarehouseRentLotManager.cs
@@ -0,0 +1,179 @@
+using Fake.DependencyInjection;
+using Oms.Domain.WarehouseAggregate.Consts;
+using Oms.Domain.WarehouseAggregate.Entities;
+using Oms.Domain.WarehouseAggregate.Repositories;
+
+namespace Oms.Application.Shared;
+
+///
+/// 仓租库龄批次维护:入库增加、出库 FIFO 扣减、移位。
+///
+public class WarehouseRentLotManager : IScopedDependency
+{
+ private readonly ICWarehouseRentLotRepository _lotRepository;
+ private readonly ICSkuRepository _skuRepository;
+
+ public WarehouseRentLotManager(
+ ICWarehouseRentLotRepository lotRepository,
+ ICSkuRepository skuRepository)
+ {
+ _lotRepository = lotRepository;
+ _skuRepository = skuRepository;
+ }
+
+ ///
+ /// 按 SKU 尺寸计算单件 CBM(cm³ / 1e6);缺尺寸返回 0。
+ ///
+ public static decimal CalcUnitCbm(CSku? sku)
+ {
+ if (sku?.LengthCm is null or <= 0
+ || sku.WidthCm is null or <= 0
+ || sku.HeightCm is null or <= 0)
+ {
+ return 0;
+ }
+
+ return Math.Round(
+ sku.LengthCm.Value * sku.WidthCm.Value * sku.HeightCm.Value / 1_000_000M,
+ 6,
+ MidpointRounding.AwayFromZero);
+ }
+
+ ///
+ /// 入库/上架新增批次。
+ ///
+ public async Task AddLotAsync(
+ int customerId,
+ int warehouseId,
+ int skuId,
+ int? binLocationId,
+ int qty,
+ string sourceType,
+ int sourceId,
+ DateTime? inboundTime = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (qty <= 0)
+ {
+ return;
+ }
+
+ var sku = await _skuRepository.FirstOrDefaultAsync(x => x.Id == skuId);
+ var lot = new CWarehouseRentLot
+ {
+ CustomerId = customerId,
+ WarehouseId = warehouseId,
+ SkuId = skuId,
+ BinLocationId = binLocationId,
+ InboundTime = inboundTime ?? DateTime.Now,
+ RemainQty = qty,
+ UnitCbm = CalcUnitCbm(sku),
+ SourceType = sourceType,
+ SourceId = sourceId
+ };
+ await _lotRepository.InsertAsync(lot, cancellationToken);
+ }
+
+ ///
+ /// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。
+ ///
+ public async Task DeductFifoAsync(
+ int customerId,
+ int warehouseId,
+ int skuId,
+ int qty,
+ int? binLocationId = null,
+ CancellationToken cancellationToken = default)
+ {
+ if (qty <= 0)
+ {
+ return;
+ }
+
+ var lots = await _lotRepository.GetListAsync(x =>
+ x.CustomerId == customerId
+ && x.WarehouseId == warehouseId
+ && x.SkuId == skuId
+ && x.RemainQty > 0
+ && (!binLocationId.HasValue || x.BinLocationId == binLocationId.Value));
+ lots = lots.OrderBy(x => x.InboundTime).ThenBy(x => x.Id).ToList();
+
+ var remaining = qty;
+ foreach (var lot in lots)
+ {
+ if (remaining <= 0)
+ {
+ break;
+ }
+
+ var take = Math.Min(lot.RemainQty, remaining);
+ if (take <= 0)
+ {
+ continue;
+ }
+
+ lot.RemainQty -= take;
+ remaining -= take;
+ await _lotRepository.UpdateAsync(lot, cancellationToken);
+ }
+ }
+
+ ///
+ /// 库位移位:从源库位 FIFO 扣减并在目标库位写入同库龄批次。
+ ///
+ public async Task RelocateAsync(
+ int customerId,
+ int warehouseId,
+ int skuId,
+ int sourceBinLocationId,
+ int targetBinLocationId,
+ int qty,
+ CancellationToken cancellationToken = default)
+ {
+ if (qty <= 0 || sourceBinLocationId == targetBinLocationId)
+ {
+ return;
+ }
+
+ var lots = await _lotRepository.GetListAsync(x =>
+ x.CustomerId == customerId
+ && x.WarehouseId == warehouseId
+ && x.SkuId == skuId
+ && x.BinLocationId == sourceBinLocationId
+ && x.RemainQty > 0);
+ lots = lots.OrderBy(x => x.InboundTime).ThenBy(x => x.Id).ToList();
+
+ var remaining = qty;
+ foreach (var lot in lots)
+ {
+ if (remaining <= 0)
+ {
+ break;
+ }
+
+ var take = Math.Min(lot.RemainQty, remaining);
+ if (take <= 0)
+ {
+ continue;
+ }
+
+ lot.RemainQty -= take;
+ remaining -= take;
+ await _lotRepository.UpdateAsync(lot, cancellationToken);
+
+ var moved = new CWarehouseRentLot
+ {
+ CustomerId = customerId,
+ WarehouseId = warehouseId,
+ SkuId = skuId,
+ BinLocationId = targetBinLocationId,
+ InboundTime = lot.InboundTime,
+ RemainQty = take,
+ UnitCbm = lot.UnitCbm,
+ SourceType = lot.SourceType,
+ SourceId = lot.SourceId
+ };
+ await _lotRepository.InsertAsync(moved, cancellationToken);
+ }
+ }
+}
diff --git a/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs b/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs
new file mode 100644
index 0000000..372c750
--- /dev/null
+++ b/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs
@@ -0,0 +1,120 @@
+using Fake.UnitOfWork;
+using Microsoft.Extensions.DependencyInjection;
+using Microsoft.Extensions.Hosting;
+using Microsoft.Extensions.Logging;
+using Oms.Application.Services.Warehouse;
+using Oms.Domain.WarehouseAggregate.Repositories;
+
+namespace Oms.Application.Workers;
+
+///
+/// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表,按组开独立 UoW。
+///
+public class WarehouseRentBillingWorker : BackgroundService
+{
+ private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1);
+ private readonly IServiceScopeFactory _scopeFactory;
+ private readonly ILogger _logger;
+
+ public WarehouseRentBillingWorker(
+ IServiceScopeFactory scopeFactory,
+ ILogger logger)
+ {
+ _scopeFactory = scopeFactory;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ await ProcessIfDueAsync(stoppingToken);
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogError(ex, "仓租日终任务异常");
+ }
+
+ try
+ {
+ await Task.Delay(PollInterval, stoppingToken);
+ }
+ catch (OperationCanceledException)
+ {
+ break;
+ }
+ }
+ }
+
+ private async Task ProcessIfDueAsync(CancellationToken cancellationToken)
+ {
+ var now = DateTime.Now;
+ if (now.Hour < 1)
+ {
+ return;
+ }
+
+ var billDate = now.Date.AddDays(-1);
+
+ List<(int CustomerId, int WarehouseId)> groups;
+ using (var scope = _scopeFactory.CreateScope())
+ {
+ var lotRepository = scope.ServiceProvider.GetRequiredService();
+ var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0);
+ groups = lots
+ .Select(x => (x.CustomerId, x.WarehouseId))
+ .Distinct()
+ .ToList();
+
+ var billRepository = scope.ServiceProvider.GetRequiredService();
+ var unpaid = await billRepository.GetListAsync(x =>
+ x.BillDate == billDate && x.Status == "unpaid");
+ foreach (var bill in unpaid)
+ {
+ groups.Add((bill.CustomerId, bill.WarehouseId));
+ }
+
+ groups = groups.Distinct().ToList();
+ }
+
+ var success = 0;
+ foreach (var group in groups)
+ {
+ cancellationToken.ThrowIfCancellationRequested();
+ try
+ {
+ using var scope = _scopeFactory.CreateScope();
+ var unitOfWorkManager = scope.ServiceProvider.GetRequiredService();
+ using var unitOfWork = unitOfWorkManager.Begin();
+ var rentService = scope.ServiceProvider.GetRequiredService();
+ await rentService.RunDailyBillingForOwnerAsync(
+ group.CustomerId,
+ group.WarehouseId,
+ billDate,
+ cancellationToken);
+ await unitOfWork.CompleteAsync(cancellationToken);
+ success++;
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogError(
+ ex,
+ "仓租日结失败:客户 {CustomerId} 仓库 {WarehouseId} 业务日 {BillDate:yyyy-MM-dd}",
+ group.CustomerId,
+ group.WarehouseId,
+ billDate);
+ }
+ }
+
+ if (success > 0)
+ {
+ _logger.LogInformation(
+ "仓租日结完成:业务日 {BillDate:yyyy-MM-dd},成功组数 {Success}/{Total}",
+ billDate,
+ success,
+ groups.Count);
+ }
+ }
+}
diff --git a/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs b/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs
index ad03bfb..c6288bf 100644
--- a/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs
+++ b/src/Oms.Domain/CustomersAggregate/Consts/CustomerAccountFlowBizTypes.cs
@@ -21,4 +21,7 @@ public static class CustomerAccountFlowBizTypes
/// 运营人工调整账户余额。
public const string ManualAdjust = "manualAdjust";
+
+ /// 仓租日结扣费。
+ public const string StorageRent = "storageRent";
}
diff --git a/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs b/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs
index b30e5a4..de1e7f3 100644
--- a/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs
+++ b/src/Oms.Domain/SystemAggregate/Consts/WechatOrderNotifyEventCodes.cs
@@ -5,6 +5,7 @@ namespace Oms.Domain.SystemAggregate.Consts;
///
public static class WechatOrderNotifyEventCodes
{
+ public const string PendingPayment = "pendingPayment";
public const string Inbound = "inbound";
public const string Outbound = "outbound";
public const string DeliverySuccess = "deliverySuccess";
@@ -13,6 +14,7 @@ public static class WechatOrderNotifyEventCodes
public static readonly IReadOnlyList<(string Code, string Name)> All =
[
+ (PendingPayment, "待支付"),
(Inbound, "入库"),
(Outbound, "出库"),
(DeliverySuccess, "签收"),
diff --git a/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs b/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs
new file mode 100644
index 0000000..ea315e2
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs
@@ -0,0 +1,32 @@
+namespace Oms.Domain.WarehouseAggregate.Consts;
+
+///
+/// 仓租相关常量。
+///
+public static class WarehouseRentFactorCodes
+{
+ public const string Warehouse = "warehouse";
+ public const string Days = "days";
+ public const string Volume = "volume";
+ public const string Customer = "customer";
+}
+
+///
+/// 仓租批次来源。
+///
+public static class WarehouseRentLotSourceCodes
+{
+ public const string Inbound = "inbound";
+ public const string Parcel = "parcel";
+}
+
+///
+/// 仓租日账单状态。
+///
+public static class WarehouseRentBillStatusCodes
+{
+ public const string Pending = "pending";
+ public const string Paid = "paid";
+ public const string Unpaid = "unpaid";
+ public const string Zero = "zero";
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBill.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBill.cs
new file mode 100644
index 0000000..81e6cb8
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBill.cs
@@ -0,0 +1,35 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租日账单。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentBill)]
+public class CWarehouseRentBill : OmsAuditedAggregateRoot
+{
+ public string BillNo { get; set; } = string.Empty;
+
+ public int CustomerId { get; set; }
+
+ public int WarehouseId { get; set; }
+
+ public DateTime BillDate { get; set; }
+
+ public decimal TotalCbm { get; set; }
+
+ public decimal Amount { get; set; }
+
+ public string Currency { get; set; } = "CNY";
+
+ public decimal? UnitPrice { get; set; }
+
+ public string Status { get; set; } = "pending";
+
+ public int? FlowId { get; set; }
+
+ public DateTime? PaidTime { get; set; }
+
+ public string? Remark { get; set; }
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBillLine.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBillLine.cs
new file mode 100644
index 0000000..5ada3dc
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentBillLine.cs
@@ -0,0 +1,31 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租日账单明细。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentBillLine)]
+public class CWarehouseRentBillLine : OmsAuditedAggregateRoot
+{
+ public int BillId { get; set; }
+
+ public int? LotId { get; set; }
+
+ public int SkuId { get; set; }
+
+ public int AgeDays { get; set; }
+
+ public int Qty { get; set; }
+
+ public decimal Cbm { get; set; }
+
+ public decimal UnitPrice { get; set; }
+
+ public decimal Amount { get; set; }
+
+ public bool MissingDimension { get; set; }
+
+ public string? Remark { get; set; }
+}
\ No newline at end of file
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentLot.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentLot.cs
new file mode 100644
index 0000000..554cfb9
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentLot.cs
@@ -0,0 +1,30 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租库龄批次(计费真相源)。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentLot)]
+public class CWarehouseRentLot : OmsAuditedAggregateRoot
+{
+ public int CustomerId { get; set; }
+
+ public int WarehouseId { get; set; }
+
+ public int SkuId { get; set; }
+
+ public int? BinLocationId { get; set; }
+
+ public DateTime InboundTime { get; set; }
+
+ public int RemainQty { get; set; }
+
+ /// 单件体积 CBM,入库时用 SKU 尺寸固化。
+ public decimal UnitCbm { get; set; }
+
+ public string SourceType { get; set; } = string.Empty;
+
+ public int SourceId { get; set; }
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRate.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRate.cs
new file mode 100644
index 0000000..5272050
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRate.cs
@@ -0,0 +1,23 @@
+using Oms.Domain.Shared;
+using Oms.Domain.Shared.Enums;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租费率头。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentRate)]
+public class CWarehouseRentRate : OmsAuditedAggregateRoot
+{
+ public string RateName { get; set; } = string.Empty;
+
+ public string Currency { get; set; } = "CNY";
+
+ /// 计费单位,默认 cbmDay(元/CBM/天)。
+ public string CostUnit { get; set; } = "cbmDay";
+
+ public EnableStatus Status { get; set; } = EnableStatus.Enabled;
+
+ public string? Remark { get; set; }
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateDetail.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateDetail.cs
new file mode 100644
index 0000000..02a52df
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateDetail.cs
@@ -0,0 +1,23 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租费率价格明细。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentRateDetail)]
+public class CWarehouseRentRateDetail : OmsAuditedAggregateRoot
+{
+ public int RateId { get; set; }
+
+ [SugarColumn(ColumnDataType = "json", IsNullable = true)]
+ public string? FactorValuesJson { get; set; }
+
+ public string CalculationFormula { get; set; } = "total";
+
+ public decimal? CalculatedValue { get; set; }
+
+ [SugarColumn(ColumnDataType = "json", IsNullable = true)]
+ public string? CustomerGroupValues { get; set; }
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateFactor.cs b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateFactor.cs
new file mode 100644
index 0000000..44a8db2
--- /dev/null
+++ b/src/Oms.Domain/WarehouseAggregate/Entities/CWarehouseRentRateFactor.cs
@@ -0,0 +1,20 @@
+using Oms.Domain.Shared;
+using SqlSugar;
+
+namespace Oms.Domain.WarehouseAggregate.Entities;
+
+///
+/// 仓租费率计费因素。
+///
+[SugarTable(WarehouseTableNames.WarehouseRentRateFactor)]
+public class CWarehouseRentRateFactor : OmsAuditedAggregateRoot
+{
+ public int RateId { get; set; }
+
+ public int SerialNumber { get; set; }
+
+ public string Factor { get; set; } = string.Empty;
+
+ [SugarColumn(ColumnDataType = "json", IsNullable = true)]
+ public string? FactorValues { get; set; }
+}
diff --git a/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs b/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs
index 26c7073..0707d44 100644
--- a/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs
+++ b/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs
@@ -34,3 +34,15 @@ public interface ICParcelItemRepository : IRepository;
public interface ICParcelArrivalRepository : IRepository;
public interface ICSkuPlatformMapRepository : IRepository;
+
+public interface ICWarehouseRentRateRepository : IRepository;
+
+public interface ICWarehouseRentRateFactorRepository : IRepository;
+
+public interface ICWarehouseRentRateDetailRepository : IRepository;
+
+public interface ICWarehouseRentLotRepository : IRepository;
+
+public interface ICWarehouseRentBillRepository : IRepository;
+
+public interface ICWarehouseRentBillLineRepository : IRepository;
diff --git a/src/Oms.Domain/WarehouseAggregate/WarehouseTableNames.cs b/src/Oms.Domain/WarehouseAggregate/WarehouseTableNames.cs
index 058d70d..44cddd7 100644
--- a/src/Oms.Domain/WarehouseAggregate/WarehouseTableNames.cs
+++ b/src/Oms.Domain/WarehouseAggregate/WarehouseTableNames.cs
@@ -15,4 +15,10 @@ public static class WarehouseTableNames
public const string ParcelArrival = "c_parcel_arrival";
public const string ParcelItem = "c_parcel_item";
public const string SkuPlatformMap = "c_sku_platform_map";
+ public const string WarehouseRentRate = "c_warehouse_rent_rate";
+ public const string WarehouseRentRateFactor = "c_warehouse_rent_rate_factor";
+ public const string WarehouseRentRateDetail = "c_warehouse_rent_rate_detail";
+ public const string WarehouseRentLot = "c_warehouse_rent_lot";
+ public const string WarehouseRentBill = "c_warehouse_rent_bill";
+ public const string WarehouseRentBillLine = "c_warehouse_rent_bill_line";
}
diff --git a/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs b/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs
index 08ecd97..93a7bd8 100644
--- a/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs
+++ b/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs
@@ -50,3 +50,15 @@ public class CParcelItemRepository : OmsSqlSugarRepository, ICParce
public class CParcelArrivalRepository : OmsSqlSugarRepository, ICParcelArrivalRepository, IScopedDependency;
public class CSkuPlatformMapRepository : OmsSqlSugarRepository, ICSkuPlatformMapRepository, IScopedDependency;
+
+public class CWarehouseRentRateRepository : OmsSqlSugarRepository, ICWarehouseRentRateRepository, IScopedDependency;
+
+public class CWarehouseRentRateFactorRepository : OmsSqlSugarRepository, ICWarehouseRentRateFactorRepository, IScopedDependency;
+
+public class CWarehouseRentRateDetailRepository : OmsSqlSugarRepository, ICWarehouseRentRateDetailRepository, IScopedDependency;
+
+public class CWarehouseRentLotRepository : OmsSqlSugarRepository, ICWarehouseRentLotRepository, IScopedDependency;
+
+public class CWarehouseRentBillRepository : OmsSqlSugarRepository, ICWarehouseRentBillRepository, IScopedDependency;
+
+public class CWarehouseRentBillLineRepository : OmsSqlSugarRepository, ICWarehouseRentBillLineRepository, IScopedDependency;