const { Client } = require('pg'); const client = new Client('postgres://postgres:csh%402018@localhost:5432/ai_pharmacy'); client.connect().then(async () => { const query = ` SELECT d.id as dispensing_id, COALESCE(pat.full_name, d.subject_ref) as patient_name, d.total_amount, json_agg( json_build_object( 'batch_no', sm.batch_no, 'qty', ABS(sm.qty_delta), 'brand_name', p.brand_name ) ) as items FROM dispensing_records d LEFT JOIN patients pat ON pat.hospital_patient_id = d.subject_ref OR pat.id::text = d.subject_ref JOIN stock_movements sm ON sm.reference_id = d.id JOIN batches b ON b.batch_no = sm.batch_no JOIN products p ON p.id = b.product_id WHERE d.tenant_id = 'usr_1785482612908' GROUP BY d.id, pat.full_name ORDER BY d.created_at DESC LIMIT 5 `; const res = await client.query(query); console.log(JSON.stringify(res.rows, null, 2)); process.exit(0); }).catch(console.error);