| 1 | DROP VIEW IF EXISTS public.v_customer_invoice_detail;
|
|---|
| 2 |
|
|---|
| 3 | CREATE VIEW public.v_customer_invoice_detail AS
|
|---|
| 4 | WITH payment_summary AS (
|
|---|
| 5 | SELECT invoice_id,
|
|---|
| 6 | SUM(amount) FILTER (WHERE status = 'completed') AS completed_payment_amount,
|
|---|
| 7 | COUNT(*) FILTER (WHERE status = 'completed') AS completed_payment_count,
|
|---|
| 8 | MAX(payment_date) FILTER (WHERE status = 'completed') AS last_payment_at
|
|---|
| 9 | FROM public.payments
|
|---|
| 10 | WHERE invoice_id IS NOT NULL
|
|---|
| 11 | GROUP BY invoice_id
|
|---|
| 12 | )
|
|---|
| 13 | SELECT
|
|---|
| 14 | c.customer_id,
|
|---|
| 15 | CASE WHEN c.customer_type = 'business' THEN c.company_name ELSE c.first_name || ' ' || c.last_name END AS customer_name,
|
|---|
| 16 | a.account_number,
|
|---|
| 17 | bc.cycle_name AS billing_cycle,
|
|---|
| 18 | i.invoice_id,
|
|---|
| 19 | i.invoice_number,
|
|---|
| 20 | i.billing_period_start,
|
|---|
| 21 | i.billing_period_end,
|
|---|
| 22 | i.issue_date,
|
|---|
| 23 | i.due_date,
|
|---|
| 24 | i.total_amount AS invoice_total,
|
|---|
| 25 | i.tax_amount,
|
|---|
| 26 | i.discount_amount,
|
|---|
| 27 | i.status AS invoice_status,
|
|---|
| 28 | COALESCE(ps.completed_payment_amount, 0) AS invoice_paid_amount,
|
|---|
| 29 | GREATEST(i.total_amount - COALESCE(ps.completed_payment_amount, 0), 0) AS invoice_remaining_amount,
|
|---|
| 30 | ps.completed_payment_count,
|
|---|
| 31 | ps.last_payment_at,
|
|---|
| 32 | ii.invoice_item_id,
|
|---|
| 33 | ii.item_type,
|
|---|
| 34 | ii.description AS item_description,
|
|---|
| 35 | ii.quantity,
|
|---|
| 36 | ii.unit_price,
|
|---|
| 37 | ii.line_amount,
|
|---|
| 38 | s.subscription_number,
|
|---|
| 39 | p.plan_name
|
|---|
| 40 | FROM public.customers c
|
|---|
| 41 | JOIN public.accounts a ON a.customer_id = c.customer_id
|
|---|
| 42 | LEFT JOIN public.billing_cycles bc ON bc.billing_cycle_id = a.billing_cycle_id
|
|---|
| 43 | JOIN public.invoices i ON i.account_id = a.account_id
|
|---|
| 44 | JOIN public.invoice_items ii ON ii.invoice_id = i.invoice_id
|
|---|
| 45 | LEFT JOIN public.subscriptions s ON s.subscription_id = ii.subscription_id
|
|---|
| 46 | LEFT JOIN public.plans p ON p.plan_id = s.plan_id
|
|---|
| 47 | LEFT JOIN payment_summary ps ON ps.invoice_id = i.invoice_id;
|
|---|
| 48 |
|
|---|
| 49 |
|
|---|
| 50 | COMMENT ON VIEW public.v_customer_invoice_detail IS
|
|---|
| 51 | 'One row per invoice item. Invoice-level payment totals repeat by design and must not be summed across item rows.';
|
|---|