admin/src/Oms.Application/Services/Orders/Issues/OrderFormulaFieldResolver.cs
zzh 935f017f21 feat: 预报前/落库前中文赋值脚本求值与执行
渠道 PreScript 改预报报文,销售产品 PreStorageScript 在创单落库前改写入参;字段白名单对齐下单页并补 AI skill。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-11-24 15:10:14 +08:00

582 lines
18 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Globalization;
using System.Reflection;
using Oms.Application.Dtos.Orders;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
namespace Oms.Application.Services.Orders.Issues;
public static class OrderFormulaFieldResolver
{
public static decimal GetNumericValue(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context)
{
var value = GetRawValue(fieldRef, context);
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 / 非空白),用于必填校验,如 国家包含('')
if (string.IsNullOrEmpty(needle))
{
return HasValue(fieldRef, context);
}
if (fieldRef.Table == "t_order_declaration")
{
return context.Declarations.Any(d => ContainsValue(GetDeclarationValue(d, fieldRef.Field), needle))
|| context.CreateInput?.Items.Any(i => ContainsValue(GetDeclarationInputValue(i, fieldRef.Field), needle)) == true;
}
if (fieldRef.Table == "t_order_fee")
{
return RuleFees(context).Any(f => ContainsValue(GetPropertyValue(f, fieldRef.Field), needle));
}
var raw = GetRawValue(fieldRef, context);
return ContainsValue(raw, needle);
}
/// <summary>
/// 字段有值:非 null;字符串另要求非空白。数值 0 / 布尔 false 视为有值。
/// </summary>
public static bool HasValue(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context) =>
IsPresent(GetRawValue(fieldRef, context));
/// <summary>
/// 字段为空:null,或字符串空白。
/// </summary>
public static bool IsEmpty(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context) =>
!HasValue(fieldRef, context);
private static bool IsPresent(object? value)
{
if (value == null)
{
return false;
}
if (value is string s)
{
return !string.IsNullOrWhiteSpace(s);
}
return true;
}
private static object? GetRawValue(FormulaFieldRef fieldRef, OrderRuleEvaluationContext context)
{
if (fieldRef.Virtual)
{
return ResolveVirtual(fieldRef.Field, context);
}
return fieldRef.Table switch
{
"t_order" => ResolveOrderField(fieldRef.Field, context),
"t_order_recipient" => ResolveRecipientField(fieldRef.Field, context),
"t_order_sender" => ResolveSenderField(fieldRef.Field, context),
"t_order_declaration" => ResolveDeclarationField(fieldRef.Field, context),
"t_order_weight" => ResolveWeightField(fieldRef.Field, context),
"t_order_fee" => ResolveFeeField(fieldRef.Field, context),
"t_customer" => GetPropertyValue(context.Customer, fieldRef.Field),
_ => null
};
}
private static object? ResolveVirtual(string field, OrderRuleEvaluationContext context)
{
var (length, width, height) = GetPieceDimensions(context);
return field switch
{
"PieceMaxLength" => length,
"PieceMaxWidth" => width,
"PieceMaxHeight" => height,
"PieceSumLwh" => length + width + height,
_ => null
};
}
private static (decimal Length, decimal Width, decimal Height) GetPieceDimensions(OrderRuleEvaluationContext context)
{
var forecast = GetForecastWeight(context);
if (forecast != null)
{
return (forecast.Length ?? 0, forecast.Width ?? 0, forecast.Height ?? 0);
}
var input = context.CreateInput;
if (input != null)
{
return (input.Length ?? 0, input.Width ?? 0, input.Height ?? 0);
}
return (0, 0, 0);
}
private static OrderWeight? GetForecastWeight(OrderRuleEvaluationContext context) =>
context.Weights.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Forecast)
?? context.Weights.FirstOrDefault();
private static object? ResolveOrderField(string field, OrderRuleEvaluationContext context)
{
if (context.Order != null)
{
return GetPropertyValue(context.Order, field);
}
var input = context.CreateInput;
if (input == null)
{
return null;
}
return field switch
{
"RequestId" => input.RequestId,
"ClientNo" => input.ClientNo,
"TrackNo" => input.TrackNo,
"ServiceNo" => input.ServiceNo,
"ProductCode" => input.ProductCode,
"ChannelCode" => input.ChannelCode,
"ConsigneeCountry" => context.ConsigneeCountryCode,
"ConsigneeCountryName" => context.ConsigneeCountryName,
"CargoAttribute" => input.CargoAttribute,
"ExportCustomsMode" => input.ExportCustomsMode,
"WarehouseId" => input.WarehouseId,
"CustomerId" => input.CustomerId,
"IsCod" => input.IsCod ? (byte)1 : (byte)0,
"CodCurrency" => input.CodCurrency,
"CodSum" => input.CodSum,
"DeclaredCurrency" => input.DeclaredCurrency,
"DeclaredSum" => input.DeclaredSum,
"Quantity" => input.Quantity,
"IsRemote" => input.IsRemote,
"AdditionalServices" => SerializeAdditionalServices(input.AdditionalServices),
_ => null
};
}
private static string? SerializeAdditionalServices(List<string>? codes)
{
if (codes == null || codes.Count == 0)
{
return null;
}
var normalized = codes
.Where(x => !string.IsNullOrWhiteSpace(x))
.Select(x => x.Trim())
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
return normalized.Count == 0
? null
: global::System.Text.Json.JsonSerializer.Serialize(normalized);
}
private static object? ResolveRecipientField(string field, OrderRuleEvaluationContext context)
{
if (context.Recipient != null)
{
return GetPropertyValue(context.Recipient, field);
}
var receiver = context.CreateInput?.Receiver;
if (receiver == null)
{
return null;
}
return field switch
{
"RecipientsName" => receiver.RecipientsName,
"CompanyName" => receiver.CompanyName,
"Phone" => receiver.Phone,
"TelePhone" => receiver.TelePhone,
"Email" => receiver.Email,
"Province" => receiver.Province,
"City" => receiver.City,
"StreetNumber" => receiver.StreetNumber,
"StreetAddress1" => receiver.StreetAddress1,
"StreetAddress2" => receiver.StreetAddress2,
"StreetAddress3" => receiver.StreetAddress3,
"ZipCode" => receiver.ZipCode,
"TaxType" => receiver.TaxType,
"TaxNo" => receiver.TaxNo,
"CertificateType" => receiver.CertificateType,
"CertificateNo" => receiver.CertificateNo,
"Eori" => receiver.Eori,
"Vat" => receiver.Vat,
_ => null
};
}
private static object? ResolveSenderField(string field, OrderRuleEvaluationContext context)
{
if (context.Sender != null)
{
return GetPropertyValue(context.Sender, field);
}
var sender = context.CreateInput?.Sender;
if (sender == null)
{
return null;
}
return field switch
{
"SenderName" => sender.SenderName,
"Company" => sender.Company,
"Phone" => sender.Phone,
"TelePhone" => sender.TelePhone,
"Email" => sender.Email,
"Province" => sender.Province,
"City" => sender.City,
"ZipCode" => sender.ZipCode,
"StreetAddress1" => sender.StreetAddress1,
"StreetAddress2" => sender.StreetAddress2,
"StreetAddress3" => sender.StreetAddress3,
"HouseNumber" => sender.HouseNumber,
_ => null
};
}
private static object? ResolveDeclarationField(string field, OrderRuleEvaluationContext context)
{
var declaration = context.Declarations.FirstOrDefault();
if (declaration != null)
{
return GetDeclarationValue(declaration, field);
}
var item = context.CreateInput?.Items.FirstOrDefault();
return item == null ? null : GetDeclarationInputValue(item, field);
}
private static object? ResolveWeightField(string field, OrderRuleEvaluationContext context)
{
var weight = GetForecastWeight(context);
if (weight != null)
{
return GetPropertyValue(weight, field);
}
var input = context.CreateInput;
if (input == null)
{
return null;
}
return field switch
{
"Length" => input.Length,
"Width" => input.Width,
"Height" => input.Height,
"ActualWeight" => input.ActualWeight,
"VolumetricWeight" => input.VolumetricWeight,
"ChargeableWeight" => input.ChargeableWeight,
"Cubic" => input.Cubic,
_ => null
};
}
private static object? ResolveFeeField(string field, OrderRuleEvaluationContext context)
{
var fee = RuleFees(context).FirstOrDefault();
return fee == null ? null : GetPropertyValue(fee, field);
}
/// <summary>
/// 规则只看计费产生的费用行,忽略支付写入的营销抵扣负数行。
/// </summary>
private static IEnumerable<OrderFee> RuleFees(OrderRuleEvaluationContext context) =>
context.Fees.Where(f => !OrderFeeDiscountCostItems.IsDiscount(f.CostItem));
private static object? GetDeclarationValue(OrderDeclaration declaration, string field) =>
field switch
{
"HsCode" => declaration.HsCode ?? declaration.ImHsCode ?? declaration.ExHsCode,
_ => GetPropertyValue(declaration, field)
};
private static object? GetDeclarationInputValue(OrderParcelItemInput item, string field) =>
field switch
{
"HsCode" => item.ImHsCode ?? item.ExHsCode,
"IsMagnetic" => item.IsMagnetic ? (byte)1 : (byte)0,
_ => GetPropertyValue(item, field)
};
private static object? GetPropertyValue(object? target, string fieldName)
{
if (target == null)
{
return null;
}
var prop = target.GetType().GetProperty(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
return prop?.GetValue(target);
}
private static decimal ToDecimal(object? value)
{
if (value == null)
{
return 0;
}
return value switch
{
bool b => b ? 1m : 0m,
byte bt => bt,
sbyte sb => sb,
short s => s,
ushort us => us,
int i => i,
uint ui => ui,
long l => l,
ulong ul => ul,
float f => (decimal)f,
double d => (decimal)d,
decimal m => m,
DateTime => 0,
Enum e => Convert.ToDecimal(e, CultureInfo.InvariantCulture),
_ => decimal.TryParse(Convert.ToString(value, CultureInfo.InvariantCulture), NumberStyles.Any, CultureInfo.InvariantCulture, out var parsed)
? parsed
: 0
};
}
private static bool ContainsValue(object? source, string needle) =>
!string.IsNullOrWhiteSpace(Convert.ToString(source, CultureInfo.InvariantCulture))
&& Convert.ToString(source, CultureInfo.InvariantCulture)!
.Contains(needle, StringComparison.OrdinalIgnoreCase);
}