feat(库存/分拣): 出库扣库存量兜底 + 真实单补扣(开发者:可以)
开发者确认「2.可以」:① 现在给存量单补扣;② 把「已过 50 但无出库流水」的存量单做成调度器兜底。
一、真库补扣(两张存量单,都是"状态 50、分拣已出库、却零出库流水"):
· ORD_API_20261013_BR003_0003(苹果30/瘦肉15/抄手皮8/土豆10,全额库存抵扣 63 斤)
⇒ delivery_loading_out 4 条共 63 斤;批次可用量 61/15/78/30 → 31/0/70/20
· ORD_API_20261013_BR003_0002(米块 8 斤全额抵扣)⇒ 出库 8 斤,米块批次 30 → 22
补扣后兜底取数返回空。
二、兜底任务:scheduledJobs.runOutboundSettleBackfill()(10 分钟节流,挂在主系统对账同一组 Promise.all)
→ inventoryOutboundService.listOrdersMissingOutboundSettlement() 取数(本文件不写裸 SQL)
谓词:未删除 + order_status BETWEEN 50 AND 89 + 近 45 天 + 有拣货实拣/核货量 + 无
picking_out/delivery_loading_out 流水
⚠️ 只到 89:已结案(90)的单不动 —— 历史结案白名单是有意跳过 FIFO 扣库的
→ 逐单 ensureOrderInventorySettledOnComplete({softInventory:true})(软扣、流水守卫幂等)
三、退货口径(开发者本轮确认,设计文 §12 记录;实现另行提交):
回补按**核货量**(拣 30 核货 29 ⇒ 退 29)+**差额必须留痕**(写日志/备注,便于盘点追溯);
未出库退货不回补;已发车/已结案等"货回仓确认"再补;抵扣过的行退货要把账外余额退回;
幂等判据=该行已有 order_return_in 流水;退货后清 FIFO 批次计划。
测试:pickingCompleteDeductsInventory 增至 5 例(新增兜底契约:任务注册 + 取数谓词 + 不得捞 90 单),
与 pickupSettleInventoryOnClose 共 11 例全绿;root+server tsc exit 0;门禁 8/1/1。
This commit is contained in:
@@ -100,7 +100,34 @@
|
||||
| 再跑一次推进 | 流水仍 1 条 ⇒ **幂等,不重复扣** |
|
||||
| 清理 | 删单 + 回补批次 6 斤 + 回补账外 ¥18,批次恢复 30.00 |
|
||||
|
||||
## 10. 回滚
|
||||
## 11. 存量补扣与兜底(2026-10-13 已执行)
|
||||
|
||||
改动落地**之前**越过「分拣完成」时点的单不会自己回补,加上留痕 SQL bug 让扣库事务长期回滚,
|
||||
真库积了两张「状态 50、分拣已出库、却零出库流水」的单:
|
||||
|
||||
| 单 | 内容 | 补扣前 | 补扣后 |
|
||||
| - | ---- | ------ | ------ |
|
||||
| `ORD_API_20261013_BR003_0003` | 苹果30 / 瘦肉15 / 抄手皮8 / 土豆10(全额库存抵扣 63 斤) | 批次可用量 61/15/78/30,无出库流水 | 31/0/70/20,`delivery_loading_out` **4 条共 63 斤** |
|
||||
| `ORD_API_20261013_BR003_0002` | 米块 8 斤(全额抵扣) | 无出库流水 | `delivery_loading_out` 8 斤,米块批次 30 → 22 |
|
||||
|
||||
**兜底任务**:`scheduledJobs.runOutboundSettleBackfill()`(10 分钟节流,注册在主系统对账那组 `Promise.all` 里)
|
||||
→ `inventoryOutboundService.listOrdersMissingOutboundSettlement()` 取数
|
||||
(未删除 + `order_status BETWEEN 50 AND 89` + 近 45 天 + 有拣货实拣/核货量 + **无 `picking_out`/`delivery_loading_out` 流水**)
|
||||
→ 逐单 `ensureOrderInventorySettledOnComplete({softInventory:true})`(软扣、幂等)。
|
||||
⚠️ **只到 89**:已结案(90)的单不动 —— 历史结案白名单是有意跳过 FIFO 扣库的。
|
||||
执行后取数返回空(两张存量单已清零)。
|
||||
|
||||
## 12. 退货(分拣完毕后退货)设计口径(已与开发者确认)
|
||||
|
||||
- **回补量按核货量**(`loaded_qty`):拣 30、核货 29 ⇒ 退货**回补 29**;
|
||||
- **差额必须留痕**:分拣实拣 30 与回补 29 的 1 斤差额要写进日志/备注,便于盘点追溯(分拣员责任);
|
||||
- 未出库就退货 ⇒ **不回补**(没扣过),只撤拣货行 + 释放预留;
|
||||
- 已发车/已结案才退货 ⇒ 等「货回仓确认」再回补,不无脑 +qty;
|
||||
- 抵扣过的行退货 ⇒ 除红冲外要把账外持有余额退回(`inventory_cover` 金额 → `inventory_holding`);
|
||||
- 幂等判据:该行已有退货回库流水(`order_return_in`)就不再补;
|
||||
- 退货后清 FIFO 批次计划(`clearAutoCoverBatchPlan` / `clearCoverBatchesForItems`),避免把不会出库的批次推给主系统。
|
||||
|
||||
## 13. 回滚
|
||||
|
||||
纯代码改动、无迁移、无数据变更:`git revert` 即回到「发车扣库」;
|
||||
存量若已按新口径扣过,仅影响**时点**(数量口径不变:实拣量),无需数据修复。
|
||||
|
||||
@@ -1281,6 +1281,38 @@ export async function cleanupStaleReservationsForCompletedOrders(options?: {
|
||||
* 订单结案前:幂等补出库(装车优先,否则验收实收)并消费预留。
|
||||
* 真缺货时抛错,禁止带着幽灵预留完结。
|
||||
*/
|
||||
/**
|
||||
* 兜底取数:**状态 50–89、有拣货实拣/核货量、却没有任何出库流水的单**(2026-10-13 开发者要求)。
|
||||
*
|
||||
* 用在调度器的「出库扣库兜底」(`scheduledJobs.runOutboundSettleBackfill`):
|
||||
* 扣库时点前移到「分拣完成」之前就已经越过该时点的存量单,靠它被捞出来补扣。
|
||||
* ⚠️ 只到 89:**已结案(90)的单不动** —— 历史结案白名单是有意跳过 FIFO 扣库的。
|
||||
*/
|
||||
export async function listOrdersMissingOutboundSettlement(limit = 30): Promise<string[]> {
|
||||
const cap = Math.min(Math.max(Number(limit) || 30, 1), 200);
|
||||
const result = await pool.query<{ order_code: string }>(
|
||||
`SELECT o.order_code
|
||||
FROM orders o
|
||||
WHERE o.deleted_at IS NULL
|
||||
AND o.order_status BETWEEN 50 AND 89
|
||||
AND COALESCE(o.created_at, NOW()) > NOW() - INTERVAL '45 days'
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM picking_items pi
|
||||
WHERE pi.order_code = o.order_code
|
||||
AND (COALESCE(pi.picked_qty, 0) > 0 OR COALESCE(pi.loaded_qty, 0) > 0)
|
||||
)
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM inventory_logs il
|
||||
WHERE il.related_order_code = o.order_code
|
||||
AND il.operation_type IN ('picking_out', 'delivery_loading_out')
|
||||
)
|
||||
ORDER BY o.updated_at DESC NULLS LAST
|
||||
LIMIT $1`,
|
||||
[cap]
|
||||
);
|
||||
return result.rows.map((row) => String(row.order_code || '')).filter(Boolean);
|
||||
}
|
||||
|
||||
export async function ensureOrderInventorySettledOnComplete(
|
||||
orderCode: string,
|
||||
options?: { operatorId?: string | null; client?: PoolClient; softInventory?: boolean }
|
||||
|
||||
@@ -515,6 +515,63 @@ async function runReportPushReconcile() {
|
||||
* 纯本地写(不扣库、不碰主系统);本模块内部对每个补到计划的订单触发一次推送,故跟随 tick 限流。
|
||||
*/
|
||||
let lastCoverBatchPlanBackfillAt = 0;
|
||||
/** 出库扣库兜底的节流时间戳(10 分钟) */
|
||||
let lastOutboundSettleBackfillAt = 0;
|
||||
|
||||
/**
|
||||
* 存量兜底:**「货已出库/已拣但库存没扣」的单补扣一次**(2026-10-13 开发者要求)。
|
||||
*
|
||||
* 为什么需要:扣库时点已前移到「分拣完成」(见
|
||||
* docs/design/20261013-分拣完毕即出库扣库存(全单统一).md),但**改动之前**已经越过该时点的单
|
||||
* 不会自己回补;再加上当时出库留痕的 SQL bug 让整个扣库事务回滚,存量里积了一批
|
||||
* 「状态 ≥50、有拣货实拣量、却没有任何出库流水」的单(真库实证 BR003 三张)。
|
||||
*
|
||||
* 判据:`order_status BETWEEN 50 AND 89`(未结案;**历史结案白名单的单不动** ——
|
||||
* 它们是有意跳过 FIFO 扣库的)+ 未删除 + 近 45 天 + **无 picking_out/delivery_loading_out 流水**
|
||||
* + 至少一行拣货实拣/核货量 > 0(没东西可扣的不进)。
|
||||
*
|
||||
* 动作:`ensureOrderInventorySettledOnComplete(orderCode, {softInventory:true})` ——
|
||||
* 复用既有出库口径(FIFO/批次行锁/流水/批次计划),**软扣不拦**、流水守卫保证幂等;
|
||||
* 直送/免入库/加菜行本就被跳过,扣库计划为空时它自己返回 `no_loading_items`(no-op)。
|
||||
*/
|
||||
async function runOutboundSettleBackfill() {
|
||||
try {
|
||||
if (Date.now() - lastOutboundSettleBackfillAt < 10 * 60 * 1000) return;
|
||||
lastOutboundSettleBackfillAt = Date.now();
|
||||
const { ensureOrderInventorySettledOnComplete, listOrdersMissingOutboundSettlement } =
|
||||
await import('./inventoryOutboundService');
|
||||
const branches = await listActiveBranchCodes();
|
||||
let settled = 0;
|
||||
for (const branchCode of branches) {
|
||||
let orderCodes: string[] = [];
|
||||
try {
|
||||
// 取数在 service 里(本文件不写业务 SQL);未删除 + 近 45 天 + 只到 89(结案白名单不动)
|
||||
orderCodes = await runWithTenantDbContext(branchCode, () =>
|
||||
listOrdersMissingOutboundSettlement(30)
|
||||
);
|
||||
} catch (error: any) {
|
||||
console.error(`[scheduler] 出库扣库兜底取数失败(${branchCode}):`, error?.message || error);
|
||||
continue;
|
||||
}
|
||||
for (const orderCode of orderCodes) {
|
||||
try {
|
||||
const result = await runWithTenantDbContext(branchCode, () =>
|
||||
ensureOrderInventorySettledOnComplete(orderCode, { softInventory: true })
|
||||
);
|
||||
if (result.deducted) {
|
||||
settled += 1;
|
||||
console.log(`[scheduler] 出库扣库兜底:${orderCode} 补扣成功(${result.reason || 'ok'})`);
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.error(`[scheduler] 出库扣库兜底失败 ${orderCode}:`, error?.message || error);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (settled > 0) console.log(`[scheduler] 出库扣库兜底:本轮补扣 ${settled} 张单`);
|
||||
} catch (error) {
|
||||
console.error('[scheduler] 出库扣库兜底异常:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async function runStockCoverBatchPlanBackfill() {
|
||||
try {
|
||||
@@ -822,6 +879,8 @@ export function startScheduledJobs() {
|
||||
runPriceQtyRequestReconcile(),
|
||||
// 库存抵扣 ⇒ FIFO 批次计划兜底(纯本地)
|
||||
runStockCoverBatchPlanBackfill(),
|
||||
// 「已过待配送但没扣过库存」的存量单补扣兜底(纯本地,软扣 + 幂等)
|
||||
runOutboundSettleBackfill(),
|
||||
// 「我方指定抵扣批次」残留清扫(纯本地)
|
||||
runCoverBatchesSweep(),
|
||||
// 已退货行残留抵扣清扫(纯本地)
|
||||
|
||||
@@ -74,3 +74,24 @@ describe('出库留痕不得拖垮扣库事务', () => {
|
||||
expect(outbound).toContain('ROLLBACK TO SAVEPOINT ${outboundAuditSavepoint}');
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 存量兜底:扣库时点前移到「分拣完成」**之前**就已经越过该时点的单,靠调度器捞出来补扣
|
||||
* (2026-10-13 开发者要求)。真库实证:BR003 有两张单(`…_0002` 米块 8 斤、`…_0003` 四行 63 斤)
|
||||
* 「状态 50、已出库、却无任何出库流水」,本轮已用同一函数补扣完成。
|
||||
*/
|
||||
describe('出库扣库兜底(存量单)', () => {
|
||||
const jobs = readFileSync(path.join(__dirname, '../src/services/scheduledJobs.ts'), 'utf8');
|
||||
|
||||
it('⑤ 调度器注册了兜底任务,取数在 service、只覆盖未结案的单', () => {
|
||||
expect(jobs).toContain('runOutboundSettleBackfill()');
|
||||
expect(jobs).toContain('listOrdersMissingOutboundSettlement');
|
||||
// 节流 10 分钟(与批次计划兜底同款)
|
||||
expect(jobs).toContain('lastOutboundSettleBackfillAt');
|
||||
// 取数谓词:50–89、近 45 天、有实拣量、无出库流水
|
||||
expect(outbound).toContain('o.order_status BETWEEN 50 AND 89');
|
||||
expect(outbound).toContain("operation_type IN ('picking_out', 'delivery_loading_out')");
|
||||
// ⚠️ 不得把已结案(90)的单也捞进来:历史结案白名单是有意跳过 FIFO 扣库的
|
||||
expect(outbound).not.toContain('o.order_status >= 50');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user