const { Pool } = require('pg'); async function main() { const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const code = process.argv[2] || 'ORD_MP_17839241302808VMY'; const cd = await pool.query('SELECT * FROM cost_details WHERE order_code = $1', [code]); console.log('cost rows', JSON.stringify(cd.rows, null, 2)); const sku = cd.rows[0]?.sku_code; const items = await pool.query('SELECT * FROM order_items WHERE order_code = $1', [code]); console.log( 'items', items.rows.map((r) => ({ sku: r.sku_code, qty: r.quantity, price: r.unit_price, amount: r.amount, })) ); // purchase_order_items / purchase_orders linking const tables = await pool.query(` SELECT table_name FROM information_schema.tables WHERE table_schema='public' AND table_name ILIKE '%purchase%' ORDER BY table_name`); console.log( 'purchase tables', tables.rows.map((r) => r.table_name) ); for (const t of tables.rows.map((r) => r.table_name)) { const cols = await pool.query( `SELECT column_name FROM information_schema.columns WHERE table_name=$1`, [t] ); const names = cols.rows.map((r) => r.column_name); if (!names.includes('order_code') && !names.includes('sku_code')) continue; try { let q = `SELECT * FROM ${t} WHERE 1=0`; const params = []; if (names.includes('order_code')) { q = `SELECT * FROM ${t} WHERE order_code = $1 LIMIT 20`; params.push(code); } else if (names.includes('sku_code') && sku) { q = `SELECT * FROM ${t} WHERE sku_code = $1 ORDER BY created_at DESC NULLS LAST LIMIT 5`; params.push(sku); } const rows = await pool.query(q, params); if (rows.rows.length) { console.log(`\n== ${t} ==`, JSON.stringify(rows.rows.slice(0, 5), null, 2)); } } catch (e) { console.log(t, e.message); } } // Compare sell vs cost for this sku on the order if (sku) { const line = items.rows.find((r) => r.sku_code === sku); console.log('\nmatched sell line for cost sku', line); } await pool.end(); } main().catch((e) => { console.error(e); process.exit(1); });