#!/usr/bin/env node /** * **只读**盘点:仓库里的钱 vs 已进成本的钱(进销存口径核查) * * 回答的是开发者 2026-10-13 的问题:「独立进货、库存入库的货都放在仓库,这批肯定是算成本呀」 * —— 到底哪些已经进了成本、哪些还挂在"账外"、仓库里一共压着多少钱。 * * 三块输出(全部只读,不写任何库): * ① **账外台账**(`cost_details.cost_type='inventory_holding'`):按来源 / 账期汇总 * —— 这部分**不在**看板「所有成本」里(`excludeInventoryHoldingFromKpiSql`), * 但按现行净利公式会因 `order_code IS NULL` 落进"期间固定"(未决口径,见设计文)。 * ② **物理在库**(`inventory.available_qty > 0`):按 SKU/批次汇总 `可用量 × cost_price` * —— 仓库里实际压着的钱。 * ③ **有货无桶**(②里有量、但该 SKU 账外余额为 0):这批货的成本**已按订单计过** * (主系统分配单 / 独立进货的验收入库)⇒ 库存抵扣**不允许**再抵它们(会重复计成本)。 * * 用法(只读;不传 DSN 时用 server/.env 的 DATABASE_URL): * node server/scripts/audit-inventory-cost-ledger.mjs # 全部租户 * node server/scripts/audit-inventory-cost-ledger.mjs --branch BR002 * DATABASE_URL=postgres://... node server/scripts/audit-inventory-cost-ledger.mjs */ import { readFileSync, existsSync } from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import pg from 'pg'; const here = path.dirname(fileURLToPath(import.meta.url)); const serverDir = path.resolve(here, '..'); function loadEnvDatabaseUrl() { if (process.env.DATABASE_URL) return process.env.DATABASE_URL; const envPath = path.join(serverDir, '.env'); if (!existsSync(envPath)) return null; const line = readFileSync(envPath, 'utf8') .split('\n') .find((l) => l.trim().startsWith('DATABASE_URL=')); return line ? line.slice(line.indexOf('=') + 1).trim() : null; } function argValue(name) { const i = process.argv.indexOf(name); return i >= 0 ? String(process.argv[i + 1] || '').trim() : ''; } const money = (v) => Number(v || 0).toFixed(2); async function main() { const url = loadEnvDatabaseUrl(); if (!url) { console.error('缺少 DATABASE_URL(可传环境变量,或让 server/.env 里有)'); process.exit(1); } const dbName = (() => { try { return new URL(url).pathname.replace(/^\//, ''); } catch { return '(unparsed)'; } })(); const branchFilter = argValue('--branch').toUpperCase(); console.log('── 只读盘点:仓库里的钱 vs 已进成本的钱 ──'); console.log(`库:${dbName}|分公司过滤:${branchFilter || '(全部)'}|**本脚本不写任何数据**\n`); const pool = new pg.Pool({ connectionString: url, max: 4 }); try { const schemas = ( await pool.query( `SELECT schema_name FROM information_schema.schemata WHERE schema_name LIKE 'tenant_br%' ORDER BY 1` ) ).rows.map((r) => r.schema_name); for (const schema of schemas) { const branch = schema.replace(/^tenant_/, '').toUpperCase(); if (branchFilter && branch !== branchFilter) continue; const holding = await pool.query( `SELECT cost_source, cost_subtype, cycle_code, count(*)::int AS rows, COALESCE(SUM(amount), 0)::numeric AS amount FROM ${schema}.cost_details WHERE cost_type = 'inventory_holding' GROUP BY 1, 2, 3 ORDER BY 4 DESC` ); const holdingTotal = holding.rows.reduce((s, r) => s + Number(r.amount), 0); const stock = await pool.query( `SELECT count(*)::int AS batches, COALESCE(SUM(available_qty), 0)::numeric AS qty, COALESCE(SUM(available_qty * COALESCE(cost_price, 0)), 0)::numeric AS amount FROM ${schema}.inventory WHERE available_qty > 0` ); /** 有量但账外余额为 0 的 SKU ⇒ 成本已按订单计过 */ const noHolding = await pool.query( `WITH inv AS ( SELECT sku_code, SUM(available_qty)::numeric AS qty, SUM(available_qty * COALESCE(cost_price, 0))::numeric AS amount FROM ${schema}.inventory WHERE available_qty > 0 GROUP BY 1 ), hold AS ( SELECT sku_code, SUM(amount)::numeric AS balance FROM ${schema}.cost_details WHERE cost_type = 'inventory_holding' GROUP BY 1 ) SELECT count(*)::int AS skus, COALESCE(SUM(inv.qty), 0)::numeric AS qty, COALESCE(SUM(inv.amount), 0)::numeric AS amount FROM inv LEFT JOIN hold ON hold.sku_code = inv.sku_code WHERE COALESCE(hold.balance, 0) <= 0` ); console.log(`══ ${schema}(${branch})══`); console.log( ` ① 账外台账(inventory_holding):${holding.rows.reduce((s, r) => s + r.rows, 0)} 行 / ¥${money(holdingTotal)}` ); for (const r of holding.rows) { console.log( ` · ${r.cost_source || '—'} / ${r.cost_subtype || '—'} / 账期 ${r.cycle_code || '—'}:` + `${r.rows} 行 ¥${money(r.amount)}` ); } const s = stock.rows[0]; console.log(` ② 物理在库:${s.batches} 批 / 数量 ${Number(s.qty).toFixed(2)} / 金额 ¥${money(s.amount)}`); const n = noHolding.rows[0]; console.log( ` ③ 有货无桶(成本已按订单计过,抵扣不允许再抵):${n.skus} 个 SKU / 数量 ${Number(n.qty).toFixed(2)} / 金额 ¥${money(n.amount)}` ); const covered = Number(s.amount) - Number(n.amount); console.log( ` ④ 其中"账外可结转"部分(抵扣/领料可结转):¥${money(covered)}` + `(= ② − ③,与 ① 的台账余额应当接近;差值是已消耗未出库/跨期)` ); console.log(''); } console.log('提示:③ 的口径 = 2026-10-13 起「库存抵扣只能结转账外持有余额」的依据。'); } finally { await pool.end(); } } main().catch((error) => { console.error('盘点失败:', error?.message || error); process.exit(1); });