diff --git a/server/src/routes/data.ts b/server/src/routes/data.ts index 97ff558..1980e3a 100644 --- a/server/src/routes/data.ts +++ b/server/src/routes/data.ts @@ -20,9 +20,9 @@ router.get('/overview', async (req: AuthRequest, res) => { round(sum(received_total)::numeric, 2) AS received, round(avg(received_total)::numeric, 2) AS avg_bill_value, round(avg(CASE WHEN consumption > 0 THEN discount_total::numeric / consumption * 100 ELSE 0 END)::numeric, 2) AS discount_rate_pct, - 0 AS theoretical_margin_pct, - 0 AS member_bills, - 0 AS member_share_pct, + round(sum(theoretical_profit) / nullif(sum(received_total), 0) * 100, 2) AS theoretical_margin_pct, + count(*) FILTER (WHERE member_id IS NOT NULL AND member_id <> '') AS member_bills, + round(sum(received_total) FILTER (WHERE member_id IS NOT NULL AND member_id <> '') / nullif(sum(received_total), 0) * 100, 2) AS member_share_pct, round(sum(consumption)::numeric, 2) AS consumption, round(sum(discount_total)::numeric, 2) AS discount FROM analytics.bill_fact @@ -31,13 +31,19 @@ router.get('/overview', async (req: AuthRequest, res) => { sendSuccess(res, result.rows[0]) } else { const result = await query(` - SELECT o.bill_count, o.received, o.avg_bill_value, o.discount_rate_pct, o.theoretical_margin_pct, o.member_bills, o.member_share_pct, - round(b.consumption::numeric, 2) AS consumption, - round(b.discount::numeric, 2) AS discount + SELECT o.bill_count, o.received, o.avg_bill_value, o.discount_rate_pct, + round(b.theoretical_margin_pct, 2) AS theoretical_margin_pct, + b.member_bills, b.member_share_pct, + round(b.consumption, 2) AS consumption, + round(b.discount, 2) AS discount FROM analytics.mv_overview_monthly o LEFT JOIN ( - SELECT round(sum(consumption)::numeric, 2) AS consumption, - round(sum(discount_total)::numeric, 2) AS discount + SELECT + round(sum(consumption)::numeric, 2) AS consumption, + round(sum(discount_total)::numeric, 2) AS discount, + round(sum(theoretical_profit) / nullif(sum(received_total), 0) * 100, 2) AS theoretical_margin_pct, + count(*) FILTER (WHERE member_id IS NOT NULL AND member_id <> '') AS member_bills, + round(sum(received_total) FILTER (WHERE member_id IS NOT NULL AND member_id <> '') / nullif(sum(received_total), 0) * 100, 2) AS member_share_pct FROM analytics.bill_fact WHERE closed_at >= $1::date AND closed_at < ($1::date + interval '1 month') ) b ON true