20261127 #31
10
db.sql
10
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 '创建人',
|
||||
@ -583,6 +584,7 @@ CREATE TABLE `t_sales_product` (
|
||||
`WeightRuleId` INT NULL COMMENT '计重规则ID',
|
||||
`WeightRoundingId` INT NULL COMMENT '计重进位ID',
|
||||
`ProductDescription` TEXT COMMENT '产品描述',
|
||||
`CoverImage` VARCHAR(512) NULL COMMENT '官网线路封面图 object key',
|
||||
`PreStorageScript` TEXT COMMENT '入库前脚本',
|
||||
`CustomerGuideMarkdown` MEDIUMTEXT COMMENT '对客说明 Markdown',
|
||||
`IsActive` TINYINT NOT NULL DEFAULT 2 COMMENT 'EnableStatus:0=None未设置,1=Disabled禁用,2=Enabled启用',
|
||||
@ -720,6 +722,9 @@ CREATE TABLE `t_service_channel` (
|
||||
`ForecastCode` VARCHAR(128) NULL COMMENT '预报单号',
|
||||
`Description` TEXT COMMENT '描述',
|
||||
`RemoteAreaId` INT NULL COMMENT '偏远分区KPI AreaId',
|
||||
`BlacklistAreaId` 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 +2265,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 '承运计费重(对照)',
|
||||
|
||||
107
sql/migrate_channel_payable_weight_20261123.sql
Normal file
107
sql/migrate_channel_payable_weight_20261123.sql
Normal file
@ -0,0 +1,107 @@
|
||||
-- 服务渠道:黑名单分区 + 独立计重(应付);订单/揽收件重尺应付计费重。
|
||||
-- 销售产品:官网线路封面图 CoverImage。
|
||||
-- 可重复执行。不改 ChargeableWeight 语义(仍为应收计费重)。
|
||||
|
||||
SET @db := DATABASE();
|
||||
|
||||
-- t_service_channel.BlacklistAreaId
|
||||
SET @exists := (
|
||||
SELECT COUNT(1)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db
|
||||
AND TABLE_NAME = 't_service_channel'
|
||||
AND COLUMN_NAME = 'BlacklistAreaId'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@exists = 0,
|
||||
'ALTER TABLE `t_service_channel` ADD COLUMN `BlacklistAreaId` INT NULL COMMENT ''黑名单分区KPI AreaId'' AFTER `RemoteAreaId`',
|
||||
'SELECT ''t_service_channel.BlacklistAreaId already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
|
||||
-- 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 `BlacklistAreaId`',
|
||||
'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;
|
||||
|
||||
-- t_sales_product.CoverImage(官网线路封面图 object key)
|
||||
SET @exists := (
|
||||
SELECT COUNT(1)
|
||||
FROM information_schema.COLUMNS
|
||||
WHERE TABLE_SCHEMA = @db
|
||||
AND TABLE_NAME = 't_sales_product'
|
||||
AND COLUMN_NAME = 'CoverImage'
|
||||
);
|
||||
SET @sql := IF(
|
||||
@exists = 0,
|
||||
'ALTER TABLE `t_sales_product` ADD COLUMN `CoverImage` VARCHAR(512) NULL COMMENT ''官网线路封面图 object key'' AFTER `ProductDescription`',
|
||||
'SELECT ''t_sales_product.CoverImage already exists'' AS info'
|
||||
);
|
||||
PREPARE stmt FROM @sql;
|
||||
EXECUTE stmt;
|
||||
DEALLOCATE PREPARE stmt;
|
||||
@ -61,8 +61,12 @@ public class SalesProductBillingSimulateInput
|
||||
/// </summary>
|
||||
public class SalesProductBillingSimulateOutput
|
||||
{
|
||||
/// <summary>应收计费重(销售产品计重)。</summary>
|
||||
public decimal ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>应付计费重(首个可用渠道计重;未算出则为 null)。</summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
public List<string> ZoneKeys { get; set; } = [];
|
||||
|
||||
public bool IsRemote { get; set; }
|
||||
|
||||
@ -90,6 +90,17 @@ public class SalesProductDetailOutput
|
||||
/// </summary>
|
||||
public string? ProductDescription { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网线路封面图 object key(保存用)。
|
||||
/// </summary>
|
||||
public string? CoverImage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网线路封面图可访问 URL(预览用)。
|
||||
/// </summary>
|
||||
/// <summary>封面同源预览地址(/channel/sales-product/cover/file,非 COS 直链)。</summary>
|
||||
public string? CoverImageUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预入库脚本。
|
||||
/// </summary>
|
||||
|
||||
@ -103,6 +103,11 @@ public class SalesProductPortalItemOutput
|
||||
/// </summary>
|
||||
public string? ProductDescription { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网线路封面图同源地址(/channel/sales-product/cover/file,非 COS 直链;无图时为空)。
|
||||
/// </summary>
|
||||
public string? CoverImageUrl { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网目的地区域编码:us / eu / sea / ca_mx / au / global。
|
||||
/// 优先由价格分区国家推导;国际快递跨区时含 global。
|
||||
|
||||
@ -92,6 +92,11 @@ public class SalesProductSaveInput
|
||||
/// </summary>
|
||||
public string? ProductDescription { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网线路封面图 object key。
|
||||
/// </summary>
|
||||
public string? CoverImage { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预入库脚本。
|
||||
/// </summary>
|
||||
|
||||
@ -60,6 +60,21 @@ public class ServiceChannelDetailOutput
|
||||
/// </summary>
|
||||
public int? RemoteAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 黑名单分区 KPI AreaId。
|
||||
/// </summary>
|
||||
public int? BlacklistAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重规则 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRuleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重进位 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRoundingId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预处理脚本。
|
||||
/// </summary>
|
||||
|
||||
@ -60,6 +60,21 @@ public class ServiceChannelListOutput
|
||||
/// </summary>
|
||||
public int? RemoteAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 黑名单分区 KPI AreaId。
|
||||
/// </summary>
|
||||
public int? BlacklistAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重规则 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRuleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重进位 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRoundingId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 是否启用。
|
||||
/// </summary>
|
||||
|
||||
@ -24,4 +24,35 @@ public class ServiceChannelRulesPublishSnapshotDto
|
||||
/// <summary>运行时 hydrate / LIVE 用,不落发布 JSON。</summary>
|
||||
[JsonIgnore]
|
||||
public List<KpiAreaSnapshotRuleDto> RemoteAreaInfos { get; set; } = [];
|
||||
|
||||
/// <summary>黑名单分区 ID。</summary>
|
||||
public int? BlacklistAreaId { get; set; }
|
||||
|
||||
/// <summary>黑名单分区名称。</summary>
|
||||
public string? BlacklistAreaName { get; set; }
|
||||
|
||||
/// <summary>黑名单分区包引用(规则发布时钉包)。</summary>
|
||||
public KpiAreaPackRefDto? BlacklistAreaRef { get; set; }
|
||||
|
||||
/// <summary>运行时 hydrate / LIVE 用,不落发布 JSON。</summary>
|
||||
[JsonIgnore]
|
||||
public List<KpiAreaSnapshotRuleDto> BlacklistAreaInfos { get; set; } = [];
|
||||
|
||||
/// <summary>计重规则 ID(应付,发布时固化)。</summary>
|
||||
public int? WeightRuleId { get; set; }
|
||||
|
||||
/// <summary>计重规则名称。</summary>
|
||||
public string? WeightRuleName { get; set; }
|
||||
|
||||
/// <summary>计重规则明细,发布时从 t_weight_rule_info 固化。</summary>
|
||||
public List<WeightRuleSnapshotRuleDto> WeightRuleInfos { get; set; } = [];
|
||||
|
||||
/// <summary>计重进位 ID(应付,发布时固化)。</summary>
|
||||
public int? WeightRoundingId { get; set; }
|
||||
|
||||
/// <summary>计重进位名称。</summary>
|
||||
public string? WeightRoundingName { get; set; }
|
||||
|
||||
/// <summary>计重进位区间,发布时从 t_weight_rounding_info 固化。</summary>
|
||||
public List<WeightRoundingSnapshotRangeDto> WeightRoundingInfos { get; set; } = [];
|
||||
}
|
||||
|
||||
@ -57,6 +57,21 @@ public class ServiceChannelSaveInput
|
||||
/// </summary>
|
||||
public int? RemoteAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 黑名单分区 KPI AreaId。
|
||||
/// </summary>
|
||||
public int? BlacklistAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重规则 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRuleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重进位 ID(应付)。
|
||||
/// </summary>
|
||||
public int? WeightRoundingId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 预处理脚本。
|
||||
/// </summary>
|
||||
|
||||
@ -19,8 +19,12 @@ public class OrderAllocationTraceOutput
|
||||
|
||||
public string? SchemeSourceName { get; set; }
|
||||
|
||||
/// <summary>选中渠道的应付计费重(渠道计重;历史字段名保留兼容)。</summary>
|
||||
public decimal? ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>选中渠道的应付计费重(与 ChargeableWeight 同值,便于前端区分应收)。</summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>订单解析出的价格分区键(用于对照买价明细分区)。</summary>
|
||||
public List<string> ZoneKeys { get; set; } = [];
|
||||
|
||||
@ -67,6 +71,9 @@ public class OrderAllocationCandidateOutput
|
||||
/// <summary>综合权重(综合最优主指标)。</summary>
|
||||
public int Weight { get; set; }
|
||||
|
||||
/// <summary>该候选渠道按渠道计重算出的应付计费重。</summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
public bool Selected { get; set; }
|
||||
|
||||
public List<OrderAllocationFeeLineOutput> FeeLines { get; set; } = [];
|
||||
|
||||
@ -36,10 +36,15 @@ public class OrderWeightOutput
|
||||
public decimal? VolumetricWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计费重量。
|
||||
/// 应收计费重(销售产品计重)。
|
||||
/// </summary>
|
||||
public decimal? ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应付计费重(服务渠道计重)。
|
||||
/// </summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 体积。
|
||||
/// </summary>
|
||||
|
||||
@ -309,8 +309,12 @@ public class PickupOrderOutput
|
||||
|
||||
public decimal? TotalActualWeight { get; set; }
|
||||
|
||||
/// <summary>应收计费重(销售产品计重)。</summary>
|
||||
public decimal? ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>应付计费重(渠道计重)。</summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
public decimal? VolumetricWeight { get; set; }
|
||||
|
||||
public List<PickupPackageSizeOutput> PackageSizes { get; set; } = [];
|
||||
@ -400,8 +404,12 @@ public class PickupOpenApiPushFeeResult
|
||||
|
||||
public decimal TotalActualWeight { get; set; }
|
||||
|
||||
/// <summary>应收计费重(销售产品计重)。</summary>
|
||||
public decimal ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>应付计费重(渠道计重)。</summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
public decimal? VolumetricWeight { get; set; }
|
||||
|
||||
public decimal ReceivableAmount { get; set; }
|
||||
|
||||
File diff suppressed because one or more lines are too long
@ -20,6 +20,9 @@ public class AiSkillService : ApplicationService
|
||||
public const string SceneReceiverAddressParse = "receiverAddressParse";
|
||||
public const string SceneItfxPrefixScript = "itfxPrefixScript";
|
||||
public const string SceneItfxParameterMap = "itfxParameterMap";
|
||||
public const string SceneServiceChannelPreScript = "serviceChannelPreScript";
|
||||
public const string SceneSalesProductPreStorageScript = "salesProductPreStorageScript";
|
||||
public const string SceneChannelQuoteImport = "channelQuoteImport";
|
||||
|
||||
public const string KeyPricePublish = "oms-sales-price-publish-risk";
|
||||
public const string KeyAutoTriggerFormula = "oms-auto-trigger-formula";
|
||||
@ -27,6 +30,9 @@ public class AiSkillService : ApplicationService
|
||||
public const string KeyReceiverAddressParse = "oms-receiver-address-parse";
|
||||
public const string KeyItfxPrefixScript = "itfx-prefix-script";
|
||||
public const string KeyItfxCreateOrderMap = "itfx-create-order-map";
|
||||
public const string KeyServiceChannelPreScript = "oms-service-channel-pre-script";
|
||||
public const string KeySalesProductPreStorageScript = "oms-sales-product-pre-storage-script";
|
||||
public const string KeyChannelQuoteExtract = "oms-channel-quote-extract";
|
||||
|
||||
private IAiSkillRepository AiSkillRepository => LazyServiceProvider.GetRequiredService<IAiSkillRepository>();
|
||||
|
||||
@ -212,6 +218,9 @@ public class AiSkillService : ApplicationService
|
||||
[
|
||||
new SeedDef(KeyPricePublish, ScenePricePublish, "销售产品价格发布风险",
|
||||
"对比线上生效价与待发布价,输出中文风险报告", payload.Price, 10),
|
||||
new SeedDef(KeyChannelQuoteExtract, SceneChannelQuoteImport, "渠道报价表提取",
|
||||
"补齐本地规则未识别的报价 sheet(一口价 / 公斤+票费),供定价工作台更新买价",
|
||||
payload.ChannelQuote, 15),
|
||||
new SeedDef(KeyAutoTriggerFormula, SceneAutoTriggerFormula, "自动触发公式助手",
|
||||
"根据中文描述生成可粘贴的自动触发公式(字段目录由前端追加)", payload.Formula, 20),
|
||||
new SeedDef(KeyBillingConditionFormula, SceneBillingConditionFormula, "计费条件公式助手",
|
||||
@ -222,6 +231,10 @@ public class AiSkillService : ApplicationService
|
||||
"按用户需求生成 Natasha C# 前置签名脚本", payload.Itfx, 40),
|
||||
new SeedDef(KeyItfxCreateOrderMap, SceneItfxParameterMap, "创建订单自动映射",
|
||||
"按订单基本信息/收件人/发件人/申报信息四模块初步匹配上下游参数", payload.ParameterMap, 50),
|
||||
new SeedDef(KeyServiceChannelPreScript, SceneServiceChannelPreScript, "服务渠道预报前脚本助手",
|
||||
"根据中文描述生成预报前字段改写/拼接赋值脚本(字段目录由前端追加)", payload.PreScript, 55),
|
||||
new SeedDef(KeySalesProductPreStorageScript, SceneSalesProductPreStorageScript, "销售产品落库前脚本助手",
|
||||
"根据中文描述生成落库前字段改写/拼接赋值脚本(会写入订单)", payload.PreStorageScript, 56),
|
||||
];
|
||||
}
|
||||
|
||||
@ -256,5 +269,8 @@ public class AiSkillService : ApplicationService
|
||||
public string Itfx { get; set; } = string.Empty;
|
||||
public string Address { get; set; } = string.Empty;
|
||||
public string ParameterMap { get; set; } = string.Empty;
|
||||
public string PreScript { get; set; } = string.Empty;
|
||||
public string PreStorageScript { get; set; } = string.Empty;
|
||||
public string ChannelQuote { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
@ -180,12 +180,13 @@ public partial class SalesProductService
|
||||
}).ToList();
|
||||
|
||||
var payableFees = new List<SalesProductBillingSimulateFeeOutput>();
|
||||
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<List<SalesProductBillingSimulateFeeOutput>> TrySimulatePayableFeesAsync(
|
||||
private async Task<(List<SalesProductBillingSimulateFeeOutput> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 试算应付:按服务渠道计重规则/进位(不改应收计重)。
|
||||
/// </summary>
|
||||
private async Task<decimal> 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<List<ServiceChannelPriceListOutput>> BuildChannelPriceOutputsAsync(int serviceChannelId)
|
||||
|
||||
@ -3,6 +3,7 @@ using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Consts;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
@ -615,6 +616,9 @@ public partial class SalesProductService
|
||||
entity.WeightRuleId = input.WeightRuleId;
|
||||
entity.WeightRoundingId = input.WeightRoundingId;
|
||||
entity.ProductDescription = input.ProductDescription;
|
||||
entity.CoverImage = string.IsNullOrWhiteSpace(input.CoverImage)
|
||||
? null
|
||||
: OmsObjectStorageExtensions.ToStorageKey(input.CoverImage.Trim());
|
||||
entity.PreStorageScript = input.PreStorageScript;
|
||||
// 对客说明仅通过 /customer-guide/save 维护,产品配置保存/发布不覆盖
|
||||
entity.IsActive = input.IsActive;
|
||||
@ -857,6 +861,7 @@ public partial class SalesProductService
|
||||
WeightRuleId = entity.WeightRuleId,
|
||||
WeightRoundingId = entity.WeightRoundingId,
|
||||
ProductDescription = entity.ProductDescription,
|
||||
CoverImage = entity.CoverImage,
|
||||
PreStorageScript = entity.PreStorageScript,
|
||||
CustomerGuideMarkdown = entity.CustomerGuideMarkdown,
|
||||
IsActive = (byte)entity.IsActive,
|
||||
|
||||
@ -1,6 +1,8 @@
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Channels;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Entities;
|
||||
using Oms.Domain.Shared.Enums;
|
||||
using Oms.Domain.SystemAggregate.Repositories;
|
||||
@ -119,6 +121,9 @@ public partial class SalesProductService
|
||||
TradeTerms = string.IsNullOrWhiteSpace(p.TradeTerms) ? null : p.TradeTerms.Trim().ToUpperInvariant(),
|
||||
RouteSort = p.RouteSort,
|
||||
ProductDescription = p.ProductDescription,
|
||||
CoverImageUrl = string.IsNullOrWhiteSpace(p.CoverImage)
|
||||
? null
|
||||
: OmsManagedImageHelper.BuildSalesProductCoverUrl(p.CoverImage),
|
||||
DestRegions = destRegions,
|
||||
CoverageCountries = coverageCountries.Take(PortalCoverageCountryLimit).ToList(),
|
||||
CargoTags = cargoTags
|
||||
|
||||
@ -1,10 +1,14 @@
|
||||
using System.Linq.Expressions;
|
||||
using Fake.Application;
|
||||
using Fake.ObjectStorage;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Dtos.Channels;
|
||||
using Oms.Application.Dtos.Shared;
|
||||
using Oms.Application.Services.Approval.Contracts;
|
||||
using Oms.Application.Shared;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ApprovalAggregate.Consts;
|
||||
using Oms.Domain.ApprovalAggregate.Enums;
|
||||
using Oms.Domain.ApprovalAggregate.Repositories;
|
||||
@ -41,6 +45,53 @@ public partial class SalesProductService : ApplicationService
|
||||
private IApprovalDefinitionRepository ApprovalDefinitionRepository =>
|
||||
LazyServiceProvider.GetRequiredService<IApprovalDefinitionRepository>();
|
||||
|
||||
private IObjectStorage FileStorage => LazyServiceProvider.GetRequiredService<IObjectStorage>();
|
||||
|
||||
/// <summary>
|
||||
/// 上传销售产品官网封面图(multipart 经后端落对象存储,不走 COS 浏览器直传)。
|
||||
/// 返回 object key(落库)与同源 /cover/file 相对地址(预览,非 COS 直链)。
|
||||
/// </summary>
|
||||
/// <param name="file">入参:封面图片文件(jpg/png/webp 等,≤5MB)。</param>
|
||||
[HttpPost("/channel/sales-product/upload-cover")]
|
||||
[Consumes("multipart/form-data")]
|
||||
public async Task<object> UploadCoverImageAsync(IFormFile file)
|
||||
{
|
||||
var key = await OmsFileUploadHelper.SaveSalesProductCoverAsync(file, FileStorage);
|
||||
var url = OmsManagedImageHelper.BuildSalesProductCoverUrl(key);
|
||||
return new { key, url, fileUrl = key };
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按 object key 输出销售产品封面图字节(同源代理,避免浏览器直连 COS)。官网匿名可读。
|
||||
/// URL 带 v= 缓存戳时浏览器可长期缓存,刷新精选封面走磁盘缓存。
|
||||
/// </summary>
|
||||
/// <param name="key">入参:uploads/sales-product-cover/... object key。</param>
|
||||
/// <param name="v">缓存戳,可选。</param>
|
||||
/// <param name="cancellationToken">取消令牌。</param>
|
||||
[AllowAnonymous]
|
||||
[HttpGet("/channel/sales-product/cover/file")]
|
||||
public async Task<FileContentResult> GetCoverImageFileAsync(
|
||||
[FromQuery] string key,
|
||||
[FromQuery] string? v = null,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
_ = v;
|
||||
var result = await OmsManagedImageHelper.StreamByKeyAsync(
|
||||
FileStorage,
|
||||
key,
|
||||
cancellationToken,
|
||||
OmsManagedImageHelper.SalesProductCoverKeyPrefix);
|
||||
|
||||
// v= 随 object key 文件名变化;允许浏览器长期缓存,加速官网刷新
|
||||
var http = LazyServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
|
||||
if (http != null)
|
||||
{
|
||||
http.Response.Headers["Cache-Control"] = "public, max-age=31536000, immutable";
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询销售产品列表。
|
||||
/// </summary>
|
||||
@ -78,7 +129,11 @@ public partial class SalesProductService : ApplicationService
|
||||
var entity = await GetProductOrThrowAsync(id);
|
||||
var auditUserNameMap = await UserDisplayNameResolver.ResolveManyAsync(
|
||||
[entity.CreateUserId, entity.UpdateUserId]);
|
||||
return MapDetailOutput(entity, auditUserNameMap);
|
||||
var detail = MapDetailOutput(entity, auditUserNameMap);
|
||||
detail.CoverImageUrl = string.IsNullOrWhiteSpace(entity.CoverImage)
|
||||
? null
|
||||
: OmsManagedImageHelper.BuildSalesProductCoverUrl(entity.CoverImage);
|
||||
return detail;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@ -301,7 +301,8 @@ public partial class ServiceChannelService
|
||||
{
|
||||
Channel = MapChannelToSaveInput(entity),
|
||||
Downstream = downstream,
|
||||
RemoteAreaInfos = []
|
||||
RemoteAreaInfos = [],
|
||||
BlacklistAreaInfos = []
|
||||
};
|
||||
|
||||
if (entity.RemoteAreaId is > 0)
|
||||
@ -322,11 +323,30 @@ public partial class ServiceChannelService
|
||||
snapshot.RemoteAreaRef = null;
|
||||
}
|
||||
|
||||
if (entity.BlacklistAreaId is > 0)
|
||||
{
|
||||
var packRef = await KpiAreaPackService.EnsurePackAsync(
|
||||
entity.BlacklistAreaId.Value,
|
||||
KpiAreaPackService.AreaTypeBlacklist,
|
||||
ResolvePublishUser(),
|
||||
description: "service-channel-rules-publish");
|
||||
snapshot.BlacklistAreaId = entity.BlacklistAreaId;
|
||||
snapshot.BlacklistAreaName = packRef.AreaName;
|
||||
snapshot.BlacklistAreaRef = packRef;
|
||||
}
|
||||
else
|
||||
{
|
||||
snapshot.BlacklistAreaId = null;
|
||||
snapshot.BlacklistAreaName = null;
|
||||
snapshot.BlacklistAreaRef = null;
|
||||
}
|
||||
|
||||
await ApplyChannelWeightToRulesSnapshotAsync(snapshot, entity);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渠道规则同步态:偏远分区不 Ensure。
|
||||
/// 渠道规则同步态:偏远/黑名单分区不 Ensure。
|
||||
/// </summary>
|
||||
private async Task<ServiceChannelRulesPublishSnapshotDto> BuildRulesPublishSnapshotForSyncAsync(int serviceChannelId)
|
||||
{
|
||||
@ -345,7 +365,8 @@ public partial class ServiceChannelService
|
||||
{
|
||||
Channel = MapChannelToSaveInput(entity),
|
||||
Downstream = downstream,
|
||||
RemoteAreaInfos = []
|
||||
RemoteAreaInfos = [],
|
||||
BlacklistAreaInfos = []
|
||||
};
|
||||
|
||||
if (entity.RemoteAreaId is > 0)
|
||||
@ -362,9 +383,62 @@ public partial class ServiceChannelService
|
||||
snapshot.RemoteAreaRef = null;
|
||||
}
|
||||
|
||||
if (entity.BlacklistAreaId is > 0)
|
||||
{
|
||||
var packRef = await KpiAreaPackService.ResolvePackRefForSyncAsync(entity.BlacklistAreaId.Value);
|
||||
snapshot.BlacklistAreaId = entity.BlacklistAreaId;
|
||||
snapshot.BlacklistAreaName = packRef.AreaName;
|
||||
snapshot.BlacklistAreaRef = packRef;
|
||||
}
|
||||
else
|
||||
{
|
||||
snapshot.BlacklistAreaId = null;
|
||||
snapshot.BlacklistAreaName = null;
|
||||
snapshot.BlacklistAreaRef = null;
|
||||
}
|
||||
|
||||
await ApplyChannelWeightToRulesSnapshotAsync(snapshot, entity);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渠道规则快照固化计重规则/进位明细(应付)。
|
||||
/// </summary>
|
||||
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<int>().ToString()
|
||||
@ -383,6 +457,9 @@ public partial class ServiceChannelService
|
||||
ForecastCode = entity.ForecastCode,
|
||||
Description = entity.Description,
|
||||
RemoteAreaId = entity.RemoteAreaId,
|
||||
BlacklistAreaId = entity.BlacklistAreaId,
|
||||
WeightRuleId = entity.WeightRuleId,
|
||||
WeightRoundingId = entity.WeightRoundingId,
|
||||
PreScript = entity.PreScript,
|
||||
IsActive = entity.IsActive
|
||||
};
|
||||
@ -469,6 +546,9 @@ public partial class ServiceChannelService
|
||||
entity.ForecastCode = input.ForecastCode;
|
||||
entity.Description = input.Description;
|
||||
entity.RemoteAreaId = input.RemoteAreaId;
|
||||
entity.BlacklistAreaId = input.BlacklistAreaId;
|
||||
entity.WeightRuleId = input.WeightRuleId;
|
||||
entity.WeightRoundingId = input.WeightRoundingId;
|
||||
entity.PreScript = input.PreScript;
|
||||
entity.IsActive = input.IsActive;
|
||||
}
|
||||
@ -564,6 +644,9 @@ public partial class ServiceChannelService
|
||||
ForecastCode = entity.ForecastCode,
|
||||
Description = entity.Description,
|
||||
RemoteAreaId = entity.RemoteAreaId,
|
||||
BlacklistAreaId = entity.BlacklistAreaId,
|
||||
WeightRuleId = entity.WeightRuleId,
|
||||
WeightRoundingId = entity.WeightRoundingId,
|
||||
IsActive = (byte)entity.IsActive,
|
||||
CreateTime = entity.CreateTime,
|
||||
CreateBy = OmsRbacUserDisplayNameResolver.FormatUserId(entity.CreateUserId, auditUserNameMap),
|
||||
@ -590,6 +673,9 @@ public partial class ServiceChannelService
|
||||
ForecastCode = entity.ForecastCode,
|
||||
Description = entity.Description,
|
||||
RemoteAreaId = entity.RemoteAreaId,
|
||||
BlacklistAreaId = entity.BlacklistAreaId,
|
||||
WeightRuleId = entity.WeightRuleId,
|
||||
WeightRoundingId = entity.WeightRoundingId,
|
||||
PreScript = entity.PreScript,
|
||||
IsActive = (byte)entity.IsActive,
|
||||
CreateTime = entity.CreateTime,
|
||||
|
||||
@ -21,6 +21,8 @@ public partial class ServiceChannelService : ApplicationService
|
||||
private IServiceChannelRepository ServiceChannelRepository => LazyServiceProvider.GetRequiredService<IServiceChannelRepository>();
|
||||
private IServiceChannelGroupRepository ServiceChannelGroupRepository => LazyServiceProvider.GetRequiredService<IServiceChannelGroupRepository>();
|
||||
private IKpiAreaRepository KpiAreaRepository => LazyServiceProvider.GetRequiredService<IKpiAreaRepository>();
|
||||
private IWeightRuleRepository WeightRuleRepository => LazyServiceProvider.GetRequiredService<IWeightRuleRepository>();
|
||||
private IWeightRoundingRepository WeightRoundingRepository => LazyServiceProvider.GetRequiredService<IWeightRoundingRepository>();
|
||||
private KpiAreaPackService KpiAreaPackService => LazyServiceProvider.GetRequiredService<KpiAreaPackService>();
|
||||
private AllocationProviderSnapshotEnricher AllocationProviderSnapshotEnricher =>
|
||||
LazyServiceProvider.GetRequiredService<AllocationProviderSnapshotEnricher>();
|
||||
|
||||
@ -0,0 +1,577 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Fake.Application;
|
||||
|
||||
namespace Oms.Application.Services.Orders.Issues;
|
||||
|
||||
/// <summary>
|
||||
/// 中文赋值脚本求值器(渠道预报前 / 销售产品落库前共用)。
|
||||
/// 语法示例:收件人地址1 = 收件人地址1 + ' ' + 收件人地址2
|
||||
/// </summary>
|
||||
public static class ChineseAssignScriptEvaluator
|
||||
{
|
||||
public const int MaxLength = 10000;
|
||||
|
||||
/// <summary>
|
||||
/// 与下单页 / 前端 preScriptMeta 可写白名单对齐(table.field)。
|
||||
/// 必须排在 WritableLabels 之前初始化。
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> WritableFieldKeys = new(StringComparer.Ordinal)
|
||||
{
|
||||
"t_order_recipient.RecipientsName",
|
||||
"t_order_recipient.CompanyName",
|
||||
"t_order_recipient.Phone",
|
||||
"t_order_recipient.TelePhone",
|
||||
"t_order_recipient.Email",
|
||||
"t_order_recipient.ZipCode",
|
||||
"t_order_recipient.Province",
|
||||
"t_order_recipient.City",
|
||||
"t_order_recipient.StreetNumber",
|
||||
"t_order_recipient.StreetAddress1",
|
||||
"t_order_recipient.StreetAddress2",
|
||||
"t_order_recipient.StreetAddress3",
|
||||
"t_order_recipient.TaxNo",
|
||||
"t_order_recipient.CertificateNo",
|
||||
"t_order_recipient.Eori",
|
||||
"t_order_recipient.Vat",
|
||||
"t_order_sender.SenderName",
|
||||
"t_order_sender.Company",
|
||||
"t_order_sender.Province",
|
||||
"t_order_sender.City",
|
||||
"t_order_sender.ZipCode",
|
||||
"t_order_sender.StreetAddress1",
|
||||
"t_order_sender.StreetAddress2",
|
||||
"t_order_sender.StreetAddress3",
|
||||
"t_order_sender.HouseNumber",
|
||||
"t_order_sender.Phone",
|
||||
"t_order_sender.TelePhone",
|
||||
"t_order_sender.Email",
|
||||
"t_order_declaration.CnName",
|
||||
"t_order_declaration.EnName",
|
||||
"t_order_declaration.Sku",
|
||||
"t_order_declaration.Unit",
|
||||
"t_order_declaration.ImHsCode",
|
||||
"t_order_declaration.ExHsCode",
|
||||
"t_order_declaration.DeclareElement",
|
||||
"t_order_declaration.ProductId",
|
||||
"t_order_declaration.NonStdProductId",
|
||||
"t_order_declaration.StdProductId",
|
||||
"t_order_declaration.Category",
|
||||
"t_order_declaration.Brand",
|
||||
"t_order_declaration.BrandType",
|
||||
"t_order_declaration.Distribution",
|
||||
"t_order_declaration.Material",
|
||||
"t_order_declaration.EnMaterial",
|
||||
"t_order_declaration.Purpose",
|
||||
"t_order_declaration.Attributes",
|
||||
"t_order_declaration.OriginCountry",
|
||||
"t_order_declaration.SalesLink",
|
||||
"t_order_declaration.Model",
|
||||
"t_order_declaration.Specifications",
|
||||
"t_order_declaration.Comment",
|
||||
"t_order_weight.Length",
|
||||
"t_order_weight.Width",
|
||||
"t_order_weight.Height",
|
||||
"t_order_weight.ActualWeight",
|
||||
};
|
||||
|
||||
private static readonly HashSet<string> WritableLabels = BuildWritableLabels();
|
||||
|
||||
/// <summary>
|
||||
/// 执行赋值脚本;空脚本视为成功。失败抛 <see cref="BusinessException"/>。
|
||||
/// </summary>
|
||||
public static void Apply(string? script, OrderRuleEvaluationContext context)
|
||||
{
|
||||
var text = script?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (text.Length > MaxLength)
|
||||
{
|
||||
throw new BusinessException($"赋值脚本超过 {MaxLength} 字符");
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var parser = new Parser(text, context);
|
||||
parser.ParseScript();
|
||||
}
|
||||
catch (AssignScriptException ex)
|
||||
{
|
||||
throw new BusinessException($"赋值脚本错误:{ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>左侧可赋值的中文 label。</summary>
|
||||
public static bool IsWritableLabel(string label) => WritableLabels.Contains(label);
|
||||
|
||||
public static IReadOnlyCollection<string> WritableLabelList => WritableLabels;
|
||||
|
||||
private static HashSet<string> BuildWritableLabels()
|
||||
{
|
||||
var set = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (var (label, fieldRef) in AutoTriggerFormulaMeta.LabelToRef)
|
||||
{
|
||||
if (fieldRef.Virtual)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = $"{fieldRef.Table}.{fieldRef.Field}";
|
||||
if (WritableFieldKeys.Contains(key))
|
||||
{
|
||||
set.Add(label);
|
||||
}
|
||||
}
|
||||
|
||||
return set;
|
||||
}
|
||||
|
||||
private sealed class AssignScriptException(string message) : Exception(message);
|
||||
|
||||
private enum TokenKind
|
||||
{
|
||||
Number,
|
||||
String,
|
||||
Label,
|
||||
Plus,
|
||||
Minus,
|
||||
Multiply,
|
||||
Divide,
|
||||
Assign,
|
||||
LeftParen,
|
||||
RightParen,
|
||||
Semicolon,
|
||||
End
|
||||
}
|
||||
|
||||
private readonly record struct Token(TokenKind Kind, string Text, decimal Number = 0);
|
||||
|
||||
private sealed class Lexer(string source)
|
||||
{
|
||||
private int _pos;
|
||||
|
||||
public Token Next()
|
||||
{
|
||||
SkipWhitespaceAndComments();
|
||||
if (_pos >= source.Length)
|
||||
{
|
||||
return new Token(TokenKind.End, string.Empty);
|
||||
}
|
||||
|
||||
var ch = source[_pos];
|
||||
if (ch is >= '0' and <= '9' || (ch == '.' && _pos + 1 < source.Length && source[_pos + 1] is >= '0' and <= '9'))
|
||||
{
|
||||
return ReadNumber();
|
||||
}
|
||||
|
||||
if (ch == '\'')
|
||||
{
|
||||
return ReadString();
|
||||
}
|
||||
|
||||
if (ch == ';')
|
||||
{
|
||||
_pos++;
|
||||
return new Token(TokenKind.Semicolon, ";");
|
||||
}
|
||||
|
||||
if (TryReadOperator(out var opToken))
|
||||
{
|
||||
return opToken;
|
||||
}
|
||||
|
||||
if (TryReadLabel(out var labelToken))
|
||||
{
|
||||
return labelToken;
|
||||
}
|
||||
|
||||
throw new AssignScriptException($"无法识别的字符:{source[_pos]}");
|
||||
}
|
||||
|
||||
private void SkipWhitespaceAndComments()
|
||||
{
|
||||
while (_pos < source.Length)
|
||||
{
|
||||
if (char.IsWhiteSpace(source[_pos]))
|
||||
{
|
||||
_pos++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (source[_pos] == '#')
|
||||
{
|
||||
while (_pos < source.Length && source[_pos] is not ('\r' or '\n'))
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private Token ReadNumber()
|
||||
{
|
||||
var start = _pos;
|
||||
while (_pos < source.Length && (char.IsDigit(source[_pos]) || source[_pos] == '.'))
|
||||
{
|
||||
_pos++;
|
||||
}
|
||||
|
||||
var text = source[start.._pos];
|
||||
if (!decimal.TryParse(text, NumberStyles.Any, CultureInfo.InvariantCulture, out var number))
|
||||
{
|
||||
throw new AssignScriptException($"无效数字:{text}");
|
||||
}
|
||||
|
||||
return new Token(TokenKind.Number, text, number);
|
||||
}
|
||||
|
||||
private Token ReadString()
|
||||
{
|
||||
_pos++;
|
||||
var sb = new StringBuilder();
|
||||
while (_pos < source.Length)
|
||||
{
|
||||
var ch = source[_pos++];
|
||||
if (ch == '\'')
|
||||
{
|
||||
if (_pos < source.Length && source[_pos] == '\'')
|
||||
{
|
||||
sb.Append('\'');
|
||||
_pos++;
|
||||
continue;
|
||||
}
|
||||
|
||||
return new Token(TokenKind.String, sb.ToString());
|
||||
}
|
||||
|
||||
sb.Append(ch);
|
||||
}
|
||||
|
||||
throw new AssignScriptException("字符串未闭合");
|
||||
}
|
||||
|
||||
private bool TryReadOperator(out Token token)
|
||||
{
|
||||
token = default;
|
||||
// 禁止把 == 当赋值;赋值仅单 =
|
||||
if (_pos + 1 < source.Length && source[_pos] == '=' && source[_pos + 1] == '=')
|
||||
{
|
||||
throw new AssignScriptException("赋值脚本不支持比较运算符 ==,请使用赋值 =");
|
||||
}
|
||||
|
||||
var ch = source[_pos];
|
||||
token = ch switch
|
||||
{
|
||||
'=' => new Token(TokenKind.Assign, "="),
|
||||
'+' => new Token(TokenKind.Plus, "+"),
|
||||
'-' => new Token(TokenKind.Minus, "-"),
|
||||
'*' => new Token(TokenKind.Multiply, "*"),
|
||||
'/' => new Token(TokenKind.Divide, "/"),
|
||||
'(' => new Token(TokenKind.LeftParen, "("),
|
||||
')' => new Token(TokenKind.RightParen, ")"),
|
||||
_ => default
|
||||
};
|
||||
if (token.Kind == default)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_pos++;
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TryReadLabel(out Token token)
|
||||
{
|
||||
token = default;
|
||||
foreach (var label in AutoTriggerFormulaMeta.LabelsByLengthDesc)
|
||||
{
|
||||
if (!source.AsSpan(_pos).StartsWith(label, StringComparison.Ordinal))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
_pos += label.Length;
|
||||
// 可选空括号:收件人地址1() 与 收件人地址1 等价(读值)
|
||||
SkipWhitespaceAndComments();
|
||||
if (_pos + 2 <= source.Length && source.AsSpan(_pos, 2).SequenceEqual("()".AsSpan()))
|
||||
{
|
||||
_pos += 2;
|
||||
}
|
||||
|
||||
token = new Token(TokenKind.Label, label);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class Parser
|
||||
{
|
||||
private readonly Lexer _lexer;
|
||||
private readonly OrderRuleEvaluationContext _context;
|
||||
private Token _current;
|
||||
|
||||
public Parser(string source, OrderRuleEvaluationContext context)
|
||||
{
|
||||
_lexer = new Lexer(source);
|
||||
_context = context;
|
||||
_current = _lexer.Next();
|
||||
}
|
||||
|
||||
public void ParseScript()
|
||||
{
|
||||
while (_current.Kind != TokenKind.End)
|
||||
{
|
||||
while (_current.Kind == TokenKind.Semicolon)
|
||||
{
|
||||
Advance();
|
||||
}
|
||||
|
||||
if (_current.Kind == TokenKind.End)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
ParseStatement();
|
||||
if (_current.Kind is TokenKind.Semicolon)
|
||||
{
|
||||
Advance();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ParseStatement()
|
||||
{
|
||||
if (_current.Kind != TokenKind.Label)
|
||||
{
|
||||
throw new AssignScriptException($"期望左侧字段名,实际:{_current.Text}");
|
||||
}
|
||||
|
||||
var leftLabel = _current.Text;
|
||||
Advance();
|
||||
if (_current.Kind != TokenKind.Assign)
|
||||
{
|
||||
throw new AssignScriptException($"字段「{leftLabel}」后期望 =");
|
||||
}
|
||||
|
||||
Advance();
|
||||
var value = ParseAdditive();
|
||||
if (!IsWritableLabel(leftLabel))
|
||||
{
|
||||
throw new AssignScriptException(
|
||||
$"字段「{leftLabel}」不可赋值(仅下单相关可写字段;申报首行;件重尺仅长宽高/实重)");
|
||||
}
|
||||
|
||||
if (!AutoTriggerFormulaMeta.TryResolve(leftLabel, out var fieldRef) || fieldRef == null)
|
||||
{
|
||||
throw new AssignScriptException($"未知字段:{leftLabel}");
|
||||
}
|
||||
|
||||
if (!OrderFormulaFieldResolver.TrySetValue(fieldRef, _context, value))
|
||||
{
|
||||
throw new AssignScriptException($"无法写入字段:{leftLabel}");
|
||||
}
|
||||
}
|
||||
|
||||
private object? ParseAdditive()
|
||||
{
|
||||
var left = ParseMultiplicative();
|
||||
while (_current.Kind is TokenKind.Plus or TokenKind.Minus)
|
||||
{
|
||||
var op = _current.Kind;
|
||||
Advance();
|
||||
var right = ParseMultiplicative();
|
||||
left = ApplyAdd(left, right, op == TokenKind.Plus);
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private object? ParseMultiplicative()
|
||||
{
|
||||
var left = ParseUnary();
|
||||
while (_current.Kind is TokenKind.Multiply or TokenKind.Divide)
|
||||
{
|
||||
var op = _current.Kind;
|
||||
Advance();
|
||||
var right = ParseUnary();
|
||||
left = ApplyMul(left, right, op == TokenKind.Multiply);
|
||||
}
|
||||
|
||||
return left;
|
||||
}
|
||||
|
||||
private object? ParseUnary()
|
||||
{
|
||||
if (_current.Kind == TokenKind.Minus)
|
||||
{
|
||||
Advance();
|
||||
var v = ParsePrimary();
|
||||
return -ToDecimal(v);
|
||||
}
|
||||
|
||||
if (_current.Kind == TokenKind.Plus)
|
||||
{
|
||||
Advance();
|
||||
return ParsePrimary();
|
||||
}
|
||||
|
||||
return ParsePrimary();
|
||||
}
|
||||
|
||||
private object? ParsePrimary()
|
||||
{
|
||||
if (_current.Kind == TokenKind.Number)
|
||||
{
|
||||
var n = _current.Number;
|
||||
Advance();
|
||||
return n;
|
||||
}
|
||||
|
||||
if (_current.Kind == TokenKind.String)
|
||||
{
|
||||
var s = _current.Text;
|
||||
Advance();
|
||||
return s;
|
||||
}
|
||||
|
||||
if (_current.Kind == TokenKind.Label)
|
||||
{
|
||||
var label = _current.Text;
|
||||
Advance();
|
||||
if (!AutoTriggerFormulaMeta.TryResolve(label, out var fieldRef) || fieldRef == null)
|
||||
{
|
||||
throw new AssignScriptException($"未知字段:{label}");
|
||||
}
|
||||
|
||||
return OrderFormulaFieldResolver.GetRawValuePublic(fieldRef, _context);
|
||||
}
|
||||
|
||||
if (_current.Kind == TokenKind.LeftParen)
|
||||
{
|
||||
Advance();
|
||||
var inner = ParseAdditive();
|
||||
if (_current.Kind != TokenKind.RightParen)
|
||||
{
|
||||
throw new AssignScriptException("缺少右括号 )");
|
||||
}
|
||||
|
||||
Advance();
|
||||
return inner;
|
||||
}
|
||||
|
||||
throw new AssignScriptException($"无法解析表达式,意外标记:{_current.Text}");
|
||||
}
|
||||
|
||||
private static object? ApplyAdd(object? left, object? right, bool plus)
|
||||
{
|
||||
if (!plus)
|
||||
{
|
||||
return ToDecimal(left) - ToDecimal(right);
|
||||
}
|
||||
|
||||
// 任一为字符串 → 拼接(null 当空串)
|
||||
if (left is string || right is string || LooksLikeNonNumericString(left) || LooksLikeNonNumericString(right))
|
||||
{
|
||||
return ValueToString(left) + ValueToString(right);
|
||||
}
|
||||
|
||||
// 两边都可当数字
|
||||
if (TryAsDecimal(left, out var ld) && TryAsDecimal(right, out var rd))
|
||||
{
|
||||
return ld + rd;
|
||||
}
|
||||
|
||||
return ValueToString(left) + ValueToString(right);
|
||||
}
|
||||
|
||||
private static object ApplyMul(object? left, object? right, bool multiply)
|
||||
{
|
||||
var ld = ToDecimal(left);
|
||||
var rd = ToDecimal(right);
|
||||
if (!multiply && rd == 0)
|
||||
{
|
||||
throw new AssignScriptException("除数不能为 0");
|
||||
}
|
||||
|
||||
return multiply ? ld * rd : ld / rd;
|
||||
}
|
||||
|
||||
private static bool LooksLikeNonNumericString(object? value) =>
|
||||
value is string s && !decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out _);
|
||||
|
||||
private static bool TryAsDecimal(object? value, out decimal number)
|
||||
{
|
||||
number = 0;
|
||||
if (value == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value is decimal or int or long or float or double or byte or short)
|
||||
{
|
||||
number = ToDecimal(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value is string s)
|
||||
{
|
||||
return decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out number);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static decimal ToDecimal(object? value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
return value switch
|
||||
{
|
||||
decimal m => m,
|
||||
int i => i,
|
||||
long l => l,
|
||||
float f => (decimal)f,
|
||||
double d => (decimal)d,
|
||||
byte b => b,
|
||||
short s => s,
|
||||
string str => decimal.TryParse(str, NumberStyles.Any, CultureInfo.InvariantCulture, out var parsed)
|
||||
? parsed
|
||||
: throw new AssignScriptException($"无法将「{str}」作为数字运算"),
|
||||
_ => decimal.TryParse(Convert.ToString(value, CultureInfo.InvariantCulture), NumberStyles.Any,
|
||||
CultureInfo.InvariantCulture, out var n)
|
||||
? n
|
||||
: 0
|
||||
};
|
||||
}
|
||||
|
||||
private static string ValueToString(object? value)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return value switch
|
||||
{
|
||||
string s => s,
|
||||
decimal m => m.ToString(CultureInfo.InvariantCulture),
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture) ?? string.Empty,
|
||||
_ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty
|
||||
};
|
||||
}
|
||||
|
||||
private void Advance() => _current = _lexer.Next();
|
||||
}
|
||||
}
|
||||
@ -14,6 +14,232 @@ public static class OrderFormulaFieldResolver
|
||||
return ToDecimal(value);
|
||||
}
|
||||
|
||||
/// <summary>供预报前赋值脚本读取任意已注册字段。</summary>
|
||||
public static object? GetRawValuePublic(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context) =>
|
||||
GetRawValue(fieldRef, context);
|
||||
|
||||
/// <summary>
|
||||
/// 写入可赋值字段:收/发件人与申报字符串、件重尺数值。
|
||||
/// 优先写实体(预报前工作副本);否则写 CreateInput(落库前改写入参)。
|
||||
/// </summary>
|
||||
public static bool TrySetValue(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context, object? value)
|
||||
{
|
||||
if (fieldRef.Virtual)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fieldRef.Table == "t_order_weight")
|
||||
{
|
||||
return TrySetWeightValue(fieldRef.Field, context, value);
|
||||
}
|
||||
|
||||
var asString = value switch
|
||||
{
|
||||
null => null,
|
||||
string s => s,
|
||||
IFormattable f => f.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => Convert.ToString(value, CultureInfo.InvariantCulture)
|
||||
};
|
||||
return TrySetString(fieldRef, context, asString);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 写入收件人/发件人/申报(首行)字符串字段。
|
||||
/// </summary>
|
||||
public static bool TrySetString(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context, string? value)
|
||||
{
|
||||
if (fieldRef.Virtual)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fieldRef.Table == "t_order_declaration")
|
||||
{
|
||||
return TrySetDeclarationString(fieldRef.Field, context, value);
|
||||
}
|
||||
|
||||
object? target = fieldRef.Table switch
|
||||
{
|
||||
"t_order_recipient" => (object?)context.Recipient ?? EnsureCreateReceiver(context),
|
||||
"t_order_sender" => (object?)context.Sender ?? EnsureCreateSender(context),
|
||||
_ => null
|
||||
};
|
||||
if (target == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return TrySetStringProperty(target, fieldRef.Field, value);
|
||||
}
|
||||
|
||||
private static bool TrySetWeightValue(string field, OrderRuleEvaluationContext context, object? value)
|
||||
{
|
||||
if (string.Equals(field, "Type", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!TryToNullableDecimal(value, out var decimalValue))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var weight = GetForecastWeight(context);
|
||||
if (weight != null)
|
||||
{
|
||||
return TrySetDecimalProperty(weight, field, decimalValue);
|
||||
}
|
||||
|
||||
if (context.CreateInput == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
return TrySetDecimalProperty(context.CreateInput, field, decimalValue);
|
||||
}
|
||||
|
||||
private static bool TryToNullableDecimal(object? value, out decimal? number)
|
||||
{
|
||||
number = null;
|
||||
if (value == null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (value is string s)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(s))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!decimal.TryParse(s, NumberStyles.Any, CultureInfo.InvariantCulture, out var parsed))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
number = parsed;
|
||||
return true;
|
||||
}
|
||||
|
||||
number = ToDecimal(value);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static bool TrySetDecimalProperty(object target, string fieldName, decimal? value)
|
||||
{
|
||||
var prop = target.GetType().GetProperty(
|
||||
fieldName,
|
||||
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
||||
if (prop == null || !prop.CanWrite)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(decimal?))
|
||||
{
|
||||
prop.SetValue(target, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
if (prop.PropertyType == typeof(decimal))
|
||||
{
|
||||
prop.SetValue(target, value ?? 0m);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool TrySetDeclarationString(
|
||||
string field,
|
||||
OrderRuleEvaluationContext context,
|
||||
string? value)
|
||||
{
|
||||
var declaration = context.Declarations.FirstOrDefault();
|
||||
if (declaration != null)
|
||||
{
|
||||
// HS编码:实体有 HsCode;无该属性时回写 ImHsCode
|
||||
if (string.Equals(field, "HsCode", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
declaration.HsCode = value;
|
||||
if (string.IsNullOrWhiteSpace(declaration.ImHsCode))
|
||||
{
|
||||
declaration.ImHsCode = value;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return TrySetStringProperty(declaration, field, value);
|
||||
}
|
||||
|
||||
var item = EnsureCreateFirstItem(context);
|
||||
if (item == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (string.Equals(field, "HsCode", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
item.ImHsCode = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
return TrySetStringProperty(item, field, value);
|
||||
}
|
||||
|
||||
private static bool TrySetStringProperty(object target, string fieldName, string? value)
|
||||
{
|
||||
var prop = target.GetType().GetProperty(
|
||||
fieldName,
|
||||
BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
|
||||
if (prop == null || !prop.CanWrite || prop.PropertyType != typeof(string))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
prop.SetValue(target, value);
|
||||
return true;
|
||||
}
|
||||
|
||||
private static OrderParcelReceiverInput? EnsureCreateReceiver(OrderRuleEvaluationContext context)
|
||||
{
|
||||
if (context.CreateInput == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return context.CreateInput.Receiver ??= new OrderParcelReceiverInput();
|
||||
}
|
||||
|
||||
private static OrderParcelSenderInput? EnsureCreateSender(OrderRuleEvaluationContext context)
|
||||
{
|
||||
if (context.CreateInput == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return context.CreateInput.Sender ??= new OrderParcelSenderInput();
|
||||
}
|
||||
|
||||
private static OrderParcelItemInput? EnsureCreateFirstItem(OrderRuleEvaluationContext context)
|
||||
{
|
||||
if (context.CreateInput == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
context.CreateInput.Items ??= [];
|
||||
if (context.CreateInput.Items.Count == 0)
|
||||
{
|
||||
context.CreateInput.Items.Add(new OrderParcelItemInput());
|
||||
}
|
||||
|
||||
return context.CreateInput.Items[0];
|
||||
}
|
||||
|
||||
public static bool StringContains(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context, string needle)
|
||||
{
|
||||
// 空参数:表示「字段有值」(非 null / 非空白),用于必填校验,如 国家包含('')
|
||||
|
||||
@ -1116,6 +1116,7 @@ public partial class OrderService
|
||||
ActualWeight = x.ActualWeight,
|
||||
VolumetricWeight = x.VolumetricWeight,
|
||||
ChargeableWeight = x.ChargeableWeight,
|
||||
PayableChargeableWeight = x.PayableChargeableWeight,
|
||||
Cubic = x.Cubic
|
||||
};
|
||||
}
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -163,16 +163,20 @@ public partial class OrderService
|
||||
|
||||
EnsureAdditionalServicesAllowed(product, input.AdditionalServices);
|
||||
|
||||
// 销售产品「落库前脚本」:改写入参收/发件人,随后持久化与拦截校验都基于改写后的值
|
||||
ApplyPreStorageScript(product.PreStorageScript, input, sessionCustomer);
|
||||
|
||||
var snapshotBinding = await ResolveSnapshotBindingAsync(product, bindTime);
|
||||
var country = await GetCountryOrThrowAsync(input.Receiver.CountryCode);
|
||||
|
||||
var channelCode = string.IsNullOrWhiteSpace(input.ChannelCode)
|
||||
? product.ProductCode
|
||||
// 单号上下文里的 ChannelCode 仅在入参显式指定时带上;未排货前不要用产品编码冒充渠道。
|
||||
var channelCodeForDoc = string.IsNullOrWhiteSpace(input.ChannelCode)
|
||||
? null
|
||||
: input.ChannelCode.Trim();
|
||||
var numberContext = new DocNumberGenerateContext
|
||||
{
|
||||
ProductCode = product.ProductCode,
|
||||
ChannelCode = channelCode,
|
||||
ChannelCode = channelCodeForDoc,
|
||||
CountryCode = country.CountryCode,
|
||||
CustomerId = sessionCustomer.Id
|
||||
};
|
||||
@ -447,6 +451,28 @@ public partial class OrderService
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 销售产品落库前脚本:改写 CreateInput 收/发件人,随后落库与拦截校验均基于改写结果。
|
||||
/// </summary>
|
||||
private static void ApplyPreStorageScript(
|
||||
string? script,
|
||||
OrderParcelCreateInput input,
|
||||
Customer customer)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(script))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var countryCode = input.Receiver?.CountryCode?.Trim() ?? string.Empty;
|
||||
var context = OrderRuleEvaluationContext.FromPreCommit(
|
||||
input,
|
||||
customer,
|
||||
countryCode,
|
||||
consigneeCountryName: null);
|
||||
ChineseAssignScriptEvaluator.Apply(script, context);
|
||||
}
|
||||
|
||||
private async Task ValidateParcelCreateInputAsync(OrderParcelCreateInput input)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(input.ClientNo))
|
||||
@ -972,7 +998,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 +1010,8 @@ public partial class OrderService
|
||||
chargingStage,
|
||||
schemeOverride,
|
||||
forceServiceChannelId,
|
||||
allowDesignatedOutsidePool);
|
||||
allowDesignatedOutsidePool,
|
||||
payableWeightOverride);
|
||||
|
||||
ApplyAllocationTraceToOrder(order, evaluation);
|
||||
|
||||
@ -1003,10 +1031,12 @@ public partial class OrderService
|
||||
|
||||
var previousChannelCode = order.ChannelCode?.Trim();
|
||||
var newChannelCode = selectedCandidate.Channel.ChannelCode?.Trim() ?? string.Empty;
|
||||
var channelChanged = !string.Equals(
|
||||
previousChannelCode,
|
||||
newChannelCode,
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
// 仅「已有渠道 → 换成另一渠道」才算换渠道;首次从空排到渠道不算,避免误清跟踪号。
|
||||
var channelChanged = !string.IsNullOrWhiteSpace(previousChannelCode)
|
||||
&& !string.Equals(
|
||||
previousChannelCode,
|
||||
newChannelCode,
|
||||
StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
order.ChannelCode = selectedCandidate.Channel.ChannelCode;
|
||||
AllocationProviderSnapshotEnricher.ApplyDownstreamFieldsToOrder(
|
||||
@ -1023,6 +1053,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 +1091,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 +1225,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 +1290,61 @@ public partial class OrderService
|
||||
}
|
||||
|
||||
var channelRulesBinding = await ResolveChannelRulesBindingAsync(channel, bindTime);
|
||||
|
||||
if (IsChannelBlacklistHit(
|
||||
channelRulesBinding,
|
||||
order.ConsigneeCountry ?? string.Empty,
|
||||
recipient?.Province,
|
||||
recipient?.City,
|
||||
recipient?.ZipCode))
|
||||
{
|
||||
skipped.Add(new OrderAllocationSkippedOutput
|
||||
{
|
||||
ServiceChannelId = channel.Id,
|
||||
ChannelCode = channel.ChannelCode,
|
||||
ChannelName = channel.ChannelName,
|
||||
Stage = AllocationResolver.SkipStageChannel,
|
||||
MatchCondition = AllocationResolver.TruncateMatchCondition(provider.MatchCondition),
|
||||
Reason = "收件地址命中渠道黑名单区域"
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
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 +1386,7 @@ public partial class OrderService
|
||||
channelPriceBinding.Prices,
|
||||
channelPriceBinding.PriceVersion,
|
||||
channelPriceBinding.PriceEffectiveTime,
|
||||
chargeableWeight,
|
||||
channelPayableWeight,
|
||||
channelZoneKeys,
|
||||
cargoAttribute,
|
||||
chargingStage,
|
||||
@ -1273,7 +1400,7 @@ public partial class OrderService
|
||||
{
|
||||
var miss = ParcelBillingCalculator.ExplainPayablePriceMiss(
|
||||
channelPriceBinding.Prices,
|
||||
chargeableWeight,
|
||||
channelPayableWeight,
|
||||
channelZoneKeys,
|
||||
cargoAttribute,
|
||||
order.WarehouseId,
|
||||
@ -1298,6 +1425,7 @@ public partial class OrderService
|
||||
Provider = provider,
|
||||
Channel = channel,
|
||||
TotalPayableCost = previewFees.Sum(x => x.Amount),
|
||||
PayableChargeableWeight = channelPayableWeight,
|
||||
PayableFees = previewFees
|
||||
});
|
||||
}
|
||||
@ -1308,19 +1436,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 +1463,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 +1503,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 +1526,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 +1593,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 +1605,8 @@ public partial class OrderService
|
||||
billing.PriceTierKey,
|
||||
schemeOverride,
|
||||
forceServiceChannelId,
|
||||
allowDesignatedOutsidePool);
|
||||
allowDesignatedOutsidePool,
|
||||
payableWeightOverride);
|
||||
|
||||
/// <summary>
|
||||
/// 尝试排货并写入应付;失败时不抛异常,写入 <see cref="Order.AllocationPendingReason"/> 供运营补配置。
|
||||
@ -1506,10 +1636,40 @@ public partial class OrderService
|
||||
{
|
||||
var message = ex.Message.Trim();
|
||||
order.AllocationPendingReason = message.Length > 512 ? message[..512] : message;
|
||||
// 清掉历史「用产品 code 占位 ChannelCode」的脏数据;已真实排过的渠道(含与产品同码)予以保留。
|
||||
ClearUnallocatedProductCodeChannelPlaceholder(order);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 未真正排货成功前,曾把 ProductCode 写入 ChannelCode 作占位;排货失败时清掉该占位,避免详情误显示。
|
||||
/// 若 ChannelCode 与产品同码但已带下游字段,视为真实渠道,不清。
|
||||
/// </summary>
|
||||
private static void ClearUnallocatedProductCodeChannelPlaceholder(Order order)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(order.ChannelCode) || string.IsNullOrWhiteSpace(order.ProductCode))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.Equals(order.ChannelCode.Trim(), order.ProductCode.Trim(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var hasDownstream = !string.IsNullOrWhiteSpace(order.DownstreamSupplierCode)
|
||||
|| !string.IsNullOrWhiteSpace(order.DownstreamSupplierName)
|
||||
|| !string.IsNullOrWhiteSpace(order.ChannelForecastCode)
|
||||
|| order.DownstreamAppId is > 0;
|
||||
if (hasDownstream)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
order.ChannelCode = null;
|
||||
}
|
||||
|
||||
private async Task<List<SalesProductAllocationProviderSnapshotDto>> ResolveAllocationProvidersAsync(
|
||||
SalesProduct product,
|
||||
SalesProductRulesPublishSnapshotDto rulesSnapshot)
|
||||
@ -1630,13 +1790,39 @@ public partial class OrderService
|
||||
Channel = new ServiceChannelSaveInput
|
||||
{
|
||||
Id = channel.Id,
|
||||
RemoteAreaId = channel.RemoteAreaId
|
||||
RemoteAreaId = channel.RemoteAreaId,
|
||||
BlacklistAreaId = channel.BlacklistAreaId,
|
||||
WeightRuleId = channel.WeightRuleId,
|
||||
WeightRoundingId = channel.WeightRoundingId
|
||||
},
|
||||
RemoteAreaInfos = []
|
||||
WeightRuleId = channel.WeightRuleId,
|
||||
WeightRoundingId = channel.WeightRoundingId,
|
||||
RemoteAreaInfos = [],
|
||||
BlacklistAreaInfos = []
|
||||
};
|
||||
await KpiAreaPackService.LoadLiveRemoteIntoChannelRulesSnapshotAsync(
|
||||
live,
|
||||
channel.RemoteAreaId);
|
||||
await KpiAreaPackService.LoadLiveBlacklistIntoChannelRulesSnapshotAsync(
|
||||
live,
|
||||
channel.BlacklistAreaId);
|
||||
// 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,
|
||||
@ -1730,6 +1916,33 @@ public partial class OrderService
|
||||
return false;
|
||||
}
|
||||
|
||||
private static bool IsChannelBlacklistHit(
|
||||
ChannelRulesBinding binding,
|
||||
string countryCode,
|
||||
string? province,
|
||||
string? city,
|
||||
string? zipCode)
|
||||
{
|
||||
var snapshot = binding.Snapshot;
|
||||
if (snapshot.BlacklistAreaRef != null && snapshot.BlacklistAreaInfos is not { Count: > 0 })
|
||||
{
|
||||
throw new BusinessException(
|
||||
$"渠道黑名单分区包未加载: areaId={snapshot.BlacklistAreaRef.AreaId} version={snapshot.BlacklistAreaRef.PackVersion}");
|
||||
}
|
||||
|
||||
if (snapshot.BlacklistAreaInfos is { Count: > 0 })
|
||||
{
|
||||
return GeoPartitionMatcher.IsHit(
|
||||
snapshot.BlacklistAreaInfos,
|
||||
countryCode,
|
||||
province,
|
||||
city,
|
||||
zipCode);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private async Task<SalesProductRulesPublishSnapshotDto> BuildLiveRulesSnapshotAsync(SalesProduct product)
|
||||
{
|
||||
var snapshot = new SalesProductRulesPublishSnapshotDto
|
||||
@ -1975,6 +2188,188 @@ public partial class OrderService
|
||||
return Task.FromResult<IReadOnlyList<string>?>(null);
|
||||
}
|
||||
|
||||
private static bool HasPayableWeightDimensions(OrderWeight row) =>
|
||||
row.Length is > 0
|
||||
&& row.Width is > 0
|
||||
&& row.Height is > 0
|
||||
&& row.ActualWeight is > 0;
|
||||
|
||||
/// <summary>
|
||||
/// 按服务渠道计重规则/进位计算应付计费重(不写应收 ChargeableWeight)。
|
||||
/// </summary>
|
||||
private async Task<decimal> 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<WeightRuleInfo> 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<WeightRoundingInfo> 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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅写应付计费重;不改 ChargeableWeight / VolumetricWeight。
|
||||
/// </summary>
|
||||
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,
|
||||
@ -2280,7 +2675,8 @@ public partial class OrderService
|
||||
TrackNo = input.TrackNo,
|
||||
ServiceNo = serviceNo,
|
||||
ProductCode = input.ProductCode,
|
||||
ChannelCode = input.ChannelCode ?? product.ProductCode,
|
||||
// 服务渠道仅排货成功后写入;未排货保持空,避免详情把产品 code 当成渠道 code。
|
||||
ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim(),
|
||||
ConsigneeCountry = consigneeCountry,
|
||||
ConsigneeCountryName = consigneeCountryName,
|
||||
CargoAttribute = input.CargoAttribute ?? CargoAttributeCodes.General,
|
||||
|
||||
@ -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<List<OrderFee>> CalculatePayableAsync(
|
||||
private async Task<(List<OrderFee> Fees, decimal PayableChargeableWeight)> CalculatePayableAsync(
|
||||
SalesProduct product,
|
||||
PickupOrder pickup,
|
||||
OrderWeight weightRow,
|
||||
IReadOnlyList<string> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 揽收应付:按服务渠道计重规则/进位(不改应收 ChargeableWeight)。
|
||||
/// </summary>
|
||||
private async Task<decimal> 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<List<ServiceChannelPriceListOutput>> GetChannelPriceOutputsAsync(int serviceChannelId)
|
||||
|
||||
@ -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<List<PickupPackageSizeOutput>>(entity.PackageSizesJson) ?? [],
|
||||
CarrierFreightWeight = entity.CarrierFreightWeight,
|
||||
|
||||
@ -27,6 +27,9 @@ public static class AllocationResolver
|
||||
|
||||
public decimal TotalPayableCost { get; init; }
|
||||
|
||||
/// <summary>该候选渠道按渠道计重算出的应付计费重。</summary>
|
||||
public decimal PayableChargeableWeight { get; init; }
|
||||
|
||||
/// <summary>候选渠道已算出的应付费用(选渠后可直接落库,避免重复算价)。</summary>
|
||||
public IReadOnlyList<OrderFee> PayableFees { get; init; } = [];
|
||||
}
|
||||
|
||||
@ -331,7 +331,7 @@ public class KpiAreaPackService : IScopedDependency
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 渠道规则:偏远 Ref hydrate。
|
||||
/// 渠道规则:偏远 / 黑名单 Ref hydrate。
|
||||
/// </summary>
|
||||
public async Task HydrateChannelRulesSnapshotAsync(
|
||||
ServiceChannelRulesPublishSnapshotDto snapshot,
|
||||
@ -343,6 +343,13 @@ public class KpiAreaPackService : IScopedDependency
|
||||
snapshot.RemoteAreaId = snapshot.RemoteAreaRef.AreaId;
|
||||
snapshot.RemoteAreaName = snapshot.RemoteAreaRef.AreaName;
|
||||
}
|
||||
|
||||
if (snapshot.BlacklistAreaRef != null)
|
||||
{
|
||||
snapshot.BlacklistAreaInfos = await GetRulesOrThrowAsync(snapshot.BlacklistAreaRef, cancellationToken);
|
||||
snapshot.BlacklistAreaId = snapshot.BlacklistAreaRef.AreaId;
|
||||
snapshot.BlacklistAreaName = snapshot.BlacklistAreaRef.AreaName;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task LoadLiveInfosIntoChannelPriceSnapshotAsync(
|
||||
@ -412,6 +419,30 @@ public class KpiAreaPackService : IScopedDependency
|
||||
}
|
||||
}
|
||||
|
||||
public async Task LoadLiveBlacklistIntoChannelRulesSnapshotAsync(
|
||||
ServiceChannelRulesPublishSnapshotDto snapshot,
|
||||
int? blacklistAreaId,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
snapshot.BlacklistAreaRef = null;
|
||||
if (blacklistAreaId is > 0)
|
||||
{
|
||||
var area = await _kpiAreaRepository.FirstOrDefaultAsync(x => x.Id == blacklistAreaId.Value, cancellationToken);
|
||||
var infos = await _kpiAreaRepository.GetAllInfosByAreaIdAsync(blacklistAreaId.Value, cancellationToken);
|
||||
var rules = infos.Select(i => KpiAreaSnapshotMapper.MapToSnapshotRule(i, area?.Name)).ToList();
|
||||
PublishSnapshotNormalizer.NormalizeKpiAreas(rules);
|
||||
snapshot.BlacklistAreaId = blacklistAreaId;
|
||||
snapshot.BlacklistAreaName = area?.Name;
|
||||
snapshot.BlacklistAreaInfos = rules;
|
||||
}
|
||||
else
|
||||
{
|
||||
snapshot.BlacklistAreaId = null;
|
||||
snapshot.BlacklistAreaName = null;
|
||||
snapshot.BlacklistAreaInfos = [];
|
||||
}
|
||||
}
|
||||
|
||||
public async Task LoadLiveInfosIntoRulesSnapshotAsync(
|
||||
SalesProductRulesPublishSnapshotDto snapshot,
|
||||
int? blacklistAreaId,
|
||||
|
||||
@ -32,6 +32,9 @@ public static class OmsFileUploadHelper
|
||||
public static Task<string> SaveBrandLogoAsync(IFormFile file, IObjectStorage storage) =>
|
||||
SaveImageAsync(file, storage, "brand-logo", "品牌 Logo");
|
||||
|
||||
public static Task<string> SaveSalesProductCoverAsync(IFormFile file, IObjectStorage storage) =>
|
||||
SaveImageAsync(file, storage, "sales-product-cover", "销售产品封面图");
|
||||
|
||||
private static async Task<string> SaveImageAsync(
|
||||
IFormFile? file,
|
||||
IObjectStorage storage,
|
||||
|
||||
161
src/Oms.Application/Shared/OmsManagedImageHelper.cs
Normal file
161
src/Oms.Application/Shared/OmsManagedImageHelper.cs
Normal file
@ -0,0 +1,161 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Fake.Application;
|
||||
using Fake.ObjectStorage;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Oms.Application.Storage;
|
||||
|
||||
namespace Oms.Application.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// 托管图片同源访问:存 object key,对外只签发 /xxx/file 相对路径(不签发 COS 直链)。
|
||||
/// </summary>
|
||||
public static class OmsManagedImageHelper
|
||||
{
|
||||
public const string SalesProductCoverFilePath = "/channel/sales-product/cover/file";
|
||||
public const string SalesProductCoverKeyPrefix = "uploads/sales-product-cover/";
|
||||
|
||||
/// <summary>
|
||||
/// 生成浏览器可直开的同源相对路径;物理文件可在 COS/Local,但不把 cos.* 签发给前端。
|
||||
/// </summary>
|
||||
public static string BuildSameOriginUrlByKey(string path, string? objectKey)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0")
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
string logicalKey;
|
||||
try
|
||||
{
|
||||
logicalKey = FileStoragePath.NormalizeKey(objectKey);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (string.IsNullOrWhiteSpace(logicalKey))
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var stamp = Path.GetFileNameWithoutExtension(logicalKey.Replace('\\', '/'));
|
||||
if (string.IsNullOrWhiteSpace(stamp))
|
||||
{
|
||||
stamp = Math.Abs(logicalKey.GetHashCode(StringComparison.Ordinal)).ToString("x");
|
||||
}
|
||||
|
||||
return $"{path}?key={Uri.EscapeDataString(logicalKey)}&v={Uri.EscapeDataString(stamp)}";
|
||||
}
|
||||
|
||||
public static string BuildSalesProductCoverUrl(string? objectKey) =>
|
||||
BuildSameOriginUrlByKey(SalesProductCoverFilePath, objectKey);
|
||||
|
||||
/// <summary>
|
||||
/// 按 object key 输出图片字节(同源代理,避免浏览器直连 COS)。
|
||||
/// </summary>
|
||||
public static async Task<FileContentResult> StreamByKeyAsync(
|
||||
IObjectStorage storage,
|
||||
string? objectKey,
|
||||
CancellationToken cancellationToken,
|
||||
string? requiredKeyPrefix = null)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(objectKey) || objectKey == "0")
|
||||
{
|
||||
throw new BusinessException("图片未配置");
|
||||
}
|
||||
|
||||
string logicalKey;
|
||||
try
|
||||
{
|
||||
logicalKey = FileStoragePath.NormalizeKey(objectKey);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new BusinessException("图片路径无效");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(requiredKeyPrefix)
|
||||
&& !logicalKey.StartsWith(requiredKeyPrefix, StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new BusinessException("图片路径无效");
|
||||
}
|
||||
|
||||
foreach (var candidate in FileStoragePath.ExpandReadKeys(logicalKey))
|
||||
{
|
||||
try
|
||||
{
|
||||
if (!await storage.ExistsAsync(candidate, cancellationToken))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
await using var stream = await storage.GetAsync(candidate, cancellationToken);
|
||||
using var ms = new MemoryStream();
|
||||
await stream.CopyToAsync(ms, cancellationToken);
|
||||
var bytes = ms.ToArray();
|
||||
if (bytes.Length <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// 不设 FileDownloadName,避免 Content-Disposition: attachment 影响 CSS/img 内联展示
|
||||
return new FileContentResult(bytes, GuessImageMime(candidate));
|
||||
}
|
||||
catch (UnauthorizedAccessException)
|
||||
{
|
||||
}
|
||||
catch (DirectoryNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (FileNotFoundException)
|
||||
{
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
throw new BusinessException("图片不存在或无法读取");
|
||||
}
|
||||
|
||||
public static string GuessImageMime(string pathOrKey)
|
||||
{
|
||||
if (Regex.IsMatch(pathOrKey, @"\.png(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/png";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.jpe?g(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/jpeg";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.webp(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/webp";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.gif(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/gif";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.bmp(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/bmp";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.svg(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/svg+xml";
|
||||
}
|
||||
|
||||
if (Regex.IsMatch(pathOrKey, @"\.ico(\?|#|$)", RegexOptions.IgnoreCase))
|
||||
{
|
||||
return "image/x-icon";
|
||||
}
|
||||
|
||||
return "application/octet-stream";
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
using Fake.ObjectStorage;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
using Oms.Application.Storage;
|
||||
using Oms.Domain.ChannelsAggregate.Repositories;
|
||||
using Oms.Domain.OrdersAggregate.Consts;
|
||||
@ -40,21 +41,34 @@ public static class OrderDownstreamCreateOneBodyBuilder
|
||||
: await countryRepository.GetListAsync(x => countryIds.Contains(x.Id));
|
||||
var idToCode = countries.ToDictionary(x => x.Id, x => x.CountryCode);
|
||||
|
||||
var forecast = weights.FirstOrDefault(x =>
|
||||
string.Equals(x.Type, OrderWeightTypeCodes.Forecast, StringComparison.OrdinalIgnoreCase))
|
||||
?? weights.FirstOrDefault();
|
||||
|
||||
var productCode = await ResolveForecastProductCodeAsync(
|
||||
var channelSnapshot = await ResolveChannelForecastAsync(
|
||||
order,
|
||||
serviceChannelRepository,
|
||||
cancellationToken);
|
||||
|
||||
// 预报前脚本:只改工作副本,不回写订单库
|
||||
var workRecipient = CloneRecipient(recipient);
|
||||
var workSender = CloneSender(sender);
|
||||
var workDeclarations = declarations.Select(CloneDeclaration).ToList();
|
||||
var workWeights = weights.Select(CloneWeight).ToList();
|
||||
ApplyPreScript(
|
||||
channelSnapshot.PreScript,
|
||||
order,
|
||||
workRecipient,
|
||||
workSender,
|
||||
workDeclarations,
|
||||
workWeights);
|
||||
|
||||
var forecast = workWeights.FirstOrDefault(x =>
|
||||
string.Equals(x.Type, OrderWeightTypeCodes.Forecast, StringComparison.OrdinalIgnoreCase))
|
||||
?? workWeights.FirstOrDefault();
|
||||
|
||||
return new ItfxCreateOrderOneBody
|
||||
{
|
||||
ClientNo = order.ClientNo,
|
||||
TrackNo = order.TrackNo,
|
||||
ServiceNo = order.ServiceNo,
|
||||
ProductCode = productCode,
|
||||
ProductCode = channelSnapshot.ForecastCode,
|
||||
CargoAttribute = order.CargoAttribute,
|
||||
WarehouseId = order.WarehouseId,
|
||||
CustomerId = order.CustomerId,
|
||||
@ -71,38 +85,163 @@ public static class OrderDownstreamCreateOneBodyBuilder
|
||||
DeclaredCurrency = order.DeclaredCurrency,
|
||||
DeclaredSum = FormatDecimal(order.DeclaredSum),
|
||||
Quantity = order.Quantity?.ToString(),
|
||||
Receiver = MapReceiver(recipient, order.ConsigneeCountry, idToCode),
|
||||
Sender = MapSender(sender, idToCode),
|
||||
Items = declarations.Select(x => MapItem(x, fileStorage)).ToList()
|
||||
Receiver = MapReceiver(workRecipient, order.ConsigneeCountry, idToCode),
|
||||
Sender = MapSender(workSender, idToCode),
|
||||
Items = workDeclarations.Select(x => MapItem(x, fileStorage)).ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private static void ApplyPreScript(
|
||||
string? preScript,
|
||||
Order order,
|
||||
OrderRecipient workRecipient,
|
||||
OrderSender workSender,
|
||||
IReadOnlyList<OrderDeclaration> workDeclarations,
|
||||
IReadOnlyList<OrderWeight> weights)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(preScript))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var context = OrderRuleEvaluationContext.FromOrder(
|
||||
order,
|
||||
customer: null,
|
||||
workRecipient,
|
||||
workSender,
|
||||
workDeclarations,
|
||||
weights,
|
||||
fees: null);
|
||||
ChineseAssignScriptEvaluator.Apply(preScript, context);
|
||||
}
|
||||
|
||||
private static OrderWeight CloneWeight(OrderWeight src) =>
|
||||
new()
|
||||
{
|
||||
Type = src.Type,
|
||||
Length = src.Length,
|
||||
Width = src.Width,
|
||||
Height = src.Height,
|
||||
ActualWeight = src.ActualWeight,
|
||||
VolumetricWeight = src.VolumetricWeight,
|
||||
ChargeableWeight = src.ChargeableWeight,
|
||||
PayableChargeableWeight = src.PayableChargeableWeight,
|
||||
Cubic = src.Cubic
|
||||
};
|
||||
|
||||
private static OrderDeclaration CloneDeclaration(OrderDeclaration src) =>
|
||||
new()
|
||||
{
|
||||
CnName = src.CnName,
|
||||
EnName = src.EnName,
|
||||
Sku = src.Sku,
|
||||
Unit = src.Unit,
|
||||
UnitPrice = src.UnitPrice,
|
||||
UnitWeight = src.UnitWeight,
|
||||
Quantity = src.Quantity,
|
||||
Amount = src.Amount,
|
||||
Weight = src.Weight,
|
||||
HsCode = src.HsCode,
|
||||
ImHsCode = src.ImHsCode,
|
||||
ExHsCode = src.ExHsCode,
|
||||
DeclareElement = src.DeclareElement,
|
||||
ProductId = src.ProductId,
|
||||
NonStdProductId = src.NonStdProductId,
|
||||
StdProductId = src.StdProductId,
|
||||
SkuImage = src.SkuImage,
|
||||
Category = src.Category,
|
||||
Brand = src.Brand,
|
||||
BrandType = src.BrandType,
|
||||
IsMagnetic = src.IsMagnetic,
|
||||
Distribution = src.Distribution,
|
||||
Material = src.Material,
|
||||
EnMaterial = src.EnMaterial,
|
||||
Purpose = src.Purpose,
|
||||
Attributes = src.Attributes,
|
||||
OriginCountry = src.OriginCountry,
|
||||
SalesLink = src.SalesLink,
|
||||
Model = src.Model,
|
||||
Specifications = src.Specifications,
|
||||
Comment = src.Comment
|
||||
};
|
||||
|
||||
private sealed record ChannelForecastSnapshot(string? ForecastCode, string? PreScript);
|
||||
|
||||
/// <summary>
|
||||
/// createOrderOne.productCode = 渠道「预报渠道 code」:
|
||||
/// 优先订单固化的 ChannelForecastCode,否则 live 查 t_service_channel.ForecastCode。
|
||||
/// PreScript 始终按收货渠道 live 读取(定制改写只挂在渠道上)。
|
||||
/// </summary>
|
||||
private static async Task<string?> ResolveForecastProductCodeAsync(
|
||||
private static async Task<ChannelForecastSnapshot> ResolveChannelForecastAsync(
|
||||
Order order,
|
||||
IServiceChannelRepository serviceChannelRepository,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var snapshotted = order.ChannelForecastCode?.Trim();
|
||||
if (!string.IsNullOrWhiteSpace(snapshotted))
|
||||
{
|
||||
return snapshotted;
|
||||
}
|
||||
|
||||
var channelCode = order.ChannelCode?.Trim();
|
||||
if (string.IsNullOrWhiteSpace(channelCode))
|
||||
string? preScript = null;
|
||||
string? liveForecastCode = null;
|
||||
if (!string.IsNullOrWhiteSpace(channelCode))
|
||||
{
|
||||
return null;
|
||||
var channel = await serviceChannelRepository.GetByChannelCodeAsync(channelCode, cancellationToken);
|
||||
preScript = channel?.PreScript;
|
||||
liveForecastCode = channel?.ForecastCode?.Trim();
|
||||
}
|
||||
|
||||
var channel = await serviceChannelRepository.GetByChannelCodeAsync(channelCode, cancellationToken);
|
||||
var forecastCode = channel?.ForecastCode?.Trim();
|
||||
return string.IsNullOrWhiteSpace(forecastCode) ? null : forecastCode;
|
||||
var snapshotted = order.ChannelForecastCode?.Trim();
|
||||
var forecastCode = !string.IsNullOrWhiteSpace(snapshotted)
|
||||
? snapshotted
|
||||
: (string.IsNullOrWhiteSpace(liveForecastCode) ? null : liveForecastCode);
|
||||
|
||||
return new ChannelForecastSnapshot(forecastCode, preScript);
|
||||
}
|
||||
|
||||
private static OrderRecipient CloneRecipient(OrderRecipient? src) =>
|
||||
src == null
|
||||
? new OrderRecipient()
|
||||
: new OrderRecipient
|
||||
{
|
||||
RecipientsName = src.RecipientsName,
|
||||
CompanyName = src.CompanyName,
|
||||
Country = src.Country,
|
||||
Phone = src.Phone,
|
||||
TelePhone = src.TelePhone,
|
||||
ZipCode = src.ZipCode,
|
||||
Province = src.Province,
|
||||
City = src.City,
|
||||
StreetNumber = src.StreetNumber,
|
||||
StreetAddress1 = src.StreetAddress1,
|
||||
StreetAddress2 = src.StreetAddress2,
|
||||
StreetAddress3 = src.StreetAddress3,
|
||||
Email = src.Email,
|
||||
TaxType = src.TaxType,
|
||||
TaxNo = src.TaxNo,
|
||||
CertificateType = src.CertificateType,
|
||||
CertificateNo = src.CertificateNo,
|
||||
Eori = src.Eori,
|
||||
Vat = src.Vat
|
||||
};
|
||||
|
||||
private static OrderSender CloneSender(OrderSender? src) =>
|
||||
src == null
|
||||
? new OrderSender()
|
||||
: new OrderSender
|
||||
{
|
||||
SenderName = src.SenderName,
|
||||
Company = src.Company,
|
||||
Country = src.Country,
|
||||
Province = src.Province,
|
||||
City = src.City,
|
||||
ZipCode = src.ZipCode,
|
||||
StreetAddress1 = src.StreetAddress1,
|
||||
StreetAddress2 = src.StreetAddress2,
|
||||
StreetAddress3 = src.StreetAddress3,
|
||||
HouseNumber = src.HouseNumber,
|
||||
Phone = src.Phone,
|
||||
TelePhone = src.TelePhone,
|
||||
Email = src.Email,
|
||||
IsDefault = src.IsDefault
|
||||
};
|
||||
|
||||
private static string? FormatDecimal(decimal? value) =>
|
||||
value.HasValue ? value.Value.ToString(System.Globalization.CultureInfo.InvariantCulture) : null;
|
||||
|
||||
@ -137,6 +276,33 @@ public static class OrderDownstreamCreateOneBodyBuilder
|
||||
: new OrderParcelReceiverInput { CountryCode = orderConsigneeCountry.Trim().ToUpperInvariant() };
|
||||
}
|
||||
|
||||
var hasAny =
|
||||
!string.IsNullOrWhiteSpace(recipient.RecipientsName)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.CompanyName)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.Phone)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.TelePhone)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.Email)
|
||||
|| recipient.Country is > 0
|
||||
|| !string.IsNullOrWhiteSpace(recipient.Province)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.City)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.StreetNumber)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.StreetAddress1)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.StreetAddress2)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.StreetAddress3)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.ZipCode)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.TaxNo)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.CertificateNo)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.Eori)
|
||||
|| !string.IsNullOrWhiteSpace(recipient.Vat)
|
||||
|| !string.IsNullOrWhiteSpace(orderConsigneeCountry);
|
||||
|
||||
if (!hasAny)
|
||||
{
|
||||
return string.IsNullOrWhiteSpace(orderConsigneeCountry)
|
||||
? null
|
||||
: new OrderParcelReceiverInput { CountryCode = orderConsigneeCountry.Trim().ToUpperInvariant() };
|
||||
}
|
||||
|
||||
return new OrderParcelReceiverInput
|
||||
{
|
||||
RecipientsName = recipient.RecipientsName,
|
||||
@ -168,6 +334,26 @@ public static class OrderDownstreamCreateOneBodyBuilder
|
||||
return null;
|
||||
}
|
||||
|
||||
var hasAny =
|
||||
!string.IsNullOrWhiteSpace(sender.SenderName)
|
||||
|| !string.IsNullOrWhiteSpace(sender.Company)
|
||||
|| !string.IsNullOrWhiteSpace(sender.Phone)
|
||||
|| !string.IsNullOrWhiteSpace(sender.TelePhone)
|
||||
|| !string.IsNullOrWhiteSpace(sender.Email)
|
||||
|| sender.Country is > 0
|
||||
|| !string.IsNullOrWhiteSpace(sender.Province)
|
||||
|| !string.IsNullOrWhiteSpace(sender.City)
|
||||
|| !string.IsNullOrWhiteSpace(sender.ZipCode)
|
||||
|| !string.IsNullOrWhiteSpace(sender.StreetAddress1)
|
||||
|| !string.IsNullOrWhiteSpace(sender.StreetAddress2)
|
||||
|| !string.IsNullOrWhiteSpace(sender.StreetAddress3)
|
||||
|| !string.IsNullOrWhiteSpace(sender.HouseNumber);
|
||||
|
||||
if (!hasAny)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return new OrderParcelSenderInput
|
||||
{
|
||||
SenderName = sender.SenderName,
|
||||
|
||||
@ -51,6 +51,11 @@ public class SalesProduct : OmsAuditedAggregateRoot
|
||||
|
||||
public string? ProductDescription { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 官网线路封面图 object key(如 uploads/sales-product-cover/...)。
|
||||
/// </summary>
|
||||
public string? CoverImage { get; set; }
|
||||
|
||||
public string? PreStorageScript { get; set; }
|
||||
|
||||
public string? CustomerGuideMarkdown { get; set; }
|
||||
|
||||
@ -28,6 +28,21 @@ public class ServiceChannel : OmsAuditedAggregateRoot
|
||||
/// </summary>
|
||||
public int? RemoteAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 黑名单分区 KPI AreaId(渠道侧排货命中则跳过)。
|
||||
/// </summary>
|
||||
public int? BlacklistAreaId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重规则 ID(应付计费重)。
|
||||
/// </summary>
|
||||
public int? WeightRuleId { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 计重进位 ID(应付计费重)。
|
||||
/// </summary>
|
||||
public int? WeightRoundingId { get; set; }
|
||||
|
||||
public string? PreScript { get; set; }
|
||||
|
||||
public EnableStatus IsActive { get; set; }
|
||||
|
||||
@ -20,7 +20,15 @@ public class OrderWeight : OmsAuditedEntity
|
||||
|
||||
public decimal? VolumetricWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应收计费重(销售产品计重规则/进位)。
|
||||
/// </summary>
|
||||
public decimal? ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应付计费重(服务渠道计重规则/进位)。
|
||||
/// </summary>
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
public decimal? Cubic { get; set; }
|
||||
}
|
||||
|
||||
@ -102,9 +102,18 @@ public class PickupOrder : OmsAuditedAggregateRoot
|
||||
[SugarColumn(DecimalDigits = 3, IsNullable = true)]
|
||||
public decimal? TotalActualWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应收计费重(销售产品计重)。
|
||||
/// </summary>
|
||||
[SugarColumn(DecimalDigits = 3, IsNullable = true)]
|
||||
public decimal? ChargeableWeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 应付计费重(服务渠道计重)。
|
||||
/// </summary>
|
||||
[SugarColumn(DecimalDigits = 3, IsNullable = true)]
|
||||
public decimal? PayableChargeableWeight { get; set; }
|
||||
|
||||
[SugarColumn(DecimalDigits = 3, IsNullable = true)]
|
||||
public decimal? VolumetricWeight { get; set; }
|
||||
|
||||
|
||||
171
src/Oms.Tests/ChineseAssignScriptEvaluatorTests.cs
Normal file
171
src/Oms.Tests/ChineseAssignScriptEvaluatorTests.cs
Normal file
@ -0,0 +1,171 @@
|
||||
using FluentAssertions;
|
||||
using Oms.Application.Dtos.Orders;
|
||||
using Oms.Application.Services.Orders.Issues;
|
||||
using Oms.Domain.CustomersAggregate.Entities;
|
||||
using Oms.Domain.OrdersAggregate.Entities;
|
||||
using Xunit;
|
||||
|
||||
namespace Oms.Tests;
|
||||
|
||||
public class ChineseAssignScriptEvaluatorTests
|
||||
{
|
||||
[Fact]
|
||||
public void Apply_ConcatAddress2IntoAddress1_AndClearAddress2()
|
||||
{
|
||||
var recipient = new OrderRecipient
|
||||
{
|
||||
StreetAddress1 = "Line1",
|
||||
StreetAddress2 = "Line2"
|
||||
};
|
||||
var context = OrderRuleEvaluationContext.FromOrder(
|
||||
new Order { ClientNo = "C1" },
|
||||
customer: null,
|
||||
recipient,
|
||||
sender: new OrderSender(),
|
||||
declarations: null,
|
||||
weights: null,
|
||||
fees: null);
|
||||
|
||||
ChineseAssignScriptEvaluator.Apply(
|
||||
"收件人地址1 = 收件人地址1 + ' ' + 收件人地址2\n收件人地址2 = ''",
|
||||
context);
|
||||
|
||||
recipient.StreetAddress1.Should().Be("Line1 Line2");
|
||||
recipient.StreetAddress2.Should().Be("");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_EmptyScript_IsNoOp()
|
||||
{
|
||||
var recipient = new OrderRecipient { StreetAddress1 = "A" };
|
||||
var context = OrderRuleEvaluationContext.FromOrder(
|
||||
new Order(),
|
||||
null,
|
||||
recipient,
|
||||
new OrderSender(),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
ChineseAssignScriptEvaluator.Apply(" ", context);
|
||||
|
||||
recipient.StreetAddress1.Should().Be("A");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_ReadonlyOrderFieldOnLeft_Throws()
|
||||
{
|
||||
var context = OrderRuleEvaluationContext.FromOrder(
|
||||
new Order { ClientNo = "C1" },
|
||||
null,
|
||||
new OrderRecipient(),
|
||||
new OrderSender(),
|
||||
null,
|
||||
null,
|
||||
null);
|
||||
|
||||
var act = () => ChineseAssignScriptEvaluator.Apply("客户单号 = 'X'", context);
|
||||
|
||||
act.Should().Throw<Fake.Application.BusinessException>()
|
||||
.WithMessage("*不可赋值*");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_PreCommitCreateInput_WritesReceiver()
|
||||
{
|
||||
var input = new OrderParcelCreateInput
|
||||
{
|
||||
ProductCode = "P1",
|
||||
Receiver = new OrderParcelReceiverInput
|
||||
{
|
||||
CountryCode = "US",
|
||||
StreetAddress1 = "A",
|
||||
StreetAddress2 = "B"
|
||||
}
|
||||
};
|
||||
var context = OrderRuleEvaluationContext.FromPreCommit(
|
||||
input,
|
||||
new Customer { CustomerName = "c" },
|
||||
"US",
|
||||
"美国");
|
||||
|
||||
ChineseAssignScriptEvaluator.Apply(
|
||||
"收件人地址1 = 收件人地址1 + ' ' + 收件人地址2\n收件人地址2 = ''",
|
||||
context);
|
||||
|
||||
input.Receiver!.StreetAddress1.Should().Be("A B");
|
||||
input.Receiver.StreetAddress2.Should().Be("");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_PreCommitCreateInput_WritesFirstDeclarationItem()
|
||||
{
|
||||
var input = new OrderParcelCreateInput
|
||||
{
|
||||
ProductCode = "P1",
|
||||
Receiver = new OrderParcelReceiverInput { CountryCode = "US" },
|
||||
Items =
|
||||
[
|
||||
new OrderParcelItemInput { CnName = "壳", EnName = "Case", Sku = "S1" }
|
||||
]
|
||||
};
|
||||
var context = OrderRuleEvaluationContext.FromPreCommit(
|
||||
input,
|
||||
new Customer { CustomerName = "c" },
|
||||
"US",
|
||||
null);
|
||||
|
||||
ChineseAssignScriptEvaluator.Apply(
|
||||
"英文品名 = 中文品名 + '-' + SKU",
|
||||
context);
|
||||
|
||||
input.Items[0].EnName.Should().Be("壳-S1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_PreCommitCreateInput_WritesWeightFields()
|
||||
{
|
||||
var input = new OrderParcelCreateInput
|
||||
{
|
||||
ProductCode = "P1",
|
||||
Receiver = new OrderParcelReceiverInput { CountryCode = "US" },
|
||||
Length = 10,
|
||||
Width = 8,
|
||||
Height = 6,
|
||||
ActualWeight = 1.2m
|
||||
};
|
||||
var context = OrderRuleEvaluationContext.FromPreCommit(
|
||||
input,
|
||||
new Customer { CustomerName = "c" },
|
||||
"US",
|
||||
null);
|
||||
|
||||
ChineseAssignScriptEvaluator.Apply(
|
||||
"实重 = 实重 + 0.1\n长度 = 长度 + 1",
|
||||
context);
|
||||
|
||||
input.ActualWeight.Should().Be(1.3m);
|
||||
input.Length.Should().Be(11m);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Apply_ChargeableWeight_NotWritable()
|
||||
{
|
||||
var input = new OrderParcelCreateInput
|
||||
{
|
||||
ProductCode = "P1",
|
||||
Receiver = new OrderParcelReceiverInput { CountryCode = "US" },
|
||||
ActualWeight = 1.2m
|
||||
};
|
||||
var context = OrderRuleEvaluationContext.FromPreCommit(
|
||||
input,
|
||||
new Customer { CustomerName = "c" },
|
||||
"US",
|
||||
null);
|
||||
|
||||
var act = () => ChineseAssignScriptEvaluator.Apply("计费重 = 实重", context);
|
||||
|
||||
act.Should().Throw<Fake.Application.BusinessException>()
|
||||
.WithMessage("*不可赋值*");
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user