DatabaseCreation: Total monthly reccuring charge.sql

File Total monthly reccuring charge.sql, 1.3 KB (added by 231094, 3 weeks ago)
Line 
1CREATE OR REPLACE FUNCTION fn_get_customer_monthly_recurring_charge(
2 p_customer_id BIGINT
3)
4RETURNS NUMERIC
5LANGUAGE plpgsql
6AS $$
7DECLARE
8 v_total NUMERIC;
9BEGIN
10 SELECT COALESCE(SUM(x.amount), 0)
11 INTO v_total
12 FROM (
13 -- Active plan monthly fees
14 SELECT p.monthly_fee AS amount
15 FROM accounts a
16 JOIN subscriptions s
17 ON s.account_id = a.account_id
18 JOIN plans p
19 ON p.plan_id = s.plan_id
20 WHERE a.customer_id = p_customer_id
21 AND s.status = 'active'
22 AND p.status = 'active'
23
24 UNION ALL
25
26 -- Active recurring add-ons
27 SELECT sa.price_at_activation AS amount
28 FROM accounts a
29 JOIN subscriptions s
30 ON s.account_id = a.account_id
31 JOIN subscription_addons sa
32 ON sa.subscription_id = s.subscription_id
33 JOIN addons ad
34 ON ad.addon_id = sa.addon_id
35 WHERE a.customer_id = p_customer_id
36 AND s.status = 'active'
37 AND sa.status = 'active'
38 AND sa.deactivation_date IS NULL
39 AND ad.is_recurring = true
40 AND ad.status = 'active'
41 ) x;
42
43 RETURN v_total;
44END;
45$$;
46
47SELECT fn_get_customer_monthly_recurring_charge(1);