DatabaseProgramming: 01 Subscription status change trigger.sql

File 01 Subscription status change trigger.sql, 1.4 KB (added by 231139, 10 days ago)
Line 
1DROP TRIGGER IF EXISTS trg_log_subscription_status_change ON public.subscriptions;
2CREATE OR REPLACE FUNCTION public.trg_fn_log_subscription_status_change()
3RETURNS trigger
4LANGUAGE plpgsql
5AS $$
6DECLARE
7 v_employee_id bigint;
8 v_reason text;
9BEGIN
10 v_employee_id := NULLIF(current_setting('app.employee_id', true), '')::bigint;
11 v_reason := COALESCE(
12 NULLIF(current_setting('app.change_reason', true), ''),
13 format('Automatic log: status changed from %s to %s', OLD.status, NEW.status)
14 );
15
16 INSERT INTO public.subscription_status_history (
17 subscription_id, old_status, new_status, changed_at,
18 changed_by_employee_id, reason
19 ) VALUES (
20 NEW.subscription_id, OLD.status, NEW.status, CURRENT_TIMESTAMP,
21 v_employee_id, v_reason
22 );
23
24 UPDATE public.sim_cards sc
25 SET status = CASE
26 WHEN NEW.status = 'active' THEN 'active'
27 WHEN NEW.status = 'suspended' THEN 'suspended'
28 ELSE 'deactivated'
29 END
30 FROM public.sim_card_subscription_history ssh
31 WHERE ssh.subscription_id = NEW.subscription_id
32 AND ssh.end_date IS NULL
33 AND sc.sim_id = ssh.sim_id;
34
35 RETURN NEW;
36END;
37$$;
38
39CREATE TRIGGER trg_log_subscription_status_change
40AFTER UPDATE OF status ON public.subscriptions
41FOR EACH ROW
42WHEN (OLD.status IS DISTINCT FROM NEW.status)
43EXECUTE FUNCTION public.trg_fn_log_subscription_status_change();