diff --git a/docs/design/20261014-抵扣成本口径(成本随货走+去重).md b/docs/design/20261014-抵扣成本口径(成本随货走+去重).md index a1d40e0..8ddfa39 100644 --- a/docs/design/20261014-抵扣成本口径(成本随货走+去重).md +++ b/docs/design/20261014-抵扣成本口径(成本随货走+去重).md @@ -52,6 +52,7 @@ | `server/src/services/dashboardService.ts` / `marginQueryService.ts` / `orderManagementQueryService.ts` | 运行期兜底表达式同步按缺口量 | | `server/tests/coverCostFollowsGoods.test.ts` | 契约测试(本文件的验收项):结转金额 = 批次价 × 抵扣量、无账外余额照样结转、加权均价回写、`unit_cost` 已有值不覆盖、成本价 ≤ 0 批次不参与 | | `server/tests/stockCoverOutsourcedOnly.test.ts` | 结转侧契约改测"抵扣计入成本";旧"账外余额封顶"路径保留在显式开关下 | +| `server/scripts/repair-cover-cost-follows-goods.ts` | **新增**:存量回填脚本(**默认干跑**;`--apply` 必须带 `--mode=carryover\|add`,两种语义都实现)。存量回填**尚未执行**——原因见 §7 | ## 4. 与"防同一批货计两次成本"的关系(边界,务必读) @@ -84,6 +85,32 @@ ## 6. 回滚 代码:`git revert` 本次提交即可(无迁移、无 DDL、无新开关)。 -数据:本次若执行存量回填,脚本自带 `--apply` 开关;回滚方式是删除按本口径新增的 -`cost_source='inventory_cover'` 成本行并把 `order_items.unit_cost` 复位为 0 -(脚本打印每行的改前/改后金额,可直接反向执行)。 +数据:存量回填脚本**默认干跑,不写库**;若将来执行了回填,回滚方式是 +`--mode=carryover` 把被改挂的成本行 `order_code` 改回原单(脚本逐行打印"原单"), +或 `--mode=add` 删除新增的 `cost_source='inventory_cover'` 成本行并把 `order_items.unit_cost` 复位为 0 +(脚本逐行打印 unit_cost 改前值)。 + +## 7. 存量回填:**尚未执行**(2026-10-14 开发者裁决:暂不回填,只保留代码修复) + +干跑(`npx tsx --env-file=.env scripts/repair-cover-cost-follows-goods.ts`,只读,未改数据): + +| 分公司 | 命中行 | 单 | 状态 / cycle | 应记成本 | 同批已在账 | 结论 | +| ------ | ------ | -- | ------------ | -------- | ---------- | ---- | +| BR002 | 3 | `ORD_API_20261014_BR002_0002` | 45 / `MOBILE` | **¥246.00** | **¥246.00**(挂 `ORD_WEB_20261014_BR002_0002`) | 结转安全前提**满足** | +| BR003 | 1 | `ORD_API_20261014_BR003_0002` | 45 / `MOBILE` | ¥50.00 | ¥0(批次 `STK20261012LF6LHB` 无验收成本行) | 只能"新增";结转不可用 | +| BR001 / BR004 | 0 | — | — | — | — | — | +| 合计 | 4 | | | **¥296.00** | ¥246.00 | | + +**两种语义的差别(分公司口径)**:`--mode=carryover` 净增 **¥0**(本单 +¥246、占位单 −¥246); +`--mode=add` 净增 **+¥296.00**(同一批货计两次)。**当前选择:两种都不执行。** + +### 待办(按依赖排序) + +1. **`orders.cycle_code = 'MOBILE'`**(真库 12 行 / ¥1,285.70):上表两张单**都是 `MOBILE`** ⇒ + **即使回填了成本,月度口径也取不到**。应先定 `MOBILE` 行的归期规则(或修移动端下单写入),再谈回填; +2. **BR002 那 ¥246 的归属**:现挂 `ORD_WEB_20261014_BR002_0002`(我方 `orders` 里 `status=90`、`total_amount=0` 的占位单, + 该占位单名下 `inspection_inbound` 共 15 行 / ¥1,449)。需确认这张占位单是什么、其成本是否该留在它身上; +3. **BR003 `ORD_API_20261014_BR003_0002` 的 ¥50**:批次 `STK20261012LF6LHB` 走的是 `stock_in`(无验收单), + 其成本在 `purchase` 桶里 ⇒ 只能"新增",同样有重复计成本问题; +4. 回填执行前的门禁:`orders.cycle_code` 归期先定;已结案单(status ≥ 90)脚本默认"只报不动", + 需另批 `--include-closed` 之类开关(当前脚本未提供,刻意不做)。 diff --git a/server/scripts/repair-cover-cost-follows-goods.ts b/server/scripts/repair-cover-cost-follows-goods.ts new file mode 100644 index 0000000..1a9f629 --- /dev/null +++ b/server/scripts/repair-cover-cost-follows-goods.ts @@ -0,0 +1,362 @@ +/** + * 存量回填:**被库存抵扣的部分计入订单成本(按被抵扣批次成本价)**。 + * + * 口径见 `docs/design/20261014-抵扣成本口径(成本随货走+去重).md`(2026-10-14 二次校正)。 + * 新写入点已改(`postInventoryCoverPurchaseCost` + 抵扣侧调用),本脚本只处理**存量**: + * 找"有抵扣量(`order_items.stock_cover_qty > 0`)却没有任何 `inventory_cover` 成本行"的行, + * 按 FIFO 批次价算出**应记成本**,并给出两种语义供选择: + * + * `--mode=carryover`(结转):把**已经在账**的同批成本行(验收入库 `inspection_inbound`) + * 改挂到本单 ⇒ 本单成本补齐,**分公司总成本不变**。 + * 安全前提:该批次对应的验收单**只有一张**,且其 `actual_qty` 与本行抵扣量**相等** + * (不相等时不动,打印"需人工判断"——避免把整张验收单的成本错记到部分抵扣上)。 + * `--mode=add`(新增):按现行代码写一张新的 `inventory_cover` 成本行 + * ⇒ 本单成本补齐,**分公司总成本 +应记金额**(同一批货计两次)。 + * + * ⚠️ **默认干跑,不改数据**。要写必须同时给 `--apply` 与 `--mode=`: + * + * cd server + * npx tsx --env-file=.env scripts/repair-cover-cost-follows-goods.ts # 干跑全部分公司 + * npx tsx --env-file=.env scripts/repair-cover-cost-follows-goods.ts BR002 # 只干跑 BR002 + * npx tsx --env-file=.env scripts/repair-cover-cost-follows-goods.ts --apply --mode=carryover BR002 + * npx tsx --env-file=.env scripts/repair-cover-cost-follows-goods.ts --apply --mode=add BR002 + * + * 幂等:写完 `inventory_cover` 成本行后,`NOT EXISTS(...)` 判据不再命中该行 ⇒ 重跑不再处理。 + * 回滚: + * · carryover:把被改挂的成本行 `order_code` 改回原单(脚本每行都打印"原单 → 本单"); + * · add:`DELETE FROM cost_details WHERE cost_source='inventory_cover' AND order_code IN (...)`, + * 并把 `order_items.unit_cost` 复位为 0(脚本打印每行 unit_cost 改前值)。 + */ +import { pool } from '../src/db'; +import { runWithTenantDbContext } from '../src/services/tenantDbContext'; + +const APPLY = process.argv.includes('--apply'); +const MODE = (process.argv.find((a) => a.startsWith('--mode=')) || '').split('=')[1] || ''; +const BRANCH_ARGS = process.argv + .filter((a) => /^BR\d+$/i.test(a)) + .map((a) => a.toUpperCase()); +const round2 = (n: number) => Math.round((Number(n) || 0) * 100) / 100; +const round4 = (n: number) => Math.round((Number(n) || 0) * 10000) / 10000; + +if (APPLY && MODE !== 'carryover' && MODE !== 'add') { + console.error('❌ `--apply` 必须同时指定语义:`--mode=carryover`(结转,总额不变)或 `--mode=add`(新增,总额 +)。'); + process.exit(2); +} + +type TargetRow = { + order_code: string; + order_status: number; + cycle_code: string | null; + sku_code: string; + item_name: string | null; + quantity: number; + cover_qty: number; + unit_cost: number; +}; + +type BatchTake = { batchNo: string; qty: number; unit: number; amount: number }; + +type ExistingBatchCost = { + id: string; + order_code: string; + amount: number; + cost_subtype: string | null; + cost_source: string | null; + inspection_qty: number | null; + inbound_batch_no: string | null; +}; + +async function resolveBranches(): Promise { + if (BRANCH_ARGS.length) return BRANCH_ARGS; + const r = await pool.query<{ branch_code: string }>( + `SELECT branch_code FROM public.branches ORDER BY branch_code` + ); + return r.rows.map((row) => String(row.branch_code)).filter(Boolean); +} + +/** 有抵扣量、却没有任何 `inventory_cover` 成本行的行 */ +async function loadTargets(): Promise { + const r = await pool.query( + `SELECT o.order_code, + o.order_status, + o.cycle_code, + oi.sku_code, + oi.item_name, + COALESCE(oi.quantity, 0)::float AS quantity, + COALESCE(oi.stock_cover_qty, 0)::float AS cover_qty, + COALESCE(oi.unit_cost, 0)::float AS unit_cost + FROM order_items oi + JOIN orders o ON o.order_code = oi.order_code + WHERE COALESCE(oi.stock_cover_qty, 0) > 1e-9 + AND NOT EXISTS ( + SELECT 1 FROM cost_details cd + WHERE cd.order_code = o.order_code + AND cd.sku_code = oi.sku_code + AND cd.cost_source = 'inventory_cover') + ORDER BY o.order_code, oi.sku_code` + ); + return r.rows; +} + +/** 与 `postInventoryCoverPurchaseCost` 完全同序的 FIFO 折算(只读,用于干跑报数) */ +async function fifoTake( + skuCode: string, + branchCode: string, + coverQty: number +): Promise<{ takes: BatchTake[]; totalCost: number; usedQty: number }> { + const r = await pool.query<{ batch_no: string; available_qty: number; cost_price: number }>( + `SELECT batch_no, + COALESCE(available_qty, 0)::float AS available_qty, + COALESCE(cost_price, 0)::float AS cost_price + FROM inventory + WHERE sku_code = $1 + AND available_qty > 0 + AND ($2::text IS NULL OR branch_code IS NOT DISTINCT FROM $2) + ORDER BY created_at ASC NULLS LAST, id ASC`, + [skuCode, branchCode] + ); + let remain = Math.max(0, coverQty); + let totalCost = 0; + let usedQty = 0; + const takes: BatchTake[] = []; + for (const b of r.rows) { + if (remain <= 1e-9) break; + const avail = Number(b.available_qty) || 0; + const unit = Number(b.cost_price) || 0; + if (unit <= 0) continue; + const take = Math.min(remain, avail); + if (take <= 1e-9) continue; + takes.push({ batchNo: String(b.batch_no), qty: take, unit, amount: round2(take * unit) }); + totalCost += take * unit; + usedQty += take; + remain -= take; + } + return { takes, totalCost: round2(totalCost), usedQty }; +} + +/** 这些批次**已经在账**的成本行(验收单 → cost_details) */ +async function findExistingBatchCosts( + skuCode: string, + batchNos: string[] +): Promise { + if (!batchNos.length) return []; + const r = await pool.query( + `SELECT cd.id::text AS id, + cd.order_code AS order_code, + cd.amount::float AS amount, + cd.cost_subtype AS cost_subtype, + cd.cost_source AS cost_source, + i.actual_qty::float AS inspection_qty, + i.inbound_batch_no AS inbound_batch_no + FROM inspections i + JOIN cost_details cd + ON cd.reference_type = 'inspection' + AND cd.reference_id = i.id::text + WHERE i.sku_code = $1 + AND i.inbound_batch_no = ANY($2::text[])`, + [skuCode, batchNos] + ); + return r.rows; +} + +type LinePlan = { + target: TargetRow; + takes: BatchTake[]; + totalCost: number; + usedQty: number; + existing: ExistingBatchCost[]; + carryoverOk: boolean; + carryoverNote: string; +}; + +async function planLine(target: TargetRow, branch: string): Promise { + const { takes, totalCost, usedQty } = await fifoTake(target.sku_code, branch, target.cover_qty); + const existing = await findExistingBatchCosts( + target.sku_code, + takes.map((t) => t.batchNo) + ); + let carryoverOk = takes.length > 0; + let carryoverNote = ''; + for (const t of takes) { + const rows = existing.filter((e) => e.inbound_batch_no === t.batchNo); + if (rows.length !== 1) { + carryoverOk = false; + carryoverNote = `批次 ${t.batchNo} 命中验收成本行 ${rows.length} 条(需 1 条)⇒ 需人工判断`; + break; + } + const row = rows[0]; + if (Math.abs((Number(row.inspection_qty) || 0) - t.qty) > 1e-6) { + carryoverOk = false; + carryoverNote = + `批次 ${t.batchNo} 验收量 ${row.inspection_qty} ≠ 抵扣量 ${round4(t.qty)}` + + ` ⇒ 整张改挂会错记,需人工判断(可拆分成本行后再处理)`; + break; + } + if (round2(Number(row.amount) || 0) !== round2(t.amount)) { + carryoverOk = false; + carryoverNote = + `批次 ${t.batchNo} 在账金额 ¥${row.amount} ≠ 批次价折算 ¥${t.amount} ⇒ 需人工判断`; + break; + } + } + return { target, takes, totalCost, usedQty, existing, carryoverOk, carryoverNote }; +} + +/** 结转:把已在账的同批成本行改挂本单 */ +async function applyCarryover(plan: LinePlan): Promise { + const orderCode = plan.target.order_code; + for (const t of plan.takes) { + const row = plan.existing.find((e) => e.inbound_batch_no === t.batchNo)!; + if (row.order_code === orderCode) continue; + await pool.query(`UPDATE cost_details SET order_code = $2 WHERE id = $1::uuid`, [ + row.id, + orderCode, + ]); + } + await writeBackUnitCost(plan); +} + +/** 新增:按现行代码写一张 `inventory_cover` 成本行(并原地冲减持有桶) */ +async function applyAdd(plan: LinePlan, branch: string): Promise { + const { postInventoryCoverPurchaseCost } = await import( + '../src/services/inventorySurplusCostService' + ); + await postInventoryCoverPurchaseCost(pool as never, { + orderCode: plan.target.order_code, + skuCode: plan.target.sku_code, + coverQty: plan.target.cover_qty, + branchCode: branch, + }); + await writeBackUnitCost(plan); +} + +/** 回写订单行成本价(仅 `unit_cost = 0` 时,与现行代码同判据) */ +async function writeBackUnitCost(plan: LinePlan): Promise { + if (plan.target.unit_cost > 1e-9 || plan.usedQty <= 1e-9) return; + const unitCost = round4(plan.totalCost / plan.usedQty); + await pool.query( + `UPDATE order_items SET unit_cost = $3 + WHERE order_code = $1 AND sku_code = $2 + AND COALESCE(unit_cost, 0) = 0`, + [plan.target.order_code, plan.target.sku_code, unitCost] + ); +} + +async function main(): Promise { + const branches = await resolveBranches(); + let plannedAmount = 0; + let existingAmount = 0; + let openLines = 0; + let closedLines = 0; + let manualLines = 0; + let applied = 0; + + console.log( + `\n模式:${APPLY ? `**执行**(--mode=${MODE})` : '干跑(不改数据)'}` + + ` 范围:${branches.join(', ') || '(无分公司)'}` + ); + + for (const branch of branches) { + await runWithTenantDbContext(branch, async () => { + const targets = await loadTargets(); + console.log(`\n════════ ${branch}:命中 ${targets.length} 行(有抵扣量、无 inventory_cover 成本行)════════`); + if (!targets.length) return; + + const byOrder = new Map(); + for (const target of targets) { + const plan = await planLine(target, branch); + const list = byOrder.get(target.order_code) || []; + list.push(plan); + byOrder.set(target.order_code, list); + } + + for (const [orderCode, plans] of byOrder) { + const status = plans[0].target.order_status; + const orderPlanned = round2(plans.reduce((s, p) => s + p.totalCost, 0)); + const orderExisting = round2( + plans.reduce((s, p) => s + p.existing.reduce((a, e) => a + Number(e.amount || 0), 0), 0) + ); + const anyManual = plans.some((p) => !p.carryoverOk); + console.log( + ` ${orderCode}(状态 ${status},cycle ${plans[0].target.cycle_code ?? '—'})` + + `应记成本 ¥${orderPlanned.toFixed(2)};同批已在账 ¥${orderExisting.toFixed(2)}` + ); + for (const p of plans) { + const t = p.target; + const batchText = p.takes.length + ? p.takes.map((x) => `${x.batchNo}(${round4(x.qty)}@${x.unit})`).join(' + ') + : '(无可用且成本价 > 0 的批次 ⇒ 无法折算)'; + console.log( + ` ${t.sku_code} ${t.item_name || ''}:量 ${round4(t.quantity)}、抵扣 ${round4(t.cover_qty)}` + + ` ⇒ 应记 ¥${p.totalCost.toFixed(2)} unit_cost ${t.unit_cost} → ${p.usedQty > 1e-9 ? round4(p.totalCost / p.usedQty) : '—'}` + ); + console.log(` 批次:${batchText}`); + if (p.existing.length) { + for (const e of p.existing) { + console.log( + ` 已在账:${e.cost_source}/${e.cost_subtype} ¥${Number(e.amount).toFixed(2)}` + + ` 挂在 ${e.order_code}${e.inbound_batch_no === null ? '' : `(批次 ${e.inbound_batch_no})`}` + ); + } + } else { + console.log(` 已在账:无同批成本行(结转模式不可用)`); + } + if (!p.carryoverOk) console.log(` ⚠️ ${p.carryoverNote}`); + } + + plannedAmount = round2(plannedAmount + orderPlanned); + existingAmount = round2(existingAmount + orderExisting); + if (status >= 90) closedLines += plans.length; + else openLines += plans.length; + if (anyManual) manualLines += plans.filter((p) => !p.carryoverOk).length; + + if (!APPLY) continue; + + // ⚠️ 已结案单(>=90)的成本影响已出报表,默认不动,需人工先确认报表口径 + if (status >= 90) { + console.log(` → ⏸ 已结案(status=${status}),按"只报不动"跳过`); + continue; + } + for (const p of plans) { + try { + if (MODE === 'carryover') { + if (!p.carryoverOk) { + console.log(` → ⏸ ${p.target.sku_code}:不满足结转安全前提,跳过`); + continue; + } + await applyCarryover(p); + console.log(` → ✅ ${p.target.sku_code}:已结转 ¥${p.totalCost.toFixed(2)}(改挂到本单)`); + } else { + await applyAdd(p, branch); + console.log(` → ✅ ${p.target.sku_code}:已新增 inventory_cover ¥${p.totalCost.toFixed(2)}`); + } + applied += 1; + } catch (error) { + console.error(` → ❌ ${p.target.sku_code} 失败:${(error as Error)?.message || error}`); + } + } + } + }); + } + + console.log( + `\n${APPLY ? `已执行 ${applied} 行(--mode=${MODE})` : '干跑(未改数据)'}:` + + `应记成本合计 ¥${plannedAmount.toFixed(2)};同批已在账 ¥${existingAmount.toFixed(2)};` + + `未结案 ${openLines} 行 / 已结案(只报)${closedLines} 行` + + (manualLines ? `;结转安全前提不满足 ${manualLines} 行(需人工判断)` : '') + ); + if (!APPLY) { + console.log( + '\n按需选择一种语义执行(--apply 必须带 --mode):\n' + + ' --apply --mode=carryover 结转:本单成本补齐,分公司总成本不变(需满足安全前提)\n' + + ' --apply --mode=add 新增:本单成本补齐,分公司总成本 +应记金额(同一批货计两次)' + ); + } + await pool.end(); +} + +main().catch(async (error) => { + console.error('[repair-cover-cost-follows-goods] 失败:', error); + await pool.end(); + process.exit(1); +});