fix: harden warehouse rent with lot backfill, billing lock, and unpaid inbound block
All checks were successful
Build and Deploy / deploy (push) Successful in 1m17s

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
zzh 2026-11-15 15:26:55 +08:00
parent ae0444b226
commit 80830e310f
16 changed files with 620 additions and 75 deletions

View File

@ -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;

View File

@ -151,3 +151,35 @@ public class WarehouseRentRunBillingInput
/// <summary>业务日,默认昨日。</summary> /// <summary>业务日,默认昨日。</summary>
public DateTime? BillDate { get; set; } public DateTime? BillDate { get; set; }
} }
/// <summary>
/// 存量库存反灌仓租批次入参。
/// </summary>
public class WarehouseRentLotBackfillInput
{
/// <summary>可选:仅反灌指定客户。</summary>
public int? CustomerId { get; set; }
/// <summary>可选:仅反灌指定仓库。</summary>
public int? WarehouseId { get; set; }
/// <summary>
/// 同时把 UnitCbm=0 且 SKU 已有尺寸的存量 lot 回刷体积。默认 true。
/// </summary>
public bool RefreshMissingUnitCbm { get; set; } = true;
}
/// <summary>
/// 存量反灌结果。
/// </summary>
public class WarehouseRentLotBackfillOutput
{
/// <summary>新建 lot 条数。</summary>
public int CreatedLots { get; set; }
/// <summary>新建 lot 件数合计。</summary>
public int CreatedQty { get; set; }
/// <summary>回刷 UnitCbm 的 lot 条数。</summary>
public int RefreshedLots { get; set; }
}

View File

@ -40,6 +40,8 @@ public class PlatformStoreOrderService : ApplicationService
LazyServiceProvider.GetRequiredService<PlatformStoreOrderFulfillmentService>(); LazyServiceProvider.GetRequiredService<PlatformStoreOrderFulfillmentService>();
private WarehouseRentLotManager RentLotManager => private WarehouseRentLotManager RentLotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>(); LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
private WarehouseRentGuard RentGuard =>
LazyServiceProvider.GetRequiredService<WarehouseRentGuard>();
/// <summary> /// <summary>
/// 查询店铺订单列表。 /// 查询店铺订单列表。
@ -938,6 +940,11 @@ public class PlatformStoreOrderService : ApplicationService
private async Task RestoreInventoryAsync(int customerId, int warehouseId, IReadOnlyCollection<InventoryDeduction> deductions) private async Task RestoreInventoryAsync(int customerId, int warehouseId, IReadOnlyCollection<InventoryDeduction> deductions)
{ {
if (deductions.Count > 0)
{
await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId);
}
foreach (var item in deductions) foreach (var item in deductions)
{ {
var inventory = await InventoryRepository.FirstOrDefaultAsync(x => var inventory = await InventoryRepository.FirstOrDefaultAsync(x =>

View File

@ -1,6 +1,7 @@
using System.Linq.Expressions; using System.Linq.Expressions;
using Fake.Application; using Fake.Application;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Oms.Application.Dtos.Channels; using Oms.Application.Dtos.Channels;
using Oms.Application.Dtos.Shared; using Oms.Application.Dtos.Shared;
using Oms.Application.Dtos.Warehouse; using Oms.Application.Dtos.Warehouse;
@ -33,6 +34,8 @@ public class WarehouseRentService : ApplicationService
LazyServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>(); LazyServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>();
private ICWarehouseRentBillLineRepository BillLineRepository => private ICWarehouseRentBillLineRepository BillLineRepository =>
LazyServiceProvider.GetRequiredService<ICWarehouseRentBillLineRepository>(); LazyServiceProvider.GetRequiredService<ICWarehouseRentBillLineRepository>();
private ICInventoryRepository InventoryRepository =>
LazyServiceProvider.GetRequiredService<ICInventoryRepository>();
private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService<ICSkuRepository>(); private ICSkuRepository SkuRepository => LazyServiceProvider.GetRequiredService<ICSkuRepository>();
private ICustomerRepository CustomerRepository => private ICustomerRepository CustomerRepository =>
LazyServiceProvider.GetRequiredService<ICustomerRepository>(); LazyServiceProvider.GetRequiredService<ICustomerRepository>();
@ -40,6 +43,10 @@ public class WarehouseRentService : ApplicationService
LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>(); LazyServiceProvider.GetRequiredService<IWarehouseAddressRepository>();
private CustomerBalanceMutator BalanceMutator => private CustomerBalanceMutator BalanceMutator =>
LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>(); LazyServiceProvider.GetRequiredService<CustomerBalanceMutator>();
private WarehouseRentLotManager LotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
private ILogger<WarehouseRentService> RentLogger =>
LazyServiceProvider.GetRequiredService<ILogger<WarehouseRentService>>();
/// <summary> /// <summary>
/// 分页查询仓租费率。 /// 分页查询仓租费率。
@ -255,6 +262,98 @@ public class WarehouseRentService : ApplicationService
}; };
} }
/// <summary>
/// 按现库存缺口反灌仓租批次(可重复执行);可选回刷缺尺寸 lot 的 UnitCbm。
/// </summary>
[HttpPost("/warehouse/storage-rent/lot/backfill")]
public async Task<WarehouseRentLotBackfillOutput> 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
};
}
/// <summary> /// <summary>
/// 日终结算入口:按客户+仓库生成昨日账单并尝试扣款。 /// 日终结算入口:按客户+仓库生成昨日账单并尝试扣款。
/// </summary> /// </summary>
@ -287,7 +386,7 @@ public class WarehouseRentService : ApplicationService
} }
/// <summary> /// <summary>
/// 对单个客户+仓库执行指定业务日仓租结算(幂等)。 /// 对单个客户+仓库执行指定业务日仓租结算(幂等;MySQL 命名锁防双单)。
/// </summary> /// </summary>
public async Task RunDailyBillingForOwnerAsync( public async Task RunDailyBillingForOwnerAsync(
int customerId, int customerId,
@ -296,31 +395,50 @@ public class WarehouseRentService : ApplicationService
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
billDate = billDate.Date; billDate = billDate.Date;
var existing = await BillRepository.FirstOrDefaultAsync(x => var lockName = $"wr_bill_{customerId}_{warehouseId}_{billDate:yyyyMMdd}";
x.CustomerId == customerId if (lockName.Length > 64)
&& x.WarehouseId == warehouseId
&& x.BillDate == billDate);
if (existing != null)
{ {
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 => await CreateAndPayBillAsync(customerId, warehouseId, billDate, lots, cancellationToken);
x.CustomerId == customerId }
&& x.WarehouseId == warehouseId finally
&& x.RemainQty > 0);
if (lots.Count == 0)
{ {
return; await BillRepository.ReleaseBillingLockAsync(lockName, cancellationToken);
} }
await CreateAndPayBillAsync(customerId, warehouseId, billDate, lots, cancellationToken);
} }
private async Task CreateAndPayBillAsync( private async Task CreateAndPayBillAsync(
@ -334,6 +452,9 @@ public class WarehouseRentService : ApplicationService
var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == warehouseId); var warehouse = await WarehouseAddressRepository.FirstOrDefaultAsync(x => x.Id == warehouseId);
var warehouseName = warehouse?.WarehouseName; var warehouseName = warehouse?.WarehouseName;
// 日结前尽量用最新 SKU 尺寸回刷 0 体积批次
await LotManager.RefreshUnitCbmForLotsAsync(lots, cancellationToken);
var lineDrafts = new List<(CWarehouseRentLot Lot, int AgeDays, decimal Cbm, bool MissingDim)>(); var lineDrafts = new List<(CWarehouseRentLot Lot, int AgeDays, decimal Cbm, bool MissingDim)>();
decimal totalCbm = 0; decimal totalCbm = 0;
foreach (var lot in lots) foreach (var lot in lots)
@ -347,26 +468,36 @@ public class WarehouseRentService : ApplicationService
totalCbm = Math.Round(totalCbm, 6, MidpointRounding.AwayFromZero); totalCbm = Math.Round(totalCbm, 6, MidpointRounding.AwayFromZero);
// 体积段按客户当日该仓总 CBM 匹配;天数按各 lot 库龄分别取价后对明细分摊 // 体积段:客户当日该仓总 CBM;天数:各 lot 库龄分别取价后累加
// 简化:同一客户仓使用「最大库龄」匹配天数段(保守,偏高龄段),再 × 总 CBM
// 更精确:按 lot 分别匹配后汇总。采用按 lot 匹配并累加。
var rateBundles = await LoadEnabledRateBundlesAsync(); var rateBundles = await LoadEnabledRateBundlesAsync();
decimal amount = 0; decimal amount = 0;
decimal? sampleUnitPrice = null; decimal? sampleUnitPrice = null;
var lineEntities = new List<CWarehouseRentBillLine>(); var lineEntities = new List<CWarehouseRentBillLine>();
var unmatchedRateLines = 0;
foreach (var draft in lineDrafts) foreach (var draft in lineDrafts)
{ {
var unitPrice = WarehouseRentCalculator.MatchUnitPrice( var matched = WarehouseRentCalculator.MatchUnitPrice(
rateBundles, rateBundles,
warehouseId, warehouseId,
warehouseName, warehouseName,
draft.AgeDays, draft.AgeDays,
totalCbm, totalCbm,
customer?.PriceTierKey) ?? 0M; customer?.PriceTierKey);
sampleUnitPrice ??= unitPrice; 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); var lineAmount = Math.Round(draft.Cbm * unitPrice, 2, MidpointRounding.AwayFromZero);
amount += lineAmount; amount += lineAmount;
var lineRemark = draft.MissingDim
? "SKU 缺尺寸,体积计 0"
: matched is null && draft.Cbm > 0
? "未命中仓租费率"
: null;
lineEntities.Add(new CWarehouseRentBillLine lineEntities.Add(new CWarehouseRentBillLine
{ {
LotId = draft.Lot.Id, LotId = draft.Lot.Id,
@ -377,11 +508,40 @@ public class WarehouseRentService : ApplicationService
UnitPrice = unitPrice, UnitPrice = unitPrice,
Amount = lineAmount, Amount = lineAmount,
MissingDimension = draft.MissingDim, MissingDimension = draft.MissingDim,
Remark = draft.MissingDim ? "SKU 缺尺寸,体积计 0" : null Remark = lineRemark
}); });
} }
amount = Math.Round(amount, 2, MidpointRounding.AwayFromZero); amount = Math.Round(amount, 2, MidpointRounding.AwayFromZero);
var missingDimLines = lineDrafts.Count(x => x.MissingDim);
var remarkParts = new List<string>();
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 var bill = new CWarehouseRentBill
{ {
BillNo = await GenerateBillNoAsync(cancellationToken), BillNo = await GenerateBillNoAsync(cancellationToken),
@ -393,7 +553,7 @@ public class WarehouseRentService : ApplicationService
Currency = "CNY", Currency = "CNY",
UnitPrice = sampleUnitPrice, UnitPrice = sampleUnitPrice,
Status = amount <= 0 ? WarehouseRentBillStatusCodes.Zero : WarehouseRentBillStatusCodes.Pending, 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); await BillRepository.InsertAsync(bill, cancellationToken);

View File

@ -1,5 +1,6 @@
using Fake.Application; using Fake.Application;
using Oms.Application.Shared; using Oms.Application.Shared;
using Oms.Domain.WarehouseAggregate.Consts;
using Oms.Domain.WarehouseAggregate.Entities; using Oms.Domain.WarehouseAggregate.Entities;
namespace Oms.Application.Services.Warehouse; namespace Oms.Application.Services.Warehouse;
@ -34,12 +35,16 @@ public partial class WarehouseService
return entity; return entity;
} }
// syncRentLot=true 时同步仓租影子账;移库等已自行维护 lot 的路径保持 false
private async Task UpsertInventoryQtyAsync( private async Task UpsertInventoryQtyAsync(
int customerId, int customerId,
int warehouseId, int warehouseId,
int skuId, int skuId,
int binLocationId, int binLocationId,
int deltaQty) int deltaQty,
bool syncRentLot = false,
string rentSourceType = WarehouseRentLotSourceCodes.Inbound,
int rentSourceId = 0)
{ {
if (deltaQty == 0) if (deltaQty == 0)
{ {
@ -69,6 +74,18 @@ public partial class WarehouseService
AvailableQty = deltaQty AvailableQty = deltaQty
}; };
await InventoryRepository.InsertAsync(inventory); await InventoryRepository.InsertAsync(inventory);
if (syncRentLot)
{
await RentLotManager.AddLotAsync(
customerId,
warehouseId,
skuId,
binLocationId,
deltaQty,
rentSourceType,
rentSourceId);
}
return; return;
} }
@ -86,6 +103,32 @@ public partial class WarehouseService
inventory.Qty = newQty; inventory.Qty = newQty;
inventory.AvailableQty = Math.Max(0, inventory.Qty - inventory.FrozenQty); inventory.AvailableQty = Math.Max(0, inventory.Qty - inventory.FrozenQty);
await InventoryRepository.UpdateAsync(inventory); 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( private async Task DeductInventoryAsync(
@ -125,6 +168,7 @@ public partial class WarehouseService
row.AvailableQty = Math.Max(0, row.Qty - row.FrozenQty); row.AvailableQty = Math.Max(0, row.Qty - row.FrozenQty);
remaining -= deduct; remaining -= deduct;
await InventoryRepository.UpdateAsync(row); await InventoryRepository.UpdateAsync(row);
// 影子账不足只记日志,库存仍按实物扣;避免出库被仓租账卡住
await RentLotManager.DeductFifoAsync( await RentLotManager.DeductFifoAsync(
customerId, customerId,
warehouseId, warehouseId,

View File

@ -273,6 +273,7 @@ public partial class WarehouseService
public async Task ConfirmInboundReceiveAsync(WarehouseInboundConfirmReceiveInput input) public async Task ConfirmInboundReceiveAsync(WarehouseInboundConfirmReceiveInput input)
{ {
var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId); var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId);
await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId);
var notice = await GetInboundNoticeOrThrowAsync(customerId, input.InboundNoticeId); var notice = await GetInboundNoticeOrThrowAsync(customerId, input.InboundNoticeId);
if (notice.ReceiptStatus == WarehouseReceiptStatusCodes.Completed) if (notice.ReceiptStatus == WarehouseReceiptStatusCodes.Completed)
{ {
@ -322,22 +323,22 @@ public partial class WarehouseService
line.BinLocationId = lineInput.ReceivedQty > 0 ? lineInput.BinLocationId : null; line.BinLocationId = lineInput.ReceivedQty > 0 ? lineInput.BinLocationId : null;
await InboundBoxLineRepository.UpdateAsync(line); 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( await UpsertInventoryQtyAsync(
customerId, customerId,
notice.WarehouseId, notice.WarehouseId,
line.SkuId, line.SkuId,
lineInput.BinLocationId, binId,
deltaQty);
await RentLotManager.AddLotAsync(
customerId,
notice.WarehouseId,
line.SkuId,
lineInput.BinLocationId,
deltaQty, deltaQty,
WarehouseRentLotSourceCodes.Inbound, syncRentLot: true,
notice.Id); rentSourceType: WarehouseRentLotSourceCodes.Inbound,
rentSourceId: notice.Id);
} }
} }

View File

@ -280,6 +280,7 @@ public partial class WarehouseService
public async Task PutawayParcelAsync(WarehouseParcelPutawayInput input) public async Task PutawayParcelAsync(WarehouseParcelPutawayInput input)
{ {
var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId); var customerId = await ResolveMutationCustomerIdAsync(input.CustomerId);
await RentGuard.EnsureNoUnpaidStorageRentAsync(customerId);
var parcel = await GetParcelOrThrowAsync(customerId, input.ParcelId); var parcel = await GetParcelOrThrowAsync(customerId, input.ParcelId);
if (parcel.LifecycleStatus == WarehouseParcelLifecycleCodes.Stored) if (parcel.LifecycleStatus == WarehouseParcelLifecycleCodes.Stored)
{ {
@ -313,19 +314,14 @@ public partial class WarehouseService
await ParcelItemRepository.UpdateAsync(item); await ParcelItemRepository.UpdateAsync(item);
await UpsertInventoryQtyAsync( await UpsertInventoryQtyAsync(
customerId,
parcel.WarehouseId,
sku.Id,
putawayItem.BinLocationId,
item.Quantity);
await RentLotManager.AddLotAsync(
customerId, customerId,
parcel.WarehouseId, parcel.WarehouseId,
sku.Id, sku.Id,
putawayItem.BinLocationId, putawayItem.BinLocationId,
item.Quantity, item.Quantity,
WarehouseRentLotSourceCodes.Parcel, syncRentLot: true,
parcel.Id); rentSourceType: WarehouseRentLotSourceCodes.Parcel,
rentSourceId: parcel.Id);
} }
parcel.LifecycleStatus = WarehouseParcelLifecycleCodes.Stored; parcel.LifecycleStatus = WarehouseParcelLifecycleCodes.Stored;

View File

@ -159,6 +159,12 @@ public partial class WarehouseService
await SkuRepository.InsertAsync(entity); await SkuRepository.InsertAsync(entity);
} }
// SKU 补尺寸后回刷在库仓租批次体积,避免日结继续按 0 CBM 漏收
if (entity.Id > 0)
{
await RentLotManager.RefreshUnitCbmForSkuAsync(entity.Id);
}
return MapSkuOutput(entity, null); return MapSkuOutput(entity, null);
} }

View File

@ -32,4 +32,6 @@ public partial class WarehouseService : ApplicationService
private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService<ILabelPdfRenderer>(); private ILabelPdfRenderer LabelPdfRenderer => LazyServiceProvider.GetRequiredService<ILabelPdfRenderer>();
private WarehouseRentLotManager RentLotManager => private WarehouseRentLotManager RentLotManager =>
LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>(); LazyServiceProvider.GetRequiredService<WarehouseRentLotManager>();
private WarehouseRentGuard RentGuard =>
LazyServiceProvider.GetRequiredService<WarehouseRentGuard>();
} }

View File

@ -51,12 +51,25 @@ public static class WarehouseRentCalculator
continue; continue;
} }
if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Days, "天数", ageDays, out var daysWidth)) // 库龄按整数天闭区间 [start,end];体积仍沿用运费左开右闭
if (!MatchIntervalFactor(
factors,
WarehouseRentFactorCodes.Days,
"天数",
ageDays,
inclusiveBounds: true,
out var daysWidth))
{ {
continue; continue;
} }
if (!MatchIntervalFactor(factors, WarehouseRentFactorCodes.Volume, "体积", totalCbm, out var volumeWidth)) if (!MatchIntervalFactor(
factors,
WarehouseRentFactorCodes.Volume,
"体积",
totalCbm,
inclusiveBounds: false,
out var volumeWidth))
{ {
continue; continue;
} }
@ -133,6 +146,7 @@ public static class WarehouseRentCalculator
string code, string code,
string label, string label,
decimal value, decimal value,
bool inclusiveBounds,
out int widthScore) out int widthScore)
{ {
widthScore = 0; widthScore = 0;
@ -146,13 +160,12 @@ public static class WarehouseRentCalculator
return false; 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 的区间 return false;
if (!(value == 0 && start == 0 && end > 0 && value <= end))
{
return false;
}
} }
widthScore = (int)Math.Min(int.MaxValue, Math.Round((end - start) * 1000M)); widthScore = (int)Math.Min(int.MaxValue, Math.Round((end - start) * 1000M));

View File

@ -0,0 +1,41 @@
using Fake.Application;
using Fake.DependencyInjection;
using Oms.Domain.WarehouseAggregate.Consts;
using Oms.Domain.WarehouseAggregate.Repositories;
namespace Oms.Application.Shared;
/// <summary>
/// 仓租业务守卫:欠费拦截等。
/// </summary>
public class WarehouseRentGuard : IScopedDependency
{
private readonly ICWarehouseRentBillRepository _billRepository;
public WarehouseRentGuard(ICWarehouseRentBillRepository billRepository)
{
_billRepository = billRepository;
}
/// <summary>
/// 客户存在 unpaid 仓租账单时禁止继续入库/上架(避免欠费滚大)。
/// 出库/移库不拦截。
/// </summary>
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("客户存在未结清仓租账单,请先到仓租日账单补扣后再入库/上架");
}
}
}

View File

@ -1,4 +1,5 @@
using Fake.DependencyInjection; using Fake.DependencyInjection;
using Microsoft.Extensions.Logging;
using Oms.Domain.WarehouseAggregate.Consts; using Oms.Domain.WarehouseAggregate.Consts;
using Oms.Domain.WarehouseAggregate.Entities; using Oms.Domain.WarehouseAggregate.Entities;
using Oms.Domain.WarehouseAggregate.Repositories; using Oms.Domain.WarehouseAggregate.Repositories;
@ -12,13 +13,16 @@ public class WarehouseRentLotManager : IScopedDependency
{ {
private readonly ICWarehouseRentLotRepository _lotRepository; private readonly ICWarehouseRentLotRepository _lotRepository;
private readonly ICSkuRepository _skuRepository; private readonly ICSkuRepository _skuRepository;
private readonly ILogger<WarehouseRentLotManager> _logger;
public WarehouseRentLotManager( public WarehouseRentLotManager(
ICWarehouseRentLotRepository lotRepository, ICWarehouseRentLotRepository lotRepository,
ICSkuRepository skuRepository) ICSkuRepository skuRepository,
ILogger<WarehouseRentLotManager> logger)
{ {
_lotRepository = lotRepository; _lotRepository = lotRepository;
_skuRepository = skuRepository; _skuRepository = skuRepository;
_logger = logger;
} }
/// <summary> /// <summary>
@ -39,6 +43,68 @@ public class WarehouseRentLotManager : IScopedDependency
MidpointRounding.AwayFromZero); MidpointRounding.AwayFromZero);
} }
/// <summary>
/// 按 SKU 当前尺寸回刷仍缺体积的在库批次 UnitCbm。
/// </summary>
public async Task<int> 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;
}
/// <summary>
/// 对给定批次列表回刷 UnitCbm=0(就地更新实体,便于日结直接用)。
/// </summary>
public async Task RefreshUnitCbmForLotsAsync(
IReadOnlyList<CWarehouseRentLot> 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);
}
}
/// <summary> /// <summary>
/// 入库/上架新增批次。 /// 入库/上架新增批次。
/// </summary> /// </summary>
@ -75,9 +141,9 @@ public class WarehouseRentLotManager : IScopedDependency
} }
/// <summary> /// <summary>
/// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。 /// 按客户+仓+SKU FIFO 扣减剩余量(可选限定库位)。返回未能扣减的数量(&gt;0 表示影子账不足)。
/// </summary> /// </summary>
public async Task DeductFifoAsync( public async Task<int> DeductFifoAsync(
int customerId, int customerId,
int warehouseId, int warehouseId,
int skuId, int skuId,
@ -87,15 +153,17 @@ public class WarehouseRentLotManager : IScopedDependency
{ {
if (qty <= 0) if (qty <= 0)
{ {
return; return 0;
} }
var hasBin = binLocationId is > 0;
var binId = binLocationId.GetValueOrDefault();
var lots = await _lotRepository.GetListAsync(x => var lots = await _lotRepository.GetListAsync(x =>
x.CustomerId == customerId x.CustomerId == customerId
&& x.WarehouseId == warehouseId && x.WarehouseId == warehouseId
&& x.SkuId == skuId && x.SkuId == skuId
&& x.RemainQty > 0 && x.RemainQty > 0
&& (!binLocationId.HasValue || x.BinLocationId == binLocationId.Value)); && (!hasBin || x.BinLocationId == binId));
lots = lots.OrderBy(x => x.InboundTime).ThenBy(x => x.Id).ToList(); lots = lots.OrderBy(x => x.InboundTime).ThenBy(x => x.Id).ToList();
var remaining = qty; var remaining = qty;
@ -116,6 +184,20 @@ public class WarehouseRentLotManager : IScopedDependency
remaining -= take; remaining -= take;
await _lotRepository.UpdateAsync(lot, cancellationToken); 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;
} }
/// <summary> /// <summary>
@ -175,5 +257,17 @@ public class WarehouseRentLotManager : IScopedDependency
}; };
await _lotRepository.InsertAsync(moved, cancellationToken); await _lotRepository.InsertAsync(moved, cancellationToken);
} }
if (remaining > 0)
{
_logger.LogWarning(
"仓租批次移位不足:客户 {CustomerId} 仓 {WarehouseId} SKU {SkuId} {SourceBin}->{TargetBin} 仍缺 {Shortfall}",
customerId,
warehouseId,
skuId,
sourceBinLocationId,
targetBinLocationId,
remaining);
}
} }
} }

View File

@ -3,18 +3,21 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Oms.Application.Services.Warehouse; using Oms.Application.Services.Warehouse;
using Oms.Domain.WarehouseAggregate.Consts;
using Oms.Domain.WarehouseAggregate.Repositories; using Oms.Domain.WarehouseAggregate.Repositories;
namespace Oms.Application.Workers; namespace Oms.Application.Workers;
/// <summary> /// <summary>
/// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表,按组开独立 UoW。 /// 仓租日终任务:每日 01:00 起对「昨日」按客户+仓生成账单并扣费;幂等依赖账单表 + MySQL 命名锁。
/// 全日扫批只跑一轮,之后仅重试 unpaid。
/// </summary> /// </summary>
public class WarehouseRentBillingWorker : BackgroundService public class WarehouseRentBillingWorker : BackgroundService
{ {
private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1); private static readonly TimeSpan PollInterval = TimeSpan.FromMinutes(1);
private readonly IServiceScopeFactory _scopeFactory; private readonly IServiceScopeFactory _scopeFactory;
private readonly ILogger<WarehouseRentBillingWorker> _logger; private readonly ILogger<WarehouseRentBillingWorker> _logger;
private DateTime? _fullScanDoneBillDate;
public WarehouseRentBillingWorker( public WarehouseRentBillingWorker(
IServiceScopeFactory scopeFactory, IServiceScopeFactory scopeFactory,
@ -57,29 +60,40 @@ public class WarehouseRentBillingWorker : BackgroundService
} }
var billDate = now.Date.AddDays(-1); var billDate = now.Date.AddDays(-1);
var needFullScan = _fullScanDoneBillDate != billDate;
List<(int CustomerId, int WarehouseId)> groups; List<(int CustomerId, int WarehouseId)> groups;
using (var scope = _scopeFactory.CreateScope()) using (var scope = _scopeFactory.CreateScope())
{ {
var lotRepository = scope.ServiceProvider.GetRequiredService<ICWarehouseRentLotRepository>();
var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0);
groups = lots
.Select(x => (x.CustomerId, x.WarehouseId))
.Distinct()
.ToList();
var billRepository = scope.ServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>(); var billRepository = scope.ServiceProvider.GetRequiredService<ICWarehouseRentBillRepository>();
var unpaid = await billRepository.GetListAsync(x => var unpaid = await billRepository.GetListAsync(x =>
x.BillDate == billDate && x.Status == "unpaid"); x.BillDate == billDate && x.Status == WarehouseRentBillStatusCodes.Unpaid);
foreach (var bill in unpaid) groups = unpaid
.Select(x => (x.CustomerId, x.WarehouseId))
.ToList();
if (needFullScan)
{ {
groups.Add((bill.CustomerId, bill.WarehouseId)); var lotRepository = scope.ServiceProvider.GetRequiredService<ICWarehouseRentLotRepository>();
var lots = await lotRepository.GetListAsync(x => x.RemainQty > 0);
groups.AddRange(lots.Select(x => (x.CustomerId, x.WarehouseId)));
} }
groups = groups.Distinct().ToList(); groups = groups.Distinct().ToList();
} }
if (groups.Count == 0)
{
if (needFullScan)
{
_fullScanDoneBillDate = billDate;
}
return;
}
var success = 0; var success = 0;
var failed = 0;
foreach (var group in groups) foreach (var group in groups)
{ {
cancellationToken.ThrowIfCancellationRequested(); cancellationToken.ThrowIfCancellationRequested();
@ -99,6 +113,7 @@ public class WarehouseRentBillingWorker : BackgroundService
} }
catch (Exception ex) when (ex is not OperationCanceledException) catch (Exception ex) when (ex is not OperationCanceledException)
{ {
failed++;
_logger.LogError( _logger.LogError(
ex, ex,
"仓租日结失败:客户 {CustomerId} 仓库 {WarehouseId} 业务日 {BillDate:yyyy-MM-dd}", "仓租日结失败:客户 {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( _logger.LogInformation(
"仓租日结完成:业务日 {BillDate:yyyy-MM-dd},成功组数 {Success}/{Total}", "仓租日结完成:业务日 {BillDate:yyyy-MM-dd},成功 {Success}/{Total},失败 {Failed},模式 {Mode}",
billDate, billDate,
success, success,
groups.Count); groups.Count,
failed,
needFullScan ? "full" : "unpaid-retry");
} }
} }
} }

View File

@ -18,6 +18,9 @@ public static class WarehouseRentLotSourceCodes
{ {
public const string Inbound = "inbound"; public const string Inbound = "inbound";
public const string Parcel = "parcel"; public const string Parcel = "parcel";
/// <summary>存量库存反灌(上线补齐)。</summary>
public const string Backfill = "backfill";
} }
/// <summary> /// <summary>

View File

@ -43,6 +43,20 @@ public interface ICWarehouseRentRateDetailRepository : IRepository<CWarehouseRen
public interface ICWarehouseRentLotRepository : IRepository<CWarehouseRentLot>; public interface ICWarehouseRentLotRepository : IRepository<CWarehouseRentLot>;
public interface ICWarehouseRentBillRepository : IRepository<CWarehouseRentBill>; public interface ICWarehouseRentBillRepository : IRepository<CWarehouseRentBill>
{
/// <summary>
/// 获取 MySQL 命名锁(同连接会话内有效),用于日结防双单。
/// </summary>
Task<bool> TryAcquireBillingLockAsync(
string lockName,
int timeoutSeconds,
CancellationToken cancellationToken = default);
/// <summary>
/// 释放 MySQL 命名锁。
/// </summary>
Task ReleaseBillingLockAsync(string lockName, CancellationToken cancellationToken = default);
}
public interface ICWarehouseRentBillLineRepository : IRepository<CWarehouseRentBillLine>; public interface ICWarehouseRentBillLineRepository : IRepository<CWarehouseRentBillLine>;

View File

@ -59,6 +59,27 @@ public class CWarehouseRentRateDetailRepository : OmsSqlSugarRepository<CWarehou
public class CWarehouseRentLotRepository : OmsSqlSugarRepository<CWarehouseRentLot>, ICWarehouseRentLotRepository, IScopedDependency; public class CWarehouseRentLotRepository : OmsSqlSugarRepository<CWarehouseRentLot>, ICWarehouseRentLotRepository, IScopedDependency;
public class CWarehouseRentBillRepository : OmsSqlSugarRepository<CWarehouseRentBill>, ICWarehouseRentBillRepository, IScopedDependency; public class CWarehouseRentBillRepository : OmsSqlSugarRepository<CWarehouseRentBill>, ICWarehouseRentBillRepository, IScopedDependency
{
public async Task<bool> TryAcquireBillingLockAsync(
string lockName,
int timeoutSeconds,
CancellationToken cancellationToken = default)
{
var db = await GetDbContextAsync(cancellationToken);
var result = await db.Ado.SqlQuerySingleAsync<int?>(
"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<int?>(
"SELECT RELEASE_LOCK(@lockName)",
new { lockName });
}
}
public class CWarehouseRentBillLineRepository : OmsSqlSugarRepository<CWarehouseRentBillLine>, ICWarehouseRentBillLineRepository, IScopedDependency; public class CWarehouseRentBillLineRepository : OmsSqlSugarRepository<CWarehouseRentBillLine>, ICWarehouseRentBillLineRepository, IScopedDependency;