#!/usr/bin/env node process.chdir('/opt/ai-fresh-delivery/server'); require('./dist/env.js').loadEnv(); const { pool } = require('./dist/db.js'); const EXECUTE = process.argv.includes('--execute'); (async () => { const client = await pool.connect(); const cycle = '202607'; try { const stmts = await client.query( `SELECT statement_no, supplier_code, total_amount, payable_amount, deduction_amount FROM supplier_statements WHERE cycle_code = $1 ORDER BY statement_no`, [cycle] ); for (const stmt of stmts.rows) { const statementNo = stmt.statement_no; const sum = await client.query( `SELECT COALESCE(SUM(line_amount), 0)::numeric AS total, COUNT(*)::int AS cnt FROM statement_lines WHERE statement_no = $1 AND statement_type = 'supplier'`, [statementNo] ); const total = Number(sum.rows[0]?.total || 0); const cnt = sum.rows[0]?.cnt || 0; const deduction = Number(stmt.deduction_amount || 0); const payable = total - deduction; if (cnt === 0) { console.log(`${statementNo}: no lines -> ${EXECUTE ? 'DELETE' : 'would delete'}`); if (EXECUTE) { await client.query(`DELETE FROM statement_disputes WHERE statement_no = $1`, [statementNo]); await client.query(`DELETE FROM supplier_statements WHERE statement_no = $1`, [statementNo]); } } else if (Number(stmt.total_amount) !== total || Number(stmt.payable_amount) !== payable) { console.log( `${statementNo}: ${stmt.total_amount}->${total}, payable ${stmt.payable_amount}->${payable} (${cnt} lines)` ); if (EXECUTE) { await client.query( `UPDATE supplier_statements SET total_amount = $2, payable_amount = $3 WHERE statement_no = $1`, [statementNo, total, payable] ); } } else { console.log(`${statementNo}: OK (${cnt} lines, ${total})`); } } } finally { client.release(); await pool.end(); } })().catch((e) => { console.error(e); process.exit(1); });