/** * Re-run fixed cost daily allocation on prod after bugfix. * Usage: cd server && NODE_PATH=./node_modules node --env-file=.env /tmp/prod-reallocate-fixed-costs.cjs * ... --execute */ const { Pool } = require('pg'); const EXECUTE = process.argv.includes('--execute'); const CYCLE = process.argv.find((a) => a.startsWith('--cycle='))?.slice(8) || '202607'; function round2(n) { return Math.round(Number(n || 0) * 100) / 100; } function daysInCycle(cycleCode) { if (/^\d{6}$/.test(cycleCode)) { const y = Number(cycleCode.slice(0, 4)); const m = Number(cycleCode.slice(4, 6)); return new Date(Date.UTC(y, m, 0)).getUTCDate(); } return 30; } const LEDGER = { rent: 'rent', vehicle: 'transport', salary: 'labor', equipment: 'warehouse', packaging: 'packaging', other: 'fixed_overhead', }; async function allocateOne(client, row) { const costType = LEDGER[String(row.cost_type)] || 'fixed_overhead'; const poolAmount = round2(row.actual_amount); const dayCount = daysInCycle(String(row.cycle_code)); const dailyRate = round2(poolAmount / dayCount); await client.query(`DELETE FROM cost_details WHERE reference_type = 'fixed_cost' AND reference_id = $1`, [ row.id, ]); const orders = await client.query( `SELECT o.order_code, o.branch_code, to_char((COALESCE(o.delivery_date, o.created_at) AT TIME ZONE 'Asia/Shanghai')::date, 'YYYY-MM-DD') AS delivery_day FROM orders o WHERE o.cycle_code = $1 AND ($2::text IS NULL OR o.branch_code = $2) AND o.order_status >= 20 ORDER BY o.order_code`, [row.cycle_code, row.branch_code || null] ); const dayCounts = new Map(); for (const o of orders.rows) { const key = o.delivery_day || o.order_code; dayCounts.set(key, (dayCounts.get(key) || 0) + 1); } const activeDays = dayCounts.size; let orderSum = 0; for (const o of orders.rows) { const key = o.delivery_day || o.order_code; const sameDay = dayCounts.get(key) || 1; const allocated = round2(dailyRate / sameDay); if (allocated <= 0) continue; orderSum = round2(orderSum + allocated); await client.query( `INSERT INTO cost_details ( cycle_code, cost_type, cost_subtype, order_code, amount, allocation_method, allocated_amount, status, branch_code, reference_type, reference_id, created_at ) VALUES ($1,$2,$3,$4,$5,'days30',$5,20,$6,'fixed_cost',$7,NOW())`, [ row.cycle_code, costType, row.cost_type, o.order_code, allocated, o.branch_code || row.branch_code || null, row.id, ] ); } // fix rounding vs activeDays * dailyRate const target = round2(dailyRate * activeDays); const diff = round2(target - orderSum); if (diff !== 0 && orders.rows.length) { await client.query( `UPDATE cost_details SET amount = amount + $1, allocated_amount = allocated_amount + $1 WHERE reference_type = 'fixed_cost' AND reference_id = $2 AND order_code = $3`, [diff, row.id, orders.rows[orders.rows.length - 1].order_code] ); orderSum = round2(orderSum + diff); } const residual = round2(poolAmount - orderSum); if (residual > 0.009) { await client.query( `INSERT INTO cost_details ( cycle_code, cost_type, cost_subtype, order_code, amount, allocation_method, allocated_amount, status, branch_code, reference_type, reference_id, created_at ) VALUES ($1,$2,$3,NULL,$4,'days30',$4,20,$5,'fixed_cost',$6,NOW())`, [ row.cycle_code, costType, `${row.cost_type}_residual`, residual, row.branch_code || null, row.id, ] ); } return { id: row.id, cost_type: row.cost_type, poolAmount, dayCount, activeDays, orderSum, residual }; } async function main() { const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const client = await pool.connect(); try { const fc = await client.query( `SELECT * FROM fixed_costs WHERE status = 20 AND cycle_code = $1 AND COALESCE(actual_amount,0) > 0 ORDER BY created_at ASC`, [CYCLE] ); console.log(`=== fixed cost reallocate cycle=${CYCLE} (${EXECUTE ? 'EXECUTE' : 'DRY-RUN'}) ===`); console.log(`rows=${fc.rows.length}`); if (!EXECUTE) { for (const row of fc.rows) { const dayCount = daysInCycle(String(row.cycle_code)); console.log( `- ${row.cost_type} ¥${row.actual_amount} / ${dayCount}天 = ¥${round2(Number(row.actual_amount) / dayCount)}/天` ); } console.log('加 --execute 执行'); return; } await client.query('BEGIN'); // wipe unreferenced historical days30 lines in cycle const wiped = await client.query( `DELETE FROM cost_details WHERE cycle_code = $1 AND allocation_method = 'days30' AND (reference_id IS NULL OR reference_type IS DISTINCT FROM 'fixed_cost')`, [CYCLE] ); console.log('wiped legacy days30 rows', wiped.rowCount); for (const row of fc.rows) { const result = await allocateOne(client, row); console.log(JSON.stringify(result)); } await client.query('COMMIT'); console.log('done'); } catch (e) { await client.query('ROLLBACK').catch(() => undefined); throw e; } finally { client.release(); await pool.end(); } } main().catch((e) => { console.error(e); process.exit(1); });