diff --git a/sql/migrate_warehouse_rent_lot_backfill_20261115.sql b/sql/migrate_warehouse_rent_lot_backfill_20261115.sql new file mode 100644 index 0000000..5a77f79 --- /dev/null +++ b/sql/migrate_warehouse_rent_lot_backfill_20261115.sql @@ -0,0 +1,89 @@ +# migrate_warehouse_rent_lot_backfill_20261115.sql +# backfill c_warehouse_rent_lot from c_inventory gaps (idempotent by gap qty) +# inbound age approx = inventory CreateTime; UnitCbm from c_sku dims +# no UNIQUE KEY + +SET @db := DATABASE(); + +SET @inv := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_inventory' +); +SET @lot := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_warehouse_rent_lot' +); +SET @sku := ( + SELECT COUNT(1) FROM information_schema.TABLES + WHERE TABLE_SCHEMA = @db AND TABLE_NAME = 'c_sku' +); + +SET @sql := IF( + @inv > 0 AND @lot > 0 AND @sku > 0, + 'INSERT INTO `c_warehouse_rent_lot` ( + `CustomerId`, `WarehouseId`, `SkuId`, `BinLocationId`, `InboundTime`, + `RemainQty`, `UnitCbm`, `SourceType`, `SourceId`, + `IsDeleted`, `CreateUserId`, `CreateTime` + ) + SELECT + i.`CustomerId`, + i.`WarehouseId`, + i.`SkuId`, + i.`BinLocationId`, + IFNULL(i.`CreateTime`, NOW()) AS `InboundTime`, + (i.`Qty` - IFNULL(l.`LotQty`, 0)) AS `RemainQty`, + CASE + WHEN s.`LengthCm` IS NOT NULL AND s.`LengthCm` > 0 + AND s.`WidthCm` IS NOT NULL AND s.`WidthCm` > 0 + AND s.`HeightCm` IS NOT NULL AND s.`HeightCm` > 0 + THEN ROUND(s.`LengthCm` * s.`WidthCm` * s.`HeightCm` / 1000000, 6) + ELSE 0 + END AS `UnitCbm`, + ''backfill'' AS `SourceType`, + i.`Id` AS `SourceId`, + 0 AS `IsDeleted`, + 0 AS `CreateUserId`, + NOW() AS `CreateTime` + FROM `c_inventory` i + LEFT JOIN `c_sku` s + ON s.`Id` = i.`SkuId` AND IFNULL(s.`IsDeleted`, 0) = 0 + LEFT JOIN ( + SELECT + `CustomerId`, + `WarehouseId`, + `SkuId`, + IFNULL(`BinLocationId`, 0) AS `BinLocationId`, + SUM(`RemainQty`) AS `LotQty` + FROM `c_warehouse_rent_lot` + WHERE IFNULL(`IsDeleted`, 0) = 0 + AND `RemainQty` > 0 + GROUP BY `CustomerId`, `WarehouseId`, `SkuId`, IFNULL(`BinLocationId`, 0) + ) l + ON l.`CustomerId` = i.`CustomerId` + AND l.`WarehouseId` = i.`WarehouseId` + AND l.`SkuId` = i.`SkuId` + AND l.`BinLocationId` = i.`BinLocationId` + WHERE IFNULL(i.`IsDeleted`, 0) = 0 + AND i.`Qty` > 0 + AND (i.`Qty` - IFNULL(l.`LotQty`, 0)) > 0', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +# refresh UnitCbm=0 lots when SKU dims exist +SET @sql := IF( + @lot > 0 AND @sku > 0, + 'UPDATE `c_warehouse_rent_lot` lot + INNER JOIN `c_sku` s + ON s.`Id` = lot.`SkuId` AND IFNULL(s.`IsDeleted`, 0) = 0 + SET lot.`UnitCbm` = ROUND(s.`LengthCm` * s.`WidthCm` * s.`HeightCm` / 1000000, 6), + lot.`UpdateTime` = NOW() + WHERE IFNULL(lot.`IsDeleted`, 0) = 0 + AND lot.`RemainQty` > 0 + AND IFNULL(lot.`UnitCbm`, 0) <= 0 + AND s.`LengthCm` IS NOT NULL AND s.`LengthCm` > 0 + AND s.`WidthCm` IS NOT NULL AND s.`WidthCm` > 0 + AND s.`HeightCm` IS NOT NULL AND s.`HeightCm` > 0', + 'SELECT 1' +); +PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; diff --git a/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs b/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs index dcac6b7..4ee90a5 100644 --- a/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs +++ b/src/Oms.Application/Dtos/Warehouse/WarehouseRentDtos.cs @@ -151,3 +151,35 @@ public class WarehouseRentRunBillingInput /// 业务日,默认昨日。 public DateTime? BillDate { get; set; } } + +/// +/// 存量库存反灌仓租批次入参。 +/// +public class WarehouseRentLotBackfillInput +{ + /// 可选:仅反灌指定客户。 + public int? CustomerId { get; set; } + + /// 可选:仅反灌指定仓库。 + public int? WarehouseId { get; set; } + + /// + /// 同时把 UnitCbm=0 且 SKU 已有尺寸的存量 lot 回刷体积。默认 true。 + /// + public bool RefreshMissingUnitCbm { get; set; } = true; +} + +/// +/// 存量反灌结果。 +/// +public class WarehouseRentLotBackfillOutput +{ + /// 新建 lot 条数。 + public int CreatedLots { get; set; } + + /// 新建 lot 件数合计。 + public int CreatedQty { get; set; } + + /// 回刷 UnitCbm 的 lot 条数。 + public int RefreshedLots { get; set; } +} diff --git a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs index f6003f9..acda47b 100644 --- a/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs +++ b/src/Oms.Application/Services/Orders/PlatformStoreOrderService.cs @@ -40,6 +40,8 @@ public class PlatformStoreOrderService : ApplicationService LazyServiceProvider.GetRequiredService(); private WarehouseRentLotManager RentLotManager => LazyServiceProvider.GetRequiredService(); + private WarehouseRentGuard RentGuard => + LazyServiceProvider.GetRequiredService(); /// /// 查询店铺订单列表。 @@ -938,6 +940,11 @@ public class PlatformStoreOrderService : ApplicationService private async Task RestoreInventoryAsync(int customerId, int warehouseId, IReadOnlyCollection deductions) { + if (deductions.Count > 0) + { + await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId); + } + foreach (var item in deductions) { var inventory = await InventoryRepository.FirstOrDefaultAsync(x => diff --git a/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs b/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs index 2d4c009..bb2029a 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseRentService.cs @@ -1,6 +1,7 @@ using System.Linq.Expressions; using Fake.Application; using Microsoft.AspNetCore.Mvc; +using Microsoft.Extensions.Logging; using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.Warehouse; @@ -33,6 +34,8 @@ public class WarehouseRentService : ApplicationService LazyServiceProvider.GetRequiredService(); private ICWarehouseRentBillLineRepository BillLineRepository => LazyServiceProvider.GetRequiredService(); + private ICInventoryRepository InventoryRepository => + LazyServiceProvider.GetRequiredService(); private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService(); private ICustomerRepository CustomerRepository => LazyServiceProvider.GetRequiredService(); @@ -40,6 +43,10 @@ public class WarehouseRentService : ApplicationService LazyServiceProvider.GetRequiredService(); private CustomerBalanceMutator BalanceMutator => LazyServiceProvider.GetRequiredService(); + private WarehouseRentLotManager LotManager => + LazyServiceProvider.GetRequiredService(); + private ILogger RentLogger => + LazyServiceProvider.GetRequiredService>(); /// /// 分页查询仓租费率。 @@ -255,6 +262,98 @@ public class WarehouseRentService : ApplicationService }; } + /// + /// 按现库存缺口反灌仓租批次(可重复执行);可选回刷缺尺寸 lot 的 UnitCbm。 + /// + [HttpPost("/warehouse/storage-rent/lot/backfill")] + public async Task BackfillLotsAsync(WarehouseRentLotBackfillInput input) + { + var hasCustomer = input.CustomerId is > 0; + var customerId = input.CustomerId.GetValueOrDefault(); + var hasWarehouse = input.WarehouseId is > 0; + var warehouseId = input.WarehouseId.GetValueOrDefault(); + + var inventories = await InventoryRepository.GetListAsync(x => + x.Qty > 0 + && (!hasCustomer || x.CustomerId == customerId) + && (!hasWarehouse || x.WarehouseId == warehouseId)); + + var createdLots = 0; + var createdQty = 0; + foreach (var inv in inventories) + { + var binId = inv.BinLocationId; + var lots = await LotRepository.GetListAsync(x => + x.CustomerId == inv.CustomerId + && x.WarehouseId == inv.WarehouseId + && x.SkuId == inv.SkuId + && x.RemainQty > 0 + && x.BinLocationId == binId); + var lotQty = lots.Sum(x => x.RemainQty); + var gap = inv.Qty - lotQty; + if (gap <= 0) + { + continue; + } + + var sku = await SkuRepository.FirstOrDefaultAsync(x => x.Id == inv.SkuId); + var inboundTime = inv.CreateTime == default ? DateTime.Now : inv.CreateTime; + await LotRepository.InsertAsync(new CWarehouseRentLot + { + CustomerId = inv.CustomerId, + WarehouseId = inv.WarehouseId, + SkuId = inv.SkuId, + BinLocationId = binId, + InboundTime = inboundTime, + RemainQty = gap, + UnitCbm = WarehouseRentLotManager.CalcUnitCbm(sku), + SourceType = WarehouseRentLotSourceCodes.Backfill, + SourceId = inv.Id + }); + createdLots++; + createdQty += gap; + } + + var refreshedLots = 0; + if (input.RefreshMissingUnitCbm) + { + var zeroLots = await LotRepository.GetListAsync(x => + x.RemainQty > 0 + && x.UnitCbm <= 0 + && (!hasCustomer || x.CustomerId == customerId) + && (!hasWarehouse || x.WarehouseId == warehouseId)); + var skuIds = zeroLots.Select(x => x.SkuId).Distinct().ToArray(); + var skus = skuIds.Length == 0 + ? [] + : await SkuRepository.GetListAsync(x => skuIds.Contains(x.Id)); + var skuMap = skus.ToDictionary(x => x.Id); + foreach (var lot in zeroLots) + { + if (!skuMap.TryGetValue(lot.SkuId, out var sku)) + { + continue; + } + + var cbm = WarehouseRentLotManager.CalcUnitCbm(sku); + if (cbm <= 0) + { + continue; + } + + lot.UnitCbm = cbm; + await LotRepository.UpdateAsync(lot); + refreshedLots++; + } + } + + return new WarehouseRentLotBackfillOutput + { + CreatedLots = createdLots, + CreatedQty = createdQty, + RefreshedLots = refreshedLots + }; + } + /// /// 日终结算入口:按客户+仓库生成昨日账单并尝试扣款。 /// @@ -287,7 +386,7 @@ public class WarehouseRentService : ApplicationService } /// - /// 对单个客户+仓库执行指定业务日仓租结算(幂等)。 + /// 对单个客户+仓库执行指定业务日仓租结算(幂等;MySQL 命名锁防双单)。 /// public async Task RunDailyBillingForOwnerAsync( int customerId, @@ -296,31 +395,50 @@ public class WarehouseRentService : ApplicationService CancellationToken cancellationToken = default) { billDate = billDate.Date; - var existing = await BillRepository.FirstOrDefaultAsync(x => - x.CustomerId == customerId - && x.WarehouseId == warehouseId - && x.BillDate == billDate); - - if (existing != null) + var lockName = $"wr_bill_{customerId}_{warehouseId}_{billDate:yyyyMMdd}"; + if (lockName.Length > 64) { - if (existing.Status == WarehouseRentBillStatusCodes.Unpaid) + lockName = lockName[..64]; + } + + var acquired = await BillRepository.TryAcquireBillingLockAsync(lockName, 15, cancellationToken); + if (!acquired) + { + return; + } + + try + { + var existing = await BillRepository.FirstOrDefaultAsync(x => + x.CustomerId == customerId + && x.WarehouseId == warehouseId + && x.BillDate == billDate); + + if (existing != null) { - await TryDebitBillAsync(existing, cancellationToken); + if (existing.Status == WarehouseRentBillStatusCodes.Unpaid) + { + await TryDebitBillAsync(existing, cancellationToken); + } + + return; } - return; - } + var lots = await LotRepository.GetListAsync(x => + x.CustomerId == customerId + && x.WarehouseId == warehouseId + && x.RemainQty > 0); + if (lots.Count == 0) + { + return; + } - var lots = await LotRepository.GetListAsync(x => - x.CustomerId == customerId - && x.WarehouseId == warehouseId - && x.RemainQty > 0); - if (lots.Count == 0) + await CreateAndPayBillAsync(customerId, warehouseId, billDate, lots, cancellationToken); + } + finally { - return; + await BillRepository.ReleaseBillingLockAsync(lockName, cancellationToken); } - - await CreateAndPayBillAsync(customerId, warehouseId, billDate, lots, cancellationToken); } private async Task CreateAndPayBillAsync( @@ -334,6 +452,9 @@ public class WarehouseRentService : ApplicationService var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == warehouseId); var warehouseName = warehouse?.WarehouseName; + // 日结前尽量用最新 SKU 尺寸回刷 0 体积批次 + await LotManager.RefreshUnitCbmForLotsAsync(lots, cancellationToken); + var lineDrafts = new List<(CWarehouseRentLot Lot, int AgeDays, decimal Cbm, bool MissingDim)>(); decimal totalCbm = 0; foreach (var lot in lots) @@ -347,26 +468,36 @@ public class WarehouseRentService : ApplicationService totalCbm = Math.Round(totalCbm, 6, MidpointRounding.AwayFromZero); - // 体积段按客户当日该仓总 CBM 匹配;天数按各 lot 库龄分别取价后对明细分摊 - // 简化:同一客户仓使用「最大库龄」匹配天数段(保守,偏高龄段),再 × 总 CBM - // 更精确:按 lot 分别匹配后汇总。采用按 lot 匹配并累加。 + // 体积段:客户当日该仓总 CBM;天数:各 lot 库龄分别取价后累加 var rateBundles = await LoadEnabledRateBundlesAsync(); decimal amount = 0; decimal? sampleUnitPrice = null; var lineEntities = new List(); + var unmatchedRateLines = 0; foreach (var draft in lineDrafts) { - var unitPrice = WarehouseRentCalculator.MatchUnitPrice( + var matched = WarehouseRentCalculator.MatchUnitPrice( rateBundles, warehouseId, warehouseName, draft.AgeDays, totalCbm, - customer?.PriceTierKey) ?? 0M; - sampleUnitPrice ??= unitPrice; + customer?.PriceTierKey); + var unitPrice = matched ?? 0M; + if (!matched.HasValue && !draft.MissingDim && draft.Cbm > 0) + { + unmatchedRateLines++; + } + + sampleUnitPrice ??= matched; var lineAmount = Math.Round(draft.Cbm * unitPrice, 2, MidpointRounding.AwayFromZero); amount += lineAmount; + var lineRemark = draft.MissingDim + ? "SKU 缺尺寸,体积计 0" + : matched is null && draft.Cbm > 0 + ? "未命中仓租费率" + : null; lineEntities.Add(new CWarehouseRentBillLine { LotId = draft.Lot.Id, @@ -377,11 +508,40 @@ public class WarehouseRentService : ApplicationService UnitPrice = unitPrice, Amount = lineAmount, MissingDimension = draft.MissingDim, - Remark = draft.MissingDim ? "SKU 缺尺寸,体积计 0" : null + Remark = lineRemark }); } amount = Math.Round(amount, 2, MidpointRounding.AwayFromZero); + var missingDimLines = lineDrafts.Count(x => x.MissingDim); + var remarkParts = new List(); + if (missingDimLines > 0) + { + remarkParts.Add($"缺尺寸明细 {missingDimLines} 行"); + } + + if (unmatchedRateLines > 0) + { + remarkParts.Add($"未命中费率 {unmatchedRateLines} 行"); + } + + if (amount <= 0) + { + remarkParts.Add(remarkParts.Count == 0 ? "应付为 0" : "应付为 0(请核缺尺寸/费率)"); + } + + if (missingDimLines > 0 || unmatchedRateLines > 0) + { + RentLogger.LogWarning( + "仓租日结告警:客户 {CustomerId} 仓 {WarehouseId} 日 {BillDate:yyyy-MM-dd} 缺尺寸 {Missing} 未命中费率 {Unmatched} 金额 {Amount}", + customerId, + warehouseId, + billDate, + missingDimLines, + unmatchedRateLines, + amount); + } + var bill = new CWarehouseRentBill { BillNo = await GenerateBillNoAsync(cancellationToken), @@ -393,7 +553,7 @@ public class WarehouseRentService : ApplicationService Currency = "CNY", UnitPrice = sampleUnitPrice, Status = amount <= 0 ? WarehouseRentBillStatusCodes.Zero : WarehouseRentBillStatusCodes.Pending, - Remark = amount <= 0 ? "应付为 0" : null + Remark = remarkParts.Count == 0 ? null : string.Join(";", remarkParts) }; await BillRepository.InsertAsync(bill, cancellationToken); diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs index ea44a61..247c6b4 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Helpers.cs @@ -1,5 +1,6 @@ using Fake.Application; using Oms.Application.Shared; +using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Entities; namespace Oms.Application.Services.Warehouse; @@ -34,12 +35,16 @@ public partial class WarehouseService return entity; } + // syncRentLot=true 时同步仓租影子账;移库等已自行维护 lot 的路径保持 false private async Task UpsertInventoryQtyAsync( int customerId, int warehouseId, int skuId, int binLocationId, - int deltaQty) + int deltaQty, + bool syncRentLot = false, + string rentSourceType = WarehouseRentLotSourceCodes.Inbound, + int rentSourceId = 0) { if (deltaQty == 0) { @@ -69,6 +74,18 @@ public partial class WarehouseService AvailableQty = deltaQty }; await InventoryRepository.InsertAsync(inventory); + if (syncRentLot) + { + await RentLotManager.AddLotAsync( + customerId, + warehouseId, + skuId, + binLocationId, + deltaQty, + rentSourceType, + rentSourceId); + } + return; } @@ -86,6 +103,32 @@ public partial class WarehouseService inventory.Qty = newQty; inventory.AvailableQty = Math.Max(0, inventory.Qty - inventory.FrozenQty); await InventoryRepository.UpdateAsync(inventory); + + if (!syncRentLot) + { + return; + } + + if (deltaQty > 0) + { + await RentLotManager.AddLotAsync( + customerId, + warehouseId, + skuId, + binLocationId, + deltaQty, + rentSourceType, + rentSourceId); + } + else + { + await RentLotManager.DeductFifoAsync( + customerId, + warehouseId, + skuId, + -deltaQty, + binLocationId); + } } private async Task DeductInventoryAsync( @@ -125,6 +168,7 @@ public partial class WarehouseService row.AvailableQty = Math.Max(0, row.Qty - row.FrozenQty); remaining -= deduct; await InventoryRepository.UpdateAsync(row); + // 影子账不足只记日志,库存仍按实物扣;避免出库被仓租账卡住 await RentLotManager.DeductFifoAsync( customerId, warehouseId, diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs index ef53b63..e3761e9 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Inbound.cs @@ -273,6 +273,7 @@ public partial class WarehouseService public async Task ConfirmInboundReceiveAsync(WarehouseInboundConfirmReceiveInput input) { var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId); + await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId); var notice = await GetInboundNoticeOrThrowAsync(customerId, input.InboundNoticeId); if (notice.ReceiptStatus == WarehouseReceiptStatusCodes.Completed) { @@ -322,22 +323,22 @@ public partial class WarehouseService line.BinLocationId = lineInput.ReceivedQty > 0 ? lineInput.BinLocationId : null; await InboundBoxLineRepository.UpdateAsync(line); - if (deltaQty > 0) + if (deltaQty != 0) { + var binId = deltaQty > 0 + ? lineInput.BinLocationId + : (lineInput.BinLocationId > 0 + ? lineInput.BinLocationId + : line.BinLocationId.GetValueOrDefault()); await UpsertInventoryQtyAsync( customerId, notice.WarehouseId, line.SkuId, - lineInput.BinLocationId, - deltaQty); - await RentLotManager.AddLotAsync( - customerId, - notice.WarehouseId, - line.SkuId, - lineInput.BinLocationId, + binId, deltaQty, - WarehouseRentLotSourceCodes.Inbound, - notice.Id); + syncRentLot: true, + rentSourceType: WarehouseRentLotSourceCodes.Inbound, + rentSourceId: notice.Id); } } diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs index 14cd4aa..fec8437 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Parcel.cs @@ -280,6 +280,7 @@ public partial class WarehouseService public async Task PutawayParcelAsync(WarehouseParcelPutawayInput input) { var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId); + await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId); var parcel = await GetParcelOrThrowAsync(customerId, input.ParcelId); if (parcel.LifecycleStatus == WarehouseParcelLifecycleCodes.Stored) { @@ -313,19 +314,14 @@ public partial class WarehouseService await ParcelItemRepository.UpdateAsync(item); await UpsertInventoryQtyAsync( - customerId, - parcel.WarehouseId, - sku.Id, - putawayItem.BinLocationId, - item.Quantity); - await RentLotManager.AddLotAsync( customerId, parcel.WarehouseId, sku.Id, putawayItem.BinLocationId, item.Quantity, - WarehouseRentLotSourceCodes.Parcel, - parcel.Id); + syncRentLot: true, + rentSourceType: WarehouseRentLotSourceCodes.Parcel, + rentSourceId: parcel.Id); } parcel.LifecycleStatus = WarehouseParcelLifecycleCodes.Stored; diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs index 599c21b..fb24e4b 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.Sku.cs @@ -159,6 +159,12 @@ public partial class WarehouseService await SkuRepository.InsertAsync(entity); } + // SKU 补尺寸后回刷在库仓租批次体积,避免日结继续按 0 CBM 漏收 + if (entity.Id > 0) + { + await RentLotManager.RefreshUnitCbmForSkuAsync(entity.Id); + } + return MapSkuOutput(entity, null); } diff --git a/src/Oms.Application/Services/Warehouse/WarehouseService.cs b/src/Oms.Application/Services/Warehouse/WarehouseService.cs index c07e256..af8ab71 100644 --- a/src/Oms.Application/Services/Warehouse/WarehouseService.cs +++ b/src/Oms.Application/Services/Warehouse/WarehouseService.cs @@ -32,4 +32,6 @@ public partial class WarehouseService : ApplicationService private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService(); private WarehouseRentLotManager RentLotManager => LazyServiceProvider.GetRequiredService(); + private WarehouseRentGuard RentGuard => + LazyServiceProvider.GetRequiredService(); } diff --git a/src/Oms.Application/Shared/WarehouseRentCalculator.cs b/src/Oms.Application/Shared/WarehouseRentCalculator.cs index 0078520..a9201ed 100644 --- a/src/Oms.Application/Shared/WarehouseRentCalculator.cs +++ b/src/Oms.Application/Shared/WarehouseRentCalculator.cs @@ -51,12 +51,25 @@ public static class WarehouseRentCalculator continue; } - if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Days, "天数", ageDays, out var daysWidth)) + // 库龄按整数天闭区间 [start,end];体积仍沿用运费左开右闭 + if (!MatchIntervalFactor( + factors, + WarehouseRentFactorCodes.Days, + "天数", + ageDays, + inclusiveBounds: true, + out var daysWidth)) { continue; } - if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Volume, "体积", totalCbm, out var volumeWidth)) + if (!MatchIntervalFactor( + factors, + WarehouseRentFactorCodes.Volume, + "体积", + totalCbm, + inclusiveBounds: false, + out var volumeWidth)) { continue; } @@ -133,6 +146,7 @@ public static class WarehouseRentCalculator string code, string label, decimal value, + bool inclusiveBounds, out int widthScore) { widthScore = 0; @@ -146,13 +160,12 @@ public static class WarehouseRentCalculator return false; } - if (!ParcelBillingCalculator.WeightInLeftOpenRightClosedInterval(value, start, end)) + var matched = inclusiveBounds + ? value >= start && value <= end + : ParcelBillingCalculator.WeightInLeftOpenRightClosedInterval(value, start, end); + if (!matched) { - // 天数允许 0:左开右闭时 0 不会命中 (0-N],对 ageDays=0 特判落入起点为 0 的区间 - if (!(value == 0 && start == 0 && end > 0 && value <= end)) - { - return false; - } + return false; } widthScore = (int)Math.Min(int.MaxValue, Math.Round((end - start) * 1000M)); diff --git a/src/Oms.Application/Shared/WarehouseRentGuard.cs b/src/Oms.Application/Shared/WarehouseRentGuard.cs new file mode 100644 index 0000000..6cee72d --- /dev/null +++ b/src/Oms.Application/Shared/WarehouseRentGuard.cs @@ -0,0 +1,41 @@ +using Fake.Application; +using Fake.DependencyInjection; +using Oms.Domain.WarehouseAggregate.Consts; +using Oms.Domain.WarehouseAggregate.Repositories; + +namespace Oms.Application.Shared; + +/// +/// 仓租业务守卫:欠费拦截等。 +/// +public class WarehouseRentGuard : IScopedDependency +{ + private readonly ICWarehouseRentBillRepository _billRepository; + + public WarehouseRentGuard(ICWarehouseRentBillRepository billRepository) + { + _billRepository = billRepository; + } + + /// + /// 客户存在 unpaid 仓租账单时禁止继续入库/上架(避免欠费滚大)。 + /// 出库/移库不拦截。 + /// + public async Task EnsureNoUnpaidStorageRentAsync( + int customerId, + CancellationToken cancellationToken = default) + { + if (customerId <= 0) + { + return; + } + + var hasUnpaid = await _billRepository.AnyAsync( + x => x.CustomerId == customerId && x.Status == WarehouseRentBillStatusCodes.Unpaid, + cancellationToken); + if (hasUnpaid) + { + throw new BusinessException("客户存在未结清仓租账单,请先到仓租日账单补扣后再入库/上架"); + } + } +} diff --git a/src/Oms.Application/Shared/WarehouseRentLotManager.cs b/src/Oms.Application/Shared/WarehouseRentLotManager.cs index 35eb2bb..9741af2 100644 --- a/src/Oms.Application/Shared/WarehouseRentLotManager.cs +++ b/src/Oms.Application/Shared/WarehouseRentLotManager.cs @@ -1,4 +1,5 @@ using Fake.DependencyInjection; +using Microsoft.Extensions.Logging; using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Entities; using Oms.Domain.WarehouseAggregate.Repositories; @@ -12,13 +13,16 @@ public class WarehouseRentLotManager : IScopedDependency { private readonly ICWarehouseRentLotRepository _lotRepository; private readonly ICSkuRepository _skuRepository; + private readonly ILogger _logger; public WarehouseRentLotManager( ICWarehouseRentLotRepository lotRepository, - ICSkuRepository skuRepository) + ICSkuRepository skuRepository, + ILogger logger) { _lotRepository = lotRepository; _skuRepository = skuRepository; + _logger = logger; } /// @@ -39,6 +43,68 @@ public class WarehouseRentLotManager : IScopedDependency MidpointRounding.AwayFromZero); } + /// + /// 按 SKU 当前尺寸回刷仍缺体积的在库批次 UnitCbm。 + /// + public async Task RefreshUnitCbmForSkuAsync(int skuId, CancellationToken cancellationToken = default) + { + if (skuId <= 0) + { + return 0; + } + + var sku = await _skuRepository.FirstOrDefaultAsync(x => x.Id == skuId); + var cbm = CalcUnitCbm(sku); + if (cbm <= 0) + { + return 0; + } + + var lots = await _lotRepository.GetListAsync(x => + x.SkuId == skuId && x.RemainQty > 0 && x.UnitCbm <= 0); + foreach (var lot in lots) + { + lot.UnitCbm = cbm; + await _lotRepository.UpdateAsync(lot, cancellationToken); + } + + return lots.Count; + } + + /// + /// 对给定批次列表回刷 UnitCbm=0(就地更新实体,便于日结直接用)。 + /// + public async Task RefreshUnitCbmForLotsAsync( + IReadOnlyList lots, + CancellationToken cancellationToken = default) + { + var need = lots.Where(x => x.UnitCbm <= 0 && x.RemainQty > 0).ToList(); + if (need.Count == 0) + { + return; + } + + var skuIds = need.Select(x => x.SkuId).Distinct().ToArray(); + var skus = await _skuRepository.GetListAsync(x => skuIds.Contains(x.Id)); + var skuMap = skus.ToDictionary(x => x.Id); + foreach (var lot in need) + { + if (!skuMap.TryGetValue(lot.SkuId, out var sku)) + { + continue; + } + + var cbm = CalcUnitCbm(sku); + if (cbm <= 0) + { + continue; + } + + lot.UnitCbm = cbm; + await _lotRepository.UpdateAsync(lot, cancellationToken); + } + } + /// /// 入库/上架新增批次。 /// @@ -75,9 +141,9 @@ public class WarehouseRentLotManager : IScopedDependency } /// - /// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。 + /// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。返回未能扣减的数量(>0 表示影子账不足)。 /// - public async Task DeductFifoAsync( + public async Task DeductFifoAsync( int customerId, int warehouseId, int skuId, @@ -87,15 +153,17 @@ public class WarehouseRentLotManager : IScopedDependency { if (qty <= 0) { - return; + return 0; } + var hasBin = binLocationId is > 0; + var binId = binLocationId.GetValueOrDefault(); var lots = await _lotRepository.GetListAsync(x => x.CustomerId == customerId && x.WarehouseId == warehouseId && x.SkuId == skuId && x.RemainQty > 0 - && (!binLocationId.HasValue || x.BinLocationId == binLocationId.Value)); + && (!hasBin || x.BinLocationId == binId)); lots = lots.OrderBy(x => x.InboundTime).ThenBy(x => x.Id).ToList(); var remaining = qty; @@ -116,6 +184,20 @@ public class WarehouseRentLotManager : IScopedDependency remaining -= take; await _lotRepository.UpdateAsync(lot, cancellationToken); } + + if (remaining > 0) + { + _logger.LogWarning( + "仓租批次 FIFO 不足:客户 {CustomerId} 仓 {WarehouseId} SKU {SkuId} 库位 {BinLocationId} 仍缺 {Shortfall}(请求扣 {Qty})", + customerId, + warehouseId, + skuId, + hasBin ? binId : (int?)null, + remaining, + qty); + } + + return remaining; } /// @@ -175,5 +257,17 @@ public class WarehouseRentLotManager : IScopedDependency }; await _lotRepository.InsertAsync(moved, cancellationToken); } + + if (remaining > 0) + { + _logger.LogWarning( + "仓租批次移位不足:客户 {CustomerId} 仓 {WarehouseId} SKU {SkuId} {SourceBin}->{TargetBin} 仍缺 {Shortfall}", + customerId, + warehouseId, + skuId, + sourceBinLocationId, + targetBinLocationId, + remaining); + } } } diff --git a/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs b/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs index 372c750..f6f5876 100644 --- a/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs +++ b/src/Oms.Application/Workers/WarehouseRentBillingWorker.cs @@ -3,18 +3,21 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Oms.Application.Services.Warehouse; +using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Repositories; namespace Oms.Application.Workers; /// -/// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表,按组开独立 UoW。 +/// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表 + MySQL 命名锁。 +/// 全日扫批只跑一轮,之后仅重试 unpaid。 /// public class WarehouseRentBillingWorker : BackgroundService { private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1); private readonly IServiceScopeFactory _scopeFactory; private readonly ILogger _logger; + private DateTime? _fullScanDoneBillDate; public WarehouseRentBillingWorker( IServiceScopeFactory scopeFactory, @@ -57,29 +60,40 @@ public class WarehouseRentBillingWorker : BackgroundService } var billDate = now.Date.AddDays(-1); + var needFullScan = _fullScanDoneBillDate != billDate; List<(int CustomerId, int WarehouseId)> groups; using (var scope = _scopeFactory.CreateScope()) { - var lotRepository = scope.ServiceProvider.GetRequiredService(); - var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0); - groups = lots - .Select(x => (x.CustomerId, x.WarehouseId)) - .Distinct() - .ToList(); - var billRepository = scope.ServiceProvider.GetRequiredService(); var unpaid = await billRepository.GetListAsync(x => - x.BillDate == billDate && x.Status == "unpaid"); - foreach (var bill in unpaid) + x.BillDate == billDate && x.Status == WarehouseRentBillStatusCodes.Unpaid); + groups = unpaid + .Select(x => (x.CustomerId, x.WarehouseId)) + .ToList(); + + if (needFullScan) { - groups.Add((bill.CustomerId, bill.WarehouseId)); + var lotRepository = scope.ServiceProvider.GetRequiredService(); + var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0); + groups.AddRange(lots.Select(x => (x.CustomerId, x.WarehouseId))); } groups = groups.Distinct().ToList(); } + if (groups.Count == 0) + { + if (needFullScan) + { + _fullScanDoneBillDate = billDate; + } + + return; + } + var success = 0; + var failed = 0; foreach (var group in groups) { cancellationToken.ThrowIfCancellationRequested(); @@ -99,6 +113,7 @@ public class WarehouseRentBillingWorker : BackgroundService } catch (Exception ex) when (ex is not OperationCanceledException) { + failed++; _logger.LogError( ex, "仓租日结失败:客户 {CustomerId} 仓库 {WarehouseId} 业务日 {BillDate:yyyy-MM-dd}", @@ -108,13 +123,20 @@ public class WarehouseRentBillingWorker : BackgroundService } } - if (success > 0) + if (needFullScan && failed == 0) + { + _fullScanDoneBillDate = billDate; + } + + if (success > 0 || failed > 0) { _logger.LogInformation( - "仓租日结完成:业务日 {BillDate:yyyy-MM-dd},成功组数 {Success}/{Total}", + "仓租日结完成:业务日 {BillDate:yyyy-MM-dd},成功 {Success}/{Total},失败 {Failed},模式 {Mode}", billDate, success, - groups.Count); + groups.Count, + failed, + needFullScan ? "full" : "unpaid-retry"); } } } diff --git a/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs b/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs index ea315e2..3e3dd88 100644 --- a/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs +++ b/src/Oms.Domain/WarehouseAggregate/Consts/WarehouseRentCodes.cs @@ -18,6 +18,9 @@ public static class WarehouseRentLotSourceCodes { public const string Inbound = "inbound"; public const string Parcel = "parcel"; + + /// 存量库存反灌(上线补齐)。 + public const string Backfill = "backfill"; } /// diff --git a/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs b/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs index 0707d44..15abb49 100644 --- a/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs +++ b/src/Oms.Domain/WarehouseAggregate/Repositories/IWarehouseRepositories.cs @@ -43,6 +43,20 @@ public interface ICWarehouseRentRateDetailRepository : IRepository; -public interface ICWarehouseRentBillRepository : IRepository; +public interface ICWarehouseRentBillRepository : IRepository +{ + /// + /// 获取 MySQL 命名锁(同连接会话内有效),用于日结防双单。 + /// + Task TryAcquireBillingLockAsync( + string lockName, + int timeoutSeconds, + CancellationToken cancellationToken = default); + + /// + /// 释放 MySQL 命名锁。 + /// + Task ReleaseBillingLockAsync(string lockName, CancellationToken cancellationToken = default); +} public interface ICWarehouseRentBillLineRepository : IRepository; diff --git a/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs b/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs index 93a7bd8..ae4a554 100644 --- a/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs +++ b/src/Oms.SqlSugarCore/Warehouse/WarehouseRepositories.cs @@ -59,6 +59,27 @@ public class CWarehouseRentRateDetailRepository : OmsSqlSugarRepository, ICWarehouseRentLotRepository, IScopedDependency; -public class CWarehouseRentBillRepository : OmsSqlSugarRepository, ICWarehouseRentBillRepository, IScopedDependency; +public class CWarehouseRentBillRepository : OmsSqlSugarRepository, ICWarehouseRentBillRepository, IScopedDependency +{ + public async Task TryAcquireBillingLockAsync( + string lockName, + int timeoutSeconds, + CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + var result = await db.Ado.SqlQuerySingleAsync( + "SELECT GET_LOCK(@lockName, @timeoutSeconds)", + new { lockName, timeoutSeconds }); + return result == 1; + } + + public async Task ReleaseBillingLockAsync(string lockName, CancellationToken cancellationToken = default) + { + var db = await GetDbContextAsync(cancellationToken); + await db.Ado.SqlQuerySingleAsync( + "SELECT RELEASE_LOCK(@lockName)", + new { lockName }); + } +} public class CWarehouseRentBillLineRepository : OmsSqlSugarRepository, ICWarehouseRentBillLineRepository, IScopedDependency;