| 1 | CREATE OR REPLACE FUNCTION fn_get_customer_monthly_recurring_charge(
|
|---|
| 2 | p_customer_id BIGINT
|
|---|
| 3 | )
|
|---|
| 4 | RETURNS NUMERIC
|
|---|
| 5 | LANGUAGE plpgsql
|
|---|
| 6 | AS $$
|
|---|
| 7 | DECLARE
|
|---|
| 8 | v_total NUMERIC;
|
|---|
| 9 | BEGIN
|
|---|
| 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;
|
|---|
| 44 | END;
|
|---|
| 45 | $$;
|
|---|
| 46 |
|
|---|
| 47 | SELECT fn_get_customer_monthly_recurring_charge(1);
|
|---|