From f66d567c49f335a2e72a1f736140381a79d1be30 Mon Sep 17 00:00:00 2001 From: zzh <1368735060@qq.com> Date: Mon, 23 Nov 2026 16:32:05 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=9C=8D=E5=8A=A1=E6=B8=A0=E9=81=93?= =?UTF-8?q?=E7=8B=AC=E7=AB=8B=E8=AE=A1=E9=87=8D=EF=BC=8C=E5=BA=94=E4=BB=98?= =?UTF-8?q?=E4=B8=8E=E6=8F=BD=E6=94=B6=E5=BA=94=E4=BB=98=E7=94=A8=E6=B8=A0?= =?UTF-8?q?=E9=81=93=E8=AE=A1=E8=B4=B9=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 应收仍走销售产品计重;排货/重算应付/对账/揽收推费按渠道计重写入 PayableChargeableWeight,不改 ChargeableWeight。 Co-authored-by: Cursor --- db.sql | 8 +- ...igrate_channel_payable_weight_20261123.sql | 72 ++++ .../SalesProductBillingSimulateDtos.cs | 4 + .../Channels/ServiceChannelDetailOutput.cs | 10 + .../Dtos/Channels/ServiceChannelListOutput.cs | 10 + .../ServiceChannelRulesPublishSnapshotDto.cs | 18 + .../Dtos/Channels/ServiceChannelSaveInput.cs | 10 + .../Dtos/Orders/OrderAllocationTraceDtos.cs | 7 + .../Dtos/Orders/OrderWeightOutput.cs | 7 +- .../Dtos/Orders/PickupOrderDtos.cs | 8 + .../SalesProductService.BillingSimulate.cs | 78 ++++- .../Channels/ServiceChannelService.Helpers.cs | 48 +++ .../Channels/ServiceChannelService.cs | 2 + .../Services/Orders/OrderService.Helpers.cs | 1 + .../Services/Orders/OrderService.OrderEdit.cs | 41 ++- .../Orders/OrderService.ParcelBilling.cs | 320 +++++++++++++++++- .../Orders/PickupOrderFeePushService.cs | 54 ++- .../Services/Orders/PickupOrderService.cs | 1 + .../Shared/AllocationResolver.cs | 3 + .../Entities/ServiceChannel.cs | 10 + .../OrdersAggregate/Entities/OrderWeight.cs | 8 + .../OrdersAggregate/Entities/PickupOrder.cs | 9 + 22 files changed, 673 insertions(+), 56 deletions(-) create mode 100644 sql/migrate_channel_payable_weight_20261123.sql diff --git a/db.sql b/db.sql index 6abd3ef..9b61816 100644 --- a/db.sql +++ b/db.sql @@ -479,7 +479,8 @@ CREATE TABLE `t_order_weight` ( `Height` DECIMAL(10,2) NULL COMMENT '高(cm)', `ActualWeight` DECIMAL(10,3) NULL COMMENT '实重(kg)', `VolumetricWeight` DECIMAL(10,3) NULL COMMENT '体积重(kg)', - `ChargeableWeight` DECIMAL(10,3) NULL COMMENT '计费重(kg)', + `ChargeableWeight` DECIMAL(10,3) NULL COMMENT '计费重(kg)(应收,销售产品计重)', + `PayableChargeableWeight` DECIMAL(10,3) NULL COMMENT '应付计费重(kg)(渠道计重)', `Cubic` DECIMAL(12,6) NULL COMMENT '立方(m³)', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', `CreateUserId` INT NOT NULL DEFAULT 0 COMMENT '创建人', @@ -720,6 +721,8 @@ CREATE TABLE `t_service_channel` ( `ForecastCode` VARCHAR(128) NULL COMMENT '预报单号', `Description` TEXT COMMENT '描述', `RemoteAreaId` INT NULL COMMENT '偏远分区KPI AreaId', + `WeightRuleId` INT NULL COMMENT '计重规则ID(应付)', + `WeightRoundingId` INT NULL COMMENT '计重进位ID(应付)', `PreScript` TEXT COMMENT '入库前脚本', `IsActive` TINYINT NOT NULL DEFAULT 2 COMMENT 'EnableStatus:0=None未设置,1=Disabled禁用,2=Enabled启用', `IsDeleted` TINYINT NOT NULL DEFAULT 0 COMMENT '软删除:0-否,1-是', @@ -2260,7 +2263,8 @@ CREATE TABLE `t_pickup_order` ( `Status` VARCHAR(32) NOT NULL DEFAULT 'draft' COMMENT 'draft/scheduled/dispatched/picked/inbound/cancelled/failed', `ParcelCount` INT NOT NULL DEFAULT 0 COMMENT '关联票数', `TotalActualWeight` DECIMAL(18,3) NULL COMMENT '汇总实重', - `ChargeableWeight` DECIMAL(18,3) NULL COMMENT '计费重', + `ChargeableWeight` DECIMAL(18,3) NULL COMMENT '应收计费重(销售产品计重)', + `PayableChargeableWeight` DECIMAL(18,3) NULL COMMENT '应付计费重(渠道计重)', `VolumetricWeight` DECIMAL(18,3) NULL COMMENT '体积重', `PackageSizesJson` TEXT NULL COMMENT '承运回传尺寸 JSON', `CarrierFreightWeight` DECIMAL(18,3) NULL COMMENT '承运计费重(对照)', diff --git a/sql/migrate_channel_payable_weight_20261123.sql b/sql/migrate_channel_payable_weight_20261123.sql new file mode 100644 index 0000000..fd06e4c --- /dev/null +++ b/sql/migrate_channel_payable_weight_20261123.sql @@ -0,0 +1,72 @@ +-- 服务渠道独立计重(应付);订单件重尺增加应付计费重。 +-- 可重复执行。不改 ChargeableWeight 语义(仍为应收计费重)。 + +SET @db := DATABASE(); + +-- t_service_channel.WeightRuleId +SET @exists := ( + SELECT COUNT(1) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_service_channel' + AND COLUMN_NAME = 'WeightRuleId' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE `t_service_channel` ADD COLUMN `WeightRuleId` INT NULL COMMENT ''计重规则ID(应付)'' AFTER `RemoteAreaId`', + 'SELECT ''t_service_channel.WeightRuleId already exists'' AS info' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- t_service_channel.WeightRoundingId +SET @exists := ( + SELECT COUNT(1) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_service_channel' + AND COLUMN_NAME = 'WeightRoundingId' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE `t_service_channel` ADD COLUMN `WeightRoundingId` INT NULL COMMENT ''计重进位ID(应付)'' AFTER `WeightRuleId`', + 'SELECT ''t_service_channel.WeightRoundingId already exists'' AS info' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- t_order_weight.PayableChargeableWeight +SET @exists := ( + SELECT COUNT(1) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_order_weight' + AND COLUMN_NAME = 'PayableChargeableWeight' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE `t_order_weight` ADD COLUMN `PayableChargeableWeight` DECIMAL(10,3) NULL COMMENT ''应付计费重(kg),渠道计重'' AFTER `ChargeableWeight`', + 'SELECT ''t_order_weight.PayableChargeableWeight already exists'' AS info' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; + +-- t_pickup_order.PayableChargeableWeight +SET @exists := ( + SELECT COUNT(1) + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = @db + AND TABLE_NAME = 't_pickup_order' + AND COLUMN_NAME = 'PayableChargeableWeight' +); +SET @sql := IF( + @exists = 0, + 'ALTER TABLE `t_pickup_order` ADD COLUMN `PayableChargeableWeight` DECIMAL(18,3) NULL COMMENT ''应付计费重(kg),渠道计重'' AFTER `ChargeableWeight`', + 'SELECT ''t_pickup_order.PayableChargeableWeight already exists'' AS info' +); +PREPARE stmt FROM @sql; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs b/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs index fcda3e1..cafcdcd 100644 --- a/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs +++ b/src/Oms.Application/Dtos/Channels/SalesProductBillingSimulateDtos.cs @@ -61,8 +61,12 @@ public class SalesProductBillingSimulateInput /// public class SalesProductBillingSimulateOutput { + /// 应收计费重(销售产品计重)。 public decimal ChargeableWeight { get; set; } + /// 应付计费重(首个可用渠道计重;未算出则为 null)。 + public decimal? PayableChargeableWeight { get; set; } + public List ZoneKeys { get; set; } = []; public bool IsRemote { get; set; } diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs index 106135a..165f781 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelDetailOutput.cs @@ -60,6 +60,16 @@ public class ServiceChannelDetailOutput /// public int? RemoteAreaId { get; set; } + /// + /// 计重规则 ID(应付)。 + /// + public int? WeightRuleId { get; set; } + + /// + /// 计重进位 ID(应付)。 + /// + public int? WeightRoundingId { get; set; } + /// /// 预处理脚本。 /// diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs index e491347..b419110 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelListOutput.cs @@ -60,6 +60,16 @@ public class ServiceChannelListOutput /// public int? RemoteAreaId { get; set; } + /// + /// 计重规则 ID(应付)。 + /// + public int? WeightRuleId { get; set; } + + /// + /// 计重进位 ID(应付)。 + /// + public int? WeightRoundingId { get; set; } + /// /// 是否启用。 /// diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelRulesPublishSnapshotDto.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelRulesPublishSnapshotDto.cs index e192c5e..53bcb69 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelRulesPublishSnapshotDto.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelRulesPublishSnapshotDto.cs @@ -24,4 +24,22 @@ public class ServiceChannelRulesPublishSnapshotDto /// 运行时 hydrate / LIVE 用,不落发布 JSON。 [JsonIgnore] public List RemoteAreaInfos { get; set; } = []; + + /// 计重规则 ID(应付,发布时固化)。 + public int? WeightRuleId { get; set; } + + /// 计重规则名称。 + public string? WeightRuleName { get; set; } + + /// 计重规则明细,发布时从 t_weight_rule_info 固化。 + public List WeightRuleInfos { get; set; } = []; + + /// 计重进位 ID(应付,发布时固化)。 + public int? WeightRoundingId { get; set; } + + /// 计重进位名称。 + public string? WeightRoundingName { get; set; } + + /// 计重进位区间,发布时从 t_weight_rounding_info 固化。 + public List WeightRoundingInfos { get; set; } = []; } diff --git a/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs b/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs index c54b6c2..be46ba4 100644 --- a/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs +++ b/src/Oms.Application/Dtos/Channels/ServiceChannelSaveInput.cs @@ -57,6 +57,16 @@ public class ServiceChannelSaveInput /// public int? RemoteAreaId { get; set; } + /// + /// 计重规则 ID(应付)。 + /// + public int? WeightRuleId { get; set; } + + /// + /// 计重进位 ID(应付)。 + /// + public int? WeightRoundingId { get; set; } + /// /// 预处理脚本。 /// diff --git a/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs b/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs index 438e3cb..ee2a235 100644 --- a/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs +++ b/src/Oms.Application/Dtos/Orders/OrderAllocationTraceDtos.cs @@ -19,8 +19,12 @@ public class OrderAllocationTraceOutput public string? SchemeSourceName { get; set; } + /// 选中渠道的应付计费重(渠道计重;历史字段名保留兼容)。 public decimal? ChargeableWeight { get; set; } + /// 选中渠道的应付计费重(与 ChargeableWeight 同值,便于前端区分应收)。 + public decimal? PayableChargeableWeight { get; set; } + /// 订单解析出的价格分区键(用于对照买价明细分区)。 public List ZoneKeys { get; set; } = []; @@ -67,6 +71,9 @@ public class OrderAllocationCandidateOutput /// 综合权重(综合最优主指标)。 public int Weight { get; set; } + /// 该候选渠道按渠道计重算出的应付计费重。 + public decimal? PayableChargeableWeight { get; set; } + public bool Selected { get; set; } public List FeeLines { get; set; } = []; diff --git a/src/Oms.Application/Dtos/Orders/OrderWeightOutput.cs b/src/Oms.Application/Dtos/Orders/OrderWeightOutput.cs index a39d132..440f239 100644 --- a/src/Oms.Application/Dtos/Orders/OrderWeightOutput.cs +++ b/src/Oms.Application/Dtos/Orders/OrderWeightOutput.cs @@ -36,10 +36,15 @@ public class OrderWeightOutput public decimal? VolumetricWeight { get; set; } /// - /// 计费重量。 + /// 应收计费重(销售产品计重)。 /// public decimal? ChargeableWeight { get; set; } + /// + /// 应付计费重(服务渠道计重)。 + /// + public decimal? PayableChargeableWeight { get; set; } + /// /// 体积。 /// diff --git a/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs b/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs index 3633ccd..50849f2 100644 --- a/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs +++ b/src/Oms.Application/Dtos/Orders/PickupOrderDtos.cs @@ -309,8 +309,12 @@ public class PickupOrderOutput public decimal? TotalActualWeight { get; set; } + /// 应收计费重(销售产品计重)。 public decimal? ChargeableWeight { get; set; } + /// 应付计费重(渠道计重)。 + public decimal? PayableChargeableWeight { get; set; } + public decimal? VolumetricWeight { get; set; } public List PackageSizes { get; set; } = []; @@ -400,8 +404,12 @@ public class PickupOpenApiPushFeeResult public decimal TotalActualWeight { get; set; } + /// 应收计费重(销售产品计重)。 public decimal ChargeableWeight { get; set; } + /// 应付计费重(渠道计重)。 + public decimal? PayableChargeableWeight { get; set; } + public decimal? VolumetricWeight { get; set; } public decimal ReceivableAmount { get; set; } diff --git a/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs b/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs index 3c6d5f9..243cc27 100644 --- a/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs +++ b/src/Oms.Application/Services/Channels/SalesProductService.BillingSimulate.cs @@ -180,12 +180,13 @@ public partial class SalesProductService }).ToList(); var payableFees = new List(); + decimal? payableChargeableWeight = null; try { - payableFees = await TrySimulatePayableFeesAsync( + (payableFees, payableChargeableWeight) = await TrySimulatePayableFeesAsync( product, rulesSnapshot, - chargeableWeight, + weight, cargoAttribute, input.WarehouseId, warehouseName, @@ -227,6 +228,7 @@ public partial class SalesProductService return new SalesProductBillingSimulateOutput { ChargeableWeight = chargeableWeight, + PayableChargeableWeight = payableChargeableWeight, ZoneKeys = zoneKeys.ToList(), IsRemote = isRemote, ReceivableFees = receivableFees, @@ -316,10 +318,10 @@ public partial class SalesProductService return warehouse?.WarehouseName; } - private async Task> TrySimulatePayableFeesAsync( + private async Task<(List Fees, decimal? PayableChargeableWeight)> TrySimulatePayableFeesAsync( SalesProduct product, SalesProductRulesPublishSnapshotDto rulesSnapshot, - decimal chargeableWeight, + OrderWeight weight, string cargoAttribute, int? warehouseId, string? warehouseName, @@ -356,10 +358,28 @@ public partial class SalesProductService if (provider?.ServiceChannelId is not > 0) { warnings.Add("未配置可用排货服务渠道,跳过应付估算"); - return []; + return ([], null); } var channelId = provider.ServiceChannelId.Value; + var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == channelId); + if (channel == null) + { + warnings.Add($"服务渠道 {channelId} 不存在,跳过应付估算"); + return ([], null); + } + + decimal payableChargeableWeight; + try + { + payableChargeableWeight = await ResolveSimulateChannelPayableWeightAsync(channel, weight); + } + catch (Exception ex) + { + warnings.Add($"服务渠道 {channelId} 计重失败,跳过应付估算:{ex.Message}"); + return ([], null); + } + var channelPriceSnapshot = new ServiceChannelPricePublishSnapshotDto { ServiceChannelId = channelId, @@ -370,7 +390,7 @@ public partial class SalesProductService if (channelPriceSnapshot.Prices.Count == 0) { warnings.Add($"服务渠道 {channelId} 无买价,跳过应付估算"); - return []; + return ([], payableChargeableWeight); } await PriceAreaSnapshotHelper.ApplyLiveChannelPriceAreaInfosAsync( @@ -393,14 +413,13 @@ public partial class SalesProductService if (resolved == null || resolved.Count == 0) { warnings.Add($"服务渠道 {channelId} 买价分区未匹配,跳过应付估算"); - return []; + return ([], payableChargeableWeight); } payableZoneKeys = resolved; } - var channel = await ServiceChannelRepository.FirstOrDefaultAsync(x => x.Id == channelId); - var channelRemoteAreaId = channel?.RemoteAreaId; + var channelRemoteAreaId = channel.RemoteAreaId; var channelIsRemote = productIsRemote; if (channelRemoteAreaId is > 0) { @@ -440,7 +459,7 @@ public partial class SalesProductService channelPrices, priceVersion, priceEffectiveTime, - chargeableWeight, + payableChargeableWeight, payableZoneKeys, cargoAttribute, OrderFeeChargingStageCodes.Forecast, @@ -454,16 +473,41 @@ public partial class SalesProductService if (payable.Count == 0) { warnings.Add($"服务渠道 {channelId} 买价未匹配,跳过应付估算"); - return []; + return ([], payableChargeableWeight); } - warnings.Add($"应付按排货服务渠道 {channelId} 估算(首个可用渠道,渠道价区)"); - return payable.Select(x => new SalesProductBillingSimulateFeeOutput + warnings.Add($"应付按排货服务渠道 {channelId} 估算(首个可用渠道,渠道计重+价区)"); + return ( + payable.Select(x => new SalesProductBillingSimulateFeeOutput + { + CostItem = x.CostItem, + Amount = x.Amount, + Currency = x.Currency ?? string.Empty + }).ToList(), + payableChargeableWeight); + } + + /// + /// 试算应付:按服务渠道计重规则/进位(不改应收计重)。 + /// + private async Task ResolveSimulateChannelPayableWeightAsync( + ServiceChannel channel, + OrderWeight weight) + { + if (channel.WeightRuleId is not > 0) { - CostItem = x.CostItem, - Amount = x.Amount, - Currency = x.Currency ?? string.Empty - }).ToList(); + throw new BusinessException("渠道未配置计重规则"); + } + + if (channel.WeightRoundingId is not > 0) + { + throw new BusinessException("渠道未配置计重进位"); + } + + var ruleInfos = await WeightRuleRepository.GetAllInfosByRuleIdAsync(channel.WeightRuleId.Value); + var (_, rawWeight) = ParcelBillingCalculator.CalculateRawBillableWeight(weight, ruleInfos); + var ranges = await WeightRoundingRepository.GetAllInfosByRoundingIdAsync(channel.WeightRoundingId.Value); + return ParcelBillingCalculator.ApplyRounding(rawWeight, ranges); } private async Task> BuildChannelPriceOutputsAsync(int serviceChannelId) diff --git a/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs b/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs index b986819..738db6e 100644 --- a/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs +++ b/src/Oms.Application/Services/Channels/ServiceChannelService.Helpers.cs @@ -322,6 +322,7 @@ public partial class ServiceChannelService snapshot.RemoteAreaRef = null; } + await ApplyChannelWeightToRulesSnapshotAsync(snapshot, entity); return snapshot; } @@ -362,9 +363,48 @@ public partial class ServiceChannelService snapshot.RemoteAreaRef = null; } + await ApplyChannelWeightToRulesSnapshotAsync(snapshot, entity); return snapshot; } + /// + /// 渠道规则快照固化计重规则/进位明细(应付)。 + /// + private async Task ApplyChannelWeightToRulesSnapshotAsync( + ServiceChannelRulesPublishSnapshotDto snapshot, + ServiceChannel entity) + { + if (entity.WeightRuleId is > 0) + { + snapshot.WeightRuleId = entity.WeightRuleId; + var rule = await WeightRuleRepository.FirstOrDefaultAsync(x => x.Id == entity.WeightRuleId.Value); + snapshot.WeightRuleName = rule?.Name; + var infos = await WeightRuleRepository.GetAllInfosByRuleIdAsync(entity.WeightRuleId.Value); + snapshot.WeightRuleInfos = infos.Select(PublishSnapshotSlimmer.SlimWeightRule).ToList(); + } + else + { + snapshot.WeightRuleId = null; + snapshot.WeightRuleName = null; + snapshot.WeightRuleInfos = []; + } + + if (entity.WeightRoundingId is > 0) + { + snapshot.WeightRoundingId = entity.WeightRoundingId; + var rounding = await WeightRoundingRepository.FirstOrDefaultAsync(x => x.Id == entity.WeightRoundingId.Value); + snapshot.WeightRoundingName = rounding?.Name; + var ranges = await WeightRoundingRepository.GetAllInfosByRoundingIdAsync(entity.WeightRoundingId.Value); + snapshot.WeightRoundingInfos = ranges.Select(PublishSnapshotSlimmer.SlimWeightRounding).ToList(); + } + else + { + snapshot.WeightRoundingId = null; + snapshot.WeightRoundingName = null; + snapshot.WeightRoundingInfos = []; + } + } + private string ResolvePublishUser() => string.IsNullOrWhiteSpace(CurrentUser.UserName) ? CurrentUser.GetId().ToString() @@ -383,6 +423,8 @@ public partial class ServiceChannelService ForecastCode = entity.ForecastCode, Description = entity.Description, RemoteAreaId = entity.RemoteAreaId, + WeightRuleId = entity.WeightRuleId, + WeightRoundingId = entity.WeightRoundingId, PreScript = entity.PreScript, IsActive = entity.IsActive }; @@ -469,6 +511,8 @@ public partial class ServiceChannelService entity.ForecastCode = input.ForecastCode; entity.Description = input.Description; entity.RemoteAreaId = input.RemoteAreaId; + entity.WeightRuleId = input.WeightRuleId; + entity.WeightRoundingId = input.WeightRoundingId; entity.PreScript = input.PreScript; entity.IsActive = input.IsActive; } @@ -564,6 +608,8 @@ public partial class ServiceChannelService ForecastCode = entity.ForecastCode, Description = entity.Description, RemoteAreaId = entity.RemoteAreaId, + WeightRuleId = entity.WeightRuleId, + WeightRoundingId = entity.WeightRoundingId, IsActive = (byte)entity.IsActive, CreateTime = entity.CreateTime, CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, auditUserNameMap), @@ -590,6 +636,8 @@ public partial class ServiceChannelService ForecastCode = entity.ForecastCode, Description = entity.Description, RemoteAreaId = entity.RemoteAreaId, + WeightRuleId = entity.WeightRuleId, + WeightRoundingId = entity.WeightRoundingId, PreScript = entity.PreScript, IsActive = (byte)entity.IsActive, CreateTime = entity.CreateTime, diff --git a/src/Oms.Application/Services/Channels/ServiceChannelService.cs b/src/Oms.Application/Services/Channels/ServiceChannelService.cs index 4e8336d..ac7a847 100644 --- a/src/Oms.Application/Services/Channels/ServiceChannelService.cs +++ b/src/Oms.Application/Services/Channels/ServiceChannelService.cs @@ -21,6 +21,8 @@ public partial class ServiceChannelService : ApplicationService private IServiceChannelRepository ServiceChannelRepository => LazyServiceProvider.GetRequiredService(); private IServiceChannelGroupRepository ServiceChannelGroupRepository => LazyServiceProvider.GetRequiredService(); private IKpiAreaRepository KpiAreaRepository => LazyServiceProvider.GetRequiredService(); + private IWeightRuleRepository WeightRuleRepository => LazyServiceProvider.GetRequiredService(); + private IWeightRoundingRepository WeightRoundingRepository => LazyServiceProvider.GetRequiredService(); private KpiAreaPackService KpiAreaPackService => LazyServiceProvider.GetRequiredService(); private AllocationProviderSnapshotEnricher AllocationProviderSnapshotEnricher => LazyServiceProvider.GetRequiredService(); diff --git a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs index 26ba52f..0881120 100644 --- a/src/Oms.Application/Services/Orders/OrderService.Helpers.cs +++ b/src/Oms.Application/Services/Orders/OrderService.Helpers.cs @@ -1116,6 +1116,7 @@ public partial class OrderService ActualWeight = x.ActualWeight, VolumetricWeight = x.VolumetricWeight, ChargeableWeight = x.ChargeableWeight, + PayableChargeableWeight = x.PayableChargeableWeight, Cubic = x.Cubic }; } diff --git a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs index 095d3cd..e0047a0 100644 --- a/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs +++ b/src/Oms.Application/Services/Orders/OrderService.OrderEdit.cs @@ -285,13 +285,20 @@ public partial class OrderService try { var row = ResolvePayableWeightRow(order, weights); - if (!row.ChargeableWeight.HasValue || row.ChargeableWeight <= 0) + // 应付优先读渠道计费重;旧单无字段时回落应收计费重仅作「可否排货」门闸。 + if (row.PayableChargeableWeight is > 0) { - return false; + chargeable = row.PayableChargeableWeight.Value; + return true; } - chargeable = row.ChargeableWeight.Value; - return true; + if (row.ChargeableWeight is > 0) + { + chargeable = row.ChargeableWeight.Value; + return true; + } + + return HasPayableWeightDimensions(row); } catch (BusinessException) { @@ -713,13 +720,16 @@ public partial class OrderService { var weights = await OrderRepository.GetWeightsByOrderIdsAsync([order.Id]); var weightRow = ResolvePayableWeightRow(order, weights); - var chargeable = weightRow.ChargeableWeight ?? 0; + // 分区上下文仍用应收计费重占位;应付比价重量在 EvaluateAllocation 内按渠道现算。 + var chargeable = weightRow.ChargeableWeight is > 0 + ? weightRow.ChargeableWeight.Value + : weightRow.ActualWeight ?? 0; // 现算与重新排货一致:规则分区 + 渠道买价均取当前有效发布。 var snapshotBinding = await ResolveSnapshotBindingAsync(product, DateTime.Now); var billing = await ResolveOrderBillingContextAsync( order, product, - chargeable, + chargeable > 0 ? chargeable : 0.001m, snapshotBinding); var (_, chargingStage) = ResolveReceivableBillingStage(order); @@ -1198,9 +1208,7 @@ public partial class OrderService } ApplyMeasuredDimensions(downstream, length.Value, width.Value, height.Value, row.ActualWeight!.Value); - - var snapshotBinding = await ResolveSnapshotBindingFromOrderAsync(product, order); - await ApplyChargeableWeightAsync(product, snapshotBinding.Rules, downstream); + // 对账导入只写件重尺尺寸/实重;应付计费重由排货按渠道计重写入 PayableChargeableWeight,不改 ChargeableWeight。 await OrderRepository.ReplaceWeightsAsync(order.Id, weights); await ReallocateCoreAsync( @@ -1305,9 +1313,11 @@ public partial class OrderService string.Equals(x.Type, OrderWeightTypeCodes.Downstream, StringComparison.OrdinalIgnoreCase)) ?? throw new BusinessException("缺少件重尺类型 downstream") : ResolvePayableWeightRow(order, weights); - if (!weightRow.ChargeableWeight.HasValue || weightRow.ChargeableWeight <= 0) + if (!HasPayableWeightDimensions(weightRow) + && weightRow.ChargeableWeight is not > 0 + && weightRow.PayableChargeableWeight is not > 0) { - throw new BusinessException("计费重无效,请先完善件重尺"); + throw new BusinessException("件重尺不完整,请先完善长宽高与实重"); } // 重新排货:产品规则/分区与渠道买价均取当前有效发布,避免沿用下单时旧快照。 @@ -1316,10 +1326,14 @@ public partial class OrderService var snapshotBinding = enforceReallocateGate ? await ResolveSnapshotBindingAsync(product, DateTime.Now) : await ResolveSnapshotBindingFromOrderAsync(product, order); + // billing.ChargeableWeight 仍用应收计费重仅作上下文占位;应付排货按渠道计重现算。 + var billingWeight = weightRow.ChargeableWeight is > 0 + ? weightRow.ChargeableWeight.Value + : weightRow.ActualWeight ?? 0; var billing = await ResolveOrderBillingContextAsync( order, product, - weightRow.ChargeableWeight ?? 0, + billingWeight, snapshotBinding); var (_, chargingStage) = ResolveReceivableBillingStage(order); @@ -1336,7 +1350,8 @@ public partial class OrderService chargingStage, schemeOverride, forceChannelId, - allowDesignatedOutsidePool: lockCurrentChannel); + allowDesignatedOutsidePool: lockCurrentChannel, + payableWeightOverride: preferDownstreamWeight ? weightRow : null); // 重新排货成功后写回规则版本,使后续重算应付与当前排货池一致;卖价版本保持契约,不随排货改写。 if (enforceReallocateGate) diff --git a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs index 438651d..ee97e12 100644 --- a/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs +++ b/src/Oms.Application/Services/Orders/OrderService.ParcelBilling.cs @@ -972,7 +972,8 @@ public partial class OrderService string? _, string? schemeOverride = null, int? forceServiceChannelId = null, - bool allowDesignatedOutsidePool = false) + bool allowDesignatedOutsidePool = false, + OrderWeight? payableWeightOverride = null) { var evaluation = await EvaluateAllocationAsync( order, @@ -983,7 +984,8 @@ public partial class OrderService chargingStage, schemeOverride, forceServiceChannelId, - allowDesignatedOutsidePool); + allowDesignatedOutsidePool, + payableWeightOverride); ApplyAllocationTraceToOrder(order, evaluation); @@ -1023,6 +1025,13 @@ public partial class OrderService order.TrackNo = null; } + // 落库选中渠道的应付计费重(不改 ChargeableWeight / 应收)。 + await PersistPayableChargeableWeightAsync( + order, + chargingStage, + selectedCandidate.PayableChargeableWeight, + payableWeightOverride); + // 有效应付只保留本阶段一套,避免 forecast+inbound 叠行虚增成本。 await OrderRepository.DeletePayableFeesAsync(order.Id); await OrderRepository.UpsertFeesAsync(order.Id, payableFees); @@ -1054,7 +1063,8 @@ public partial class OrderService string chargingStage, string? schemeOverride, int? forceServiceChannelId, - bool allowDesignatedOutsidePool = false) + bool allowDesignatedOutsidePool = false, + OrderWeight? payableWeightOverride = null) { var warehouseName = await ResolveWarehouseNameAsync(order.WarehouseId); var providers = await ResolveAllocationProvidersAsync(product, snapshotBinding.Rules); @@ -1187,6 +1197,40 @@ public partial class OrderService ?? (await OrderRepository.GetRecipientsByOrderIdsAsync([order.Id])).FirstOrDefault(); var cargoAttribute = order.CargoAttribute ?? CargoAttributeCodes.General; + // 应付计费重按渠道计重现算;件重尺取 L/W/H/实重(不读应收 ChargeableWeight)。 + OrderWeight? payableWeightRow = payableWeightOverride; + if (payableWeightRow == null) + { + var weights = await OrderRepository.GetWeightsByOrderIdsAsync([order.Id]); + try + { + payableWeightRow = ResolvePayableWeightRow(order, weights); + } + catch (BusinessException) + { + payableWeightRow = null; + } + } + + if (payableWeightRow == null + || !HasPayableWeightDimensions(payableWeightRow)) + { + return new AllocationEvaluation + { + StoredScheme = storedScheme, + SelectScheme = selectScheme, + SchemeSource = schemeSource, + ChargeableWeight = 0, + ChargingStage = chargingStage, + ZoneKeys = zoneKeys, + Candidates = candidates, + Skipped = skipped, + PoolCount = poolCount, + ConditionPassCount = conditionPassCount, + FailReason = "件重尺不完整,无法按渠道计重计算应付" + }; + } + foreach (var provider in filtered) { var channelId = provider.ServiceChannelId!.Value; @@ -1218,6 +1262,42 @@ public partial class OrderService } var channelRulesBinding = await ResolveChannelRulesBindingAsync(channel, bindTime); + + decimal channelPayableWeight; + try + { + channelPayableWeight = await ComputeChannelPayableChargeableWeightAsync( + channel, + channelRulesBinding.Snapshot, + payableWeightRow); + } + catch (BusinessException ex) + { + skipped.Add(new OrderAllocationSkippedOutput + { + ServiceChannelId = channel.Id, + ChannelCode = channel.ChannelCode, + ChannelName = channel.ChannelName, + Stage = AllocationResolver.SkipStageBuyPrice, + MatchCondition = AllocationResolver.TruncateMatchCondition(provider.MatchCondition), + Reason = ex.Message + }); + continue; + } + catch (InvalidOperationException ex) + { + skipped.Add(new OrderAllocationSkippedOutput + { + ServiceChannelId = channel.Id, + ChannelCode = channel.ChannelCode, + ChannelName = channel.ChannelName, + Stage = AllocationResolver.SkipStageBuyPrice, + MatchCondition = AllocationResolver.TruncateMatchCondition(provider.MatchCondition), + Reason = ex.Message + }); + continue; + } + var channelIsRemote = IsChannelRemoteHit( channelRulesBinding, order.ConsigneeCountry ?? string.Empty, @@ -1259,7 +1339,7 @@ public partial class OrderService channelPriceBinding.Prices, channelPriceBinding.PriceVersion, channelPriceBinding.PriceEffectiveTime, - chargeableWeight, + channelPayableWeight, channelZoneKeys, cargoAttribute, chargingStage, @@ -1273,7 +1353,7 @@ public partial class OrderService { var miss = ParcelBillingCalculator.ExplainPayablePriceMiss( channelPriceBinding.Prices, - chargeableWeight, + channelPayableWeight, channelZoneKeys, cargoAttribute, order.WarehouseId, @@ -1298,6 +1378,7 @@ public partial class OrderService Provider = provider, Channel = channel, TotalPayableCost = previewFees.Sum(x => x.Amount), + PayableChargeableWeight = channelPayableWeight, PayableFees = previewFees }); } @@ -1308,19 +1389,17 @@ public partial class OrderService var detail = skipped.FirstOrDefault(x => x.Stage == AllocationResolver.SkipStageBuyPrice && !string.IsNullOrWhiteSpace(x.Reason))?.Reason; - var failReason = chargeableWeight <= 0 - ? "计费重无效,无法计算应付费用" - : buyPriceMiss > 0 - ? (string.IsNullOrWhiteSpace(detail) - ? $"排货规则未匹配到有效渠道买价(买价未命中 {buyPriceMiss})" - : $"排货规则未匹配到有效渠道买价;{detail}") - : "排货规则未匹配到有效渠道买价"; + var failReason = buyPriceMiss > 0 + ? (string.IsNullOrWhiteSpace(detail) + ? $"排货规则未匹配到有效渠道买价(买价未命中 {buyPriceMiss})" + : $"排货规则未匹配到有效渠道买价;{detail}") + : "排货规则未匹配到有效渠道买价"; return new AllocationEvaluation { StoredScheme = storedScheme, SelectScheme = selectScheme, SchemeSource = schemeSource, - ChargeableWeight = chargeableWeight, + ChargeableWeight = 0, ChargingStage = chargingStage, ZoneKeys = zoneKeys, Candidates = candidates, @@ -1337,7 +1416,7 @@ public partial class OrderService StoredScheme = storedScheme, SelectScheme = selectScheme, SchemeSource = schemeSource, - ChargeableWeight = chargeableWeight, + ChargeableWeight = selected?.PayableChargeableWeight ?? 0, ChargingStage = chargingStage, ZoneKeys = zoneKeys, Candidates = candidates, @@ -1377,6 +1456,7 @@ public partial class OrderService TotalPayableCost = c.TotalPayableCost, MinTime = c.Channel.MinTime, Weight = c.Provider.Weight, + PayableChargeableWeight = c.PayableChargeableWeight, Selected = selectedId.HasValue && c.Channel.Id == selectedId.Value, FeeLines = c.PayableFees.Select(f => new OrderAllocationFeeLineOutput { @@ -1399,6 +1479,7 @@ public partial class OrderService SchemeSource = evaluation.SchemeSource, SchemeSourceName = ResolveAllocationSchemeSourceName(evaluation.SchemeSource), ChargeableWeight = evaluation.ChargeableWeight, + PayableChargeableWeight = evaluation.ChargeableWeight, ZoneKeys = evaluation.ZoneKeys?.ToList() ?? [], ChargingStage = evaluation.ChargingStage, ChargingStageName = ResolveChargingStageName(evaluation.ChargingStage), @@ -1465,7 +1546,8 @@ public partial class OrderService string chargingStage, string? schemeOverride = null, int? forceServiceChannelId = null, - bool allowDesignatedOutsidePool = false) => + bool allowDesignatedOutsidePool = false, + OrderWeight? payableWeightOverride = null) => ConfirmServiceChannelAndPayableAsync( order, product, @@ -1476,7 +1558,8 @@ public partial class OrderService billing.PriceTierKey, schemeOverride, forceServiceChannelId, - allowDesignatedOutsidePool); + allowDesignatedOutsidePool, + payableWeightOverride); /// /// 尝试排货并写入应付;失败时不抛异常,写入 供运营补配置。 @@ -1630,13 +1713,34 @@ public partial class OrderService Channel = new ServiceChannelSaveInput { Id = channel.Id, - RemoteAreaId = channel.RemoteAreaId + RemoteAreaId = channel.RemoteAreaId, + WeightRuleId = channel.WeightRuleId, + WeightRoundingId = channel.WeightRoundingId }, + WeightRuleId = channel.WeightRuleId, + WeightRoundingId = channel.WeightRoundingId, RemoteAreaInfos = [] }; await KpiAreaPackService.LoadLiveRemoteIntoChannelRulesSnapshotAsync( live, channel.RemoteAreaId); + // LIVE:计重明细即时读库(不固化到发布 JSON)。 + if (channel.WeightRuleId is > 0) + { + var infos = await WeightRuleRepository.GetAllInfosByRuleIdAsync(channel.WeightRuleId.Value); + live.WeightRuleInfos = infos.Select(PublishSnapshotSlimmer.SlimWeightRule).ToList(); + var rule = await WeightRuleRepository.FirstOrDefaultAsync(x => x.Id == channel.WeightRuleId.Value); + live.WeightRuleName = rule?.Name; + } + + if (channel.WeightRoundingId is > 0) + { + var ranges = await WeightRoundingRepository.GetAllInfosByRoundingIdAsync(channel.WeightRoundingId.Value); + live.WeightRoundingInfos = ranges.Select(PublishSnapshotSlimmer.SlimWeightRounding).ToList(); + var rounding = await WeightRoundingRepository.FirstOrDefaultAsync(x => x.Id == channel.WeightRoundingId.Value); + live.WeightRoundingName = rounding?.Name; + } + return new ChannelRulesBinding { RemoteAreaId = channel.RemoteAreaId, @@ -1975,6 +2079,188 @@ public partial class OrderService return Task.FromResult?>(null); } + private static bool HasPayableWeightDimensions(OrderWeight row) => + row.Length is > 0 + && row.Width is > 0 + && row.Height is > 0 + && row.ActualWeight is > 0; + + /// + /// 按服务渠道计重规则/进位计算应付计费重(不写应收 ChargeableWeight)。 + /// + private async Task ComputeChannelPayableChargeableWeightAsync( + ServiceChannel channel, + ServiceChannelRulesPublishSnapshotDto? rulesSnapshot, + OrderWeight weightRow) + { + if (!HasPayableWeightDimensions(weightRow)) + { + throw new BusinessException("件重尺不完整,无法按渠道计重计算应付"); + } + + var weightRuleId = ResolveChannelWeightRuleId(channel, rulesSnapshot); + if (!weightRuleId.HasValue) + { + throw new BusinessException("渠道未配置计重规则"); + } + + IReadOnlyList ruleInfos; + if (rulesSnapshot?.WeightRuleInfos is { Count: > 0 }) + { + ruleInfos = RulesSnapshotHelper.ToWeightRuleEntities(rulesSnapshot.WeightRuleInfos); + } + else + { + await WeightRoundingDbGate.WaitAsync(); + try + { + var weightRule = await WeightRuleRepository.FirstOrDefaultAsync(x => x.Id == weightRuleId.Value); + if (weightRule == null) + { + throw new BusinessException("渠道未配置计重规则"); + } + + ruleInfos = await WeightRuleRepository.GetAllInfosByRuleIdAsync(weightRuleId.Value); + } + finally + { + WeightRoundingDbGate.Release(); + } + } + + var (_, rawWeight) = ParcelBillingCalculator.CalculateRawBillableWeight(weightRow, ruleInfos); + + var weightRoundingId = ResolveChannelWeightRoundingId(channel, rulesSnapshot); + if (!weightRoundingId.HasValue) + { + throw new BusinessException("渠道未配置计重进位"); + } + + IReadOnlyList ranges; + var snapshotRanges = rulesSnapshot?.WeightRoundingInfos; + var fromSnapshot = snapshotRanges is { Count: > 0 } + && snapshotRanges.Any(x => !string.IsNullOrWhiteSpace(x.Public)); + if (fromSnapshot) + { + ranges = RulesSnapshotHelper.ToWeightRoundingEntities(snapshotRanges!); + } + else + { + await WeightRoundingDbGate.WaitAsync(); + try + { + var rounding = await WeightRoundingRepository.FirstOrDefaultAsync(x => x.Id == weightRoundingId.Value); + if (rounding == null) + { + throw new BusinessException("渠道未配置计重进位"); + } + + ranges = await WeightRoundingRepository.GetAllInfosByRoundingIdAsync(weightRoundingId.Value); + } + finally + { + WeightRoundingDbGate.Release(); + } + } + + try + { + return ParcelBillingCalculator.ApplyRounding(rawWeight, ranges); + } + catch (InvalidOperationException ex) + { + throw new BusinessException(ex.Message); + } + } + + private static int? ResolveChannelWeightRuleId( + ServiceChannel channel, + ServiceChannelRulesPublishSnapshotDto? rulesSnapshot) + { + if (channel.WeightRuleId is > 0) + { + return channel.WeightRuleId; + } + + if (rulesSnapshot?.WeightRuleId is > 0) + { + return rulesSnapshot.WeightRuleId; + } + + if (rulesSnapshot?.Channel?.WeightRuleId is > 0) + { + return rulesSnapshot.Channel.WeightRuleId; + } + + return null; + } + + private static int? ResolveChannelWeightRoundingId( + ServiceChannel channel, + ServiceChannelRulesPublishSnapshotDto? rulesSnapshot) + { + if (channel.WeightRoundingId is > 0) + { + return channel.WeightRoundingId; + } + + if (rulesSnapshot?.WeightRoundingId is > 0) + { + return rulesSnapshot.WeightRoundingId; + } + + if (rulesSnapshot?.Channel?.WeightRoundingId is > 0) + { + return rulesSnapshot.Channel.WeightRoundingId; + } + + return null; + } + + /// + /// 仅写应付计费重;不改 ChargeableWeight / VolumetricWeight。 + /// + private async Task PersistPayableChargeableWeightAsync( + Order order, + string chargingStage, + decimal payableChargeableWeight, + OrderWeight? payableWeightOverride = null) + { + if (payableChargeableWeight <= 0) + { + return; + } + + var weights = (await OrderRepository.GetWeightsByOrderIdsAsync([order.Id])).ToList(); + OrderWeight? row = payableWeightOverride; + if (row == null) + { + var weightType = chargingStage switch + { + OrderFeeChargingStageCodes.Inbound => OrderWeightTypeCodes.Receive, + OrderFeeChargingStageCodes.Outbound => OrderWeightTypeCodes.Ship, + _ => OrderWeightTypeCodes.Forecast + }; + row = weights.FirstOrDefault(x => + string.Equals(x.Type, weightType, StringComparison.OrdinalIgnoreCase)); + } + else + { + // override 可能是另一份列表中的引用;按 Id/Type 对齐到当前列表实体再写。 + row = weights.FirstOrDefault(x => x.Id == payableWeightOverride!.Id) + ?? weights.FirstOrDefault(x => + string.Equals(x.Type, payableWeightOverride!.Type, StringComparison.OrdinalIgnoreCase)); + } + + if (row == null) + { + return; + } + + row.PayableChargeableWeight = payableChargeableWeight; + await OrderRepository.ReplaceWeightsAsync(order.Id, weights); + } + private async Task ApplyChargeableWeightAsync( SalesProduct product, SalesProductRulesPublishSnapshotDto? rulesSnapshot, diff --git a/src/Oms.Application/Services/Orders/PickupOrderFeePushService.cs b/src/Oms.Application/Services/Orders/PickupOrderFeePushService.cs index fa7489d..b3501f0 100644 --- a/src/Oms.Application/Services/Orders/PickupOrderFeePushService.cs +++ b/src/Oms.Application/Services/Orders/PickupOrderFeePushService.cs @@ -220,11 +220,11 @@ public class PickupOrderFeePushService : IScopedDependency throw new BusinessException($"卖价未匹配到有效价格:{detail}"); } - var payable = await CalculatePayableAsync( + var (payable, payableChargeableWeight) = await CalculatePayableAsync( product, pickup, + weightRow, zoneKeys, - chargeableWeight, cargoAttribute, warehouseName, priceVersion, @@ -241,6 +241,7 @@ public class PickupOrderFeePushService : IScopedDependency pickup.TotalActualWeight = totalActualWeight; pickup.VolumetricWeight = volumetricWeight; pickup.ChargeableWeight = chargeableWeight; + pickup.PayableChargeableWeight = payableChargeableWeight; pickup.PackageSizesJson = OmsDocHelper.SerializeJson(normalizedSizes); if (carrierFreightWeight.HasValue) { @@ -280,6 +281,7 @@ public class PickupOrderFeePushService : IScopedDependency PickupNo = pickup.PickupNo, TotalActualWeight = totalActualWeight, ChargeableWeight = chargeableWeight, + PayableChargeableWeight = payableChargeableWeight, VolumetricWeight = volumetricWeight, ReceivableAmount = receivableTotal, CarrierPayableAmount = payableTotal, @@ -383,11 +385,11 @@ public class PickupOrderFeePushService : IScopedDependency }).ToList(); } - private async Task> CalculatePayableAsync( + private async Task<(List Fees, decimal PayableChargeableWeight)> CalculatePayableAsync( SalesProduct product, PickupOrder pickup, + OrderWeight weightRow, IReadOnlyList zoneKeys, - decimal chargeableWeight, string cargoAttribute, string? warehouseName, string priceVersion, @@ -400,6 +402,7 @@ public class PickupOrderFeePushService : IScopedDependency ? [] : await _serviceChannelRepository.GetListAsync(x => channelIds.Contains(x.Id)); var channelNameMap = channels.ToDictionary(x => x.Id, x => x.ChannelName); + var channelMap = channels.ToDictionary(x => x.Id); var snapshots = providers.Select(provider => new SalesProductAllocationProviderSnapshotDto { Id = provider.Id, @@ -423,6 +426,22 @@ public class PickupOrderFeePushService : IScopedDependency throw new BusinessException("未配置可用排货服务渠道,无法计算应付"); } + if (!channelMap.TryGetValue(provider.ServiceChannelId.Value, out var channel)) + { + channel = await _serviceChannelRepository.FirstOrDefaultAsync(x => x.Id == provider.ServiceChannelId.Value) + ?? throw new BusinessException($"服务渠道 {provider.ServiceChannelId} 不存在"); + } + + decimal payableChargeableWeight; + try + { + payableChargeableWeight = await CalculateChannelPayableChargeableAsync(channel, weightRow); + } + catch (InvalidOperationException ex) + { + throw new BusinessException($"渠道应付计费重计算失败:{ex.Message}"); + } + var channelPrices = await GetChannelPriceOutputsAsync(provider.ServiceChannelId.Value); if (channelPrices.Count == 0) { @@ -433,7 +452,7 @@ public class PickupOrderFeePushService : IScopedDependency channelPrices, priceVersion, priceEffectiveTime, - chargeableWeight, + payableChargeableWeight, zoneKeys, cargoAttribute, OrderFeeChargingStageCodes.Forecast, @@ -446,7 +465,30 @@ public class PickupOrderFeePushService : IScopedDependency throw new BusinessException($"服务渠道 {provider.ServiceChannelId} 买价未匹配"); } - return payable; + return (payable, payableChargeableWeight); + } + + /// + /// 揽收应付:按服务渠道计重规则/进位(不改应收 ChargeableWeight)。 + /// + private async Task CalculateChannelPayableChargeableAsync( + ServiceChannel channel, + OrderWeight weightRow) + { + if (channel.WeightRuleId is not > 0) + { + throw new BusinessException("渠道未配置计重规则"); + } + + if (channel.WeightRoundingId is not > 0) + { + throw new BusinessException("渠道未配置计重进位"); + } + + var ruleInfos = await _weightRuleRepository.GetAllInfosByRuleIdAsync(channel.WeightRuleId.Value); + var (_, raw) = ParcelBillingCalculator.CalculateRawBillableWeight(weightRow, ruleInfos); + var ranges = await _weightRoundingRepository.GetAllInfosByRoundingIdAsync(channel.WeightRoundingId.Value); + return ParcelBillingCalculator.ApplyRounding(raw, ranges); } private async Task> GetChannelPriceOutputsAsync(int serviceChannelId) diff --git a/src/Oms.Application/Services/Orders/PickupOrderService.cs b/src/Oms.Application/Services/Orders/PickupOrderService.cs index 2a23746..47dcdce 100644 --- a/src/Oms.Application/Services/Orders/PickupOrderService.cs +++ b/src/Oms.Application/Services/Orders/PickupOrderService.cs @@ -1393,6 +1393,7 @@ public class PickupOrderService : ApplicationService ParcelCount = entity.ParcelCount, TotalActualWeight = entity.TotalActualWeight, ChargeableWeight = entity.ChargeableWeight, + PayableChargeableWeight = entity.PayableChargeableWeight, VolumetricWeight = entity.VolumetricWeight, PackageSizes = OmsDocHelper.DeserializeJson>(entity.PackageSizesJson) ?? [], CarrierFreightWeight = entity.CarrierFreightWeight, diff --git a/src/Oms.Application/Shared/AllocationResolver.cs b/src/Oms.Application/Shared/AllocationResolver.cs index 80c8e54..b2754a8 100644 --- a/src/Oms.Application/Shared/AllocationResolver.cs +++ b/src/Oms.Application/Shared/AllocationResolver.cs @@ -27,6 +27,9 @@ public static class AllocationResolver public decimal TotalPayableCost { get; init; } + /// 该候选渠道按渠道计重算出的应付计费重。 + public decimal PayableChargeableWeight { get; init; } + /// 候选渠道已算出的应付费用(选渠后可直接落库,避免重复算价)。 public IReadOnlyList PayableFees { get; init; } = []; } diff --git a/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs b/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs index 109a891..7c067b7 100644 --- a/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs +++ b/src/Oms.Domain/ChannelsAggregate/Entities/ServiceChannel.cs @@ -28,6 +28,16 @@ public class ServiceChannel : OmsAuditedAggregateRoot /// public int? RemoteAreaId { get; set; } + /// + /// 计重规则 ID(应付计费重)。 + /// + public int? WeightRuleId { get; set; } + + /// + /// 计重进位 ID(应付计费重)。 + /// + public int? WeightRoundingId { get; set; } + public string? PreScript { get; set; } public EnableStatus IsActive { get; set; } diff --git a/src/Oms.Domain/OrdersAggregate/Entities/OrderWeight.cs b/src/Oms.Domain/OrdersAggregate/Entities/OrderWeight.cs index f40ad39..c687aae 100644 --- a/src/Oms.Domain/OrdersAggregate/Entities/OrderWeight.cs +++ b/src/Oms.Domain/OrdersAggregate/Entities/OrderWeight.cs @@ -20,7 +20,15 @@ public class OrderWeight : OmsAuditedEntity public decimal? VolumetricWeight { get; set; } + /// + /// 应收计费重(销售产品计重规则/进位)。 + /// public decimal? ChargeableWeight { get; set; } + /// + /// 应付计费重(服务渠道计重规则/进位)。 + /// + public decimal? PayableChargeableWeight { get; set; } + public decimal? Cubic { get; set; } } diff --git a/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs index 96acab6..95cbea0 100644 --- a/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs +++ b/src/Oms.Domain/OrdersAggregate/Entities/PickupOrder.cs @@ -102,9 +102,18 @@ public class PickupOrder : OmsAuditedAggregateRoot [SugarColumn(DecimalDigits = 3, IsNullable = true)] public decimal? TotalActualWeight { get; set; } + /// + /// 应收计费重(销售产品计重)。 + /// [SugarColumn(DecimalDigits = 3, IsNullable = true)] public decimal? ChargeableWeight { get; set; } + /// + /// 应付计费重(服务渠道计重)。 + /// + [SugarColumn(DecimalDigits = 3, IsNullable = true)] + public decimal? PayableChargeableWeight { get; set; } + [SugarColumn(DecimalDigits = 3, IsNullable = true)] public decimal? VolumetricWeight { get; set; }