| 1 | DROP VIEW IF EXISTS public.v_customer_financial_summary;
|
|---|
| 2 |
|
|---|
| 3 | CREATE VIEW public.v_customer_financial_summary AS
|
|---|
| 4 | WITH invoice_balances AS (
|
|---|
| 5 | SELECT i.account_id,
|
|---|
| 6 | i.invoice_id,
|
|---|
| 7 | i.issue_date,
|
|---|
| 8 | i.status,
|
|---|
| 9 | i.total_amount,
|
|---|
| 10 | COALESCE(SUM(p.amount) FILTER (WHERE p.status = 'completed'), 0) AS paid_amount,
|
|---|
| 11 | GREATEST(
|
|---|
| 12 | i.total_amount - COALESCE(SUM(p.amount) FILTER (WHERE p.status = 'completed'), 0),
|
|---|
| 13 | 0
|
|---|
| 14 | ) AS remaining_amount,
|
|---|
| 15 | MAX(p.payment_date) FILTER (WHERE p.status = 'completed') AS latest_payment_at
|
|---|
| 16 | FROM public.invoices i
|
|---|
| 17 | LEFT JOIN public.payments p ON p.invoice_id = i.invoice_id
|
|---|
| 18 | WHERE i.status <> 'cancelled'
|
|---|
| 19 | GROUP BY i.account_id, i.invoice_id, i.issue_date, i.status, i.total_amount
|
|---|
| 20 | ),
|
|---|
| 21 | invoice_summary AS (
|
|---|
| 22 | SELECT account_id,
|
|---|
| 23 | COUNT(*) AS invoice_count,
|
|---|
| 24 | SUM(total_amount) AS total_billed,
|
|---|
| 25 | SUM(paid_amount) AS total_paid,
|
|---|
| 26 | SUM(remaining_amount) AS outstanding_balance,
|
|---|
| 27 | SUM(remaining_amount) FILTER (WHERE status = 'overdue') AS overdue_invoice_value,
|
|---|
| 28 | COUNT(*) FILTER (WHERE status = 'overdue' AND remaining_amount > 0) AS overdue_invoice_count,
|
|---|
| 29 | MAX(issue_date) AS latest_invoice_date,
|
|---|
| 30 | MAX(latest_payment_at) AS latest_payment_at
|
|---|
| 31 | FROM invoice_balances
|
|---|
| 32 | GROUP BY account_id
|
|---|
| 33 | )
|
|---|
| 34 | SELECT
|
|---|
| 35 | c.customer_id,
|
|---|
| 36 | CASE WHEN c.customer_type = 'business' THEN c.company_name ELSE c.first_name || ' ' || c.last_name END AS customer_name,
|
|---|
| 37 | c.customer_type,
|
|---|
| 38 | a.account_id,
|
|---|
| 39 | a.account_number,
|
|---|
| 40 | a.account_status,
|
|---|
| 41 | a.credit_limit,
|
|---|
| 42 | a.current_balance,
|
|---|
| 43 | COALESCE(i.invoice_count, 0) AS invoice_count,
|
|---|
| 44 | COALESCE(i.total_billed, 0) AS total_billed,
|
|---|
| 45 | COALESCE(i.total_paid, 0) AS total_paid,
|
|---|
| 46 | COALESCE(i.outstanding_balance, 0) AS calculated_outstanding_balance,
|
|---|
| 47 | COALESCE(i.overdue_invoice_count, 0) AS overdue_invoice_count,
|
|---|
| 48 | COALESCE(i.overdue_invoice_value, 0) AS overdue_invoice_value,
|
|---|
| 49 | i.latest_invoice_date,
|
|---|
| 50 | i.latest_payment_at
|
|---|
| 51 | FROM public.customers c
|
|---|
| 52 | JOIN public.accounts a ON a.customer_id = c.customer_id
|
|---|
| 53 | LEFT JOIN invoice_summary i ON i.account_id = a.account_id;
|
|---|
| 54 |
|
|---|