#!/bin/bash set -eu cd /opt/ai-fresh-delivery/server node <<'NODE' require('./dist/env.js').loadEnv(); const { pool } = require('./dist/db.js').pool ? { pool: require('./dist/db.js').pool } : require('./dist/db.js'); function safe(n) { const v = Number(n); return Number.isFinite(v) ? v : 0; } (async () => { const cycle = process.argv[1] || new Date().toISOString().slice(0, 7).replace('-', ''); console.log('cycle_code:', cycle); const orders = await pool.query(`SELECT order_code FROM orders WHERE cycle_code = $1`, [cycle]); const orderCodes = orders.rows.map((r) => r.order_code); console.log('orders_in_cycle:', orderCodes.length); const costByType = await pool.query( `SELECT cost_type, COUNT(*)::int AS cnt, SUM(COALESCE(allocated_amount, amount, 0))::numeric AS total FROM cost_details WHERE cycle_code = $1 GROUP BY cost_type ORDER BY total DESC NULLS LAST`, [cycle] ); console.log('\n=== cost_details by type ==='); for (const r of costByType.rows) { console.log(`${r.cost_type}: count=${r.cnt} total=${Number(r.total).toFixed(2)}`); } const purchaseBySku = await pool.query( `SELECT sku_code, SUM(COALESCE(allocated_amount, amount, 0))::numeric AS purchase FROM cost_details WHERE cycle_code = $1 AND LOWER(cost_type) = 'purchase' AND sku_code IS NOT NULL GROUP BY sku_code ORDER BY purchase DESC LIMIT 15`, [cycle] ); console.log('\n=== top purchase cost by sku ==='); for (const r of purchaseBySku.rows) { console.log(`${r.sku_code}: purchase=${Number(r.purchase).toFixed(2)}`); } if (!orderCodes.length) { await pool.end(); return; } const revenueBySku = await pool.query( `SELECT oi.sku_code, SUM(COALESCE(oi.quantity,0))::numeric AS qty, SUM(COALESCE(oi.amount, oi.price * oi.quantity, 0))::numeric AS revenue FROM order_items oi WHERE oi.order_code = ANY($1::text[]) GROUP BY oi.sku_code HAVING SUM(COALESCE(oi.quantity,0)) > 0 ORDER BY revenue ASC NULLS FIRST LIMIT 20`, [orderCodes] ); console.log('\n=== lowest revenue skus (margin risk) ==='); for (const r of revenueBySku.rows) { const purchase = purchaseBySku.rows.find((p) => p.sku_code === r.sku_code); const pc = purchase ? Number(purchase.purchase) : 0; const rev = Number(r.revenue); const margin = rev > 0 ? ((rev - pc) / rev) * 100 : null; console.log( `${r.sku_code}: qty=${Number(r.qty)} revenue=${rev.toFixed(2)} purchase=${pc.toFixed(2)} margin=${margin == null ? 'n/a' : margin.toFixed(1) + '%'}` ); } const lossAll = await pool.query( `SELECT sku_code, SUM(COALESCE(loss_qty,0))::numeric AS loss_qty FROM inspections WHERE sku_code IS NOT NULL GROUP BY sku_code ORDER BY loss_qty DESC LIMIT 10` ); console.log('\n=== top loss_qty (ALL TIME, not cycle filtered!) ==='); for (const r of lossAll.rows) { console.log(`${r.sku_code}: loss_qty=${Number(r.loss_qty)}`); } const outliers = ['SKU98275980670', 'SKU98266204815']; const items = await pool.query( `SELECT oi.order_code, oi.sku_code, oi.item_name, oi.quantity, oi.price, oi.amount FROM order_items oi JOIN orders o ON o.order_code = oi.order_code WHERE o.cycle_code = $1 AND oi.sku_code = ANY($2::text[])`, [cycle, outliers] ); console.log('\n=== outlier order_items ==='); console.log(JSON.stringify(items.rows, null, 2)); const costs = await pool.query( `SELECT sku_code, cost_type, amount, allocated_amount, order_code FROM cost_details WHERE cycle_code = $1 AND sku_code = ANY($2::text[])`, [cycle, outliers] ); console.log('\n=== outlier cost_details ==='); console.log(JSON.stringify(costs.rows, null, 2)); const totalRev = await pool.query( `SELECT SUM(COALESCE(oi.amount, oi.price * oi.quantity, 0))::numeric AS revenue FROM order_items oi JOIN orders o ON o.order_code = oi.order_code WHERE o.cycle_code = $1`, [cycle] ); const totalPurchase = await pool.query( `SELECT SUM(COALESCE(allocated_amount, amount, 0))::numeric AS purchase FROM cost_details WHERE cycle_code = $1 AND LOWER(cost_type) = 'purchase'`, [cycle] ); const rev = Number(totalRev.rows[0]?.revenue || 0); const pur = Number(totalPurchase.rows[0]?.purchase || 0); const weightedMargin = rev > 0 ? ((rev - pur) / rev) * 100 : 0; console.log('\n=== cycle totals ==='); console.log(`revenue=${rev.toFixed(2)} purchase=${pur.toFixed(2)} weighted_margin=${weightedMargin.toFixed(1)}%`); const mpOrders = await pool.query( `SELECT o.order_code, o.total_amount, (SELECT SUM(COALESCE(oi.amount, oi.price*oi.quantity,0)) FROM order_items oi WHERE oi.order_code=o.order_code) AS item_rev FROM orders o WHERE o.cycle_code = $1 AND o.order_code LIKE 'ORD_MP_%'`, [cycle] ); console.log('\n=== ORD_MP orders in cycle ==='); console.log(JSON.stringify(mpOrders.rows, null, 2)); await pool.end(); })().catch(async (e) => { console.error('FAIL', e.message); await pool.end(); process.exit(1); }); NODE