#!/usr/bin/env node /** * 一次性补账:备货已完成但采购账本缺行(2026-08-31 ~ 09-10 22:00 构建期漏写)。 * * 用法(在 server/ 下): * node --env-file=.env scripts/backfill-missing-prep-purchase-cost.cjs # dry-run(默认) * node --env-file=.env scripts/backfill-missing-prep-purchase-cost.cjs --apply # 写库 * 可选:--tenant=tenant_br002 | --tenant=all(默认 all) * --since=2026-08-30T00:00:00+08:00 --until=2026-09-10T22:00:00+08:00 * --limit=1000 --all(打印全部候选行) --out=./tmp/backfill-report.json * * 口径:每 order_item 一行 purchase/order_goods/unit_cost_sync, * amount = order_items.quantity × supplier_preparations.purchase_price * 幂等:前置存在性判断 + INSERT … ON CONFLICT DO NOTHING(唯一索引兜底) * 审计:--apply 时写 operation_logs(operation_type='cost_backfill'),并把插入 id 写入 --out 报告,便于回滚。 * * 设计:docs/design/20260911-backfill-missing-prep-purchase-cost.md */ 'use strict'; const fs = require('fs'); const path = require('path'); const { Pool } = require('pg'); function parseArgs(argv) { const out = { apply: false, tenant: 'all', since: null, until: null, limit: null, printAll: false, out: null }; for (const raw of argv.slice(2)) { if (raw === '--apply') out.apply = true; else if (raw === '--all') out.printAll = true; else if (raw.startsWith('--tenant=')) out.tenant = raw.slice(9).trim() || 'all'; else if (raw.startsWith('--since=')) out.since = raw.slice(8).trim() || null; else if (raw.startsWith('--until=')) out.until = raw.slice(8).trim() || null; else if (raw.startsWith('--limit=')) out.limit = Number(raw.slice(8)) || null; else if (raw.startsWith('--out=')) out.out = raw.slice(6).trim() || null; else if (raw === '--help' || raw === '-h') { console.log(fs.readFileSync(__filename, 'utf8').split('*/')[0]); process.exit(0); } else { console.error(`未知参数: ${raw}(--help 查看用法)`); process.exit(2); } } return out; } const GAP_SQL = (schema, opts, params) => { const conds = []; if (opts.since) { params.push(opts.since); conds.push(`sp.prepare_time >= $${params.length}::timestamptz`); } if (opts.until) { params.push(opts.until); conds.push(`sp.prepare_time < $${params.length}::timestamptz`); } const limitSql = opts.limit && opts.limit > 0 ? `LIMIT ${Math.floor(opts.limit)}` : ''; return ` SELECT oi.id::text AS order_item_id, oi.order_code, oi.sku_code, oi.item_name, oi.unit, COALESCE(oi.quantity,0)::numeric AS quantity, COALESCE(sp.purchase_price,0)::numeric AS purchase_price, COALESCE(sp.prepare_qty,0)::numeric AS prepare_qty, ROUND((COALESCE(oi.quantity,0) * COALESCE(sp.purchase_price,0))::numeric, 2) AS amount, o.cycle_code, COALESCE(oi.branch_code, o.branch_code) AS branch_code, sp.prepare_time::text AS prepare_time FROM ${schema}.order_items oi JOIN ${schema}.orders o ON o.order_code = oi.order_code AND o.deleted_at IS NULL JOIN ${schema}.supplier_preparations sp ON sp.order_code = oi.order_code AND sp.sku_code = oi.sku_code WHERE COALESCE(oi.is_returned,false) = false AND COALESCE(oi.is_extra_dish,false) = false AND COALESCE(oi.quantity,0) > 0 AND COALESCE(sp.prepare_status,10) >= 30 AND COALESCE(sp.is_stockout,false) = false AND COALESCE(sp.transferred_to_purchase,false) = false AND COALESCE(sp.purchase_price,0) > 0 AND NULLIF(TRIM(COALESCE(sp.supplier_code,'')),'') IS NOT NULL AND UPPER(TRIM(COALESCE(sp.supplier_code,''))) NOT IN ('INTERNAL','UNASSIGNED') AND NOT EXISTS (SELECT 1 FROM ${schema}.cost_details cd WHERE cd.order_code = oi.order_code AND cd.sku_code IS NOT DISTINCT FROM oi.sku_code AND cd.cost_type IN ('purchase','purchase_applied')) AND NOT EXISTS (SELECT 1 FROM ${schema}.inspections i WHERE i.order_code = oi.order_code AND i.sku_code = oi.sku_code) ${conds.length ? 'AND ' + conds.join(' AND ') : ''} ORDER BY oi.order_code, oi.sort_order NULLS LAST, oi.id ${limitSql}`; }; const INSERT_SQL = (schema) => ` INSERT INTO ${schema}.cost_details ( cycle_code, cost_type, cost_subtype, amount, order_code, sku_code, allocation_method, allocated_amount, status, branch_code, cost_source, reference_type, reference_id, order_item_id, remark ) VALUES ( $1,'purchase','order_goods',$2,$3,$4,'sku',$2,20,$5,'supplier', 'order_item',$6::text,$6::uuid,'unit_cost_sync' ) ON CONFLICT DO NOTHING RETURNING id`; async function main() { const args = parseArgs(process.argv); const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 4 }); const client = await pool.connect(); const report = { started_at: new Date().toISOString(), apply: args.apply, args, tenants: {} }; try { // dry-run 强制只读;--apply 才放开写(显式授权) await client.query(args.apply ? 'SET default_transaction_read_only = off' : 'SET default_transaction_read_only = on'); const schemas = args.tenant === 'all' ? (await client.query( `SELECT nspname FROM pg_namespace WHERE nspname LIKE 'tenant\\_%' AND nspname <> 'tenant_template' ORDER BY 1` )).rows.map((r) => r.nspname) : [args.tenant]; let totalRows = 0; let totalAmount = 0; const insertPlans = []; for (const schema of schemas) { if (!/^tenant_[a-z0-9_-]{2,30}$/.test(schema)) throw new Error(`非法 schema: ${schema}`); const params = []; const rows = (await client.query(GAP_SQL(schema, args, params), params)).rows; const amount = Math.round(rows.reduce((s, r) => s + Number(r.amount || 0), 0) * 100) / 100; report.tenants[schema] = { rows: rows.length, amount, sample: rows.slice(0, 5) }; totalRows += rows.length; totalAmount += amount; if (args.apply) insertPlans.push({ schema, rows }); console.log(`[${schema}] 候选 ${rows.length} 行 / ${amount.toFixed(2)} 元`); if (rows.length) { const show = args.printAll ? rows : rows.slice(0, 10); for (const r of show) { console.log( ` ${r.order_code} ${r.sku_code} ${r.item_name || ''} 计划${r.quantity}×${r.purchase_price} = ${r.amount}` + ` (备货完成 ${r.prepare_time || '-'})` ); } if (!args.printAll && rows.length > show.length) console.log(` ... 另有 ${rows.length - show.length} 行`); } } console.log(`\n合计:${totalRows} 行 / ${totalAmount.toFixed(2)} 元(${args.apply ? 'APPLY' : 'DRY-RUN'})`); if (args.apply && totalRows) { await client.query('BEGIN'); let inserted = 0; const insertedIds = []; for (const plan of insertPlans) { for (const row of plan.rows) { if (!(Number(row.amount) > 0)) continue; const res = await client.query(INSERT_SQL(plan.schema), [ row.cycle_code, row.amount, row.order_code, row.sku_code, row.branch_code, row.order_item_id, ]); if (res.rowCount) { inserted += 1; insertedIds.push({ tenant: plan.schema, id: res.rows[0].id, order_code: row.order_code, sku_code: row.sku_code, amount: row.amount }); } } if (insertedIds.length) { await client.query( `INSERT INTO ${plan.schema}.operation_logs (operator_id, operator_name, operator_role, operation_type, target_table, target_id, old_value, new_value, action_category, created_at) VALUES (NULL, 'backfill-script', 'system', 'cost_backfill', 'cost_details', 'prep-missing-purchase-cost', NULL, $1::jsonb, 'finance', NOW())`, [ JSON.stringify({ inserted: insertedIds.filter((i) => i.tenant === plan.schema).length, scanned: plan.rows.length, since: args.since, until: args.until, source: 'backfill-missing-prep-purchase-cost.cjs', design: 'docs/design/20260911-backfill-missing-prep-purchase-cost.md', }), ] ); } } await client.query('COMMIT'); report.inserted = inserted; report.inserted_ids = insertedIds; console.log(`已补写 ${inserted} 行(期望 ${totalRows} 行,差额为唯一索引已存在/金额为 0)`); } report.finished_at = new Date().toISOString(); report.total_rows = totalRows; report.total_amount = totalAmount; const outPath = args.out || path.resolve(process.cwd(), 'tmp', `backfill-prep-cost-${Date.now()}.json`); fs.mkdirSync(path.dirname(outPath), { recursive: true }); fs.writeFileSync(outPath, JSON.stringify(report, null, 2)); console.log(`报告:${outPath}`); } catch (e) { await client.query('ROLLBACK').catch(() => undefined); console.error('失败:', e && e.message ? e.message : e); process.exitCode = 1; } finally { client.release(); await pool.end().catch(() => undefined); } } void main();