DatabaseCreation: Change plan procedure.sql

File Change plan procedure.sql, 1.7 KB (added by 231094, 3 weeks ago)
Line 
1CREATE OR REPLACE PROCEDURE proc_change_subscription_plan(
2 p_subscription_id BIGINT,
3 p_new_plan_id BIGINT
4)
5LANGUAGE plpgsql
6AS $$
7DECLARE
8 v_old_plan_id BIGINT;
9 v_status TEXT;
10BEGIN
11 -- zemi plan i status od momentalen subs
12 SELECT plan_id, status
13 INTO v_old_plan_id, v_status
14 FROM subscriptions
15 WHERE subscription_id = p_subscription_id;
16
17 IF NOT FOUND THEN
18 RAISE EXCEPTION 'Subscription % does not exist.', p_subscription_id;
19 END IF;
20
21 -- samo activni subscritpiond se eligable
22 IF v_status NOT IN ('active', 'suspended') THEN
23 RAISE EXCEPTION 'Cannot change plan for subscription with status %.', v_status;
24 END IF;
25
26 -- proverka dali planot postoi
27 IF NOT EXISTS (
28 SELECT 1
29 FROM plans
30 WHERE plan_id = p_new_plan_id
31 AND status = 'active'
32 ) THEN
33 RAISE EXCEPTION 'Plan % does not exist or is not active.', p_new_plan_id;
34 END IF;
35
36 -- ne dozvoluvame ist plan povtorno
37 IF v_old_plan_id = p_new_plan_id THEN
38 RAISE EXCEPTION 'Subscription is already on this plan.';
39 END IF;
40
41 -- promena na planot
42 UPDATE subscriptions
43 SET plan_id = p_new_plan_id
44 WHERE subscription_id = p_subscription_id;
45
46 RAISE NOTICE 'Subscription % changed to plan %.',
47 p_subscription_id, p_new_plan_id;
48END;
49$$;
50
51--propusti (treba da menuva addons, da represmetuva fakturi...)
52
53--test
54BEGIN;
55
56CALL proc_change_subscription_plan(1, 3);
57
58SELECT
59 s.subscription_id,
60 s.plan_id,
61 p.plan_name,
62 s.status
63FROM subscriptions s
64JOIN plans p
65 ON p.plan_id = s.plan_id
66WHERE s.subscription_id = 1;
67
68ROLLBACK;