using System.Collections.Generic; using System.Globalization; 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 orderNo = await _orderNumberGenerator.NextInboundOrderNoAsync(tenantId, ownerCode); var order = new InboundOrder { TenantId = tenantId, OwnerCode = ownerCode, OrderNo = orderNo, BizType = request.BizType?.Trim(), Remark = request.Remark?.Trim(), Attrs = null, OrderStatus = OrderStatus.Draft }; await _orderRepository.InsertAsync(order); for (var i = 0; i < request.Lines.Count; i++) { var line = request.Lines[i]; await ValidateInboundLineMasterDataAsync(tenantId, ownerCode, line); await _lineRepository.InsertAsync(new InboundOrderLine { 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 = null, WarehouseCode = line.WarehouseCode.Trim(), AreaCode = line.AreaCode.Trim(), LocationCode = null, Qty = line.Qty, ReceivedQty = 0, LineStatus = OrderLineStatus.Open, Unit = null, Attrs = line.Attrs }); } return MapOrder(order, order.OrderNo, order.BizType, order.OrderStatus, order.Remark, order.Attrs); }); } 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 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 ILocationRepository _locationRepository; private readonly ICurrentUserContext _userContext; public OutboundOrderService( ITransactionRunner tx, IOutboundOrderRepository orderRepository, IOutboundOrderLineRepository 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(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 CreateAsync(OutboundOrderSaveRequest request) { return await _tx.ExecuteAsync(async () => { if (await _orderRepository.GetByOrderNoAsync(_userContext.TenantId.Trim(), _userContext.OwnerCode.Trim(), request.OrderNo) is not null) { throw new BusinessException($"Outbound order '{request.OrderNo}' already exists."); } var order = new OutboundOrder { 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 OutboundOrderLine { 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, 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 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 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 inventory = await RequireInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.WarehouseCode, line.AreaCode, resolved.ZoneCode, line.LocationCode!); await InventoryMovementService.PendingOutboundAsync(inventory, 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 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 inventory = await RequireInventoryAsync( order.TenantId, order.OwnerCode, line.InventoryKind, line.MaterialCode, line.ContainerCode, line.WarehouseCode, line.AreaCode, resolved.ZoneCode, line.LocationCode!); await InventoryMovementService.ConfirmOutboundAsync(inventory, 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 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 (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 (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); }); } }