/** * 一套账 9丙:有 unit_cost、缺采购账本行 → 补 purchase; * 有采购行 → 用账本金额反写 unit_cost(按 qty 均摊单价)。 * * 用法(在 server 目录或根目录,需 DATABASE_URL): * node scripts/backfill-purchase-ledger-from-unit-cost.cjs [--dry-run] [--branch=CODE] */ /* eslint-disable no-console */ const path = require('path'); const fs = require('fs'); const { Client } = require('pg'); function loadEnv() { const candidates = [ path.join(__dirname, '../server/.env'), path.join(__dirname, '../.env'), ]; for (const p of candidates) { if (!fs.existsSync(p)) continue; for (const line of fs.readFileSync(p, 'utf8').split(/\r?\n/)) { const m = /^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line); if (!m || process.env[m[1]]) continue; let v = m[2].trim(); if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) { v = v.slice(1, -1); } process.env[m[1]] = v; } } } async function main() { loadEnv(); const dryRun = process.argv.includes('--dry-run'); const branchArg = process.argv.find((a) => a.startsWith('--branch=')); const branch = branchArg ? branchArg.slice('--branch='.length).trim() : ''; const url = process.env.ADMIN_DATABASE_URL || process.env.DATABASE_URL; if (!url) { console.error('缺少 DATABASE_URL'); process.exit(1); } const client = new Client({ connectionString: url }); await client.connect(); const branchSql = branch ? 'AND o.branch_code = $1' : ''; const params = branch ? [branch] : []; // 9甲:有 unit_cost 合计金额、无非加菜 purchase 行 → 补行 const missing = await client.query( `SELECT o.order_code, oi.sku_code, o.cycle_code, o.branch_code, SUM(COALESCE(oi.quantity,0))::numeric AS qty, SUM(COALESCE(oi.quantity,0) * COALESCE(oi.unit_cost,0))::numeric AS amt FROM orders o JOIN order_items oi ON oi.order_code = o.order_code WHERE o.deleted_at IS NULL AND oi.sku_code IS NOT NULL AND TRIM(oi.sku_code) <> '' AND COALESCE(oi.unit_cost, 0) > 0 ${branchSql} AND NOT EXISTS ( SELECT 1 FROM cost_details cd WHERE cd.order_code = o.order_code AND cd.cost_type = 'purchase' AND cd.sku_code = oi.sku_code AND COALESCE(cd.cost_source, '') IS DISTINCT FROM 'extra_dish' ) GROUP BY o.order_code, oi.sku_code, o.cycle_code, o.branch_code HAVING SUM(COALESCE(oi.quantity,0) * COALESCE(oi.unit_cost,0)) > 0`, params ); console.log(`补采购行候选: ${missing.rowCount}${dryRun ? ' (dry-run)' : ''}`); let inserted = 0; if (!dryRun) { for (const row of missing.rows) { const cycle = String(row.cycle_code || '').trim() || `${new Date().getFullYear()}${String(new Date().getMonth() + 1).padStart(2, '0')}`; const amt = Math.round(Number(row.amt || 0) * 100) / 100; try { await client.query( `INSERT INTO cost_details ( cycle_code, cost_type, cost_subtype, amount, order_code, sku_code, allocation_method, allocated_amount, status, branch_code, cost_source, remark ) VALUES ($1, 'purchase', 'order_goods', $2, $3, $4, 'sku', $2, 20, $5, 'supplier', 'backfill_unit_cost')`, [cycle, amt, row.order_code, row.sku_code, row.branch_code] ); inserted += 1; } catch (e) { if (e.code !== '23505') console.error(row.order_code, row.sku_code, e.message); } } } // 9乙:有采购行 → 回写 unit_cost = amount/qty const rewrite = await client.query( `SELECT cd.order_code, cd.sku_code, SUM(COALESCE(cd.amount,0))::numeric AS amt, ( SELECT COALESCE(SUM(COALESCE(oi.quantity,0)),0) FROM order_items oi WHERE oi.order_code = cd.order_code AND oi.sku_code = cd.sku_code )::numeric AS qty FROM cost_details cd JOIN orders o ON o.order_code = cd.order_code AND o.deleted_at IS NULL WHERE cd.cost_type = 'purchase' AND cd.sku_code IS NOT NULL AND TRIM(cd.sku_code) <> '' AND COALESCE(cd.cost_source, '') IS DISTINCT FROM 'extra_dish' ${branchSql.replace(/o\.branch_code/g, 'o.branch_code')} GROUP BY cd.order_code, cd.sku_code HAVING SUM(COALESCE(cd.amount,0)) > 0`, params ); console.log(`回写 unit_cost 候选: ${rewrite.rowCount}${dryRun ? ' (dry-run)' : ''}`); let updated = 0; if (!dryRun) { for (const row of rewrite.rows) { const qty = Number(row.qty) || 0; if (!(qty > 0)) continue; const unit = Math.round((Number(row.amt) / qty) * 10000) / 10000; const r = await client.query( `UPDATE order_items SET unit_cost = $1::numeric WHERE order_code = $2 AND sku_code = $3 AND COALESCE(unit_cost,0) IS DISTINCT FROM $1::numeric`, [unit, row.order_code, row.sku_code] ); updated += r.rowCount || 0; } } console.log(JSON.stringify({ dryRun, branch: branch || null, inserted, unitCostRowsTouched: updated }, null, 2)); await client.end(); } main().catch((e) => { console.error(e); process.exit(1); });