Files
WMSlite/WmsLite.Api/Services/InventoryAllocationService.cs
T
2026-06-01 23:30:36 +08:00

91 lines
2.7 KiB
C#

using WmsLite.Api.Common;
using WmsLite.Api.Dtos.Inventory;
using WmsLite.Api.Enums;
using WmsLite.Api.Repositories.Interfaces;
using WmsLite.Api.Services.Interfaces;
namespace WmsLite.Api.Services;
public class InventoryAllocationService : IInventoryAllocationService
{
private readonly IInventoryRepository _inventoryRepository;
public InventoryAllocationService(IInventoryRepository inventoryRepository)
{
_inventoryRepository = inventoryRepository;
}
public async Task<List<InventoryAllocationItem>> AllocateAsync(InventoryAllocationRequest request)
{
if (request.Qty <= 0)
{
throw new BusinessException("Allocation quantity must be greater than 0.");
}
ValidateStockIdentity(request);
var candidates = await _inventoryRepository.GetAllocatableAsync(
request.TenantId,
request.OwnerCode,
request.WarehouseCode,
request.AreaCode,
request.InventoryKind,
request.MaterialCode,
request.ContainerCode,
request.LocationCode);
var remain = request.Qty;
var result = new List<InventoryAllocationItem>();
foreach (var inventory in candidates)
{
var available = inventory.Qty - inventory.PendingOutboundQty - inventory.FrozenQty;
if (available <= 0)
{
continue;
}
var allocated = Math.Min(available, remain);
result.Add(new InventoryAllocationItem
{
Inventory = inventory,
Qty = allocated
});
remain -= allocated;
if (remain <= 0)
{
break;
}
}
if (remain > 0)
{
throw new BusinessException($"Available quantity is not enough. Required: {request.Qty}, short: {remain}.");
}
return result;
}
private static void ValidateStockIdentity(InventoryAllocationRequest request)
{
switch (request.InventoryKind)
{
case InventoryKind.Material:
if (string.IsNullOrWhiteSpace(request.MaterialCode))
{
throw new BusinessException("MaterialCode is required for material allocation.");
}
break;
case InventoryKind.EmptyContainer:
if (string.IsNullOrWhiteSpace(request.ContainerCode))
{
throw new BusinessException("ContainerCode is required for empty container allocation.");
}
break;
default:
throw new BusinessException("Unsupported inventory kind.");
}
}
}