using Fake.Application; using Oms.Application.Shared; using Oms.Domain.WarehouseAggregate.Entities; namespace Oms.Application.Services.Warehouse; public partial class WarehouseService { private async Task ResolveCustomerIdAsync(int? requestedCustomerId) => await WarehouseCustomerHelper.ResolveRequiredCustomerIdAsync( CustomerRepository, CurrentUser, requestedCustomerId); private async Task GetSkuOrThrowAsync(int customerId, int skuId) { var entity = await SkuRepository.FirstOrDefaultAsync(x => x.Id == skuId && x.CustomerId == customerId); if (entity == null) { throw new BusinessException("SKU 不存在"); } return entity; } private async Task UpsertInventoryQtyAsync( int customerId, int warehouseId, int skuId, int binLocationId, int deltaQty) { if (deltaQty == 0) { return; } var inventory = await InventoryRepository.FirstOrDefaultAsync(x => x.CustomerId == customerId && x.WarehouseId == warehouseId && x.SkuId == skuId && x.BinLocationId == binLocationId); if (inventory == null) { if (deltaQty < 0) { throw new BusinessException("库存不足"); } inventory = new CInventory { CustomerId = customerId, WarehouseId = warehouseId, SkuId = skuId, BinLocationId = binLocationId, Qty = deltaQty }; await InventoryRepository.InsertAsync(inventory); return; } var newQty = inventory.Qty + deltaQty; if (newQty < 0) { throw new BusinessException("库存不足"); } inventory.Qty = newQty; await InventoryRepository.UpdateAsync(inventory); } private async Task DeductInventoryAsync( int customerId, int warehouseId, int skuId, int requiredQty) { if (requiredQty <= 0) { return; } var rows = await InventoryRepository.GetListAsync(x => x.CustomerId == customerId && x.WarehouseId == warehouseId && x.SkuId == skuId && x.Qty > 0); rows = rows.OrderBy(x => x.BinLocationId).ToList(); var remaining = requiredQty; foreach (var row in rows) { if (remaining <= 0) { break; } var deduct = Math.Min(row.Qty, remaining); row.Qty -= deduct; remaining -= deduct; await InventoryRepository.UpdateAsync(row); } if (remaining > 0) { throw new BusinessException($"SKU {skuId} 库存不足,缺少 {remaining} 件"); } } }