feat: 入出库扫码支持单号类型解析与多命中候选 #29

Merged
zzh merged 1 commits from test into master 2026-11-20 14:25:26 +08:00
8 changed files with 458 additions and 306 deletions

View File

@ -8,12 +8,18 @@ namespace Oms.Application.Dtos.Operations;
public class CreateInboundRecordInput public class CreateInboundRecordInput
{ {
/// <summary> /// <summary>
/// 运单号。 /// 运单号(或按 NumberType 解析的扫码原文)。
/// </summary> /// </summary>
[Required] [Required]
[StringLength(64)] [StringLength(64)]
public string WaybillNo { get; set; } = string.Empty; public string WaybillNo { get; set; } = string.Empty;
/// <summary>
/// 单号类型:auto / waybill / customerOrder / tracking / other / parcel / sku。
/// </summary>
[StringLength(32)]
public string? NumberType { get; set; }
/// <summary> /// <summary>
/// 重量。 /// 重量。
/// </summary> /// </summary>

View File

@ -8,12 +8,18 @@ namespace Oms.Application.Dtos.Operations;
public class CreateOutboundRecordInput public class CreateOutboundRecordInput
{ {
/// <summary> /// <summary>
/// 运单号。 /// 运单号(或按 NumberType 解析的扫码原文)。
/// </summary> /// </summary>
[Required] [Required]
[StringLength(64)] [StringLength(64)]
public string WaybillNo { get; set; } = string.Empty; public string WaybillNo { get; set; } = string.Empty;
/// <summary>
/// 单号类型:auto / waybill / customerOrder / tracking / other / parcel / sku。
/// </summary>
[StringLength(32)]
public string? NumberType { get; set; }
/// <summary> /// <summary>
/// 重量。 /// 重量。
/// </summary> /// </summary>

View File

@ -64,4 +64,19 @@ public class InboundOrderLookupOutput
/// 待排货/计费失败原因。 /// 待排货/计费失败原因。
/// </summary> /// </summary>
public string? AllocationPendingReason { get; set; } public string? AllocationPendingReason { get; set; }
/// <summary>
/// 是否唯一命中。
/// </summary>
public bool Matched { get; set; } = true;
/// <summary>
/// 实际命中的单号类型。
/// </summary>
public string? MatchedNumberType { get; set; }
/// <summary>
/// 多命中候选(包裹/SKU 等)。
/// </summary>
public List<PrintLabelLookupCandidateOutput> Candidates { get; set; } = [];
} }

View File

@ -74,4 +74,19 @@ public class OutboundOrderLookupOutput
/// 订单状态名称。 /// 订单状态名称。
/// </summary> /// </summary>
public string? OrderStatusName { get; set; } public string? OrderStatusName { get; set; }
/// <summary>
/// 是否唯一命中。
/// </summary>
public bool Matched { get; set; } = true;
/// <summary>
/// 实际命中的单号类型。
/// </summary>
public string? MatchedNumberType { get; set; }
/// <summary>
/// 多命中候选(包裹/SKU 等)。
/// </summary>
public List<PrintLabelLookupCandidateOutput> Candidates { get; set; } = [];
} }

View File

@ -8,7 +8,6 @@ using Oms.Application.Services.Orders;
using Oms.Application.Services.Orders.Issues; using Oms.Application.Services.Orders.Issues;
using Oms.Application.Services.WeChatNotify; using Oms.Application.Services.WeChatNotify;
using Oms.Application.Shared; using Oms.Application.Shared;
using Oms.Application.Shared.DocNumbers;
using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.OperationsAggregate.Entities; using Oms.Domain.OperationsAggregate.Entities;
using Oms.Domain.OperationsAggregate.Repositories; using Oms.Domain.OperationsAggregate.Repositories;
@ -34,59 +33,44 @@ public class InboundRecordService : ApplicationService
private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>(); private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>();
private AutoTriggerRuntimeService AutoTriggerRuntimeService => private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>(); LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>();
private IDocNumberExtractService DocNumberExtractService => private OrderScanNumberResolver OrderScanNumberResolver =>
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>(); LazyServiceProvider.GetRequiredService<OrderScanNumberResolver>();
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher => private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>(); LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
/// <summary> /// <summary>
/// 按单号查询订单(入库扫描展示销售产品、目的国,只读)。 /// 按单号查询订单(入库扫描展示销售产品、目的国,只读;支持单号类型)。
/// </summary> /// </summary>
/// <param name="waybillNo">扫码单号。</param>
/// <param name="numberType">单号类型,默认 auto。</param>
[HttpGet("/operation/inbound/order-lookup")] [HttpGet("/operation/inbound/order-lookup")]
public async Task<InboundOrderLookupOutput> LookupOrderAsync([FromQuery] string waybillNo) public async Task<InboundOrderLookupOutput> LookupOrderAsync(
[FromQuery] string waybillNo,
[FromQuery] string? numberType = null)
{ {
if (string.IsNullOrWhiteSpace(waybillNo)) var resolved = await OrderScanNumberResolver.ResolveAsync(waybillNo, numberType);
if (resolved.Candidates is { Count: > 1 })
{ {
throw new BusinessException("请扫描或输入单号"); return new InboundOrderLookupOutput
{
Matched = false,
MatchedNumberType = resolved.MatchedType,
Candidates = resolved.Candidates
};
}
var order = resolved.Order;
if (order == null && resolved.Candidates is { Count: 1 })
{
order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == resolved.Candidates[0].OrderId);
} }
var resolved = await DocNumberExtractService.ResolveScanWaybillNoAsync(waybillNo);
var order = await OrderRepository.GetByWaybillNoAsync(resolved);
if (order == null) if (order == null)
{ {
throw new BusinessException("未找到对应订单,请检查单号"); throw new BusinessException("未找到对应订单,请检查号码或类型");
} }
var output = new InboundOrderLookupOutput return await BuildLookupOutputAsync(order, resolved.MatchedType);
{
OrderId = order.Id,
ServiceNo = order.ServiceNo,
ClientNo = order.ClientNo,
TrackNo = order.TrackNo,
ProductCode = order.ProductCode,
DestinationCountry = order.ConsigneeCountry,
OrderStatus = order.OrderStatus,
OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus),
AllocationPendingReason = order.AllocationPendingReason
};
if (!string.IsNullOrWhiteSpace(order.ProductCode))
{
var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim());
if (product != null)
{
output.SalesProductId = product.Id;
output.SalesProductName = product.ProductName;
}
}
if (!string.IsNullOrWhiteSpace(order.ConsigneeCountry))
{
var country = await CountryRepository.FirstOrDefaultAsync(x => x.CountryCode == order.ConsigneeCountry);
output.DestinationCountryName = country?.ChineseName ?? country?.EnglishName ?? order.ConsigneeCountry;
}
return output;
} }
/// <summary> /// <summary>
@ -103,12 +87,8 @@ public class InboundRecordService : ApplicationService
throw new BusinessException("运单号不能为空"); throw new BusinessException("运单号不能为空");
} }
var waybillNo = await DocNumberExtractService.ResolveScanWaybillNoAsync(input.WaybillNo); var order = await OrderScanNumberResolver.RequireSingleOrderAsync(input.WaybillNo, input.NumberType);
var order = await OrderRepository.GetByWaybillNoAsync(waybillNo); var waybillNo = order.ServiceNo;
if (order == null)
{
throw new BusinessException("未找到对应订单,请检查单号");
}
ParcelBillingValidators.EnsurePositiveDimensions( ParcelBillingValidators.EnsurePositiveDimensions(
input.Length, input.Length,
@ -271,6 +251,42 @@ public class InboundRecordService : ApplicationService
output.AllocationPendingReason = order.AllocationPendingReason; output.AllocationPendingReason = order.AllocationPendingReason;
} }
private async Task<InboundOrderLookupOutput> BuildLookupOutputAsync(Order order, string? matchedType)
{
var output = new InboundOrderLookupOutput
{
Matched = true,
MatchedNumberType = matchedType,
OrderId = order.Id,
ServiceNo = order.ServiceNo,
ClientNo = order.ClientNo,
TrackNo = order.TrackNo,
ProductCode = order.ProductCode,
DestinationCountry = order.ConsigneeCountry,
OrderStatus = order.OrderStatus,
OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus),
AllocationPendingReason = order.AllocationPendingReason
};
if (!string.IsNullOrWhiteSpace(order.ProductCode))
{
var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim());
if (product != null)
{
output.SalesProductId = product.Id;
output.SalesProductName = product.ProductName;
}
}
if (!string.IsNullOrWhiteSpace(order.ConsigneeCountry))
{
var country = await CountryRepository.FirstOrDefaultAsync(x => x.CountryCode == order.ConsigneeCountry);
output.DestinationCountryName = country?.ChineseName ?? country?.EnglishName ?? order.ConsigneeCountry;
}
return output;
}
/// <summary> /// <summary>
/// 短时幂等:处理中重复扫码直接拒绝,避免双写入库记录与双投计费任务。 /// 短时幂等:处理中重复扫码直接拒绝,避免双写入库记录与双投计费任务。
/// </summary> /// </summary>

View File

@ -5,7 +5,6 @@ using Oms.Application.Dtos.Orders;
using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.Shared;
using Oms.Application.Services.Orders; using Oms.Application.Services.Orders;
using Oms.Application.Shared; using Oms.Application.Shared;
using Oms.Application.Shared.DocNumbers;
using Oms.Domain.ChannelsAggregate.Entities; using Oms.Domain.ChannelsAggregate.Entities;
using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.OperationsAggregate.Entities; using Oms.Domain.OperationsAggregate.Entities;
@ -29,14 +28,12 @@ public class LabelPrintService : ApplicationService
private ILabelTemplateRepository LabelTemplateRepository => LazyServiceProvider.GetRequiredService<ILabelTemplateRepository>(); private ILabelTemplateRepository LabelTemplateRepository => LazyServiceProvider.GetRequiredService<ILabelTemplateRepository>();
private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService<IOrderRepository>(); private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService<IOrderRepository>();
private IOrderStockBindRepository OrderStockBindRepository => LazyServiceProvider.GetRequiredService<IOrderStockBindRepository>(); private IOrderStockBindRepository OrderStockBindRepository => LazyServiceProvider.GetRequiredService<IOrderStockBindRepository>();
private ICParcelRepository ParcelRepository => LazyServiceProvider.GetRequiredService<ICParcelRepository>();
private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService<ICSkuRepository>();
private ISalesProductRepository SalesProductRepository => LazyServiceProvider.GetRequiredService<ISalesProductRepository>(); private ISalesProductRepository SalesProductRepository => LazyServiceProvider.GetRequiredService<ISalesProductRepository>();
private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService<ICountryRepository>(); private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService<ICountryRepository>();
private IWarehouseAddressRepository WarehouseAddressRepository => LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>(); private IWarehouseAddressRepository WarehouseAddressRepository => LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>(); private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>();
private IDocNumberExtractService DocNumberExtractService => private OrderScanNumberResolver OrderScanNumberResolver =>
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>(); LazyServiceProvider.GetRequiredService<OrderScanNumberResolver>();
/// <summary> /// <summary>
/// 扫码查单:运单/客户单/跟踪号/其他单号/包裹快递单号/SKU → 订单 + 绑定明细。 /// 扫码查单:运单/客户单/跟踪号/其他单号/包裹快递单号/SKU → 订单 + 绑定明细。
@ -46,46 +43,23 @@ public class LabelPrintService : ApplicationService
[FromQuery] string number, [FromQuery] string number,
[FromQuery] string? numberType = null) [FromQuery] string? numberType = null)
{ {
var raw = number?.Trim() ?? string.Empty; var resolved = await OrderScanNumberResolver.ResolveAsync(number, numberType);
if (string.IsNullOrWhiteSpace(raw)) if (resolved.Candidates is { Count: > 1 })
{
throw new BusinessException("请扫描或输入单号");
}
// 运单路径:截取兜底(前端本地引擎为主)
var type = NormalizeNumberType(numberType);
if (type is "auto" or "waybill")
{
raw = await DocNumberExtractService.ResolveScanWaybillNoAsync(raw);
}
Order? order = null;
string? matchedType = null;
List<PrintLabelLookupCandidateOutput>? candidates = null;
if (type is "auto" or "")
{
(order, matchedType, candidates) = await ResolveAutoAsync(raw);
}
else
{
(order, matchedType, candidates) = await ResolveByTypeAsync(raw, type);
}
if (candidates is { Count: > 1 })
{ {
return new PrintLabelLookupOutput return new PrintLabelLookupOutput
{ {
Matched = false, Matched = false,
MatchedNumberType = matchedType, MatchedNumberType = resolved.MatchedType,
Warnings = ["multiMatch"], Warnings = ["multiMatch"],
Candidates = candidates Candidates = resolved.Candidates
}; };
} }
if (order == null && candidates is { Count: 1 }) var order = resolved.Order;
var matchedType = resolved.MatchedType;
if (order == null && resolved.Candidates is { Count: 1 })
{ {
order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == candidates[0].OrderId); order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == resolved.Candidates[0].OrderId);
matchedType ??= "sku"; matchedType ??= "sku";
} }
@ -94,7 +68,7 @@ public class LabelPrintService : ApplicationService
throw new BusinessException("未找到对应订单,请检查号码或类型"); throw new BusinessException("未找到对应订单,请检查号码或类型");
} }
return await BuildLookupOutputAsync(order, matchedType ?? type); return await BuildLookupOutputAsync(order, matchedType ?? OrderScanNumberResolver.NormalizeNumberType(numberType));
} }
/// <summary> /// <summary>
@ -119,22 +93,8 @@ public class LabelPrintService : ApplicationService
labelTemplate = list.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id).FirstOrDefault(); labelTemplate = list.OrderByDescending(x => x.UpdateTime).ThenByDescending(x => x.Id).FirstOrDefault();
} }
var raw = input.Number?.Trim() ?? string.Empty; var order = await OrderScanNumberResolver.RequireSingleOrderAsync(input.Number, input.NumberType);
var type = NormalizeNumberType(input.NumberType); var type = OrderScanNumberResolver.NormalizeNumberType(input.NumberType);
Order? order;
if (type is "auto" or "")
{
(order, _, _) = await ResolveAutoAsync(raw);
}
else
{
(order, _, _) = await ResolveByTypeAsync(raw, type);
}
if (order == null)
{
throw new BusinessException("未找到对应订单,无法打印面单");
}
if (labelTemplate != null) if (labelTemplate != null)
{ {
@ -241,154 +201,6 @@ public class LabelPrintService : ApplicationService
return new OmsItemsResult<LabelTemplateDropdownOutput> { Items = items }; return new OmsItemsResult<LabelTemplateDropdownOutput> { Items = items };
} }
private static string NormalizeNumberType(string? numberType)
{
var value = numberType?.Trim().ToLowerInvariant() ?? "auto";
return value switch
{
"customerorderno" or "customer-order" or "client" or "clientno" => "customerorder",
"track" or "trackno" => "tracking",
"parceltracking" or "parcelno" or "express" => "parcel",
"skucode" => "sku",
"" or "all" => "auto",
_ => value
};
}
private async Task<(Order? Order, string? MatchedType, List<PrintLabelLookupCandidateOutput>? Candidates)>
ResolveAutoAsync(string number)
{
var order = await OrderRepository.GetByWaybillNoAsync(number);
if (order != null)
{
var matched =
string.Equals(order.ServiceNo, number, StringComparison.OrdinalIgnoreCase) ? "waybill"
: string.Equals(order.TrackNo, number, StringComparison.OrdinalIgnoreCase) ? "tracking"
: string.Equals(order.ClientNo, number, StringComparison.OrdinalIgnoreCase) ? "customerorder"
: "waybill";
return (order, matched, null);
}
var byParcel = await ResolveByParcelTrackingAsync(number);
if (byParcel.Order != null || byParcel.Candidates is { Count: > 0 })
{
return byParcel;
}
return await ResolveBySkuAsync(number);
}
private async Task<(Order? Order, string? MatchedType, List<PrintLabelLookupCandidateOutput>? Candidates)>
ResolveByTypeAsync(string number, string type)
{
return type switch
{
"waybill" => (await OrderRepository.GetByServiceNoAsync(number)
?? await OrderRepository.GetByWaybillNoAsync(number), "waybill", null),
"customerorder" => (
await OrderRepository.FirstOrDefaultAsync(x => x.ClientNo == number),
"customerorder",
null),
"tracking" => (
await OrderRepository.GetByTrackNoAsync(number),
"tracking",
null),
"other" => (
await OrderRepository.FirstOrDefaultAsync(x => x.RequestId == number || x.ClientNo == number)
?? await OrderRepository.GetByWaybillNoAsync(number),
"other",
null),
"parcel" => await ResolveByParcelTrackingAsync(number),
"sku" => await ResolveBySkuAsync(number),
_ => await ResolveAutoAsync(number)
};
}
private async Task<(Order? Order, string? MatchedType, List<PrintLabelLookupCandidateOutput>? Candidates)>
ResolveByParcelTrackingAsync(string trackingNo)
{
var parcels = await ParcelRepository.GetListAsync(x => x.TrackingNo == trackingNo);
if (parcels.Count == 0)
{
return (null, "parcel", null);
}
var parcelIds = parcels.Select(x => x.Id).ToArray();
var binds = await OrderStockBindRepository.GetListAsync(x =>
x.ParcelId.HasValue
&& parcelIds.Contains(x.ParcelId.Value)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var orderIds = binds.Select(x => x.OrderId).Distinct().ToArray();
if (orderIds.Length == 0)
{
throw new BusinessException("找到包裹但未绑定到任何订单,请先绑定包裹/库存");
}
if (orderIds.Length == 1)
{
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == orderIds[0]);
return (order, "parcel", null);
}
var candidates = await BuildCandidatesAsync(orderIds, "包裹快递单号命中多笔订单");
return (null, "parcel", candidates);
}
private async Task<(Order? Order, string? MatchedType, List<PrintLabelLookupCandidateOutput>? Candidates)>
ResolveBySkuAsync(string skuCode)
{
var skus = await SkuRepository.GetListAsync(x => x.SkuCode == skuCode);
if (skus.Count == 0)
{
return (null, "sku", null);
}
var skuIds = skus.Select(x => x.Id).ToArray();
var binds = await OrderStockBindRepository.GetListAsync(x =>
x.SkuId.HasValue
&& skuIds.Contains(x.SkuId.Value)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var orderIds = binds.Select(x => x.OrderId).Distinct().ToArray();
if (orderIds.Length == 0)
{
throw new BusinessException("找到 SKU 但没有绑定中的订单,请确认是否已绑定");
}
if (orderIds.Length == 1)
{
var order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == orderIds[0]);
return (order, "sku", null);
}
var candidates = await BuildCandidatesAsync(orderIds, $"SKU {skuCode} 命中多笔订单,请选择");
return (null, "sku", candidates);
}
private async Task<List<PrintLabelLookupCandidateOutput>> BuildCandidatesAsync(int[] orderIds, string hint)
{
var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id));
var binds = await OrderStockBindRepository.GetListAsync(x =>
orderIds.Contains(x.OrderId)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var qtyMap = binds.GroupBy(x => x.OrderId).ToDictionary(g => g.Key, g => g.Sum(x => x.BindQty));
return orders
.OrderByDescending(x => x.UpdateTime)
.Select(o => new PrintLabelLookupCandidateOutput
{
OrderId = o.Id,
ServiceNo = o.ServiceNo,
ClientNo = o.ClientNo,
TrackNo = o.TrackNo,
OrderStatusName = OmsDocHelper.GetOrderStatusName(o.OrderStatus),
BindQtyTotal = qtyMap.GetValueOrDefault(o.Id),
MatchedHint = hint
})
.ToList();
}
private async Task<PrintLabelLookupOutput> BuildLookupOutputAsync(Order order, string matchedType) private async Task<PrintLabelLookupOutput> BuildLookupOutputAsync(Order order, string matchedType)
{ {
var binds = await OrderStockBindRepository.GetListAsync(x => var binds = await OrderStockBindRepository.GetListAsync(x =>

View File

@ -8,7 +8,6 @@ using Oms.Application.Services.Orders;
using Oms.Application.Services.Orders.Issues; using Oms.Application.Services.Orders.Issues;
using Oms.Application.Services.WeChatNotify; using Oms.Application.Services.WeChatNotify;
using Oms.Application.Shared; using Oms.Application.Shared;
using Oms.Application.Shared.DocNumbers;
using Oms.Domain.ChannelsAggregate.Repositories; using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.OperationsAggregate.Entities; using Oms.Domain.OperationsAggregate.Entities;
using Oms.Domain.OperationsAggregate.Repositories; using Oms.Domain.OperationsAggregate.Repositories;
@ -36,71 +35,45 @@ public class OutboundRecordService : ApplicationService
private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>(); private OrderService OrderService => LazyServiceProvider.GetRequiredService<OrderService>();
private AutoTriggerRuntimeService AutoTriggerRuntimeService => private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>(); LazyServiceProvider.GetRequiredService<AutoTriggerRuntimeService>();
private IDocNumberExtractService DocNumberExtractService => private OrderScanNumberResolver OrderScanNumberResolver =>
LazyServiceProvider.GetRequiredService<IDocNumberExtractService>(); LazyServiceProvider.GetRequiredService<OrderScanNumberResolver>();
private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher => private WechatOrderNotifyDispatcher WechatOrderNotifyDispatcher =>
LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>(); LazyServiceProvider.GetRequiredService<WechatOrderNotifyDispatcher>();
/// <summary> /// <summary>
/// 按单号查询订单(出库扫描展示销售产品、目的国、服务渠道,只读)。 /// 按单号查询订单(出库扫描展示销售产品、目的国、服务渠道,只读;支持单号类型)。
/// </summary> /// </summary>
/// <param name="waybillNo">扫码单号。</param>
/// <param name="numberType">单号类型,默认 auto。</param>
[HttpGet("/operation/outbound/order-lookup")] [HttpGet("/operation/outbound/order-lookup")]
public async Task<OutboundOrderLookupOutput> LookupOrderAsync([FromQuery] string waybillNo) public async Task<OutboundOrderLookupOutput> LookupOrderAsync(
[FromQuery] string waybillNo,
[FromQuery] string? numberType = null)
{ {
if (string.IsNullOrWhiteSpace(waybillNo)) var resolved = await OrderScanNumberResolver.ResolveAsync(waybillNo, numberType);
if (resolved.Candidates is { Count: > 1 })
{ {
throw new BusinessException("请扫描或输入单号"); return new OutboundOrderLookupOutput
{
Matched = false,
MatchedNumberType = resolved.MatchedType,
Candidates = resolved.Candidates
};
}
var order = resolved.Order;
if (order == null && resolved.Candidates is { Count: 1 })
{
order = await OrderRepository.FirstOrDefaultAsync(x => x.Id == resolved.Candidates[0].OrderId);
} }
var resolved = await DocNumberExtractService.ResolveScanWaybillNoAsync(waybillNo);
var order = await OrderRepository.GetByWaybillNoAsync(resolved);
if (order == null) if (order == null)
{ {
throw new BusinessException("未找到对应订单,请检查单号"); throw new BusinessException("未找到对应订单,请检查号码或类型");
} }
EnsureOutboundAllowed(order); EnsureOutboundAllowed(order);
return await BuildLookupOutputAsync(order, resolved.MatchedType);
var output = new OutboundOrderLookupOutput
{
OrderId = order.Id,
ServiceNo = order.ServiceNo,
ClientNo = order.ClientNo,
TrackNo = order.TrackNo,
ProductCode = order.ProductCode,
DestinationCountry = order.ConsigneeCountry,
OrderStatus = order.OrderStatus,
OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus)
};
if (!string.IsNullOrWhiteSpace(order.ProductCode))
{
var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim());
if (product != null)
{
output.SalesProductId = product.Id;
output.SalesProductName = product.ProductName;
}
}
if (!string.IsNullOrWhiteSpace(order.ConsigneeCountry))
{
var country = await CountryRepository.FirstOrDefaultAsync(x => x.CountryCode == order.ConsigneeCountry);
output.DestinationCountryName = country?.ChineseName ?? country?.EnglishName ?? order.ConsigneeCountry;
}
if (!string.IsNullOrWhiteSpace(order.ChannelCode))
{
var channel = await ServiceChannelRepository.GetByChannelCodeAsync(order.ChannelCode.Trim());
if (channel != null)
{
output.ServiceChannelId = channel.Id;
output.ChannelCode = channel.ChannelCode;
output.ServiceChannelName = await BuildServiceChannelDisplayNameAsync(channel.GroupId, channel.ChannelName);
}
}
return output;
} }
/// <summary> /// <summary>
@ -123,13 +96,9 @@ public class OutboundRecordService : ApplicationService
throw new BusinessException("发货实重与长宽高不能为空且须大于 0"); throw new BusinessException("发货实重与长宽高不能为空且须大于 0");
} }
var waybillNo = await DocNumberExtractService.ResolveScanWaybillNoAsync(input.WaybillNo); var order = await OrderScanNumberResolver.RequireSingleOrderAsync(input.WaybillNo, input.NumberType);
var waybillNo = order.ServiceNo;
input.WaybillNo = waybillNo; input.WaybillNo = waybillNo;
var order = await OrderRepository.GetByWaybillNoAsync(waybillNo);
if (order == null)
{
throw new BusinessException("未找到对应订单,请检查单号");
}
EnsureOutboundAllowed(order); EnsureOutboundAllowed(order);
@ -272,6 +241,52 @@ public class OutboundRecordService : ApplicationService
} }
} }
private async Task<OutboundOrderLookupOutput> BuildLookupOutputAsync(Order order, string? matchedType)
{
var output = new OutboundOrderLookupOutput
{
Matched = true,
MatchedNumberType = matchedType,
OrderId = order.Id,
ServiceNo = order.ServiceNo,
ClientNo = order.ClientNo,
TrackNo = order.TrackNo,
ProductCode = order.ProductCode,
DestinationCountry = order.ConsigneeCountry,
OrderStatus = order.OrderStatus,
OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus)
};
if (!string.IsNullOrWhiteSpace(order.ProductCode))
{
var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim());
if (product != null)
{
output.SalesProductId = product.Id;
output.SalesProductName = product.ProductName;
}
}
if (!string.IsNullOrWhiteSpace(order.ConsigneeCountry))
{
var country = await CountryRepository.FirstOrDefaultAsync(x => x.CountryCode == order.ConsigneeCountry);
output.DestinationCountryName = country?.ChineseName ?? country?.EnglishName ?? order.ConsigneeCountry;
}
if (!string.IsNullOrWhiteSpace(order.ChannelCode))
{
var channel = await ServiceChannelRepository.GetByChannelCodeAsync(order.ChannelCode.Trim());
if (channel != null)
{
output.ServiceChannelId = channel.Id;
output.ChannelCode = channel.ChannelCode;
output.ServiceChannelName = await BuildServiceChannelDisplayNameAsync(channel.GroupId, channel.ChannelName);
}
}
return output;
}
private async Task<string> BuildServiceChannelDisplayNameAsync(int? groupId, string channelName) private async Task<string> BuildServiceChannelDisplayNameAsync(int? groupId, string channelName)
{ {
string? groupName = null; string? groupName = null;

View File

@ -0,0 +1,267 @@
using Fake.Application;
using Fake.DependencyInjection;
using Oms.Application.Dtos.Operations;
using Oms.Application.Shared.DocNumbers;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.OrdersAggregate.Repositories;
using Oms.Domain.WarehouseAggregate.Repositories;
namespace Oms.Application.Shared;
/// <summary>
/// 仓作业扫码:按单号类型解析订单(智能识别 / 运单 / 客户单 / 跟踪号 / 包裹 / SKU 等)。
/// </summary>
public class OrderScanNumberResolver : IScopedDependency
{
private readonly IOrderRepository _orderRepository;
private readonly IOrderStockBindRepository _orderStockBindRepository;
private readonly ICParcelRepository _parcelRepository;
private readonly ICSkuRepository _skuRepository;
private readonly IDocNumberExtractService _docNumberExtractService;
public OrderScanNumberResolver(
IOrderRepository orderRepository,
IOrderStockBindRepository orderStockBindRepository,
ICParcelRepository parcelRepository,
ICSkuRepository skuRepository,
IDocNumberExtractService docNumberExtractService)
{
_orderRepository = orderRepository;
_orderStockBindRepository = orderStockBindRepository;
_parcelRepository = parcelRepository;
_skuRepository = skuRepository;
_docNumberExtractService = docNumberExtractService;
}
/// <summary>
/// 规范化单号类型。
/// </summary>
public static string NormalizeNumberType(string? numberType)
{
var value = numberType?.Trim().ToLowerInvariant() ?? "auto";
return value switch
{
"customerorderno" or "customer-order" or "client" or "clientno" or "customerorder" => "customerorder",
"track" or "trackno" => "tracking",
"parceltracking" or "parcelno" or "express" => "parcel",
"skucode" => "sku",
"" or "all" => "auto",
_ => value
};
}
/// <summary>
/// 按类型解析扫码单号为订单;多命中时返回候选列表。
/// </summary>
/// <param name="number">扫码原文。</param>
/// <param name="numberType">单号类型,默认 auto。</param>
/// <param name="applyWaybillExtract">auto/waybill 时是否做运单截取。</param>
public async Task<OrderScanResolveResult> ResolveAsync(
string? number,
string? numberType = null,
bool applyWaybillExtract = true)
{
var raw = number?.Trim() ?? string.Empty;
if (string.IsNullOrWhiteSpace(raw))
{
throw new BusinessException("请扫描或输入单号");
}
var type = NormalizeNumberType(numberType);
if (applyWaybillExtract && type is "auto" or "waybill")
{
raw = await _docNumberExtractService.ResolveScanWaybillNoAsync(raw);
}
if (type is "auto" or "")
{
return await ResolveAutoAsync(raw);
}
return await ResolveByTypeAsync(raw, type);
}
/// <summary>
/// 解析到唯一订单;多命中或未找到时抛业务异常。
/// </summary>
public async Task<Order> RequireSingleOrderAsync(
string? number,
string? numberType = null,
bool applyWaybillExtract = true)
{
var result = await ResolveAsync(number, numberType, applyWaybillExtract);
if (result.Candidates is { Count: > 1 })
{
throw new BusinessException("命中多笔订单,请改选手动单号类型或到面单打印页选择订单");
}
var order = result.Order;
if (order == null && result.Candidates is { Count: 1 })
{
order = await _orderRepository.FirstOrDefaultAsync(x => x.Id == result.Candidates[0].OrderId);
}
if (order == null)
{
throw new BusinessException("未找到对应订单,请检查号码或类型");
}
return order;
}
private async Task<OrderScanResolveResult> ResolveAutoAsync(string number)
{
var order = await _orderRepository.GetByWaybillNoAsync(number);
if (order != null)
{
var matched =
string.Equals(order.ServiceNo, number, StringComparison.OrdinalIgnoreCase) ? "waybill"
: string.Equals(order.TrackNo, number, StringComparison.OrdinalIgnoreCase) ? "tracking"
: string.Equals(order.ClientNo, number, StringComparison.OrdinalIgnoreCase) ? "customerorder"
: "waybill";
return new OrderScanResolveResult(order, matched, null);
}
var byParcel = await ResolveByParcelTrackingAsync(number);
if (byParcel.Order != null || byParcel.Candidates is { Count: > 0 })
{
return byParcel;
}
return await ResolveBySkuAsync(number);
}
private async Task<OrderScanResolveResult> ResolveByTypeAsync(string number, string type)
{
return type switch
{
"waybill" => new OrderScanResolveResult(
await _orderRepository.GetByServiceNoAsync(number)
?? await _orderRepository.GetByWaybillNoAsync(number),
"waybill",
null),
"customerorder" => new OrderScanResolveResult(
await _orderRepository.FirstOrDefaultAsync(x => x.ClientNo == number),
"customerorder",
null),
"tracking" => new OrderScanResolveResult(
await _orderRepository.GetByTrackNoAsync(number),
"tracking",
null),
"other" => new OrderScanResolveResult(
await _orderRepository.FirstOrDefaultAsync(x => x.RequestId == number || x.ClientNo == number)
?? await _orderRepository.GetByWaybillNoAsync(number),
"other",
null),
"parcel" => await ResolveByParcelTrackingAsync(number),
"sku" => await ResolveBySkuAsync(number),
_ => await ResolveAutoAsync(number)
};
}
private async Task<OrderScanResolveResult> ResolveByParcelTrackingAsync(string trackingNo)
{
var parcels = await _parcelRepository.GetListAsync(x => x.TrackingNo == trackingNo);
if (parcels.Count == 0)
{
return new OrderScanResolveResult(null, "parcel", null);
}
var parcelIds = parcels.Select(x => x.Id).ToArray();
var binds = await _orderStockBindRepository.GetListAsync(x =>
x.ParcelId.HasValue
&& parcelIds.Contains(x.ParcelId.Value)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var orderIds = binds.Select(x => x.OrderId).Distinct().ToArray();
if (orderIds.Length == 0)
{
throw new BusinessException("找到包裹但未绑定到任何订单,请先绑定包裹/库存");
}
if (orderIds.Length == 1)
{
var order = await _orderRepository.FirstOrDefaultAsync(x => x.Id == orderIds[0]);
return new OrderScanResolveResult(order, "parcel", null);
}
var candidates = await BuildCandidatesAsync(orderIds, "包裹快递单号命中多笔订单");
return new OrderScanResolveResult(null, "parcel", candidates);
}
private async Task<OrderScanResolveResult> ResolveBySkuAsync(string skuCode)
{
var skus = await _skuRepository.GetListAsync(x => x.SkuCode == skuCode);
if (skus.Count == 0)
{
return new OrderScanResolveResult(null, "sku", null);
}
var skuIds = skus.Select(x => x.Id).ToArray();
var binds = await _orderStockBindRepository.GetListAsync(x =>
x.SkuId.HasValue
&& skuIds.Contains(x.SkuId.Value)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var orderIds = binds.Select(x => x.OrderId).Distinct().ToArray();
if (orderIds.Length == 0)
{
throw new BusinessException("找到 SKU 但没有绑定中的订单,请确认是否已绑定");
}
if (orderIds.Length == 1)
{
var order = await _orderRepository.FirstOrDefaultAsync(x => x.Id == orderIds[0]);
return new OrderScanResolveResult(order, "sku", null);
}
var candidates = await BuildCandidatesAsync(orderIds, $"SKU {skuCode} 命中多笔订单,请选择");
return new OrderScanResolveResult(null, "sku", candidates);
}
private async Task<List<PrintLabelLookupCandidateOutput>> BuildCandidatesAsync(int[] orderIds, string hint)
{
var orders = await _orderRepository.GetListAsync(x => orderIds.Contains(x.Id));
var binds = await _orderStockBindRepository.GetListAsync(x =>
orderIds.Contains(x.OrderId)
&& (x.Status == OrderStockBindStatusCodes.Bound || x.Status == OrderStockBindStatusCodes.Deducted));
var qtyMap = binds.GroupBy(x => x.OrderId).ToDictionary(g => g.Key, g => g.Sum(x => x.BindQty));
return orders
.OrderByDescending(x => x.UpdateTime)
.Select(o => new PrintLabelLookupCandidateOutput
{
OrderId = o.Id,
ServiceNo = o.ServiceNo,
ClientNo = o.ClientNo,
TrackNo = o.TrackNo,
OrderStatusName = OmsDocHelper.GetOrderStatusName(o.OrderStatus),
BindQtyTotal = qtyMap.GetValueOrDefault(o.Id),
MatchedHint = hint
})
.ToList();
}
}
/// <summary>
/// 扫码单号解析结果。
/// </summary>
public sealed class OrderScanResolveResult
{
public OrderScanResolveResult(
Order? order,
string? matchedType,
List<PrintLabelLookupCandidateOutput>? candidates)
{
Order = order;
MatchedType = matchedType;
Candidates = candidates;
}
public Order? Order { get; }
public string? MatchedType { get; }
public List<PrintLabelLookupCandidateOutput>? Candidates { get; }
}