diff --git a/WmsLite.Api.Tests/InventoryAllocationServiceTests.cs b/WmsLite.Api.Tests/InventoryAllocationServiceTests.cs new file mode 100644 index 0000000..fd0bb9e --- /dev/null +++ b/WmsLite.Api.Tests/InventoryAllocationServiceTests.cs @@ -0,0 +1,165 @@ +using System.Linq.Expressions; +using WmsLite.Api.Common; +using WmsLite.Api.Dtos.Common; +using WmsLite.Api.Dtos.Inventory; +using WmsLite.Api.Enums; +using WmsLite.Api.Infrastructure.Auth; +using WmsLite.Api.Models; +using WmsLite.Api.Repositories.Interfaces; +using WmsLite.Api.Services; + +namespace WmsLite.Api.Tests; + +public class InventoryAllocationServiceTests +{ + [Fact] + public async Task AllocateAsync_AllocatesAcrossFifoCandidates() + { + var repo = new FakeInventoryRepository([ + NewInventory(1, "L-1", qty: 5, createTime: new DateTime(2026, 1, 1)), + NewInventory(2, "L-2", qty: 8, createTime: new DateTime(2026, 1, 2)), + ]); + var service = new InventoryAllocationService(repo); + + var result = await service.AllocateAsync(NewRequest(10)); + + Assert.Equal(2, result.Count); + Assert.Equal(1, result[0].Inventory.Id); + Assert.Equal(5, result[0].Qty); + Assert.Equal(2, result[1].Inventory.Id); + Assert.Equal(5, result[1].Qty); + } + + [Fact] + public async Task AllocateAsync_RespectsLocationConstraint() + { + var repo = new FakeInventoryRepository([ + NewInventory(1, "L-1", qty: 5), + NewInventory(2, "L-2", qty: 8), + ]); + var service = new InventoryAllocationService(repo); + + var result = await service.AllocateAsync(NewRequest(6, locationCode: "L-2")); + + var item = Assert.Single(result); + Assert.Equal(2, item.Inventory.Id); + Assert.Equal(6, item.Qty); + } + + [Fact] + public async Task AllocateAsync_ThrowsWhenAvailableQtyIsNotEnough() + { + var repo = new FakeInventoryRepository([ + NewInventory(1, "L-1", qty: 5, pendingOutboundQty: 3), + ]); + var service = new InventoryAllocationService(repo); + + await Assert.ThrowsAsync(() => service.AllocateAsync(NewRequest(3))); + } + + private static InventoryAllocationRequest NewRequest(decimal qty, string? locationCode = null) + { + return new InventoryAllocationRequest + { + TenantId = "default", + OwnerCode = "default", + InventoryKind = InventoryKind.Material, + MaterialCode = "MAT-1", + WarehouseCode = "WH-1", + AreaCode = "A-1", + LocationCode = locationCode, + Qty = qty + }; + } + + private static Inventory NewInventory( + long id, + string locationCode, + decimal qty, + decimal pendingOutboundQty = 0, + DateTime? createTime = null) + { + return new Inventory + { + Id = id, + TenantId = "default", + OwnerCode = "default", + InventoryKind = InventoryKind.Material, + MaterialCode = "MAT-1", + WarehouseCode = "WH-1", + AreaCode = "A-1", + ZoneCode = "Z-1", + LocationCode = locationCode, + Qty = qty, + PendingOutboundQty = pendingOutboundQty, + Unit = "pcs", + CreateTime = createTime + }; + } + + private sealed class FakeInventoryRepository : IInventoryRepository + { + private readonly List _items; + + public FakeInventoryRepository(IEnumerable items) + { + _items = items.ToList(); + } + + public Task> GetAllocatableAsync( + string tenantId, + string ownerCode, + string warehouseCode, + string areaCode, + InventoryKind inventoryKind, + string? materialCode, + string? containerCode, + string? locationCode = null) + { + var items = _items + .Where(x => !x.IsDeleted + && x.TenantId == tenantId + && x.OwnerCode == ownerCode + && x.WarehouseCode == warehouseCode + && x.AreaCode == areaCode + && x.InventoryKind == inventoryKind + && x.MaterialCode == materialCode + && x.Qty - x.PendingOutboundQty - x.FrozenQty > 0) + .Where(x => string.IsNullOrWhiteSpace(locationCode) || x.LocationCode == locationCode) + .OrderBy(x => x.CreateTime) + .ThenBy(x => x.Id) + .ToList(); + return Task.FromResult(items); + } + + public Task GetByStockKeyAsync(string tenantId, string ownerCode, string warehouseCode, string areaCode, string zoneCode, string locationCode, InventoryKind inventoryKind, string? materialCode, string? containerCode) + => Task.FromResult(null); + + public Task GetByIdAsync(long id) + => Task.FromResult(null); + + public Task GetByIdAsync(long id, string tenantId, string ownerCode) + => Task.FromResult(null); + + public Task> GetListAsync(Expression> predicate) + => Task.FromResult(new List()); + + public Task> GetPagedListAsync(BasePagedQuery query) + => Task.FromResult(new PagedResult()); + + public Task> GetPagedListAsync(InventoryPagedQuery query) + => Task.FromResult(new PagedResult()); + + public Task InsertAsync(Inventory entity) + => Task.FromResult(entity.Id); + + public Task UpdateAsync(Inventory entity) + => Task.FromResult(1); + + public Task SoftDeleteAsync(long id) + => Task.FromResult(0); + + public Task SoftDeleteAsync(long id, string tenantId, string ownerCode) + => Task.FromResult(0); + } +} diff --git a/WmsLite.Api.Tests/InventoryMovementServiceTests.cs b/WmsLite.Api.Tests/InventoryMovementServiceTests.cs new file mode 100644 index 0000000..372b0dd --- /dev/null +++ b/WmsLite.Api.Tests/InventoryMovementServiceTests.cs @@ -0,0 +1,214 @@ +using System.Linq.Expressions; +using WmsLite.Api.Common; +using WmsLite.Api.Dtos.Common; +using WmsLite.Api.Dtos.Inventory; +using WmsLite.Api.Enums; +using WmsLite.Api.Infrastructure.Auth; +using WmsLite.Api.Models; +using WmsLite.Api.Repositories.Interfaces; +using WmsLite.Api.Services; + +namespace WmsLite.Api.Tests; + +public class InventoryMovementServiceTests +{ + [Fact] + public async Task PendingOutboundAsync_ReservesAvailableQtyAndWritesTransaction() + { + var inventory = NewInventory(qty: 10); + var (_, transactionRepository, service) = CreateService(); + + await service.PendingOutboundAsync(inventory, 4, "SO-1", "pick"); + + Assert.Equal(10, inventory.Qty); + Assert.Equal(4, inventory.PendingOutboundQty); + Assert.Equal(InventoryStatus.PendingOutbound, inventory.InventoryStatus); + + var tx = Assert.Single(transactionRepository.Entities); + Assert.Equal(InventoryMovementType.PendingOutbound, tx.MovementType); + Assert.Equal(10, tx.BeforeQty); + Assert.Equal(10, tx.AfterQty); + Assert.Equal(0, tx.BeforePendingOutboundQty); + Assert.Equal(4, tx.AfterPendingOutboundQty); + Assert.Equal(4, tx.ChangeQty); + Assert.Equal("SO-1", tx.BizNo); + Assert.Equal("pick", tx.Attrs?["remark"]); + } + + [Fact] + public async Task ConfirmOutboundAsync_DecrementsPendingAndStockQty() + { + var inventory = NewInventory(qty: 10, pendingOutboundQty: 4); + var (_, transactionRepository, service) = CreateService(); + + await service.ConfirmOutboundAsync(inventory, 4, "SO-1"); + + Assert.Equal(6, inventory.Qty); + Assert.Equal(0, inventory.PendingOutboundQty); + Assert.Equal(InventoryStatus.Available, inventory.InventoryStatus); + + var tx = Assert.Single(transactionRepository.Entities); + Assert.Equal(InventoryMovementType.OutboundConfirm, tx.MovementType); + Assert.Equal(10, tx.BeforeQty); + Assert.Equal(6, tx.AfterQty); + Assert.Equal(4, tx.BeforePendingOutboundQty); + Assert.Equal(0, tx.AfterPendingOutboundQty); + Assert.Equal(-4, tx.ChangeQty); + } + + [Fact] + public async Task ConfirmInboundAsync_MovesPendingInboundToStockQty() + { + var inventory = NewInventory(qty: 2, pendingInboundQty: 5); + var (_, transactionRepository, service) = CreateService(); + + await service.ConfirmInboundAsync(inventory, 3, "IN-1"); + + Assert.Equal(5, inventory.Qty); + Assert.Equal(2, inventory.PendingInboundQty); + Assert.Equal(InventoryStatus.PendingInbound, inventory.InventoryStatus); + + var tx = Assert.Single(transactionRepository.Entities); + Assert.Equal(InventoryMovementType.InboundConfirm, tx.MovementType); + Assert.Equal(2, tx.BeforeQty); + Assert.Equal(5, tx.AfterQty); + Assert.Equal(5, tx.BeforePendingInboundQty); + Assert.Equal(2, tx.AfterPendingInboundQty); + Assert.Equal(3, tx.ChangeQty); + } + + [Fact] + public async Task PendingOutboundAsync_ThrowsWhenAvailableQtyIsNotEnough() + { + var inventory = NewInventory(qty: 10, pendingOutboundQty: 7, frozenQty: 2); + var (inventoryRepository, transactionRepository, service) = CreateService(); + + await Assert.ThrowsAsync( + () => service.PendingOutboundAsync(inventory, 2, "SO-2")); + + Assert.Equal(7, inventory.PendingOutboundQty); + Assert.Empty(inventoryRepository.UpdatedEntities); + Assert.Empty(transactionRepository.Entities); + } + + private static (FakeInventoryRepository InventoryRepository, FakeInventoryTransactionRepository TransactionRepository, InventoryMovementService Service) CreateService() + { + var inventoryRepository = new FakeInventoryRepository(); + var transactionRepository = new FakeInventoryTransactionRepository(); + var service = new InventoryMovementService( + inventoryRepository, + transactionRepository, + new FakeCurrentUserContext()); + return (inventoryRepository, transactionRepository, service); + } + + private static Inventory NewInventory(decimal qty, decimal pendingInboundQty = 0, decimal pendingOutboundQty = 0, decimal frozenQty = 0) + { + return new Inventory + { + Id = 1001, + TenantId = "default", + OwnerCode = "default", + InventoryKind = InventoryKind.Material, + MaterialCode = "MAT-001", + WarehouseCode = "WH-1", + AreaCode = "A-1", + ZoneCode = "Z-1", + LocationCode = "L-1", + Qty = qty, + PendingInboundQty = pendingInboundQty, + PendingOutboundQty = pendingOutboundQty, + FrozenQty = frozenQty, + InventoryStatus = InventoryStatus.Available, + Unit = "pcs", + Attrs = new Dictionary { ["lot"] = "L202606" }, + }; + } + + private sealed class FakeCurrentUserContext : ICurrentUserContext + { + public bool IsAuthenticated => true; + public string UserId => "tester"; + public string TenantId => "default"; + public string OwnerCode => "default"; + public string? DisplayName => "Tester"; + } + + private sealed class FakeInventoryTransactionRepository : IInventoryTransactionRepository + { + public List Entities { get; } = []; + + public Task InsertAsync(InventoryTransaction entity) + { + entity.Id = Entities.Count + 1; + Entities.Add(entity); + return Task.FromResult(entity.Id); + } + + public Task> GetPagedListAsync(InventoryTransactionPagedQuery query) + => Task.FromResult(new PagedResult()); + } + + private sealed class FakeInventoryRepository : IInventoryRepository + { + public List InsertedEntities { get; } = []; + public List UpdatedEntities { get; } = []; + + public Task GetByStockKeyAsync( + string tenantId, + string ownerCode, + string warehouseCode, + string areaCode, + string zoneCode, + string locationCode, + InventoryKind inventoryKind, + string? materialCode, + string? containerCode) + => Task.FromResult(null); + + public Task> GetAllocatableAsync( + string tenantId, + string ownerCode, + string warehouseCode, + string areaCode, + InventoryKind inventoryKind, + string? materialCode, + string? containerCode, + string? locationCode = null) + => Task.FromResult(new List()); + + public Task GetByIdAsync(long id) + => Task.FromResult(null); + + public Task GetByIdAsync(long id, string tenantId, string ownerCode) + => Task.FromResult(null); + + public Task> GetListAsync(Expression> predicate) + => Task.FromResult(new List()); + + public Task> GetPagedListAsync(BasePagedQuery query) + => Task.FromResult(new PagedResult()); + + public Task> GetPagedListAsync(InventoryPagedQuery query) + => Task.FromResult(new PagedResult()); + + public Task InsertAsync(Inventory entity) + { + entity.Id = entity.Id == 0 ? InsertedEntities.Count + 1 : entity.Id; + InsertedEntities.Add(entity); + return Task.FromResult(entity.Id); + } + + public Task UpdateAsync(Inventory entity) + { + UpdatedEntities.Add(entity); + return Task.FromResult(1); + } + + public Task SoftDeleteAsync(long id) + => Task.FromResult(0); + + public Task SoftDeleteAsync(long id, string tenantId, string ownerCode) + => Task.FromResult(0); + } +} diff --git a/WmsLite.Api.Tests/WmsLite.Api.Tests.csproj b/WmsLite.Api.Tests/WmsLite.Api.Tests.csproj new file mode 100644 index 0000000..fd34598 --- /dev/null +++ b/WmsLite.Api.Tests/WmsLite.Api.Tests.csproj @@ -0,0 +1,25 @@ + + + + net10.0 + enable + enable + false + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/WmsLite.Api/Controllers/OrderControllers.cs b/WmsLite.Api/Controllers/OrderControllers.cs index 1824278..21b9f46 100644 --- a/WmsLite.Api/Controllers/OrderControllers.cs +++ b/WmsLite.Api/Controllers/OrderControllers.cs @@ -80,6 +80,20 @@ public class OutboundOrderController : WmsLiteControllerBase : Ok(BusinessResult.Ok(list)); } + [HttpGet("{id}/pick-tasks")] + public async Task> GetPickTasks(string id) + { + if (!long.TryParse(id.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var orderId)) + { + return Ok(BusinessResult.BadRequest("Invalid id.")); + } + + var list = await _service.GetPickTasksAsync(orderId, TenantId, OwnerCode); + return list is null + ? Ok(BusinessResult.NotFound("Resource not found.")) + : Ok(BusinessResult.Ok(list)); + } + [HttpPost("create")] public async Task> Create([FromBody] OutboundOrderSaveRequest request) => Ok(BusinessResult.Ok(await _service.CreateAsync(request))); diff --git a/WmsLite.Api/Database/migrations/0011_AreaWarehouseHierarchy.cs b/WmsLite.Api/Database/migrations/0011_AreaWarehouseHierarchy.cs index 1fd86ed..7bd7a9b 100644 --- a/WmsLite.Api/Database/migrations/0011_AreaWarehouseHierarchy.cs +++ b/WmsLite.Api/Database/migrations/0011_AreaWarehouseHierarchy.cs @@ -33,12 +33,16 @@ public class AreaWarehouseHierarchy0011 : Migration private void SeedAreasAndBackfillZones() { - if (!Schema.Table("area").Exists() || !Schema.Table("zone").Exists()) + if (!Schema.Table("zone").Exists()) { return; } Execute.Sql(""" + ALTER TABLE zone ADD COLUMN IF NOT EXISTS area_code varchar(64); + UPDATE zone SET area_code = 'DEFAULT' WHERE area_code IS NULL; + ALTER TABLE zone ALTER COLUMN area_code SET NOT NULL; + WITH d AS ( SELECT DISTINCT tenant_id, owner_code, warehouse_code FROM zone @@ -77,10 +81,6 @@ public class AreaWarehouseHierarchy0011 : Migration WHERE NOT a.is_deleted AND a.tenant_id = d.tenant_id AND a.owner_code = d.owner_code AND a.warehouse_code = d.warehouse_code AND a.code = 'DEFAULT'); - ALTER TABLE zone ADD COLUMN IF NOT EXISTS area_code varchar(64); - UPDATE zone SET area_code = 'DEFAULT' WHERE area_code IS NULL; - ALTER TABLE zone ALTER COLUMN area_code SET NOT NULL; - DO $$ BEGIN ALTER TABLE zone ADD CONSTRAINT uq_zone_wh_area_code UNIQUE (tenant_id, owner_code, warehouse_code, area_code, code); EXCEPTION diff --git a/WmsLite.Api/Database/migrations/0015_OutboundAllocationPickTasks.cs b/WmsLite.Api/Database/migrations/0015_OutboundAllocationPickTasks.cs new file mode 100644 index 0000000..7e35f16 --- /dev/null +++ b/WmsLite.Api/Database/migrations/0015_OutboundAllocationPickTasks.cs @@ -0,0 +1,68 @@ +using FluentMigrator; + +namespace WmsLite.Api.Database.Migrations; + +[Migration(15, "Outbound allocation pick tasks")] +public class OutboundAllocationPickTasks0015 : Migration +{ + public override void Up() + { + if (!Schema.Table("outbound_pick_task").Exists()) + { + Create.Table("outbound_pick_task") + .WithBaseColumns() + .WithColumn("order_id").AsInt64().NotNullable() + .WithColumn("order_line_id").AsInt64().NotNullable() + .WithColumn("task_no").AsString(128).NotNullable() + .WithColumn("inventory_id").AsInt64().NotNullable() + .WithColumn("inventory_kind").AsInt32().NotNullable() + .WithColumn("material_code").AsString(64).Nullable() + .WithColumn("container_code").AsString(64).Nullable() + .WithColumn("warehouse_code").AsString(64).NotNullable() + .WithColumn("area_code").AsString(64).NotNullable() + .WithColumn("zone_code").AsString(64).NotNullable() + .WithColumn("location_code").AsString(64).NotNullable() + .WithColumn("qty").AsDecimal().NotNullable() + .WithColumn("picked_qty").AsDecimal().NotNullable().WithDefaultValue(0) + .WithColumn("unit").AsString(32).NotNullable() + .WithColumn("task_status").AsInt32().NotNullable() + .WithColumn("attrs").AsCustom("jsonb").Nullable(); + } + + Execute.Sql(""" + ALTER TABLE outbound_order_line ALTER COLUMN location_code DROP NOT NULL; + + CREATE INDEX IF NOT EXISTS idx_outbound_pick_task_order + ON outbound_pick_task (tenant_id, owner_code, order_id, task_no); + + CREATE INDEX IF NOT EXISTS idx_outbound_pick_task_line + ON outbound_pick_task (tenant_id, owner_code, order_line_id); + + CREATE INDEX IF NOT EXISTS idx_outbound_pick_task_inventory + ON outbound_pick_task (tenant_id, owner_code, inventory_id); + + CREATE UNIQUE INDEX IF NOT EXISTS uq_outbound_pick_task_no + ON outbound_pick_task (tenant_id, owner_code, task_no) WHERE NOT is_deleted; + """); + } + + public override void Down() + { + Execute.Sql(""" + DROP INDEX IF EXISTS uq_outbound_pick_task_no; + DROP INDEX IF EXISTS idx_outbound_pick_task_inventory; + DROP INDEX IF EXISTS idx_outbound_pick_task_line; + DROP INDEX IF EXISTS idx_outbound_pick_task_order; + """); + + if (Schema.Table("outbound_pick_task").Exists()) + { + Delete.Table("outbound_pick_task"); + } + + Execute.Sql(""" + UPDATE outbound_order_line SET location_code = 'DEFAULT' WHERE location_code IS NULL; + ALTER TABLE outbound_order_line ALTER COLUMN location_code SET NOT NULL; + """); + } +} diff --git a/WmsLite.Api/Dtos/Inventory/InventoryAllocationDtos.cs b/WmsLite.Api/Dtos/Inventory/InventoryAllocationDtos.cs new file mode 100644 index 0000000..7b39d1a --- /dev/null +++ b/WmsLite.Api/Dtos/Inventory/InventoryAllocationDtos.cs @@ -0,0 +1,31 @@ +using WmsLite.Api.Enums; + +namespace WmsLite.Api.Dtos.Inventory; + +public class InventoryAllocationRequest +{ + public string TenantId { get; set; } = string.Empty; + + public string OwnerCode { get; set; } = string.Empty; + + public InventoryKind InventoryKind { get; set; } = InventoryKind.Material; + + public string? MaterialCode { get; set; } + + public string? ContainerCode { get; set; } + + public string WarehouseCode { get; set; } = string.Empty; + + public string AreaCode { get; set; } = string.Empty; + + public string? LocationCode { get; set; } + + public decimal Qty { get; set; } +} + +public class InventoryAllocationItem +{ + public required Models.Inventory Inventory { get; init; } + + public decimal Qty { get; init; } +} diff --git a/WmsLite.Api/Dtos/Orders/OrderDtos.cs b/WmsLite.Api/Dtos/Orders/OrderDtos.cs index 525ca83..c316ed9 100644 --- a/WmsLite.Api/Dtos/Orders/OrderDtos.cs +++ b/WmsLite.Api/Dtos/Orders/OrderDtos.cs @@ -190,7 +190,41 @@ public class InboundConfirmLineResultDto public class OutboundOrderSaveRequest : OrderSaveRequestBase { [MinLength(1)] - public List Lines { get; set; } = new(); + public List Lines { get; set; } = new(); +} + +public class OutboundOrderLineRequest +{ + [Required] + [EnumDataType(typeof(InventoryKind))] + public InventoryKind InventoryKind { get; set; } = InventoryKind.Material; + + [StringLength(64)] + public string? MaterialCode { get; set; } + + [StringLength(64)] + public string? ContainerCode { get; set; } + + [Required] + [StringLength(64)] + public string WarehouseCode { get; set; } = string.Empty; + + [Required] + [StringLength(64)] + public string AreaCode { get; set; } = string.Empty; + + /// 可选。为空时由库存分配服务在仓库+库区范围内自动分配;有值时只从指定库位分配。 + [StringLength(64)] + public string? LocationCode { get; set; } + + [Range(typeof(decimal), "0.000001", "9999999999999999")] + public decimal Qty { get; set; } + + [Required] + [StringLength(32)] + public string Unit { get; set; } = string.Empty; + + public Dictionary? Attrs { get; set; } } public class TransferOrderSaveRequest : OrderSaveRequestBase diff --git a/WmsLite.Api/Dtos/Orders/OutboundPickTaskDtos.cs b/WmsLite.Api/Dtos/Orders/OutboundPickTaskDtos.cs new file mode 100644 index 0000000..08ee929 --- /dev/null +++ b/WmsLite.Api/Dtos/Orders/OutboundPickTaskDtos.cs @@ -0,0 +1,41 @@ +using System.Collections.Generic; +using WmsLite.Api.Enums; + +namespace WmsLite.Api.Dtos.Orders; + +public class OutboundPickTaskViewDto +{ + public string Id { get; set; } = string.Empty; + + public string OrderId { get; set; } = string.Empty; + + public string OrderLineId { get; set; } = string.Empty; + + public string TaskNo { get; set; } = string.Empty; + + public string InventoryId { get; set; } = string.Empty; + + public InventoryKind InventoryKind { get; set; } + + public string? MaterialCode { get; set; } + + public string? ContainerCode { get; set; } + + public string WarehouseCode { get; set; } = string.Empty; + + public string AreaCode { get; set; } = string.Empty; + + public string ZoneCode { get; set; } = string.Empty; + + public string LocationCode { get; set; } = string.Empty; + + public decimal Qty { get; set; } + + public decimal PickedQty { get; set; } + + public string Unit { get; set; } = string.Empty; + + public PickTaskStatus TaskStatus { get; set; } + + public Dictionary? Attrs { get; set; } +} diff --git a/WmsLite.Api/Enums/PickTaskStatus.cs b/WmsLite.Api/Enums/PickTaskStatus.cs new file mode 100644 index 0000000..b116398 --- /dev/null +++ b/WmsLite.Api/Enums/PickTaskStatus.cs @@ -0,0 +1,15 @@ +using System.ComponentModel; + +namespace WmsLite.Api.Enums; + +public enum PickTaskStatus +{ + [Description("Open")] + Open = 1, + + [Description("Picked")] + Picked = 2, + + [Description("Cancelled")] + Cancelled = 3 +} diff --git a/WmsLite.Api/Models/OutboundPickTask.cs b/WmsLite.Api/Models/OutboundPickTask.cs new file mode 100644 index 0000000..4a593b4 --- /dev/null +++ b/WmsLite.Api/Models/OutboundPickTask.cs @@ -0,0 +1,57 @@ +using System.Collections.Generic; +using SqlSugar; +using WmsLite.Api.Enums; + +namespace WmsLite.Api.Models; + +[SugarTable("outbound_pick_task")] +public class OutboundPickTask : BaseEntity +{ + [SugarColumn(ColumnName = "order_id", IsNullable = false)] + public long OrderId { get; set; } + + [SugarColumn(ColumnName = "order_line_id", IsNullable = false)] + public long OrderLineId { get; set; } + + [SugarColumn(ColumnName = "task_no", Length = 128, IsNullable = false)] + public string TaskNo { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "inventory_id", IsNullable = false)] + public long InventoryId { get; set; } + + [SugarColumn(ColumnName = "inventory_kind", IsNullable = false)] + public InventoryKind InventoryKind { get; set; } = InventoryKind.Material; + + [SugarColumn(ColumnName = "material_code", Length = 64, IsNullable = true)] + public string? MaterialCode { get; set; } + + [SugarColumn(ColumnName = "container_code", Length = 64, IsNullable = true)] + public string? ContainerCode { get; set; } + + [SugarColumn(ColumnName = "warehouse_code", Length = 64, IsNullable = false)] + public string WarehouseCode { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "area_code", Length = 64, IsNullable = false)] + public string AreaCode { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "zone_code", Length = 64, IsNullable = false)] + public string ZoneCode { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "location_code", Length = 64, IsNullable = false)] + public string LocationCode { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "qty", IsNullable = false)] + public decimal Qty { get; set; } + + [SugarColumn(ColumnName = "picked_qty", IsNullable = false, DefaultValue = "0")] + public decimal PickedQty { get; set; } + + [SugarColumn(ColumnName = "unit", Length = 32, IsNullable = false)] + public string Unit { get; set; } = string.Empty; + + [SugarColumn(ColumnName = "task_status", IsNullable = false)] + public PickTaskStatus TaskStatus { get; set; } = PickTaskStatus.Open; + + [SugarColumn(ColumnName = "attrs", IsJson = true, ColumnDataType = "jsonb", IsNullable = true)] + public Dictionary? Attrs { get; set; } +} diff --git a/WmsLite.Api/Repositories/Interfaces/IInventoryRepository.cs b/WmsLite.Api/Repositories/Interfaces/IInventoryRepository.cs index 5c0cf73..aa5b6b4 100644 --- a/WmsLite.Api/Repositories/Interfaces/IInventoryRepository.cs +++ b/WmsLite.Api/Repositories/Interfaces/IInventoryRepository.cs @@ -20,4 +20,14 @@ public interface IInventoryRepository : IBaseRepository InventoryKind inventoryKind, string? materialCode, string? containerCode); + + Task> GetAllocatableAsync( + string tenantId, + string ownerCode, + string warehouseCode, + string areaCode, + InventoryKind inventoryKind, + string? materialCode, + string? containerCode, + string? locationCode = null); } diff --git a/WmsLite.Api/Repositories/Interfaces/IOrderRepositories.cs b/WmsLite.Api/Repositories/Interfaces/IOrderRepositories.cs index d5a6d98..3b4f6c2 100644 --- a/WmsLite.Api/Repositories/Interfaces/IOrderRepositories.cs +++ b/WmsLite.Api/Repositories/Interfaces/IOrderRepositories.cs @@ -35,6 +35,13 @@ public interface IOutboundOrderLineRepository : IBaseRepository> GetByOrderIdAsync(long orderId); } +public interface IOutboundPickTaskRepository : IBaseRepository +{ + Task> GetByOrderIdAsync(long orderId); + + Task> GetByOrderLineIdAsync(long orderLineId); +} + public interface ITransferOrderRepository : IBaseRepository { Task GetByOrderNoAsync(string tenantId, string ownerCode, string orderNo); diff --git a/WmsLite.Api/Repositories/InventoryRepository.cs b/WmsLite.Api/Repositories/InventoryRepository.cs index 8855149..b141ddd 100644 --- a/WmsLite.Api/Repositories/InventoryRepository.cs +++ b/WmsLite.Api/Repositories/InventoryRepository.cs @@ -107,4 +107,38 @@ public class InventoryRepository : BaseRepository, IInventoryReposito .WhereIF(inventoryKind == InventoryKind.EmptyContainer, x => x.ContainerCode == container) .FirstAsync(); } + + public async Task> GetAllocatableAsync( + string tenantId, + string ownerCode, + string warehouseCode, + string areaCode, + InventoryKind inventoryKind, + string? materialCode, + string? containerCode, + string? locationCode = null) + { + var tenant = tenantId.Trim(); + var owner = ownerCode.Trim(); + var warehouse = warehouseCode.Trim(); + var area = areaCode.Trim(); + var material = string.IsNullOrWhiteSpace(materialCode) ? null : materialCode.Trim(); + var container = string.IsNullOrWhiteSpace(containerCode) ? null : containerCode.Trim(); + var location = string.IsNullOrWhiteSpace(locationCode) ? null : locationCode.Trim(); + + return await Db.Queryable() + .Where(x => !x.IsDeleted + && x.TenantId == tenant + && x.OwnerCode == owner + && x.WarehouseCode == warehouse + && x.AreaCode == area + && x.InventoryKind == inventoryKind + && x.Qty - x.PendingOutboundQty - x.FrozenQty > 0) + .WhereIF(inventoryKind == InventoryKind.Material, x => x.MaterialCode == material) + .WhereIF(inventoryKind == InventoryKind.EmptyContainer, x => x.ContainerCode == container) + .WhereIF(location is not null, x => x.LocationCode == location) + .OrderBy(x => x.CreateTime) + .OrderBy(x => x.Id) + .ToListAsync(); + } } diff --git a/WmsLite.Api/Repositories/OrderRepositories.cs b/WmsLite.Api/Repositories/OrderRepositories.cs index efe97e7..81b1327 100644 --- a/WmsLite.Api/Repositories/OrderRepositories.cs +++ b/WmsLite.Api/Repositories/OrderRepositories.cs @@ -178,6 +178,27 @@ public class OutboundOrderLineRepository : OrderLineRepositoryBase> GetByOrderIdAsync(long orderId) => GetByOrderIdCoreAsync(orderId); } +public class OutboundPickTaskRepository : OrderLineRepositoryBase, IOutboundPickTaskRepository +{ + public OutboundPickTaskRepository(ISqlSugarClient db, ICurrentUserContext userContext) : base(db, userContext) { } + + public async Task> GetByOrderIdAsync(long orderId) + { + return await Db.Queryable() + .Where(x => !x.IsDeleted && x.OrderId == orderId) + .OrderBy(x => x.TaskNo) + .ToListAsync(); + } + + public async Task> GetByOrderLineIdAsync(long orderLineId) + { + return await Db.Queryable() + .Where(x => !x.IsDeleted && x.OrderLineId == orderLineId) + .OrderBy(x => x.TaskNo) + .ToListAsync(); + } +} + public class TransferOrderRepository : OrderRepositoryBase, ITransferOrderRepository { public TransferOrderRepository(ISqlSugarClient db, ICurrentUserContext userContext) : base(db, userContext) { } diff --git a/WmsLite.Api/Services/Interfaces/IInventoryAllocationService.cs b/WmsLite.Api/Services/Interfaces/IInventoryAllocationService.cs new file mode 100644 index 0000000..a9c6265 --- /dev/null +++ b/WmsLite.Api/Services/Interfaces/IInventoryAllocationService.cs @@ -0,0 +1,8 @@ +using WmsLite.Api.Dtos.Inventory; + +namespace WmsLite.Api.Services.Interfaces; + +public interface IInventoryAllocationService +{ + Task> AllocateAsync(InventoryAllocationRequest request); +} diff --git a/WmsLite.Api/Services/Interfaces/IOrderServices.cs b/WmsLite.Api/Services/Interfaces/IOrderServices.cs index 3efe393..69d2d3f 100644 --- a/WmsLite.Api/Services/Interfaces/IOrderServices.cs +++ b/WmsLite.Api/Services/Interfaces/IOrderServices.cs @@ -22,6 +22,8 @@ public interface IOutboundOrderService Task?> GetLinesAsync(long orderId, string tenantId, string ownerCode); + Task?> GetPickTasksAsync(long orderId, string tenantId, string ownerCode); + Task CreateAsync(OutboundOrderSaveRequest request); Task PendingAsync(OrderActionRequest request); diff --git a/WmsLite.Api/Services/InventoryAllocationService.cs b/WmsLite.Api/Services/InventoryAllocationService.cs new file mode 100644 index 0000000..9d2ddfb --- /dev/null +++ b/WmsLite.Api/Services/InventoryAllocationService.cs @@ -0,0 +1,90 @@ +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> 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(); + 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."); + } + } +} diff --git a/WmsLite.Api/Services/OrderServices.cs b/WmsLite.Api/Services/OrderServices.cs index fbaca79..9c4b6fd 100644 --- a/WmsLite.Api/Services/OrderServices.cs +++ b/WmsLite.Api/Services/OrderServices.cs @@ -1,5 +1,6 @@ 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; @@ -570,14 +571,18 @@ 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 IInventoryAllocationService _allocationService; private readonly ICurrentUserContext _userContext; public OutboundOrderService( ITransactionRunner tx, IOutboundOrderRepository orderRepository, IOutboundOrderLineRepository lineRepository, + IOutboundPickTaskRepository pickTaskRepository, ILocationRepository locationRepository, + IInventoryAllocationService allocationService, IInventoryRepository inventoryRepository, IInventoryMovementService inventoryMovementService, ICurrentUserContext userContext) : base(inventoryRepository, inventoryMovementService) @@ -585,7 +590,9 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService _tx = tx; _orderRepository = orderRepository; _lineRepository = lineRepository; + _pickTaskRepository = pickTaskRepository; _locationRepository = locationRepository; + _allocationService = allocationService; _userContext = userContext; } @@ -614,6 +621,19 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService 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 () => @@ -649,10 +669,10 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService ContainerCode = line.InventoryKind == InventoryKind.EmptyContainer ? line.ContainerCode?.Trim() : null, WarehouseCode = line.WarehouseCode.Trim(), AreaCode = line.AreaCode.Trim(), - LocationCode = line.LocationCode.Trim(), + LocationCode = line.LocationCode?.Trim(), Qty = line.Qty, ReceivedQty = 0, - LineStatus = OrderLineStatus.Completed, + LineStatus = OrderLineStatus.Open, Unit = line.Unit.Trim(), Attrs = line.Attrs }); @@ -676,14 +696,70 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService 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( + 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 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); + } + + 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; @@ -703,17 +779,32 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService 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.Open) + { + throw new BusinessException("Only open pick tasks can be confirmed."); + } + + 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); + task.PickedQty = task.Qty; + task.TaskStatus = PickTaskStatus.Picked; + await _pickTaskRepository.UpdateAsync(task); + } + 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); + line.LineStatus = OrderLineStatus.Completed; + await _lineRepository.UpdateAsync(line); } order.OrderStatus = OrderStatus.Completed; @@ -721,6 +812,30 @@ public class OutboundOrderService : OrderServiceBase, IOutboundOrderService 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, + Unit = task.Unit, + TaskStatus = task.TaskStatus, + Attrs = task.Attrs + }; + } } public class TransferOrderService : OrderServiceBase, ITransferOrderService diff --git a/WmsLite.Api/WmsLite.Api.sln b/WmsLite.Api/WmsLite.Api.sln index 41f91fd..1c9ca3c 100644 --- a/WmsLite.Api/WmsLite.Api.sln +++ b/WmsLite.Api/WmsLite.Api.sln @@ -5,6 +5,8 @@ VisualStudioVersion = 17.5.2.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WmsLite.Api", "WmsLite.Api.csproj", "{79190F7B-E86A-BDB4-78EF-7829B20B85B1}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WmsLite.Api.Tests", "..\WmsLite.Api.Tests\WmsLite.Api.Tests.csproj", "{C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -27,6 +29,18 @@ Global {79190F7B-E86A-BDB4-78EF-7829B20B85B1}.Release|x64.Build.0 = Release|Any CPU {79190F7B-E86A-BDB4-78EF-7829B20B85B1}.Release|x86.ActiveCfg = Release|Any CPU {79190F7B-E86A-BDB4-78EF-7829B20B85B1}.Release|x86.Build.0 = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|x64.ActiveCfg = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|x64.Build.0 = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|x86.ActiveCfg = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Debug|x86.Build.0 = Debug|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|Any CPU.Build.0 = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|x64.ActiveCfg = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|x64.Build.0 = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|x86.ActiveCfg = Release|Any CPU + {C9E0FB91-E7B1-4C7C-BF92-0DCE257B2DD3}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/WmsLite.Web/src/components/OrderPage.tsx b/WmsLite.Web/src/components/OrderPage.tsx index 2dbdc03..1a3e54c 100644 --- a/WmsLite.Web/src/components/OrderPage.tsx +++ b/WmsLite.Web/src/components/OrderPage.tsx @@ -16,6 +16,7 @@ import { actionRecord, confirmInboundLine, createRecord, + getOutboundPickTasks, getRecordLines, pagedList, parseJsonObject, @@ -105,6 +106,13 @@ function lineFieldsForKind(kind: OrderKind): LineFieldDef[] { if (kind === 'transfer') return TRANSFER_LINE_FIELDS; if (kind === 'stocktake') return STOCKTAKE_LINE_FIELDS; if (kind === 'inbound') return INBOUND_LINE_FIELDS; + if (kind === 'outbound') { + return IN_OUT_LINE_FIELDS.map((field) => + field.key === 'locationCode' + ? { ...field, title: '指定库位(可选)', required: false, width: 128 } + : field, + ); + } return IN_OUT_LINE_FIELDS; } @@ -169,6 +177,9 @@ function normalizeLinesForSubmit(lines: Record[]) { attrs, inventoryKind: Number(line.inventoryKind ?? 1), }; + if ('locationCode' in next && !String(next.locationCode ?? '').trim()) { + delete next.locationCode; + } if ('qty' in next) next.qty = Number(next.qty); if ('countedQty' in next && next.countedQty !== undefined && next.countedQty !== '') next.countedQty = Number(next.countedQty); @@ -632,6 +643,7 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { const [viewerOpen, setViewerOpen] = useState(false); const [viewerLoading, setViewerLoading] = useState(false); const [viewerLines, setViewerLines] = useState[]>([]); + const [viewerPickTasks, setViewerPickTasks] = useState[]>([]); const [viewerTitle, setViewerTitle] = useState(''); const [confirmOpen, setConfirmOpen] = useState(false); const [confirmLoading, setConfirmLoading] = useState(false); @@ -704,10 +716,14 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { try { const lines = await getRecordLines>(controller, id); setViewerLines(Array.isArray(lines) ? lines : []); + if (kind === 'outbound') { + const tasks = await getOutboundPickTasks>(id); + setViewerPickTasks(Array.isArray(tasks) ? tasks : []); + } } catch { message.error('刷新明细失败'); } - }, [controller]); + }, [controller, kind]); const openConfirmInbound = useCallback( async (line: Record) => { @@ -749,17 +765,23 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { setViewerOpen(true); setViewerLoading(true); setViewerLines([]); + setViewerPickTasks([]); try { const lines = await getRecordLines>(controller, record.id); setViewerLines(Array.isArray(lines) ? lines : []); + if (kind === 'outbound') { + const tasks = await getOutboundPickTasks>(record.id); + setViewerPickTasks(Array.isArray(tasks) ? tasks : []); + } } catch { setViewerLines([]); + setViewerPickTasks([]); message.error('加载明细失败'); } finally { setViewerLoading(false); } }, - [controller], + [controller, kind], ); const viewerCols = useMemo(() => { @@ -796,6 +818,33 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { ]; }, [kind, resolveLabel, openConfirmInbound]); + const pickTaskCols = useMemo( + (): ProColumns>[] => [ + { title: '任务号', dataIndex: 'taskNo', width: 180, ellipsis: true }, + { title: '物料', dataIndex: 'materialCode', width: 120, ellipsis: true }, + { title: '容器', dataIndex: 'containerCode', width: 110, ellipsis: true }, + { title: '仓库', dataIndex: 'warehouseCode', width: 100, ellipsis: true }, + { title: '库区', dataIndex: 'areaCode', width: 88, ellipsis: true }, + { title: '分区', dataIndex: 'zoneCode', width: 88, ellipsis: true }, + { title: '拣货库位', dataIndex: 'locationCode', width: 110, ellipsis: true }, + { title: '应拣', dataIndex: 'qty', width: 88 }, + { title: '已拣', dataIndex: 'pickedQty', width: 88 }, + { title: '单位', dataIndex: 'unit', width: 72 }, + { + title: '状态', + dataIndex: 'taskStatus', + width: 88, + render: (_, row) => { + const s = row.taskStatus; + if (s === 'picked' || s === 'Picked' || s === 2) return '已拣'; + if (s === 'cancelled' || s === 'Cancelled' || s === 3) return '已取消'; + return '待拣'; + }, + }, + ], + [], + ); + const createInitialValues = useMemo( () => kind === 'inbound' @@ -952,7 +1001,7 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { setViewerOpen(false)} @@ -967,6 +1016,24 @@ export default function OrderPage({ title, controller, kind }: OrderPageProps) { dataSource={viewerLines} scroll={{ x: 'max-content' }} /> + {kind === 'outbound' && ( + <> + + 拣货任务 + + > + loading={viewerLoading} + rowKey={(row, i) => String(row.id ?? row.taskNo ?? i)} + search={false} + pagination={false} + options={false} + columns={pickTaskCols} + dataSource={viewerPickTasks} + scroll={{ x: 'max-content' }} + locale={{ emptyText: '待出库单转待拣后生成拣货任务' }} + /> + + )} (controller: string, id: string | number) }); } +export async function getOutboundPickTasks(id: string | number): Promise { + const segment = encodeURIComponent(String(orderIdToApiValue(id))); + return apiRequest(`/api/OutboundOrder/${segment}/pick-tasks`, { + method: 'GET', + }); +} + export function parseJsonObject( value?: string, fallback: any = undefined, diff --git a/docs/DEVELOPMENT_PLAN.md b/docs/DEVELOPMENT_PLAN.md new file mode 100644 index 0000000..6fdd53e --- /dev/null +++ b/docs/DEVELOPMENT_PLAN.md @@ -0,0 +1,236 @@ +# WmsLite 开发路线 + +本文档记录 WmsLite 从当前轻量 WMS 核心闭环,演进到中小型多货主标准 WMS 核心系统的后续开发计划。 + +## 目标定位 + +短期目标:从“基础库存与单据系统”升级为“可支撑真实仓库基础作业的标准 WMS 核心底座”。 + +完成本阶段后,系统应达到约 L3 级 WMS 核心能力: + +| 等级 | 标准 | 说明 | +|------|------|------| +| L1 | 库存台账系统 | 有物料、库位、库存余额、流水,能手工出入库 | +| L2 | 基础 WMS | 有标准入库、出库、移库、盘点流程,有库存预占和状态流转 | +| L3 | 标准 WMS 核心 | 有任务化作业、批次效期、策略分配、异常冲正、容器/LPN | +| L4 | 行业化 WMS | 支持电商、医药、冷链、制造、3PL 等行业特性 | +| L5 | 高级仓储执行平台 | 波次优化、路径优化、自动化设备、RF/PDA、计费、接口平台、BI | + +## 8 项后端核心改造 + +### 当前进展 + +- 已完成第一版出库库存分配:出库明细可只表达仓库、库区、物料和数量,系统在转待拣时自动按可用库存 FIFO 分配。 +- 已完成第一版拣货任务:出库转待拣时生成 `outbound_pick_task`,确认出库时按任务扣减库存并标记已拣。 +- 已保留兼容能力:出库明细填写指定库位时,只从该库位分配库存。 + +### 1. 入库流程标准化 + +当前入库流程接近“创建入库单后直接按行确认收货”。标准 WMS 需要拆分更细的作业阶段。 + +建议演进为: + +- 入库预约或到货登记 +- 收货确认 +- 质检,可配置启用 +- 上架任务生成 +- 上架确认 +- 入库完成 + +关键目标: + +- 入库确认不应总是直接进入最终库位。 +- 支持收货暂存区。 +- 支持后续扩展质检、拒收、部分收货、超收、短收。 + +### 2. 出库流程任务化 + +当前出库可以完成预占和确认扣减,但仍偏单据层。标准 WMS 需要引入任务层。 + +建议演进为: + +- 出库单创建 +- 库存分配或预占 +- 拣货任务生成 +- 拣货确认 +- 复核,可后续扩展 +- 打包,可后续扩展 +- 发运确认 +- 库存扣减 + +关键目标: + +- 单据负责业务意图。 +- 任务负责仓内执行。 +- 出库确认前应能追踪每个拣货任务的执行状态。 + +### 3. 库存分配策略抽象 + +当前库存分配逻辑不宜继续写死在出库服务中。多行业 WMS 需要可扩展策略。 + +建议新增库存分配服务,例如: + +```text +InventoryAllocationService +``` + +优先支持策略: + +- FIFO,先进先出 +- FEFO,近效期优先 +- 指定批次 +- 指定库区或库位 +- 可用库存优先,排除冻结、待出、不合格库存 +- 整箱优先或拆零优先 + +关键目标: + +- 出库单只表达需求。 +- 分配服务决定从哪些库存行、哪些库位扣减或预占。 +- 策略可配置、可替换、可测试。 + +### 4. 移库流程分层 + +当前移库更接近即时从 A 扣到 B 加。标准 WMS 需要支持计划移库和任务移库。 + +建议演进为: + +- 移库单创建 +- 移库任务生成 +- 来源库位下架确认 +- 在途库存或任务占用 +- 目标库位上架确认 +- 移库完成 + +关键目标: + +- 支持移库中断、取消和异常处理。 +- 支持下架完成但尚未上架的中间状态。 +- 支持按任务追踪操作人、时间、来源和目标。 + +### 5. 库存维度增强 + +当前库存维度主要是仓库、库区、分区、库位、物料、容器。多行业标准 WMS 需要更完整的库存属性。 + +建议补充: + +- 批次号 +- 生产日期 +- 失效日期 +- 质量状态:合格、待检、不合格、冻结 +- 序列号,适用于 3C、设备、高价值品 +- 包装单位换算:箱、包、件、托 +- 供应商批次 +- 客户批次 +- 货主 SKU 与平台 SKU 映射 + +关键目标: + +- 库存唯一键需要重新设计,不能只依赖物料和库位。 +- 库存流水必须保留完整库存属性快照。 +- 出库分配策略要能读取批次、效期、质量状态。 + +### 6. 容器/LPN 体系增强 + +当前系统已有 Container,但还不是完整 LPN 或托盘管理体系。 + +建议增强为: + +- LPN 编码管理 +- LPN 与物料、批次、数量绑定 +- 整托移动 +- 托盘拆分 +- 托盘合并 +- 容器状态管理 +- 容器当前位置 +- 单 SKU 容器和混 SKU 容器规则 + +关键目标: + +- 支持按容器移动库存。 +- 支持整托入库、整托出库、整托移库。 +- 容器变更必须写库存流水或容器流水。 + +### 7. 异常、撤销与冲正机制 + +标准 WMS 必须支持业务纠错,不能只做正向流程。 + +建议补充: + +- 入库确认后撤销 +- 出库预占释放 +- 出库确认冲正 +- 拣货短拣 +- 移库任务取消 +- 移库中断恢复 +- 库存调整审批,可后续扩展 +- 库存流水冲正 +- 单据取消释放占用 +- 并发确认防重复扣减 + +关键目标: + +- 历史流水不可物理删除。 +- 错误库存变动通过冲正流水修复。 +- 单据状态流转必须具备幂等和并发保护。 + +### 8. 后端测试体系补强 + +已新增库存移动服务单元测试,下一步应覆盖订单服务和关键业务闭环。 + +优先测试范围: + +- 入库确认生成库存和库存流水 +- 出库 pending 预占库存 +- 出库 confirm 扣减库存 +- 出库库存不足失败 +- 移库 pending 后来源库存占用 +- 移库 confirm 后来源扣减、目标增加 +- 单据状态非法流转失败 +- 重复请求或重复确认不会重复扣减库存 +- 租户和货主隔离 + +关键目标: + +- 业务服务层必须有单元测试。 +- 关键 API 应增加集成测试。 +- 库存数量、状态、流水三者必须一起断言。 + +## 建议实施顺序 + +1. 补订单服务测试,确保现有逻辑可安全演进。 +2. 抽象库存分配服务,为出库任务化做准备。 +3. 改造出库流程,引入拣货任务。 +4. 改造入库流程,引入收货暂存和上架任务。 +5. 改造移库流程,引入移库任务和在途状态。 +6. 扩展库存维度,加入批次、效期、质量状态。 +7. 增强容器/LPN 能力。 +8. 补撤销、冲正、异常恢复和并发保护。 + +## 阶段完成标准 + +本阶段完成后,系统应具备: + +- 多货主、多仓、多库区、多库位基础能力 +- 入库、出库、移库、盘点标准闭环 +- 库存预占、释放、扣减、调整、冻结、冲正 +- 基础批次、效期、质量状态管理 +- 基础任务化作业:上架、拣货、移库 +- 基础库存分配策略:FIFO、FEFO、库区优先级 +- 初级容器/LPN 管理 +- 可追溯库存流水 +- 核心业务服务测试覆盖 + +## 尚未覆盖的高级能力 + +以下能力属于后续 L4/L5 阶段,不纳入本阶段必做范围: + +- RF/PDA 作业端 +- 波次策略和拣货路径优化 +- 深度复核、打包、称重、发运交接 +- 自动化设备接口 +- 3PL 计费 +- OMS、ERP、TMS 对接 +- 医药 GSP、冷链温控、危化品等行业合规模块 +- 高级报表、BI、运营 KPI +- 细粒度组织、角色、菜单、按钮权限