using System.Collections.Generic; using System.Globalization; using WmsLite.Api.Dtos.Inventory; using WmsLite.Api.Common; using WmsLite.Api.Dtos.Orders; using WmsLite.Api.Enums; using WmsLite.Api.Models; using WmsLite.Api.Infrastructure; using WmsLite.Api.Infrastructure.Auth; using WmsLite.Api.Repositories.Interfaces; using WmsLite.Api.Services.Interfaces; namespace WmsLite.Api.Services; public abstract class OrderServiceBase { protected readonly IInventoryRepository InventoryRepository; protected readonly IInventoryMovementService InventoryMovementService; protected OrderServiceBase(IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService) { InventoryRepository = inventoryRepository; InventoryMovementService = inventoryMovementService; } protected static string FormatSnowflakeId(long value) => value.ToString(CultureInfo.InvariantCulture); protected static OrderViewDto MapOrder(BaseEntity entity, string orderNo, string? bizType, OrderStatus status, string? remark, Dictionary? attrs) { return new OrderViewDto { Id = FormatSnowflakeId(entity.Id), TenantId = entity.TenantId, OwnerCode = entity.OwnerCode, OrderNo = orderNo, BizType = bizType, OrderStatus = status, Remark = remark, Attrs = attrs, CreateTime = entity.CreateTime }; } protected async Task GetOrCreateInventoryAsync( string tenantId, string ownerCode, InventoryKind inventoryKind, string? materialCode, string? containerCode, string warehouseCode, string areaCode, string zoneCode, string locationCode, string unit, Dictionary? attrs) { var inventory = await InventoryRepository.GetByStockKeyAsync( tenantId, ownerCode, warehouseCode, areaCode, zoneCode, locationCode, inventoryKind, materialCode, containerCode); if (inventory is not null) { return inventory; } inventory = new Inventory { TenantId = tenantId.Trim(), OwnerCode = ownerCode.Trim(), InventoryKind = inventoryKind, InventoryStatus = InventoryStatus.Available, MaterialCode = inventoryKind == InventoryKind.Material ? materialCode?.Trim() : null, ContainerCode = containerCode?.Trim(), WarehouseCode = warehouseCode.Trim(), AreaCode = areaCode.Trim(), ZoneCode = zoneCode.Trim(), LocationCode = locationCode.Trim(), Qty = 0, Unit = unit.Trim(), Attrs = attrs ?? new Dictionary() }; await InventoryMovementService.ApplySnapshotAsync(inventory, null, InventoryMovementType.Adjust); return inventory; } protected async Task RequireInventoryAsync( string tenantId, string ownerCode, InventoryKind inventoryKind, string? materialCode, string? containerCode, string warehouseCode, string areaCode, string zoneCode, string locationCode) { var inventory = await InventoryRepository.GetByStockKeyAsync( tenantId, ownerCode, warehouseCode, areaCode, zoneCode, locationCode, inventoryKind, materialCode, containerCode); return inventory ?? throw new BusinessException("Inventory not found."); } protected static void EnsureDraft(OrderStatus status) { if (status != OrderStatus.Draft) { throw new BusinessException("Only draft orders can be moved to pending."); } } protected static void EnsurePending(OrderStatus status) { if (status != OrderStatus.Pending) { throw new BusinessException("Only pending orders can be confirmed."); } } protected static InventoryOrderLineViewDto MapInventoryLine(InboundOrderLine line) { var received = line.ReceivedQty; return new InventoryOrderLineViewDto { Id = FormatSnowflakeId(line.Id), OrderId = FormatSnowflakeId(line.OrderId), LineNo = line.LineNo, InventoryKind = line.InventoryKind, MaterialCode = line.MaterialCode, ContainerCode = line.ContainerCode, WarehouseCode = line.WarehouseCode, AreaCode = line.AreaCode, LocationCode = line.LocationCode ?? string.Empty, Qty = line.Qty, ReceivedQty = received, RemainingQty = Math.Max(0, line.Qty - received), LineStatus = line.LineStatus, Unit = line.Unit ?? string.Empty, Attrs = line.Attrs }; } protected static TransferOrderLineViewDto MapTransferLine(TransferOrderLine line) { return new TransferOrderLineViewDto { Id = FormatSnowflakeId(line.Id), OrderId = FormatSnowflakeId(line.OrderId), LineNo = line.LineNo, InventoryKind = line.InventoryKind, MaterialCode = line.MaterialCode, ContainerCode = line.ContainerCode, FromWarehouseCode = line.FromWarehouseCode, FromAreaCode = line.FromAreaCode, FromLocationCode = line.FromLocationCode, ToWarehouseCode = line.ToWarehouseCode, ToAreaCode = line.ToAreaCode, ToLocationCode = line.ToLocationCode, Qty = line.Qty, Unit = line.Unit ?? string.Empty, Attrs = line.Attrs }; } protected static StocktakeOrderLineViewDto MapStocktakeLine(StocktakeOrderLine line) { return new StocktakeOrderLineViewDto { Id = FormatSnowflakeId(line.Id), OrderId = FormatSnowflakeId(line.OrderId), LineNo = line.LineNo, InventoryKind = line.InventoryKind, MaterialCode = line.MaterialCode, ContainerCode = line.ContainerCode, WarehouseCode = line.WarehouseCode, AreaCode = line.AreaCode, LocationCode = line.LocationCode ?? string.Empty, Qty = line.Qty, ReceivedQty = line.ReceivedQty, RemainingQty = Math.Max(0, line.Qty - line.ReceivedQty), LineStatus = line.LineStatus, Unit = line.Unit ?? string.Empty, Attrs = line.Attrs, CountedQty = line.CountedQty }; } } public class InboundOrderService : OrderServiceBase, IInboundOrderService { private readonly ITransactionRunner _tx; private readonly IInboundOrderRepository _orderRepository; private readonly IInboundOrderLineRepository _lineRepository; private readonly IMaterialRepository _materialRepository; private readonly IContainerRepository _containerRepository; private readonly IWarehouseRepository _warehouseRepository; private readonly IAreaRepository _areaRepository; private readonly ILocationRepository _locationRepository; private readonly ICurrentUserContext _userContext; private readonly IOrderNumberGenerator _orderNumberGenerator; public InboundOrderService( ITransactionRunner tx, IInboundOrderRepository orderRepository, IInboundOrderLineRepository lineRepository, IMaterialRepository materialRepository, IContainerRepository containerRepository, IWarehouseRepository warehouseRepository, IAreaRepository areaRepository, ILocationRepository locationRepository, IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService, ICurrentUserContext userContext, IOrderNumberGenerator orderNumberGenerator) : base(inventoryRepository, inventoryMovementService) { _tx = tx; _orderRepository = orderRepository; _lineRepository = lineRepository; _materialRepository = materialRepository; _containerRepository = containerRepository; _warehouseRepository = warehouseRepository; _areaRepository = areaRepository; _locationRepository = locationRepository; _userContext = userContext; _orderNumberGenerator = orderNumberGenerator; } public async Task> GetPagedListAsync(InboundOrderPagedQuery query) { var page = await _orderRepository.GetPagedListAsync(query); return new PagedResult { PageIndex = page.PageIndex, PageSize = page.PageSize, TotalCount = page.TotalCount, Items = page.Items.ConvertAll(x => MapOrder(x, x.OrderNo, x.BizType, x.OrderStatus, x.Remark, x.Attrs)) }; } public async Task?> GetLinesAsync(long orderId, string tenantId, string ownerCode) { var t = _userContext.TenantId.Trim(); var o = _userContext.OwnerCode.Trim(); if (await _orderRepository.GetByIdAsync(orderId, t, o) is null) { return null; } var lines = await _lineRepository.GetByOrderIdAsync(orderId); var list = new List(lines.Count); foreach (var line in lines) { var dto = MapInventoryLine(line); if (line.InventoryKind == InventoryKind.Material && !string.IsNullOrWhiteSpace(line.MaterialCode)) { var mat = await _materialRepository.GetByCodeAsync(t, o, line.MaterialCode.Trim()); dto.MaterialMasterUnit = string.IsNullOrWhiteSpace(mat?.Unit) ? null : mat.Unit.Trim(); } list.Add(dto); } return list; } public async Task CreateAsync(InboundOrderCreateRequest request) { return await _tx.ExecuteAsync(async () => { var tenantId = _userContext.TenantId.Trim(); var ownerCode = _userContext.OwnerCode.Trim(); var order = await CreateHeaderCoreAsync(tenantId, ownerCode, request); for (var i = 0; i < request.Lines.Count; i++) { await InsertInboundLineAsync(order, request.Lines[i], i + 1); } return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task CreateHeaderAsync(OrderHeaderCreateRequest request) { return await _tx.ExecuteAsync(async () => { var order = await CreateHeaderCoreAsync( _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task AddLineAsync(InboundOrderAddLineRequest request) { var order = await _orderRepository.GetByIdAsync( request.OrderId, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsureDraft(order.OrderStatus); var lines = await _lineRepository.GetByOrderIdAsync(order.Id); var line = await InsertInboundLineAsync(order, request.Line, lines.Count + 1); return MapInventoryLine(line); }); } public async Task ConfirmLineAsync(InboundOrderLineConfirmRequest request) { var tenantId = _userContext.TenantId.Trim(); var ownerCode = _userContext.OwnerCode.Trim(); if (!long.TryParse( request.LineId.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var lineId)) { throw new BusinessException("Invalid line id."); } var line = await _lineRepository.GetByIdAsync(lineId, tenantId, ownerCode); if (line is null) { return null; } var order = await _orderRepository.GetByIdAsync(line.OrderId, tenantId, ownerCode); if (order is null) { return null; } if (order.OrderStatus == OrderStatus.Cancelled) { throw new BusinessException("Cancelled orders cannot receive stock."); } if (order.OrderStatus == OrderStatus.Completed) { throw new BusinessException("Completed orders cannot receive more stock."); } if (line.LineStatus == OrderLineStatus.Completed) { throw new BusinessException("This line is already fully received."); } var confirmQty = request.Qty; if (line.ReceivedQty + confirmQty > line.Qty) { throw new BusinessException("Receive quantity exceeds the remaining quantity for this line."); } var locCode = request.LocationCode.Trim(); var resolvedLoc = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( tenantId, ownerCode, line.WarehouseCode, line.AreaCode, locCode) ?? throw new BusinessException( $"Location '{locCode}' not found for warehouse '{line.WarehouseCode}' and area '{line.AreaCode}'."); var lookupMaterialCode = line.InventoryKind == InventoryKind.Material ? line.MaterialCode?.Trim() : null; string unitForInventory; if (line.InventoryKind == InventoryKind.Material) { if (string.IsNullOrWhiteSpace(lookupMaterialCode)) { throw new BusinessException("MaterialCode is required for material lines."); } var material = await _materialRepository.GetByCodeAsync(tenantId, ownerCode, lookupMaterialCode) ?? throw new BusinessException($"Material '{lookupMaterialCode}' not found."); unitForInventory = material.Unit.Trim(); if (string.IsNullOrWhiteSpace(unitForInventory)) { throw new BusinessException($"Material '{lookupMaterialCode}' has no unit in master data."); } } else { var reqUnit = request.Unit?.Trim(); if (string.IsNullOrWhiteSpace(reqUnit)) { throw new BusinessException("Unit is required for empty container lines."); } unitForInventory = reqUnit; } string? containerForInventory = null; if (line.InventoryKind == InventoryKind.EmptyContainer) { if (string.IsNullOrWhiteSpace(request.ContainerCode)) { throw new BusinessException("ContainerCode is required for empty container lines."); } containerForInventory = request.ContainerCode.Trim(); if (await _containerRepository.GetByCodeAsync(tenantId, ownerCode, containerForInventory) is null) { throw new BusinessException($"Container '{containerForInventory}' not found."); } } else if (!string.IsNullOrWhiteSpace(request.ContainerCode)) { var cc = request.ContainerCode.Trim(); if (await _containerRepository.GetByCodeAsync(tenantId, ownerCode, cc) is null) { throw new BusinessException($"Container '{cc}' not found."); } containerForInventory = cc; } var lookupContainer = containerForInventory; await _tx.ExecuteAsync(async () => { line.ReceivedQty += confirmQty; if (line.ReceivedQty >= line.Qty) { line.LineStatus = OrderLineStatus.Completed; } await _lineRepository.UpdateAsync(line); var inventory = await InventoryRepository.GetByStockKeyAsync( tenantId, ownerCode, line.WarehouseCode, line.AreaCode, resolvedLoc.ZoneCode, locCode, line.InventoryKind, lookupMaterialCode, lookupContainer); if (inventory is null) { inventory = await GetOrCreateInventoryAsync( tenantId, ownerCode, line.InventoryKind, lookupMaterialCode, containerForInventory, line.WarehouseCode, line.AreaCode, resolvedLoc.ZoneCode, locCode, unitForInventory, line.Attrs); } else { if (string.Compare(inventory.Unit.Trim(), unitForInventory, StringComparison.Ordinal) != 0) { throw new BusinessException("Unit does not match existing inventory at this location."); } if (!InventoryContainerEquals(inventory.ContainerCode, containerForInventory)) { throw new BusinessException("Container does not match existing inventory at this location."); } } await InventoryMovementService.PendingInboundAsync(inventory, confirmQty, order.OrderNo); await InventoryMovementService.ConfirmInboundAsync(inventory, confirmQty, order.OrderNo); await SyncInboundHeaderStatusAsync(order); }); var updatedOrder = await _orderRepository.GetByIdAsync(order.Id, tenantId, ownerCode) ?? order; var updatedLine = await _lineRepository.GetByIdAsync(line.Id, tenantId, ownerCode) ?? line; return new InboundConfirmLineResultDto { Order = MapOrder(updatedOrder, updatedOrder.OrderNo, updatedOrder.BizType, updatedOrder.OrderStatus, updatedOrder.Remark, updatedOrder.Attrs), Line = MapInventoryLine(updatedLine) }; } private async Task SyncInboundHeaderStatusAsync(InboundOrder order) { var lines = await _lineRepository.GetByOrderIdAsync(order.Id); var allCompleted = lines.TrueForAll(l => l.LineStatus == OrderLineStatus.Completed); var anyReceived = lines.Exists(l => l.ReceivedQty > 0); if (allCompleted) { order.OrderStatus = OrderStatus.Completed; } else if (anyReceived) { order.OrderStatus = OrderStatus.Pending; } else { order.OrderStatus = OrderStatus.Draft; } await _orderRepository.UpdateAsync(order); } private static bool InventoryContainerEquals(string? a, string? b) { var aa = string.IsNullOrWhiteSpace(a) ? null : a.Trim(); var bb = string.IsNullOrWhiteSpace(b) ? null : b.Trim(); return string.Equals(aa, bb, StringComparison.Ordinal); } private async Task CreateHeaderCoreAsync(string tenantId, string ownerCode, OrderSaveRequestBase request) { var order = new InboundOrder { TenantId = tenantId, OwnerCode = ownerCode, OrderNo = await _orderNumberGenerator.NextInboundOrderNoAsync(tenantId, ownerCode), BizType = request.BizType?.Trim(), Remark = request.Remark?.Trim(), Attrs = request.Attrs, OrderStatus = OrderStatus.Draft }; await _orderRepository.InsertAsync(order); return order; } private async Task InsertInboundLineAsync(InboundOrder order, InboundOrderLineSaveRequest line, int lineNo) { await ValidateInboundLineMasterDataAsync(order.TenantId, order.OwnerCode, line); var entity = new InboundOrderLine { TenantId = order.TenantId, OwnerCode = order.OwnerCode, OrderId = order.Id, LineNo = lineNo, InventoryKind = line.InventoryKind, MaterialCode = line.InventoryKind == InventoryKind.Material ? line.MaterialCode?.Trim() : null, ContainerCode = null, WarehouseCode = line.WarehouseCode.Trim(), AreaCode = line.AreaCode.Trim(), LocationCode = null, Qty = line.Qty, ReceivedQty = 0, LineStatus = OrderLineStatus.Open, Unit = null, Attrs = line.Attrs }; await _lineRepository.InsertAsync(entity); return entity; } private async Task ValidateInboundLineMasterDataAsync(string tenantId, string ownerCode, InboundOrderLineSaveRequest line) { var t = tenantId.Trim(); var o = ownerCode.Trim(); switch (line.InventoryKind) { case InventoryKind.Material: if (string.IsNullOrWhiteSpace(line.MaterialCode)) { throw new BusinessException("MaterialCode is required for material lines."); } if (await _materialRepository.GetByCodeAsync(t, o, line.MaterialCode.Trim()) is null) { throw new BusinessException($"Material '{line.MaterialCode}' not found."); } break; case InventoryKind.EmptyContainer: break; default: throw new BusinessException("Unsupported inventory kind."); } if (await _warehouseRepository.GetByCodeAsync(t, o, line.WarehouseCode.Trim()) is null) { throw new BusinessException($"Warehouse '{line.WarehouseCode}' not found."); } if (await _areaRepository.GetByWarehouseAndAreaCodeAsync(t, o, line.WarehouseCode.Trim(), line.AreaCode.Trim()) is null) { throw new BusinessException($"Area '{line.AreaCode}' not found for warehouse '{line.WarehouseCode}'."); } } } public class OutboundOrderService : OrderServiceBase, IOutboundOrderService { private readonly ITransactionRunner _tx; private readonly IOutboundOrderRepository _orderRepository; private readonly IOutboundOrderLineRepository _lineRepository; private readonly IOutboundPickTaskRepository _pickTaskRepository; private readonly ILocationRepository _locationRepository; private readonly IMaterialRepository _materialRepository; private readonly IInventoryAllocationService _allocationService; private readonly IOrderNumberGenerator _orderNumberGenerator; private readonly ICurrentUserContext _userContext; public OutboundOrderService( ITransactionRunner tx, IOutboundOrderRepository orderRepository, IOutboundOrderLineRepository lineRepository, IOutboundPickTaskRepository pickTaskRepository, ILocationRepository locationRepository, IMaterialRepository materialRepository, IInventoryAllocationService allocationService, IOrderNumberGenerator orderNumberGenerator, IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService, ICurrentUserContext userContext) : base(inventoryRepository, inventoryMovementService) { _tx = tx; _orderRepository = orderRepository; _lineRepository = lineRepository; _pickTaskRepository = pickTaskRepository; _locationRepository = locationRepository; _materialRepository = materialRepository; _allocationService = allocationService; _orderNumberGenerator = orderNumberGenerator; _userContext = userContext; } public async Task> GetPagedListAsync(OutboundOrderPagedQuery query) { var page = await _orderRepository.GetPagedListAsync(query); return new PagedResult { PageIndex = page.PageIndex, PageSize = page.PageSize, TotalCount = page.TotalCount, Items = page.Items.ConvertAll(x => MapOrder(x, x.OrderNo, x.BizType, x.OrderStatus, x.Remark, x.Attrs)) }; } public async Task?> GetLinesAsync(long orderId, string tenantId, string ownerCode) { var t = _userContext.TenantId.Trim(); var o = _userContext.OwnerCode.Trim(); if (await _orderRepository.GetByIdAsync(orderId, t, o) is null) { return null; } var lines = await _lineRepository.GetByOrderIdAsync(orderId); return lines.ConvertAll(x => MapInventoryLine(x)); } public async Task?> GetPickTasksAsync(long orderId, string tenantId, string ownerCode) { var t = _userContext.TenantId.Trim(); var o = _userContext.OwnerCode.Trim(); if (await _orderRepository.GetByIdAsync(orderId, t, o) is null) { return null; } var tasks = await _pickTaskRepository.GetByOrderIdAsync(orderId); return tasks.ConvertAll(MapPickTask); } public async Task CreateAsync(OutboundOrderSaveRequest request) { return await _tx.ExecuteAsync(async () => { var tenantId = _userContext.TenantId.Trim(); var ownerCode = _userContext.OwnerCode.Trim(); var order = await CreateHeaderCoreAsync(tenantId, ownerCode, request); for (var i = 0; i < request.Lines.Count; i++) { await InsertOutboundLineAsync(order, request.Lines[i], i + 1); } return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task CreateHeaderAsync(OrderHeaderCreateRequest request) { return await _tx.ExecuteAsync(async () => { var order = await CreateHeaderCoreAsync( _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task AddLineAsync(OutboundOrderAddLineRequest request) { var order = await _orderRepository.GetByIdAsync( request.OrderId, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsureDraft(order.OrderStatus); var lines = await _lineRepository.GetByOrderIdAsync(order.Id); var line = await InsertOutboundLineAsync(order, request.Line, lines.Count + 1); return MapInventoryLine(line); }); } public async Task PendingAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsureDraft(order.OrderStatus); var lines = await _lineRepository.GetByOrderIdAsync(order.Id); if (lines.Count == 0) { throw new BusinessException("Outbound order must have at least one line before picking."); } foreach (var line in lines) { var existingTasks = await _pickTaskRepository.GetByOrderLineIdAsync(line.Id); if (existingTasks.Count > 0) { throw new BusinessException("Outbound pick tasks already exist."); } if (!string.IsNullOrWhiteSpace(line.LocationCode) && await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.WarehouseCode, line.AreaCode, line.LocationCode.Trim()) is null) { throw new BusinessException( $"Location '{line.LocationCode}' not found for warehouse '{line.WarehouseCode}' and area '{line.AreaCode}'."); } var allocations = await _allocationService.AllocateAsync(new InventoryAllocationRequest { TenantId = order.TenantId, OwnerCode = order.OwnerCode, InventoryKind = line.InventoryKind, MaterialCode = line.MaterialCode, ContainerCode = line.ContainerCode, WarehouseCode = line.WarehouseCode, AreaCode = line.AreaCode, LocationCode = line.LocationCode, Qty = line.Qty }); var taskSeq = 1; foreach (var allocation in allocations) { var inventory = allocation.Inventory; if (string.Compare(inventory.Unit.Trim(), line.Unit?.Trim(), StringComparison.Ordinal) != 0) { throw new BusinessException("Unit does not match allocated inventory."); } await InventoryMovementService.PendingOutboundAsync(inventory, allocation.Qty, order.OrderNo); await _pickTaskRepository.InsertAsync(new OutboundPickTask { TenantId = order.TenantId, OwnerCode = order.OwnerCode, OrderId = order.Id, OrderLineId = line.Id, TaskNo = $"{order.OrderNo}-P{line.LineNo:D3}-{taskSeq:D3}", InventoryId = inventory.Id, InventoryKind = inventory.InventoryKind, MaterialCode = inventory.MaterialCode, ContainerCode = inventory.ContainerCode, WarehouseCode = inventory.WarehouseCode, AreaCode = inventory.AreaCode, ZoneCode = inventory.ZoneCode, LocationCode = inventory.LocationCode, Qty = allocation.Qty, PickedQty = 0, Unit = inventory.Unit, TaskStatus = PickTaskStatus.Open, Attrs = line.Attrs }); taskSeq++; } line.ReceivedQty = allocations.Sum(x => x.Qty); line.LineStatus = OrderLineStatus.Open; await _lineRepository.UpdateAsync(line); } order.OrderStatus = OrderStatus.Pending; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task ConfirmAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsurePending(order.OrderStatus); var tasks = await _pickTaskRepository.GetByOrderIdAsync(order.Id); if (tasks.Count == 0) { throw new BusinessException("Outbound pick tasks not found."); } foreach (var task in tasks) { if (task.TaskStatus != PickTaskStatus.Picked) { throw new BusinessException("All outbound pick tasks must be picked before outbound confirmation."); } var inventory = await InventoryRepository.GetByIdAsync(task.InventoryId, order.TenantId, order.OwnerCode) ?? throw new BusinessException("Allocated inventory not found."); await InventoryMovementService.ConfirmOutboundAsync(inventory, task.Qty, order.OrderNo); } var lines = await _lineRepository.GetByOrderIdAsync(order.Id); foreach (var line in lines) { line.LineStatus = OrderLineStatus.Completed; await _lineRepository.UpdateAsync(line); } order.OrderStatus = OrderStatus.Completed; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task ConfirmPickTaskAsync(PickTaskActionRequest request) { var task = await _pickTaskRepository.GetByIdAsync( request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (task is null) { return null; } return await _tx.ExecuteAsync(async () => { if (task.TaskStatus != PickTaskStatus.Open) { throw new BusinessException("Only open pick tasks can be picked."); } var order = await _orderRepository.GetByIdAsync(task.OrderId, task.TenantId, task.OwnerCode) ?? throw new BusinessException("Outbound order not found."); EnsurePending(order.OrderStatus); var pickedQty = request.PickedQty ?? task.Qty; if (pickedQty != task.Qty) { throw new BusinessException("Short picking is not supported yet. Please pick the full task quantity."); } task.PickedQty = pickedQty; task.PickerUserId = _userContext.UserId; task.PickedTime = DateTime.Now; task.ExceptionReason = string.IsNullOrWhiteSpace(request.ExceptionReason) ? null : request.ExceptionReason.Trim(); task.TaskStatus = PickTaskStatus.Picked; await _pickTaskRepository.UpdateAsync(task); return MapPickTask(task); }); } public async Task CancelAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { if (order.OrderStatus == OrderStatus.Completed) { throw new BusinessException("Completed outbound orders cannot be cancelled."); } if (order.OrderStatus == OrderStatus.Cancelled) { return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); } var tasks = await _pickTaskRepository.GetByOrderIdAsync(order.Id); foreach (var task in tasks) { if (task.TaskStatus == PickTaskStatus.Cancelled) { continue; } var inventory = await InventoryRepository.GetByIdAsync(task.InventoryId, order.TenantId, order.OwnerCode) ?? throw new BusinessException("Allocated inventory not found."); await InventoryMovementService.ReleasePendingOutboundAsync( inventory, task.Qty, order.OrderNo, "Outbound order cancelled."); task.TaskStatus = PickTaskStatus.Cancelled; task.ExceptionReason = "Outbound order cancelled."; await _pickTaskRepository.UpdateAsync(task); } var lines = await _lineRepository.GetByOrderIdAsync(order.Id); foreach (var line in lines) { line.LineStatus = OrderLineStatus.Open; line.ReceivedQty = 0; await _lineRepository.UpdateAsync(line); } order.OrderStatus = OrderStatus.Cancelled; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } private static OutboundPickTaskViewDto MapPickTask(OutboundPickTask task) { return new OutboundPickTaskViewDto { Id = FormatSnowflakeId(task.Id), OrderId = FormatSnowflakeId(task.OrderId), OrderLineId = FormatSnowflakeId(task.OrderLineId), TaskNo = task.TaskNo, InventoryId = FormatSnowflakeId(task.InventoryId), InventoryKind = task.InventoryKind, MaterialCode = task.MaterialCode, ContainerCode = task.ContainerCode, WarehouseCode = task.WarehouseCode, AreaCode = task.AreaCode, ZoneCode = task.ZoneCode, LocationCode = task.LocationCode, Qty = task.Qty, PickedQty = task.PickedQty, PickerUserId = task.PickerUserId, PickedTime = task.PickedTime, ExceptionReason = task.ExceptionReason, Unit = task.Unit, TaskStatus = task.TaskStatus, Attrs = task.Attrs }; } private async Task CreateHeaderCoreAsync(string tenantId, string ownerCode, OrderSaveRequestBase request) { var orderNo = string.IsNullOrWhiteSpace(request.OrderNo) ? await _orderNumberGenerator.NextOutboundOrderNoAsync(tenantId, ownerCode) : request.OrderNo.Trim(); if (await _orderRepository.GetByOrderNoAsync(tenantId, ownerCode, orderNo) is not null) { throw new BusinessException($"Outbound order '{orderNo}' already exists."); } var order = new OutboundOrder { TenantId = tenantId, OwnerCode = ownerCode, OrderNo = orderNo, BizType = request.BizType?.Trim(), Remark = request.Remark?.Trim(), Attrs = request.Attrs, OrderStatus = OrderStatus.Draft }; await _orderRepository.InsertAsync(order); return order; } private async Task InsertOutboundLineAsync(OutboundOrder order, OutboundOrderLineRequest line, int lineNo) { var unit = await ResolveOutboundLineUnitAsync(order.TenantId, order.OwnerCode, line); var entity = new OutboundOrderLine { TenantId = order.TenantId, OwnerCode = order.OwnerCode, OrderId = order.Id, LineNo = lineNo, InventoryKind = line.InventoryKind, MaterialCode = line.InventoryKind == InventoryKind.Material ? line.MaterialCode?.Trim() : null, ContainerCode = line.InventoryKind == InventoryKind.EmptyContainer ? line.ContainerCode?.Trim() : null, WarehouseCode = line.WarehouseCode.Trim(), AreaCode = line.AreaCode.Trim(), LocationCode = line.LocationCode?.Trim(), Qty = line.Qty, ReceivedQty = 0, LineStatus = OrderLineStatus.Open, Unit = unit, Attrs = line.Attrs }; await _lineRepository.InsertAsync(entity); return entity; } private async Task ResolveOutboundLineUnitAsync(string tenantId, string ownerCode, OutboundOrderLineRequest line) { switch (line.InventoryKind) { case InventoryKind.Material: if (string.IsNullOrWhiteSpace(line.MaterialCode)) { throw new BusinessException("MaterialCode is required for material lines."); } var material = await _materialRepository.GetByCodeAsync(tenantId, ownerCode, line.MaterialCode.Trim()) ?? throw new BusinessException($"Material '{line.MaterialCode}' not found."); var masterUnit = material.Unit.Trim(); if (string.IsNullOrWhiteSpace(masterUnit)) { throw new BusinessException($"Material '{line.MaterialCode}' has no unit in master data."); } if (!string.IsNullOrWhiteSpace(line.Unit) && !string.Equals(line.Unit.Trim(), masterUnit, StringComparison.Ordinal)) { throw new BusinessException("Line unit does not match material master unit."); } return masterUnit; case InventoryKind.EmptyContainer: if (string.IsNullOrWhiteSpace(line.ContainerCode)) { throw new BusinessException("ContainerCode is required for empty container lines."); } if (string.IsNullOrWhiteSpace(line.Unit)) { throw new BusinessException("Unit is required for empty container lines."); } return line.Unit.Trim(); default: throw new BusinessException("Unsupported inventory kind."); } } } public class TransferOrderService : OrderServiceBase, ITransferOrderService { private readonly ITransactionRunner _tx; private readonly ITransferOrderRepository _orderRepository; private readonly ITransferOrderLineRepository _lineRepository; private readonly ILocationRepository _locationRepository; private readonly ICurrentUserContext _userContext; public TransferOrderService( ITransactionRunner tx, ITransferOrderRepository orderRepository, ITransferOrderLineRepository lineRepository, ILocationRepository locationRepository, IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService, ICurrentUserContext userContext) : base(inventoryRepository, inventoryMovementService) { _tx = tx; _orderRepository = orderRepository; _lineRepository = lineRepository; _locationRepository = locationRepository; _userContext = userContext; } public async Task> GetPagedListAsync(TransferOrderPagedQuery query) { var page = await _orderRepository.GetPagedListAsync(query); return new PagedResult { PageIndex = page.PageIndex, PageSize = page.PageSize, TotalCount = page.TotalCount, Items = page.Items.ConvertAll(x => MapOrder(x, x.OrderNo, x.BizType, x.OrderStatus, x.Remark, x.Attrs)) }; } public async Task?> GetLinesAsync(long orderId, string tenantId, string ownerCode) { var t = _userContext.TenantId.Trim(); var o = _userContext.OwnerCode.Trim(); if (await _orderRepository.GetByIdAsync(orderId, t, o) is null) { return null; } var lines = await _lineRepository.GetByOrderIdAsync(orderId); return lines.ConvertAll(MapTransferLine); } public async Task CreateAsync(TransferOrderSaveRequest request) { return await _tx.ExecuteAsync(async () => { if (string.IsNullOrWhiteSpace(request.OrderNo)) { throw new BusinessException("OrderNo is required."); } if (await _orderRepository.GetByOrderNoAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.OrderNo) is not null) { throw new BusinessException($"Transfer order '{request.OrderNo}' already exists."); } var order = new TransferOrder { TenantId = _userContext.TenantId.Trim(), OwnerCode = _userContext.OwnerCode.Trim(), OrderNo = request.OrderNo.Trim(), BizType = request.BizType?.Trim(), Remark = request.Remark?.Trim(), Attrs = request.Attrs, OrderStatus = OrderStatus.Draft }; await _orderRepository.InsertAsync(order); for (var i = 0; i < request.Lines.Count; i++) { var line = request.Lines[i]; await _lineRepository.InsertAsync(new TransferOrderLine { TenantId = order.TenantId, OwnerCode = order.OwnerCode, OrderId = order.Id, LineNo = i + 1, InventoryKind = line.InventoryKind, MaterialCode = line.InventoryKind == InventoryKind.Material ? line.MaterialCode?.Trim() : null, ContainerCode = line.InventoryKind == InventoryKind.EmptyContainer ? line.ContainerCode?.Trim() : null, FromWarehouseCode = line.FromWarehouseCode.Trim(), FromAreaCode = line.FromAreaCode.Trim(), FromLocationCode = line.FromLocationCode.Trim(), ToWarehouseCode = line.ToWarehouseCode.Trim(), ToAreaCode = line.ToAreaCode.Trim(), ToLocationCode = line.ToLocationCode.Trim(), Qty = line.Qty, Unit = line.Unit.Trim(), Attrs = line.Attrs }); } return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task PendingAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsureDraft(order.OrderStatus); var lines = await _lineRepository.GetByOrderIdAsync(order.Id); foreach (var line in lines) { var fromLoc = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.FromWarehouseCode, line.FromAreaCode, line.FromLocationCode.Trim()) ?? throw new BusinessException( $"Location '{line.FromLocationCode}' not found for warehouse '{line.FromWarehouseCode}' and area '{line.FromAreaCode}'."); var toLoc = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.ToWarehouseCode, line.ToAreaCode, line.ToLocationCode.Trim()) ?? throw new BusinessException( $"Location '{line.ToLocationCode}' not found for warehouse '{line.ToWarehouseCode}' and area '{line.ToAreaCode}'."); var source = await RequireInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.FromWarehouseCode, line.FromAreaCode, fromLoc.ZoneCode, line.FromLocationCode); var target = await GetOrCreateInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.ToWarehouseCode, line.ToAreaCode, toLoc.ZoneCode, line.ToLocationCode, line.Unit, line.Attrs); await InventoryMovementService.PendingOutboundAsync(source, line.Qty, order.OrderNo); await InventoryMovementService.PendingInboundAsync(target, line.Qty, order.OrderNo); } order.OrderStatus = OrderStatus.Pending; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task ConfirmAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { EnsurePending(order.OrderStatus); var lines = await _lineRepository.GetByOrderIdAsync(order.Id); foreach (var line in lines) { var fromLoc = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.FromWarehouseCode, line.FromAreaCode, line.FromLocationCode.Trim()) ?? throw new BusinessException( $"Location '{line.FromLocationCode}' not found for warehouse '{line.FromWarehouseCode}' and area '{line.FromAreaCode}'."); var toLoc = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.ToWarehouseCode, line.ToAreaCode, line.ToLocationCode.Trim()) ?? throw new BusinessException( $"Location '{line.ToLocationCode}' not found for warehouse '{line.ToWarehouseCode}' and area '{line.ToAreaCode}'."); var source = await RequireInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.FromWarehouseCode, line.FromAreaCode, fromLoc.ZoneCode, line.FromLocationCode); var target = await RequireInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.ToWarehouseCode, line.ToAreaCode, toLoc.ZoneCode, line.ToLocationCode); await InventoryMovementService.ConfirmOutboundAsync(source, line.Qty, order.OrderNo); await InventoryMovementService.ConfirmInboundAsync(target, line.Qty, order.OrderNo); } order.OrderStatus = OrderStatus.Completed; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } } public class StocktakeOrderService : OrderServiceBase, IStocktakeOrderService { private readonly ITransactionRunner _tx; private readonly IStocktakeOrderRepository _orderRepository; private readonly IStocktakeOrderLineRepository _lineRepository; private readonly ILocationRepository _locationRepository; private readonly ICurrentUserContext _userContext; public StocktakeOrderService( ITransactionRunner tx, IStocktakeOrderRepository orderRepository, IStocktakeOrderLineRepository lineRepository, ILocationRepository locationRepository, IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService, ICurrentUserContext userContext) : base(inventoryRepository, inventoryMovementService) { _tx = tx; _orderRepository = orderRepository; _lineRepository = lineRepository; _locationRepository = locationRepository; _userContext = userContext; } public async Task> GetPagedListAsync(StocktakeOrderPagedQuery query) { var page = await _orderRepository.GetPagedListAsync(query); return new PagedResult { PageIndex = page.PageIndex, PageSize = page.PageSize, TotalCount = page.TotalCount, Items = page.Items.ConvertAll(x => MapOrder(x, x.OrderNo, x.BizType, x.OrderStatus, x.Remark, x.Attrs)) }; } public async Task?> GetLinesAsync(long orderId, string tenantId, string ownerCode) { var t = _userContext.TenantId.Trim(); var o = _userContext.OwnerCode.Trim(); if (await _orderRepository.GetByIdAsync(orderId, t, o) is null) { return null; } var lines = await _lineRepository.GetByOrderIdAsync(orderId); return lines.ConvertAll(MapStocktakeLine); } public async Task CreateAsync(StocktakeOrderSaveRequest request) { return await _tx.ExecuteAsync(async () => { if (string.IsNullOrWhiteSpace(request.OrderNo)) { throw new BusinessException("OrderNo is required."); } if (await _orderRepository.GetByOrderNoAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.OrderNo) is not null) { throw new BusinessException($"Stocktake order '{request.OrderNo}' already exists."); } var order = new StocktakeOrder { TenantId = _userContext.TenantId.Trim(), OwnerCode = _userContext.OwnerCode.Trim(), OrderNo = request.OrderNo.Trim(), BizType = request.BizType?.Trim(), Remark = request.Remark?.Trim(), Attrs = request.Attrs, OrderStatus = OrderStatus.Draft }; await _orderRepository.InsertAsync(order); for (var i = 0; i < request.Lines.Count; i++) { var line = request.Lines[i]; await _lineRepository.InsertAsync(new StocktakeOrderLine { TenantId = order.TenantId, OwnerCode = order.OwnerCode, OrderId = order.Id, LineNo = i + 1, InventoryKind = line.InventoryKind, MaterialCode = line.InventoryKind == InventoryKind.Material ? line.MaterialCode?.Trim() : null, ContainerCode = line.InventoryKind == InventoryKind.EmptyContainer ? line.ContainerCode?.Trim() : null, WarehouseCode = line.WarehouseCode.Trim(), AreaCode = line.AreaCode.Trim(), LocationCode = line.LocationCode.Trim(), Qty = line.Qty, CountedQty = line.CountedQty, ReceivedQty = 0, LineStatus = OrderLineStatus.Completed, Unit = line.Unit.Trim(), Attrs = line.Attrs }); } return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } public async Task ConfirmAsync(OrderActionRequest request) { var order = await _orderRepository.GetByIdAsync(request.Id, _userContext.TenantId.Trim(), _userContext.OwnerCode.Trim()); if (order is null) { return null; } return await _tx.ExecuteAsync(async () => { if (order.OrderStatus != OrderStatus.Draft) { throw new BusinessException("Only draft stocktake orders can be confirmed."); } var lines = await _lineRepository.GetByOrderIdAsync(order.Id); foreach (var line in lines) { var resolved = await _locationRepository.GetByWarehouseAreaAndLocationCodeAsync( order.TenantId, order.OwnerCode, line.WarehouseCode, line.AreaCode, line.LocationCode!.Trim()) ?? throw new BusinessException( $"Location '{line.LocationCode}' not found for warehouse '{line.WarehouseCode}' and area '{line.AreaCode}'."); var existing = await InventoryRepository.GetByStockKeyAsync( order.TenantId, order.OwnerCode, line.WarehouseCode, line.AreaCode, resolved.ZoneCode, line.LocationCode!, line.InventoryKind, line.MaterialCode, line.ContainerCode); var inventory = existing ?? await GetOrCreateInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.WarehouseCode, line.AreaCode, resolved.ZoneCode, line.LocationCode!, line.Unit!.Trim(), line.Attrs); var before = new Inventory { Id = inventory.Id, TenantId = inventory.TenantId, OwnerCode = inventory.OwnerCode, InventoryKind = inventory.InventoryKind, MaterialCode = inventory.MaterialCode, ContainerCode = inventory.ContainerCode, WarehouseCode = inventory.WarehouseCode, AreaCode = inventory.AreaCode, ZoneCode = inventory.ZoneCode, LocationCode = inventory.LocationCode, Qty = inventory.Qty, PendingInboundQty = inventory.PendingInboundQty, PendingOutboundQty = inventory.PendingOutboundQty, FrozenQty = inventory.FrozenQty, InventoryStatus = inventory.InventoryStatus, Unit = inventory.Unit, Attrs = inventory.Attrs }; inventory.Qty = line.CountedQty; await InventoryMovementService.ApplySnapshotAsync(inventory, before, InventoryMovementType.Adjust, order.OrderNo); } order.OrderStatus = OrderStatus.Completed; await _orderRepository.UpdateAsync(order); return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } }