20261116 #24

Merged
zzh merged 16 commits from test into master 2026-11-16 09:07:21 +08:00
33 changed files with 2043 additions and 7 deletions
Showing only changes of commit 52df7307f6 - Show all commits

123
db.sql
View File

@ -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_*,接口阶段使用)
-- ---------------------------------------------------------------------------

View File

@ -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;

View File

@ -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}'',

View File

@ -0,0 +1,153 @@
using Oms.Application.Dtos.Channels;
using Oms.Domain.Shared.Enums;
namespace Oms.Application.Dtos.Warehouse;
/// <summary>
/// 仓租费率列表查询。
/// </summary>
public class WarehouseRentRateListInput
{
/// <summary>关键词(费率名称)。</summary>
public string? Keyword { get; set; }
/// <summary>状态。</summary>
public EnableStatus? Status { get; set; }
/// <summary>页码。</summary>
public int PageIndex { get; set; } = 1;
/// <summary>每页条数。</summary>
public int PageSize { get; set; } = 50;
}
/// <summary>
/// 仓租费率保存入参。
/// </summary>
public class WarehouseRentRateSaveInput
{
/// <summary>主键。</summary>
public int? Id { get; set; }
/// <summary>费率名称。</summary>
public string RateName { get; set; } = string.Empty;
/// <summary>币种,固定 CNY。</summary>
public string Currency { get; set; } = "CNY";
/// <summary>计费单位。</summary>
public string CostUnit { get; set; } = "cbmDay";
/// <summary>状态。</summary>
public EnableStatus Status { get; set; } = EnableStatus.Enabled;
/// <summary>备注。</summary>
public string? Remark { get; set; }
/// <summary>计费因素。</summary>
public List<ChannelPriceFactorInput> Factors { get; set; } = [];
/// <summary>价格明细。</summary>
public List<ChannelPriceDetailInput> Details { get; set; } = [];
}
/// <summary>
/// 仓租费率输出。
/// </summary>
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<ChannelPriceFactorOutput> Factors { get; set; } = [];
public List<ChannelPriceDetailOutput> Details { get; set; } = [];
}
/// <summary>
/// 仓租费率启停。
/// </summary>
public class WarehouseRentRateToggleInput
{
public int Id { get; set; }
public EnableStatus Status { get; set; }
}
/// <summary>
/// 仓租账单列表查询。
/// </summary>
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;
}
/// <summary>
/// 仓租账单输出。
/// </summary>
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<WarehouseRentBillLineOutput> Lines { get; set; } = [];
}
/// <summary>
/// 仓租账单明细输出。
/// </summary>
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; }
}
/// <summary>
/// 仓租账单补扣入参。
/// </summary>
public class WarehouseRentBillRetryPayInput
{
public int Id { get; set; }
}
/// <summary>
/// 仓租日结任务触发入参(运维/手工)。
/// </summary>
public class WarehouseRentRunBillingInput
{
/// <summary>业务日,默认昨日。</summary>
public DateTime? BillDate { get; set; }
}

View File

@ -77,5 +77,6 @@ public class OmsApplicationModule : FakeModule
context.Services.AddAiLlmClient();
context.Services.AddHostedService<XhsScheduledPublishWorker>();
context.Services.AddHostedService<MarketingBackgroundWorker>();
context.Services.AddHostedService<WarehouseRentBillingWorker>();
}
}

View File

@ -146,6 +146,7 @@ public class CustomerAccountFlowService : ApplicationService
CustomerAccountFlowBizTypes.CommissionWithdraw => "佣金提现",
CustomerAccountFlowBizTypes.MarketingAdjust => "营销调整",
CustomerAccountFlowBizTypes.ManualAdjust => "人工调整",
CustomerAccountFlowBizTypes.StorageRent => "仓租扣费",
_ => bizType
};
}

View File

@ -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)

View File

@ -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

View File

@ -35,6 +35,9 @@ public partial class OrderService
private ICBinLocationRepository StockBindBinLocationRepository =>
LazyServiceProvider.GetRequiredService<ICBinLocationRepository>();
private WarehouseRentLotManager StockBindRentLotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
/// <summary>
/// 查询物流单当前仓储绑定明细。
/// </summary>
@ -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;
}

View File

@ -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<DataPermAccessAuditor>();
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
/// <summary>
/// 查询订单列表。
/// </summary>

View File

@ -38,6 +38,8 @@ public class PlatformStoreOrderService : ApplicationService
private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>();
private PlatformStoreOrderFulfillmentService FulfillmentService =>
LazyServiceProvider.GetRequiredService<PlatformStoreOrderFulfillmentService>();
private WarehouseRentLotManager RentLotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
/// <summary>
/// 查询店铺订单列表。
@ -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);
}
}

View File

@ -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;
/// <summary>
/// 仓租费率配置与日账单 API。
/// </summary>
[ApiExplorerSettings(GroupName = "OMS-Warehouse")]
public class WarehouseRentService : ApplicationService
{
private ICWarehouseRentRateRepository RateRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentRateRepository>();
private ICWarehouseRentRateFactorRepository FactorRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentRateFactorRepository>();
private ICWarehouseRentRateDetailRepository DetailRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentRateDetailRepository>();
private ICWarehouseRentLotRepository LotRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentLotRepository>();
private ICWarehouseRentBillRepository BillRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>();
private ICWarehouseRentBillLineRepository BillLineRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentBillLineRepository>();
private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService<ICSkuRepository>();
private ICustomerRepository CustomerRepository =>
LazyServiceProvider.GetRequiredService<ICustomerRepository>();
private IWarehouseAddressRepository WarehouseAddressRepository =>
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
private CustomerBalanceMutator BalanceMutator =>
LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>();
/// <summary>
/// 分页查询仓租费率。
/// </summary>
[HttpPost("/warehouse/storage-rent/rate/list")]
public async Task<OmsPageResult<WarehouseRentRateOutput>> GetRateListAsync(WarehouseRentRateListInput input)
{
var keyword = input.Keyword?.Trim();
var hasKeyword = !string.IsNullOrWhiteSpace(keyword);
var hasStatus = input.Status.HasValue && input.Status.Value != EnableStatus.None;
Expression<Func<CWarehouseRentRate, bool>> 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<string, bool>
{
[nameof(CWarehouseRentRate.UpdateTime)] = false,
[nameof(CWarehouseRentRate.Id)] = false
});
var total = await RateRepository.CountAsync(predicate);
return new OmsPageResult<WarehouseRentRateOutput>
{
Items = entities.Select(MapRateListItem).ToList(),
Total = total
};
}
/// <summary>
/// 获取仓租费率详情(含因素与价格明细)。
/// </summary>
[HttpGet("/warehouse/storage-rent/rate/get")]
public async Task<WarehouseRentRateOutput> GetRateAsync([FromQuery] int id)
{
var entity = await RateRepository.FirstOrDefaultAsync(x => x.Id == id)
?? throw new BusinessException("仓租费率不存在");
return await MapRateDetailAsync(entity);
}
/// <summary>
/// 保存仓租费率(新增或更新)。
/// </summary>
[HttpPost("/warehouse/storage-rent/rate/save")]
public async Task<WarehouseRentRateOutput> 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);
}
/// <summary>
/// 启停仓租费率。
/// </summary>
[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);
}
/// <summary>
/// 删除仓租费率。
/// </summary>
/// <param name="input">入参:费率 Id。</param>
[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);
}
}
/// <summary>
/// 分页查询仓租日账单。
/// </summary>
[HttpPost("/warehouse/storage-rent/bill/list")]
public async Task<OmsPageResult<WarehouseRentBillOutput>> 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<Func<CWarehouseRentBill, bool>> 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<string, bool>
{
[nameof(CWarehouseRentBill.BillDate)] = false,
[nameof(CWarehouseRentBill.Id)] = false
});
var total = await BillRepository.CountAsync(predicate);
var items = await MapBillsAsync(entities, includeLines: false);
return new OmsPageResult<WarehouseRentBillOutput> { Items = items, Total = total };
}
/// <summary>
/// 仓租日账单详情(含明细)。
/// </summary>
[HttpGet("/warehouse/storage-rent/bill/detail")]
public async Task<WarehouseRentBillOutput> 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];
}
/// <summary>
/// 对 unpaid 账单补扣余额并写流水。
/// </summary>
[HttpPost("/warehouse/storage-rent/bill/retry-pay")]
public async Task<WarehouseRentBillOutput> 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];
}
/// <summary>
/// 手工触发指定业务日仓租日结(默认昨日)。
/// </summary>
[HttpPost("/warehouse/storage-rent/bill/run")]
public async Task<OmsItemsResult<string>> RunBillingAsync(WarehouseRentRunBillingInput input)
{
var billDate = (input.BillDate ?? DateTime.Now.Date.AddDays(-1)).Date;
var count = await RunDailyBillingAsync(billDate);
return new OmsItemsResult<string>
{
Items = [$"业务日 {billDate:yyyy-MM-dd} 处理完成,生成/重试账单组数:{count}"]
};
}
/// <summary>
/// 日终结算入口:按客户+仓库生成昨日账单并尝试扣款。
/// </summary>
public async Task<int> 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;
}
/// <summary>
/// 对单个客户+仓库执行指定业务日仓租结算(幂等)。
/// </summary>
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<CWarehouseRentLot> 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<CWarehouseRentBillLine>();
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<List<WarehouseRentCalculator.RateBundle>> 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<ChannelPriceFactorInput> factors,
List<ChannelPriceDetailInput> 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<string> 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<WarehouseRentRateOutput> 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<List<string>>(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<List<WarehouseRentBillOutput>> MapBillsAsync(
List<CWarehouseRentBill> 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<int, List<CWarehouseRentBillLine>> lineMap = new();
Dictionary<int, CSku> 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();
}
}

View File

@ -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)

View File

@ -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);
}
}

View File

@ -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);
}
/// <summary>

View File

@ -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;

View File

@ -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<ILabelTemplateRepository>();
private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService<ILabelPdfRenderer>();
private WarehouseRentLotManager RentLotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
}

View File

@ -167,7 +167,33 @@ public class CustomerBalanceMutator : IScopedDependency
cancellationToken);
}
private async Task ApplyAsync(
/// <summary>
/// 仓租日结扣费,写入账户流水并返回流水实体。
/// </summary>
public Task<CustomerAccountFlow> 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<CustomerAccountFlow> 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<string> GenerateSerialNumberAsync(CancellationToken cancellationToken)

View File

@ -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;
/// <summary>
/// 仓租费率匹配:仓库 × 天数区间 × 体积区间 × 客户组。
/// </summary>
public static class WarehouseRentCalculator
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
PropertyNameCaseInsensitive = true
};
public sealed record RateBundle(
CWarehouseRentRate Rate,
IReadOnlyList<CWarehouseRentRateFactor> Factors,
IReadOnlyList<ChannelPriceDetailOutput> Details);
/// <summary>
/// 在启用费率中匹配单价;无命中返回 null。
/// </summary>
public static decimal? MatchUnitPrice(
IReadOnlyList<RateBundle> 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<List<string>>(warehouseFactor.FactorValues) ?? [];
if (values.Count == 0)
{
return true;
}
return values.Any(v => MatchWarehouseValue(v, warehouseId, warehouseName));
}
private static bool MatchWarehouseInDetail(
Dictionary<string, string> 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<string, string> 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<string, string> 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<string, string> ParseFactorDictionary(object? factorValuesJson)
{
if (factorValuesJson == null)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
try
{
var json = factorValuesJson is string s
? s
: JsonSerializer.Serialize(factorValuesJson, JsonOptions);
var map = JsonSerializer.Deserialize<Dictionary<string, JsonElement>>(json, JsonOptions);
if (map == null)
{
return new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
var result = new Dictionary<string, string>(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<string, string>(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<Dictionary<string, decimal>>(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;
}
}

View File

@ -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;
/// <summary>
/// 仓租库龄批次维护:入库增加、出库 FIFO 扣减、移位。
/// </summary>
public class WarehouseRentLotManager : IScopedDependency
{
private readonly ICWarehouseRentLotRepository _lotRepository;
private readonly ICSkuRepository _skuRepository;
public WarehouseRentLotManager(
ICWarehouseRentLotRepository lotRepository,
ICSkuRepository skuRepository)
{
_lotRepository = lotRepository;
_skuRepository = skuRepository;
}
/// <summary>
/// 按 SKU 尺寸计算单件 CBM(cm³ / 1e6);缺尺寸返回 0。
/// </summary>
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);
}
/// <summary>
/// 入库/上架新增批次。
/// </summary>
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);
}
/// <summary>
/// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。
/// </summary>
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);
}
}
/// <summary>
/// 库位移位:从源库位 FIFO 扣减并在目标库位写入同库龄批次。
/// </summary>
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);
}
}
}

View File

@ -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;
/// <summary>
/// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表,按组开独立 UoW。
/// </summary>
public class WarehouseRentBillingWorker : BackgroundService
{
private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1);
private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<WarehouseRentBillingWorker> _logger;
public WarehouseRentBillingWorker(
IServiceScopeFactory scopeFactory,
ILogger<WarehouseRentBillingWorker> 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<ICWarehouseRentLotRepository>();
var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0);
groups = lots
.Select(x => (x.CustomerId, x.WarehouseId))
.Distinct()
.ToList();
var billRepository = scope.ServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>();
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<IUnitOfWorkManager>();
using var unitOfWork = unitOfWorkManager.Begin();
var rentService = scope.ServiceProvider.GetRequiredService<WarehouseRentService>();
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);
}
}
}

View File

@ -21,4 +21,7 @@ public static class CustomerAccountFlowBizTypes
/// <summary>运营人工调整账户余额。</summary>
public const string ManualAdjust = "manualAdjust";
/// <summary>仓租日结扣费。</summary>
public const string StorageRent = "storageRent";
}

View File

@ -5,6 +5,7 @@ namespace Oms.Domain.SystemAggregate.Consts;
/// </summary>
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, "签收"),

View File

@ -0,0 +1,32 @@
namespace Oms.Domain.WarehouseAggregate.Consts;
/// <summary>
/// 仓租相关常量。
/// </summary>
public static class WarehouseRentFactorCodes
{
public const string Warehouse = "warehouse";
public const string Days = "days";
public const string Volume = "volume";
public const string Customer = "customer";
}
/// <summary>
/// 仓租批次来源。
/// </summary>
public static class WarehouseRentLotSourceCodes
{
public const string Inbound = "inbound";
public const string Parcel = "parcel";
}
/// <summary>
/// 仓租日账单状态。
/// </summary>
public static class WarehouseRentBillStatusCodes
{
public const string Pending = "pending";
public const string Paid = "paid";
public const string Unpaid = "unpaid";
public const string Zero = "zero";
}

View File

@ -0,0 +1,35 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租日账单。
/// </summary>
[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; }
}

View File

@ -0,0 +1,31 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租日账单明细。
/// </summary>
[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; }
}

View File

@ -0,0 +1,30 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租库龄批次(计费真相源)。
/// </summary>
[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; }
/// <summary>单件体积 CBM,入库时用 SKU 尺寸固化。</summary>
public decimal UnitCbm { get; set; }
public string SourceType { get; set; } = string.Empty;
public int SourceId { get; set; }
}

View File

@ -0,0 +1,23 @@
using Oms.Domain.Shared;
using Oms.Domain.Shared.Enums;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租费率头。
/// </summary>
[SugarTable(WarehouseTableNames.WarehouseRentRate)]
public class CWarehouseRentRate : OmsAuditedAggregateRoot
{
public string RateName { get; set; } = string.Empty;
public string Currency { get; set; } = "CNY";
/// <summary>计费单位,默认 cbmDay(元/CBM/天)。</summary>
public string CostUnit { get; set; } = "cbmDay";
public EnableStatus Status { get; set; } = EnableStatus.Enabled;
public string? Remark { get; set; }
}

View File

@ -0,0 +1,23 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租费率价格明细。
/// </summary>
[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; }
}

View File

@ -0,0 +1,20 @@
using Oms.Domain.Shared;
using SqlSugar;
namespace Oms.Domain.WarehouseAggregate.Entities;
/// <summary>
/// 仓租费率计费因素。
/// </summary>
[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; }
}

View File

@ -34,3 +34,15 @@ public interface ICParcelItemRepository : IRepository<CParcelItem>;
public interface ICParcelArrivalRepository : IRepository<CParcelArrival>;
public interface ICSkuPlatformMapRepository : IRepository<CSkuPlatformMap>;
public interface ICWarehouseRentRateRepository : IRepository<CWarehouseRentRate>;
public interface ICWarehouseRentRateFactorRepository : IRepository<CWarehouseRentRateFactor>;
public interface ICWarehouseRentRateDetailRepository : IRepository<CWarehouseRentRateDetail>;
public interface ICWarehouseRentLotRepository : IRepository<CWarehouseRentLot>;
public interface ICWarehouseRentBillRepository : IRepository<CWarehouseRentBill>;
public interface ICWarehouseRentBillLineRepository : IRepository<CWarehouseRentBillLine>;

View File

@ -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";
}

View File

@ -50,3 +50,15 @@ public class CParcelItemRepository : OmsSqlSugarRepository<CParcelItem>, ICParce
public class CParcelArrivalRepository : OmsSqlSugarRepository<CParcelArrival>, ICParcelArrivalRepository, IScopedDependency;
public class CSkuPlatformMapRepository : OmsSqlSugarRepository<CSkuPlatformMap>, ICSkuPlatformMapRepository, IScopedDependency;
public class CWarehouseRentRateRepository : OmsSqlSugarRepository<CWarehouseRentRate>, ICWarehouseRentRateRepository, IScopedDependency;
public class CWarehouseRentRateFactorRepository : OmsSqlSugarRepository<CWarehouseRentRateFactor>, ICWarehouseRentRateFactorRepository, IScopedDependency;
public class CWarehouseRentRateDetailRepository : OmsSqlSugarRepository<CWarehouseRentRateDetail>, ICWarehouseRentRateDetailRepository, IScopedDependency;
public class CWarehouseRentLotRepository : OmsSqlSugarRepository<CWarehouseRentLot>, ICWarehouseRentLotRepository, IScopedDependency;
public class CWarehouseRentBillRepository : OmsSqlSugarRepository<CWarehouseRentBill>, ICWarehouseRentBillRepository, IScopedDependency;
public class CWarehouseRentBillLineRepository : OmsSqlSugarRepository<CWarehouseRentBillLine>, ICWarehouseRentBillLineRepository, IScopedDependency;