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.Domain.OperationsAggregate.Consts;
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 OutboundRecord = Oms.Domain.OperationsAggregate.Entities.OutboundRecord;
namespace Oms.Application.Services.Operations;
///
/// 大包装袋与管理。小包可不入袋;入袋仅待发货。
///
[ApiExplorerSettings(GroupName = "OMS-Operation")]
public class ShipBagService : ApplicationService
{
private IShipBagRepository BagRepository => LazyServiceProvider.GetRequiredService();
private IShipBagItemRepository BagItemRepository => LazyServiceProvider.GetRequiredService();
private IOrderRepository OrderRepository => LazyServiceProvider.GetRequiredService();
private OrderService OrderService => LazyServiceProvider.GetRequiredService();
private AutoTriggerRuntimeService AutoTriggerRuntimeService =>
LazyServiceProvider.GetRequiredService();
private IOutboundRecordRepository OutboundRecordRepository =>
LazyServiceProvider.GetRequiredService();
///
/// 创建空大包(装袋中)。
///
[HttpPost("/operation/bag/create")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task CreateAsync(CreateShipBagInput input)
{
var bagType = string.IsNullOrWhiteSpace(input.BagType)
? ShipBagTypeCodes.Sack
: input.BagType.Trim().ToLowerInvariant();
if (bagType is not (ShipBagTypeCodes.Sack or ShipBagTypeCodes.Box))
{
throw new BusinessException("袋型仅支持 sack(麻袋)或 box(箱子)");
}
var entity = new ShipBag
{
BagNo = await NextBagNoAsync(),
BagType = bagType,
Status = ShipBagStatusCodes.Open,
WarehouseId = input.WarehouseId,
DestinationCountry = string.IsNullOrWhiteSpace(input.DestinationCountry)
? null
: input.DestinationCountry.Trim().ToUpperInvariant(),
ChannelCode = string.IsNullOrWhiteSpace(input.ChannelCode) ? null : input.ChannelCode.Trim(),
Remark = input.Remark?.Trim(),
ParcelCount = 0,
};
var saved = await BagRepository.InsertAsync(entity);
return MapBag(saved);
}
///
/// 扫小包入袋(仅待发货;可不使用大包出库路径)。
///
[HttpPost("/operation/bag/add-parcel")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task AddParcelAsync(ShipBagParcelInput input)
{
var bag = await RequireOpenBagAsync(input.BagNo);
var order = await RequireOrderByWaybillAsync(input.WaybillNo);
if (order.OrderStatus != OrderStatusCodes.PendingShip)
{
throw new BusinessException(
$"运单 {order.ServiceNo} 状态为「{OmsDocHelper.GetOrderStatusName(order.OrderStatus)}」,仅待发货可入袋");
}
if (order.IsPaid == 0)
{
throw new BusinessException($"运单 {order.ServiceNo} 未付款,禁止入袋");
}
var existing = await BagItemRepository.FindActiveByOrderIdAsync(order.Id);
if (existing != null)
{
if (existing.BagId == bag.Id)
{
throw new BusinessException("该运单已在本袋中");
}
throw new BusinessException($"该运单已在其它大包中(明细Id={existing.BagId})");
}
if (!string.IsNullOrWhiteSpace(bag.DestinationCountry)
&& !string.IsNullOrWhiteSpace(order.ConsigneeCountry)
&& !string.Equals(bag.DestinationCountry, order.ConsigneeCountry, StringComparison.OrdinalIgnoreCase))
{
throw new BusinessException(
$"目的国不一致:袋={bag.DestinationCountry},运单={order.ConsigneeCountry}");
}
await BagItemRepository.InsertAsync(
new ShipBagItem
{
BagId = bag.Id,
OrderId = order.Id,
WaybillNo = order.ServiceNo,
});
order.ShipBagId = bag.Id;
order.ShipBagNo = bag.BagNo;
await OrderRepository.UpdateAsync(order);
bag.ParcelCount = (await BagItemRepository.ListByBagIdAsync(bag.Id)).Count;
if (string.IsNullOrWhiteSpace(bag.DestinationCountry) && !string.IsNullOrWhiteSpace(order.ConsigneeCountry))
{
bag.DestinationCountry = order.ConsigneeCountry;
}
await BagRepository.UpdateAsync(bag);
return await GetDetailAsync(bag.BagNo);
}
///
/// 从袋中移除小包(仅装袋中)。
///
[HttpPost("/operation/bag/remove-parcel")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task RemoveParcelAsync(ShipBagParcelInput input)
{
var bag = await RequireOpenBagAsync(input.BagNo);
var order = await RequireOrderByWaybillAsync(input.WaybillNo);
var item = (await BagItemRepository.ListByBagIdAsync(bag.Id))
.FirstOrDefault(x => x.OrderId == order.Id);
if (item == null)
{
throw new BusinessException("袋内无此运单");
}
await BagItemRepository.DeleteAsync(item);
if (order.ShipBagId == bag.Id)
{
order.ShipBagId = null;
order.ShipBagNo = null;
await OrderRepository.UpdateAsync(order);
}
bag.ParcelCount = (await BagItemRepository.ListByBagIdAsync(bag.Id)).Count;
await BagRepository.UpdateAsync(bag);
return await GetDetailAsync(bag.BagNo);
}
///
/// 封袋。
///
[HttpPost("/operation/bag/seal")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task SealAsync(ShipBagNoInput input)
{
var bag = await RequireBagAsync(input.BagNo);
if (bag.Status != ShipBagStatusCodes.Open)
{
throw new BusinessException("仅装袋中的大包可封袋");
}
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
if (items.Count == 0)
{
throw new BusinessException("空袋不能封袋");
}
bag.Status = ShipBagStatusCodes.Sealed;
bag.SealTime = DateTime.Now;
bag.ParcelCount = items.Count;
await BagRepository.UpdateAsync(bag);
return await GetDetailAsync(bag.BagNo);
}
///
/// 作废空袋或装袋中大包(有货须先移出)。
///
[HttpPost("/operation/bag/void")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task VoidAsync(ShipBagNoInput input)
{
var bag = await RequireBagAsync(input.BagNo);
if (bag.Status is ShipBagStatusCodes.Shipped or ShipBagStatusCodes.Voided)
{
throw new BusinessException("已出库或已作废的大包不能再作废");
}
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
if (items.Count > 0)
{
throw new BusinessException("请先移出袋内运单再作废");
}
bag.Status = ShipBagStatusCodes.Voided;
await BagRepository.UpdateAsync(bag);
return MapBag(bag);
}
///
/// 大包详情(含明细)。
///
[HttpGet("/operation/bag/get")]
public async Task GetAsync([FromQuery] string bagNo) => await GetDetailAsync(bagNo);
///
/// 大包分页列表。
///
[HttpPost("/operation/bag/page")]
public async Task> PageAsync([FromBody] ShipBagPageInput input)
{
var pageIndex = PagingHelper.NormalizePageIndex(input.PageIndex);
var pageSize = PagingHelper.NormalizePageSize(input.PageSize);
var keyword = input.Keyword?.Trim();
var status = input.Status?.Trim();
var hasWh = input.WarehouseId.HasValue;
var wh = input.WarehouseId.GetValueOrDefault();
var list = await BagRepository.GetListAsync(x =>
(string.IsNullOrEmpty(status) || x.Status == status)
&& (!hasWh || x.WarehouseId == wh)
&& (string.IsNullOrEmpty(keyword)
|| x.BagNo.Contains(keyword)
|| (x.ChannelCode != null && x.ChannelCode.Contains(keyword))
|| (x.DestinationCountry != null && x.DestinationCountry.Contains(keyword))));
var ordered = list.OrderByDescending(x => x.Id).ToList();
var total = ordered.Count;
var page = ordered.Skip((pageIndex - 1) * pageSize).Take(pageSize).Select(MapBag).ToList();
return new OmsPageResult { Items = page, Total = total };
}
///
/// 按大包出库:袋须已封;袋内待发货小包全部出库(用入库/预报件重尺),整袋成功或整袋失败。
///
[HttpPost("/operation/outbound/bag-create")]
[UnitOfWork(IsTransactional = true, IsolationLevel = IsolationLevel.ReadCommitted)]
public async Task OutboundByBagAsync(CreateBagOutboundInput input)
{
var bag = await RequireBagAsync(input.BagNo);
if (bag.Status != ShipBagStatusCodes.Sealed)
{
throw new BusinessException("仅已封袋的大包可出库");
}
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
if (items.Count == 0)
{
throw new BusinessException("袋内无运单");
}
var orderIds = items.Select(x => x.OrderId).Distinct().ToArray();
var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id));
var orderMap = orders.ToDictionary(x => x.Id);
var weights = await OrderRepository.GetWeightsByOrderIdsAsync(orderIds);
var weightGroups = weights.GroupBy(x => x.OrderId).ToDictionary(g => g.Key, g => g.ToList());
foreach (var item in items)
{
if (!orderMap.TryGetValue(item.OrderId, out var order))
{
throw new BusinessException($"袋内运单缺失订单 Id={item.OrderId}");
}
if (order.OrderStatus != OrderStatusCodes.PendingShip || order.IsPaid == 0)
{
throw new BusinessException(
$"运单 {order.ServiceNo} 不可出库(状态={OmsDocHelper.GetOrderStatusName(order.OrderStatus)})");
}
if (!weightGroups.TryGetValue(order.Id, out var rows)
|| !TryResolveOutboundDims(rows, out var length, out var width, out var height, out var weight))
{
throw new BusinessException($"运单 {order.ServiceNo} 缺少可用件重尺,无法大包出库");
}
var now = DateTime.Now;
var operatorId = CurrentUser.GetId();
await OrderService.ApplyShipBillingByWaybillAsync(order.ServiceNo, length, width, height, weight);
await OutboundRecordRepository.InsertAsync(
new OutboundRecord
{
WaybillNo = order.ServiceNo,
Weight = weight,
Length = length,
Width = width,
Height = height,
DestinationCountry = order.ConsigneeCountry,
WarehouseId = input.WarehouseId ?? bag.WarehouseId ?? order.WarehouseId,
OperateTime = now,
OperatorId = operatorId,
});
await AutoTriggerRuntimeService.EnqueueFireAsync(order.Id, AutoTriggerTiming.Outbound, operatorId);
}
bag.Status = ShipBagStatusCodes.Shipped;
bag.ShipTime = DateTime.Now;
await BagRepository.UpdateAsync(bag);
return new BagOutboundResultOutput
{
BagNo = bag.BagNo,
SuccessCount = items.Count,
WaybillNos = items.Select(x => x.WaybillNo).ToList(),
};
}
private static bool TryResolveOutboundDims(
List rows,
out decimal length,
out decimal width,
out decimal height,
out decimal weight)
{
length = width = height = weight = 0;
var receive = rows.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Receive);
var forecast = rows.FirstOrDefault(x => x.Type == OrderWeightTypeCodes.Forecast);
var src = receive ?? forecast;
if (src == null)
{
return false;
}
if (src.Length is not > 0 || src.Width is not > 0 || src.Height is not > 0 || src.ActualWeight is not > 0)
{
return false;
}
length = src.Length.Value;
width = src.Width.Value;
height = src.Height.Value;
weight = src.ActualWeight.Value;
return true;
}
private async Task GetDetailAsync(string bagNo)
{
var bag = await RequireBagAsync(bagNo);
var output = MapBag(bag);
var items = await BagItemRepository.ListByBagIdAsync(bag.Id);
if (items.Count == 0)
{
output.Items = [];
return output;
}
var orderIds = items.Select(x => x.OrderId).Distinct().ToArray();
var orders = await OrderRepository.GetListAsync(x => orderIds.Contains(x.Id));
var orderMap = orders.ToDictionary(x => x.Id);
output.Items = items
.Select(i =>
{
orderMap.TryGetValue(i.OrderId, out var order);
return new ShipBagItemOutput
{
Id = i.Id,
OrderId = i.OrderId,
WaybillNo = i.WaybillNo,
OrderStatus = order?.OrderStatus,
OrderStatusName = order == null ? null : OmsDocHelper.GetOrderStatusName(order.OrderStatus),
ConsigneeCountry = order?.ConsigneeCountry,
};
})
.ToList();
return output;
}
private async Task RequireBagAsync(string bagNo)
{
if (string.IsNullOrWhiteSpace(bagNo))
{
throw new BusinessException("请输入大包号");
}
var bag = await BagRepository.GetByBagNoAsync(bagNo.Trim());
if (bag == null)
{
throw new BusinessException("未找到大包");
}
return bag;
}
private async Task RequireOpenBagAsync(string bagNo)
{
var bag = await RequireBagAsync(bagNo);
if (bag.Status != ShipBagStatusCodes.Open)
{
throw new BusinessException("仅装袋中的大包可继续装/拆");
}
return bag;
}
private async Task RequireOrderByWaybillAsync(string waybillNo)
{
if (string.IsNullOrWhiteSpace(waybillNo))
{
throw new BusinessException("请扫描运单号");
}
var order = await OrderRepository.GetByWaybillNoAsync(waybillNo.Trim());
if (order == null)
{
throw new BusinessException("未找到对应订单");
}
return order;
}
private async Task NextBagNoAsync()
{
for (var i = 0; i < 8; i++)
{
var no = $"BAG{DateTime.Now:yyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
if (await BagRepository.GetByBagNoAsync(no) == null)
{
return no;
}
}
throw new BusinessException("生成大包号失败,请重试");
}
private static ShipBagOutput MapBag(ShipBag bag) =>
new()
{
Id = bag.Id,
BagNo = bag.BagNo,
BagType = bag.BagType,
Status = bag.Status,
StatusName = bag.Status switch
{
ShipBagStatusCodes.Open => "装袋中",
ShipBagStatusCodes.Sealed => "已封袋",
ShipBagStatusCodes.Shipped => "已出库",
ShipBagStatusCodes.Voided => "已作废",
_ => bag.Status,
},
WarehouseId = bag.WarehouseId,
DestinationCountry = bag.DestinationCountry,
ChannelCode = bag.ChannelCode,
ParcelCount = bag.ParcelCount,
SealTime = bag.SealTime,
ShipTime = bag.ShipTime,
MasterId = bag.MasterId,
Remark = bag.Remark,
CreateTime = bag.CreateTime,
};
}