DatabaseProgramming: Account balance trigger.sql

File Account balance trigger.sql, 2.7 KB (added by 231094, 3 weeks ago)
Line 
1
2CREATE OR REPLACE FUNCTION trg_fn_sync_account_balance_on_payment()
3RETURNS TRIGGER
4LANGUAGE plpgsql
5AS $$
6DECLARE
7 v_invoice_total NUMERIC;
8 v_total_paid NUMERIC;
9BEGIN
10 --promena na account balance
11 IF TG_OP = 'INSERT' THEN
12
13 -- New completed payment reduces customer debt
14 IF NEW.status = 'completed' THEN
15 UPDATE accounts
16 SET current_balance = current_balance - NEW.amount,
17 updated_at = CURRENT_TIMESTAMP
18 WHERE account_id = NEW.account_id;
19 END IF;
20
21 ELSIF TG_OP = 'UPDATE' THEN
22
23 -- sve okej
24 IF OLD.status <> 'completed' AND NEW.status = 'completed' THEN
25 UPDATE accounts
26 SET current_balance = current_balance - NEW.amount,
27 updated_at = CURRENT_TIMESTAMP
28 WHERE account_id = NEW.account_id;
29
30 -- dokolku ima greshka ili e odbien ili pending seuste se vrakjaat parite
31 ELSIF OLD.status = 'completed' AND NEW.status <> 'completed' THEN
32 UPDATE accounts
33 SET current_balance = current_balance + OLD.amount,
34 updated_at = CURRENT_TIMESTAMP
35 WHERE account_id = NEW.account_id;
36
37 -- ova e dokolku treba da se vratat pari (ima promena vo cenata na nesto)
38 ELSIF OLD.status = 'completed'
39 AND NEW.status = 'completed'
40 AND OLD.amount <> NEW.amount THEN
41 UPDATE accounts
42 SET current_balance = current_balance - (NEW.amount - OLD.amount),
43 updated_at = CURRENT_TIMESTAMP
44 WHERE account_id = NEW.account_id;
45 END IF;
46
47 END IF;
48
49
50 IF NEW.invoice_id IS NOT NULL THEN --pravime update na invoice status
51
52 SELECT total_amount
53 INTO v_invoice_total
54 FROM invoices
55 WHERE invoice_id = NEW.invoice_id;
56
57 SELECT COALESCE(SUM(amount), 0)
58 INTO v_total_paid
59 FROM payments
60 WHERE invoice_id = NEW.invoice_id
61 AND status = 'completed';
62
63 UPDATE invoices
64 SET status =
65 CASE
66 WHEN v_total_paid >= v_invoice_total THEN 'paid'
67 WHEN due_date < CURRENT_DATE THEN 'overdue'
68 ELSE 'issued'
69 END
70 WHERE invoice_id = NEW.invoice_id
71 AND status <> 'cancelled';
72
73 END IF;
74
75 RETURN NEW;
76END;
77$$;
78
79
80DROP TRIGGER trg_sync_account_balance_on_payment ON payments;
81DROP function trg_fn_sync_account_balance_on_payment();
82
83CREATE TRIGGER trg_sync_account_balance_on_payment
84AFTER INSERT OR UPDATE ON payments
85FOR EACH ROW
86EXECUTE FUNCTION trg_fn_sync_account_balance_on_payment();