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;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Shared;
///
/// 从订单表及关联子表组装 itfx createOrderOne 标准请求体。
///
public static class OrderDownstreamCreateOneBodyBuilder
{
public static async Task BuildAsync(
Order order,
OrderSender? sender,
OrderRecipient? recipient,
IReadOnlyList declarations,
IReadOnlyList weights,
ICountryRepository countryRepository,
IServiceChannelRepository serviceChannelRepository,
IObjectStorage? fileStorage = null,
CancellationToken cancellationToken = default)
{
var countryIds = new List();
if (sender?.Country is > 0)
{
countryIds.Add(sender.Country.Value);
}
if (recipient?.Country is > 0)
{
countryIds.Add(recipient.Country.Value);
}
var countries = countryIds.Count == 0
? []
: await countryRepository.GetListAsync(x => countryIds.Contains(x.Id));
var idToCode = countries.ToDictionary(x => x.Id, x => x.CountryCode);
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 = channelSnapshot.ForecastCode,
CargoAttribute = order.CargoAttribute,
WarehouseId = order.WarehouseId,
CustomerId = order.CustomerId,
Length = forecast?.Length,
Width = forecast?.Width,
Height = forecast?.Height,
ActualWeight = forecast?.ActualWeight,
VolumetricWeight = forecast?.VolumetricWeight,
ChargeableWeight = forecast?.ChargeableWeight,
Cubic = forecast?.Cubic,
IsCod = order.IsCod > 0,
CodCurrency = order.CodCurrency,
CodSum = FormatDecimal(order.CodSum),
DeclaredCurrency = order.DeclaredCurrency,
DeclaredSum = FormatDecimal(order.DeclaredSum),
Quantity = order.Quantity?.ToString(),
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 workDeclarations,
IReadOnlyList 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);
///
/// createOrderOne.productCode = 渠道「预报渠道 code」:
/// 优先订单固化的 ChannelForecastCode,否则 live 查 t_service_channel.ForecastCode。
/// PreScript 始终按收货渠道 live 读取(定制改写只挂在渠道上)。
///
private static async Task ResolveChannelForecastAsync(
Order order,
IServiceChannelRepository serviceChannelRepository,
CancellationToken cancellationToken)
{
var channelCode = order.ChannelCode?.Trim();
string? preScript = null;
string? liveForecastCode = null;
if (!string.IsNullOrWhiteSpace(channelCode))
{
var channel = await serviceChannelRepository.GetByChannelCodeAsync(channelCode, cancellationToken);
preScript = channel?.PreScript;
liveForecastCode = channel?.ForecastCode?.Trim();
}
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;
private static string? ResolveCountryIso(int? countryId, string? orderConsigneeCountry, IReadOnlyDictionary idToCode)
{
if (!string.IsNullOrWhiteSpace(orderConsigneeCountry))
{
var trimmed = orderConsigneeCountry.Trim();
if (trimmed.Length == 2)
{
return trimmed.ToUpperInvariant();
}
}
if (countryId is > 0 && idToCode.TryGetValue(countryId.Value, out var iso) && !string.IsNullOrWhiteSpace(iso))
{
return iso.Trim().ToUpperInvariant();
}
return null;
}
private static OrderParcelReceiverInput? MapReceiver(
OrderRecipient? recipient,
string? orderConsigneeCountry,
IReadOnlyDictionary idToCode)
{
if (recipient == null)
{
return string.IsNullOrWhiteSpace(orderConsigneeCountry)
? null
: 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,
CompanyName = recipient.CompanyName,
Phone = recipient.Phone,
TelePhone = recipient.TelePhone,
Email = recipient.Email,
CountryCode = ResolveCountryIso(recipient.Country, orderConsigneeCountry, idToCode),
Province = recipient.Province,
City = recipient.City,
StreetNumber = recipient.StreetNumber,
StreetAddress1 = recipient.StreetAddress1,
StreetAddress2 = recipient.StreetAddress2,
StreetAddress3 = recipient.StreetAddress3,
ZipCode = recipient.ZipCode,
TaxType = recipient.TaxType,
TaxNo = recipient.TaxNo,
CertificateType = recipient.CertificateType,
CertificateNo = recipient.CertificateNo,
Eori = recipient.Eori,
Vat = recipient.Vat
};
}
private static OrderParcelSenderInput? MapSender(OrderSender? sender, IReadOnlyDictionary idToCode)
{
if (sender == null)
{
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,
Company = sender.Company,
Phone = sender.Phone,
TelePhone = sender.TelePhone,
Email = sender.Email,
CountryCode = ResolveCountryIso(sender.Country, null, idToCode),
Province = sender.Province,
City = sender.City,
ZipCode = sender.ZipCode,
StreetAddress1 = sender.StreetAddress1,
StreetAddress2 = sender.StreetAddress2,
StreetAddress3 = sender.StreetAddress3,
HouseNumber = sender.HouseNumber
};
}
private static OrderParcelItemInput MapItem(OrderDeclaration x, IObjectStorage? fileStorage) =>
new()
{
CnName = x.CnName,
EnName = x.EnName,
Sku = x.Sku,
Unit = x.Unit,
UnitPrice = x.UnitPrice,
UnitWeight = x.UnitWeight,
Quantity = x.Quantity,
Amount = x.Amount,
Weight = x.Weight,
ImHsCode = x.ImHsCode,
ExHsCode = x.ExHsCode ?? x.HsCode,
DeclareElement = x.DeclareElement,
// 始终赋值;空白→null。配合 OrderParcelItemInput 上 JsonIgnore(Never),请求体固定出现 "xxx": null。
ProductId = NullIfWhiteSpace(x.ProductId),
NonStdProductId = NullIfWhiteSpace(x.NonStdProductId),
StdProductId = NullIfWhiteSpace(x.StdProductId),
SkuImage = fileStorage?.GetPublicUrl(x.SkuImage) ?? x.SkuImage,
Category = x.Category,
Brand = x.Brand,
BrandType = x.BrandType,
IsMagnetic = x.IsMagnetic > 0,
Distribution = x.Distribution,
Material = x.Material,
EnMaterial = x.EnMaterial,
Purpose = x.Purpose,
Attributes = x.Attributes,
OriginCountry = x.OriginCountry,
SalesLink = x.SalesLink,
Model = x.Model,
Specifications = x.Specifications,
Comment = x.Comment
};
private static string? NullIfWhiteSpace(string? value) =>
string.IsNullOrWhiteSpace(value) ? null : value.Trim();
}