using System.Data;
using Fake.Application;
using Fake.UnitOfWork;
using Microsoft.AspNetCore.Mvc;
using Oms.Application.Dtos.Operations;
using Oms.Application.Dtos.Shared;
using Oms.Application.Services.Orders;
using Oms.Application.Services.Orders.Issues;
using Oms.Application.Shared;
using Oms.Application.Shared.DocNumbers;
using Oms.Domain.ChannelsAggregate.Repositories;
using Oms.Domain.OperationsAggregate.Entities;
using Oms.Domain.OperationsAggregate.Repositories;
using Oms.Domain.OrdersAggregate.Consts;
using Oms.Domain.OrdersAggregate.Entities;
using Oms.Domain.OrdersAggregate.Repositories;
using Oms.Domain.SystemAggregate.Repositories;
namespace Oms.Application.Services.Operations;
///
/// 入库记录 API 服务。
///
[ApiExplorerSettings(GroupName = "OMS-Operation")]
public class InboundRecordService : ApplicationService
{
private IInboundRecordRepository InboundRecordRepository => LazyServiceProvider.GetRequiredService();
private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService();
private ISalesProductRepository SalesProductRepository => LazyServiceProvider.GetRequiredService();
private IWarehouseAddressRepository WarehouseAddressRepository => LazyServiceProvider.GetRequiredService();
private ICountryRepository CountryRepository => LazyServiceProvider.GetRequiredService();
private OrderService OrderService => LazyServiceProvider.GetRequiredService();
private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
LazyServiceProvider.GetRequiredService();
private IDocNumberExtractService DocNumberExtractService =>
LazyServiceProvider.GetRequiredService();
///
/// 按单号查询订单(入库扫描展示销售产品、目的国,只读)。
///
[HttpGet("/operation/inbound/order-lookup")]
public async Task LookupOrderAsync([FromQuery] string waybillNo)
{
if (string.IsNullOrWhiteSpace(waybillNo))
{
throw new BusinessException("请扫描或输入单号");
}
var resolved = await DocNumberExtractService.ResolveScanWaybillNoAsync(waybillNo);
var order = await OrderRepository.GetByWaybillNoAsync(resolved);
if (order == null)
{
throw new BusinessException("未找到对应订单,请检查单号");
}
var output = new InboundOrderLookupOutput
{
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;
}
///
/// 新增入库记录(入库扫描页「入库」按钮;仓配开放接口 POST /openapi/warehouse/inbound 同源)。
///
/// 入参:入库记录创建参数。
/// 入库记录结果。
[HttpPost("/operation/inbound/create")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task CreateAsync(CreateInboundRecordInput input)
{
if (string.IsNullOrWhiteSpace(input.WaybillNo))
{
throw new BusinessException("运单号不能为空");
}
var waybillNo = await DocNumberExtractService.ResolveScanWaybillNoAsync(input.WaybillNo);
var order = await OrderRepository.GetByWaybillNoAsync(waybillNo);
if (order == null)
{
throw new BusinessException("未找到对应订单,请检查单号");
}
ParcelBillingValidators.EnsurePositiveDimensions(
input.Length,
input.Width,
input.Height,
input.Weight,
"收货");
ParcelBillingValidators.EnsureInboundOrderStatus(order.OrderStatus);
await EnsureInboundNotInFlightAsync(order, waybillNo);
int? salesProductId = null;
string? destinationCountry = order.ConsigneeCountry;
if (!string.IsNullOrWhiteSpace(order.ProductCode))
{
var product = await SalesProductRepository.GetByProductCodeAsync(order.ProductCode.Trim());
salesProductId = product?.Id;
}
var now = DateTime.Now;
var operatorId = CurrentUser.GetId();
var entity = new InboundRecord
{
WaybillNo = waybillNo,
Weight = input.Weight,
Length = input.Length,
Width = input.Width,
Height = input.Height,
SalesProductId = salesProductId,
DestinationCountry = destinationCountry,
WarehouseId = input.WarehouseId ?? order.WarehouseId,
OperateTime = now,
OperatorId = operatorId
};
await OrderService.ApplyReceiveBillingByWaybillAsync(
waybillNo,
input.Length,
input.Width,
input.Height,
input.Weight);
var savedEntity = await InboundRecordRepository.InsertAsync(entity);
// 自动触发走 Outbox,避免拉长扫码 RT
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Inbound, operatorId);
var refreshed = await OrderRepository.GetByWaybillNoAsync(waybillNo);
var output = ObjectMapper.Map(savedEntity);
ApplyOrderStatusToInboundOutput(output, refreshed);
return output;
}
///
/// 查询最近入库记录列表。
///
/// 入参:返回记录条数上限。
/// 入参:warehouseId。
/// 入库记录列表结果。
[HttpGet("/operation/inbound/recent-list")]
public async Task> GetRecentListAsync([FromQuery] int limit = 20, [FromQuery] int? warehouseId = null)
{
var hasWarehouseFilter = warehouseId.HasValue;
var warehouseIdValue = warehouseId.GetValueOrDefault();
var entities = await InboundRecordRepository.GetPagedListAsync(
x => !hasWarehouseFilter || x.WarehouseId == warehouseIdValue,
1,
limit <= 0 ? 20 : limit,
new Dictionary { [nameof(InboundRecord.OperateTime)] = false, [nameof(InboundRecord.Id)] = false });
var salesProductIds = entities.Where(x => x.SalesProductId.HasValue).Select(x => x.SalesProductId!.Value).Distinct().ToArray();
var warehouseIds = entities.Where(x => x.WarehouseId.HasValue).Select(x => x.WarehouseId!.Value).Distinct().ToArray();
var products = salesProductIds.Length == 0
? []
: await SalesProductRepository.GetListAsync(x => salesProductIds.Contains(x.Id));
var warehouses = warehouseIds.Length == 0
? []
: await WarehouseAddressRepository.GetListAsync(x => warehouseIds.Contains(x.Id));
var productMap = products.ToDictionary(x => x.Id);
var warehouseMap = warehouses.ToDictionary(x => x.Id);
var waybillNos = entities
.Select(x => x.WaybillNo?.Trim())
.Where(x => !string.IsNullOrWhiteSpace(x))
.Distinct(StringComparer.OrdinalIgnoreCase)
.Cast()
.ToArray();
var orderMap = await BuildOrderMapByWaybillNosAsync(waybillNos);
var items = entities.Select(entity =>
{
var output = ObjectMapper.Map(entity);
output.SalesProductName = entity.SalesProductId.HasValue && productMap.TryGetValue(entity.SalesProductId.Value, out var product)
? product.ProductName
: null;
output.WarehouseName = entity.WarehouseId.HasValue && warehouseMap.TryGetValue(entity.WarehouseId.Value, out var warehouse)
? warehouse.WarehouseName
: null;
output.OperatorName = entity.OperatorId?.ToString();
var key = entity.WaybillNo?.Trim() ?? string.Empty;
if (orderMap.TryGetValue(key, out var order))
{
ApplyOrderStatusToInboundOutput(output, order);
}
return output;
}).ToList();
return new OmsItemsResult { Items = items };
}
private async Task> BuildOrderMapByWaybillNosAsync(string[] waybillNos)
{
var map = new Dictionary(StringComparer.OrdinalIgnoreCase);
if (waybillNos.Length == 0)
{
return map;
}
var orders = await OrderRepository.GetListAsync(x =>
waybillNos.Contains(x.ServiceNo)
|| (x.TrackNo != null && waybillNos.Contains(x.TrackNo))
|| (x.DownstreamServiceNo != null && waybillNos.Contains(x.DownstreamServiceNo))
|| (x.ClientNo != null && waybillNos.Contains(x.ClientNo)));
foreach (var order in orders)
{
void Put(string? key)
{
if (string.IsNullOrWhiteSpace(key))
{
return;
}
map[key.Trim()] = order;
}
Put(order.ServiceNo);
Put(order.TrackNo);
Put(order.DownstreamServiceNo);
Put(order.ClientNo);
}
return map;
}
private static void ApplyOrderStatusToInboundOutput(InboundRecordOutput output, Order? order)
{
if (order == null)
{
return;
}
output.OrderId = order.Id;
output.OrderStatus = order.OrderStatus;
output.OrderStatusName = OmsDocHelper.GetOrderStatusName(order.OrderStatus);
output.AllocationPendingReason = order.AllocationPendingReason;
}
///
/// 短时幂等:处理中重复扫码直接拒绝,避免双写入库记录与双投计费任务。
///
private async Task EnsureInboundNotInFlightAsync(Order order, string waybillNo)
{
const int windowSeconds = 15;
var now = DateTime.Now;
if (string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase)
&& string.Equals(order.AllocationPendingReason?.Trim(), "入库后计费/排货处理中", StringComparison.Ordinal)
&& order.ReceiveTime.HasValue
&& (now - order.ReceiveTime.Value).TotalSeconds < windowSeconds)
{
throw new BusinessException("订单入库处理中,请勿重复扫描");
}
var latest = await InboundRecordRepository.GetLatestByWaybillNoAsync(waybillNo);
if (latest != null
&& (now - latest.OperateTime).TotalSeconds < windowSeconds
&& string.Equals(order.OrderStatus, OrderStatusCodes.PendingAllocation, StringComparison.OrdinalIgnoreCase))
{
throw new BusinessException("订单入库处理中,请勿重复扫描");
}
}
}