| 1 | -- Duplicate active SIM protection is already stronger in the DDL through the
|
|---|
| 2 | -- temporal exclusion constraint. Remove the obsolete legacy trigger if present.
|
|---|
| 3 | DROP TRIGGER IF EXISTS trg_prevent_duplicate_active_sim ON public.sim_card_subscription_history;
|
|---|
| 4 | DROP FUNCTION IF EXISTS public.trg_fn_prevent_duplicate_active_sim();
|
|---|
| 5 |
|
|---|
| 6 | -- The DDL exclusion constraint prevents one SIM from overlapping across
|
|---|
| 7 | -- subscriptions. This complementary rule prevents one subscription from
|
|---|
| 8 | -- holding two current SIMs.
|
|---|
| 9 | CREATE UNIQUE INDEX IF NOT EXISTS uq_sim_history_one_current_per_subscription
|
|---|
| 10 | ON public.sim_card_subscription_history (subscription_id)
|
|---|
| 11 | WHERE end_date IS NULL;
|
|---|
| 12 | DROP TRIGGER IF EXISTS trg_sync_sim_status_from_history ON public.sim_card_subscription_history;
|
|---|
| 13 | CREATE OR REPLACE FUNCTION public.trg_fn_sync_sim_status_from_history()
|
|---|
| 14 | RETURNS trigger
|
|---|
| 15 | LANGUAGE plpgsql
|
|---|
| 16 | AS $$
|
|---|
| 17 | DECLARE
|
|---|
| 18 | v_new_sim_id bigint;
|
|---|
| 19 | v_old_sim_id bigint;
|
|---|
| 20 | v_sim_id bigint;
|
|---|
| 21 | v_subscription_status text;
|
|---|
| 22 | BEGIN
|
|---|
| 23 | IF TG_OP <> 'DELETE' THEN v_new_sim_id := NEW.sim_id; END IF;
|
|---|
| 24 | IF TG_OP <> 'INSERT' THEN v_old_sim_id := OLD.sim_id; END IF;
|
|---|
| 25 |
|
|---|
| 26 | FOREACH v_sim_id IN ARRAY ARRAY[v_new_sim_id, v_old_sim_id]
|
|---|
| 27 | LOOP
|
|---|
| 28 | IF v_sim_id IS NULL THEN CONTINUE; END IF;
|
|---|
| 29 |
|
|---|
| 30 | SELECT s.status INTO v_subscription_status
|
|---|
| 31 | FROM public.sim_card_subscription_history ssh
|
|---|
| 32 | JOIN public.subscriptions s ON s.subscription_id = ssh.subscription_id
|
|---|
| 33 | WHERE ssh.sim_id = v_sim_id AND ssh.end_date IS NULL
|
|---|
| 34 | ORDER BY ssh.start_date DESC
|
|---|
| 35 | LIMIT 1;
|
|---|
| 36 |
|
|---|
| 37 | UPDATE public.sim_cards
|
|---|
| 38 | SET status = CASE
|
|---|
| 39 | WHEN v_subscription_status = 'suspended' THEN 'suspended'
|
|---|
| 40 | WHEN v_subscription_status IS NOT NULL THEN 'active'
|
|---|
| 41 | WHEN EXISTS (
|
|---|
| 42 | SELECT 1 FROM public.sim_card_subscription_history h WHERE h.sim_id = v_sim_id
|
|---|
| 43 | ) THEN 'deactivated'
|
|---|
| 44 | ELSE 'available'
|
|---|
| 45 | END
|
|---|
| 46 | WHERE sim_id = v_sim_id;
|
|---|
| 47 | END LOOP;
|
|---|
| 48 |
|
|---|
| 49 | IF TG_OP = 'DELETE' THEN RETURN OLD; END IF;
|
|---|
| 50 | RETURN NEW;
|
|---|
| 51 | END;
|
|---|
| 52 | $$;
|
|---|
| 53 |
|
|---|
| 54 | CREATE TRIGGER trg_sync_sim_status_from_history
|
|---|
| 55 | AFTER INSERT OR UPDATE OR DELETE ON public.sim_card_subscription_history
|
|---|
| 56 | FOR EACH ROW
|
|---|
| 57 | EXECUTE FUNCTION public.trg_fn_sync_sim_status_from_history();
|
|---|