DatabaseCreation: Outstanding customer balance.sql

File Outstanding customer balance.sql, 1.3 KB (added by 231094, 3 weeks ago)
Line 
1CREATE OR REPLACE FUNCTION fn_get_customer_outstanding_balance(p_customer_id BIGINT)
2 RETURNS NUMERIC LANGUAGE plpgsql AS $$
3DECLARE v_outstanding NUMERIC;
4BEGIN
5 SELECT COALESCE(
6 SUM(i.total_amount) - COALESCE(SUM(p_paid.amount_paid), 0), 0)
7 INTO v_outstanding
8 FROM accounts a
9 JOIN invoices i ON i.account_id = a.account_id
10 LEFT JOIN (
11 SELECT invoice_id, SUM(amount) AS amount_paid
12 FROM payments WHERE status = 'completed' GROUP BY invoice_id
13 ) p_paid ON p_paid.invoice_id = i.invoice_id
14 WHERE a.customer_id = p_customer_id
15 AND i.status NOT IN ('cancelled', 'paid');
16
17 RETURN GREATEST(v_outstanding, 0);
18END;
19$$;
20
21SELECT fn_get_customer_outstanding_balance(1) AS total_outstanding;
22
23
24-- ostatok na unpaide i uncalled za faktura
25
26SELECT
27 SUM(remaining_for_invoice) AS manual_total
28FROM (
29 SELECT
30 i.invoice_id,
31 i.total_amount - COALESCE(SUM(p.amount) FILTER (WHERE p.status = 'completed'), 0) AS remaining_for_invoice
32 FROM accounts a
33 JOIN invoices i
34 ON i.account_id = a.account_id
35 LEFT JOIN payments p
36 ON p.invoice_id = i.invoice_id
37 WHERE a.customer_id = 1
38 AND i.status not in('canceled','paid')
39 GROUP BY i.invoice_id, i.total_amount
40) x;