| 1 | CREATE OR REPLACE PROCEDURE proc_activate_subscription(
|
|---|
| 2 | p_account_id BIGINT,
|
|---|
| 3 | p_plan_id BIGINT,
|
|---|
| 4 | p_sim_id BIGINT
|
|---|
| 5 | )
|
|---|
| 6 | LANGUAGE plpgsql
|
|---|
| 7 | AS $$
|
|---|
| 8 | DECLARE
|
|---|
| 9 | v_subscription_id BIGINT;
|
|---|
| 10 | v_subscription_number TEXT;
|
|---|
| 11 | BEGIN
|
|---|
| 12 | -- Check if account exists and is active
|
|---|
| 13 | IF NOT EXISTS (
|
|---|
| 14 | SELECT 1
|
|---|
| 15 | FROM accounts
|
|---|
| 16 | WHERE account_id = p_account_id
|
|---|
| 17 | AND account_status = 'active'
|
|---|
| 18 | ) THEN
|
|---|
| 19 | RAISE EXCEPTION 'Account % does not exist or is not active.', p_account_id;
|
|---|
| 20 | END IF;
|
|---|
| 21 |
|
|---|
| 22 | -- Check if plan exists and is active
|
|---|
| 23 | IF NOT EXISTS (
|
|---|
| 24 | SELECT 1
|
|---|
| 25 | FROM plans
|
|---|
| 26 | WHERE plan_id = p_plan_id
|
|---|
| 27 | AND status = 'active'
|
|---|
| 28 | ) THEN
|
|---|
| 29 | RAISE EXCEPTION 'Plan % does not exist or is not active.', p_plan_id;
|
|---|
| 30 | END IF;
|
|---|
| 31 |
|
|---|
| 32 | -- Check if SIM card exists and is available
|
|---|
| 33 | IF NOT EXISTS (
|
|---|
| 34 | SELECT 1
|
|---|
| 35 | FROM sim_cards
|
|---|
| 36 | WHERE sim_id = p_sim_id
|
|---|
| 37 | AND status = 'available'
|
|---|
| 38 | ) THEN
|
|---|
| 39 | RAISE EXCEPTION 'SIM card % does not exist or is not available.', p_sim_id;
|
|---|
| 40 | END IF;
|
|---|
| 41 |
|
|---|
| 42 | -- Generate subscription number
|
|---|
| 43 | v_subscription_number := 'SUB-' || FLOOR(RANDOM() * 100000000)::BIGINT;
|
|---|
| 44 |
|
|---|
| 45 | -- Create subscription
|
|---|
| 46 | INSERT INTO subscriptions (
|
|---|
| 47 | account_id,
|
|---|
| 48 | plan_id,
|
|---|
| 49 | subscription_number,
|
|---|
| 50 | activation_date,
|
|---|
| 51 | status,
|
|---|
| 52 | billing_start_date
|
|---|
| 53 | )
|
|---|
| 54 | VALUES (
|
|---|
| 55 | p_account_id,
|
|---|
| 56 | p_plan_id,
|
|---|
| 57 | v_subscription_number,
|
|---|
| 58 | CURRENT_DATE,
|
|---|
| 59 | 'active',
|
|---|
| 60 | CURRENT_DATE
|
|---|
| 61 | )
|
|---|
| 62 | RETURNING subscription_id INTO v_subscription_id;
|
|---|
| 63 |
|
|---|
| 64 | -- Assign SIM card to the subscription
|
|---|
| 65 | INSERT INTO sim_card_subscription_history (
|
|---|
| 66 | sim_id,
|
|---|
| 67 | subscription_id,
|
|---|
| 68 | start_date,
|
|---|
| 69 | end_date
|
|---|
| 70 | )
|
|---|
| 71 | VALUES (
|
|---|
| 72 | p_sim_id,
|
|---|
| 73 | v_subscription_id,
|
|---|
| 74 | CURRENT_TIMESTAMP,
|
|---|
| 75 | NULL
|
|---|
| 76 | );
|
|---|
| 77 |
|
|---|
| 78 | -- Mark SIM card as active
|
|---|
| 79 | UPDATE sim_cards
|
|---|
| 80 | SET status = 'active',
|
|---|
| 81 | issued_at = CURRENT_TIMESTAMP
|
|---|
| 82 | WHERE sim_id = p_sim_id;
|
|---|
| 83 |
|
|---|
| 84 | RAISE NOTICE 'Subscription % activated successfully.', v_subscription_number;
|
|---|
| 85 | END;
|
|---|
| 86 | $$;
|
|---|
| 87 |
|
|---|