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 inspections = await pool.query( `SELECT id, sku_code, actual_qty, purchase_price, prepare_qty, ROUND((COALESCE(actual_qty,0)*COALESCE(purchase_price,0))::numeric,2) AS line_cost, inspection_time, created_at, supplier_code FROM inspections WHERE order_code = $1 ORDER BY sku_code, inspection_time DESC NULLS LAST, created_at DESC`, [code] ); console.log('inspection count', inspections.rows.length); console.log(JSON.stringify(inspections.rows, null, 2)); const latestPerSku = await pool.query( `SELECT sku_code, amt FROM ( SELECT DISTINCT ON (sku_code) sku_code, ROUND((COALESCE(actual_qty,0)*COALESCE(purchase_price,0))::numeric,2) AS amt FROM inspections WHERE order_code = $1 AND sku_code IS NOT NULL AND TRIM(sku_code) <> '' AND COALESCE(actual_qty,0) > 0 AND COALESCE(purchase_price,0) > 0 ORDER BY sku_code, inspection_time DESC NULLS LAST, created_at DESC, id DESC ) t ORDER BY amt DESC`, [code] ); const sum = latestPerSku.rows.reduce((s, r) => s + Number(r.amt), 0); console.log('\nlatest per sku sum', sum); console.log(latestPerSku.rows); const sell = await pool.query( `SELECT sku_code, item_name, quantity, price, amount FROM order_items WHERE order_code = $1`, [code] ); const bySku = Object.fromEntries(sell.rows.map((r) => [r.sku_code, r])); console.log('\nsell vs latest purchase'); for (const r of latestPerSku.rows) { const s = bySku[r.sku_code]; console.log({ sku: r.sku_code, name: s?.item_name, sell_amt: s?.amount, sell_price: s?.price, sell_qty: s?.quantity, purchase_amt: r.amt, gap: Number(r.amt) - Number(s?.amount || 0), }); } // Sum purchase_orders actual const po = await pool.query( `SELECT sku_code, COALESCE(actual_price, purchase_price, 0) AS p, COALESCE(actual_qty, purchase_qty, 0) AS q, ROUND((COALESCE(actual_price, purchase_price, 0)*COALESCE(actual_qty, purchase_qty, 0))::numeric,2) AS amt FROM purchase_orders WHERE order_code = $1`, [code] ); console.log( '\nPO sum', po.rows.reduce((s, r) => s + Number(r.amt), 0), po.rows ); await pool.end(); } main().catch((e) => { console.error(e); process.exit(1); });