Files
acmcc/supabase/migrations/20260420224120_b25a17f7-e7c4-4de4-aa4b-4cdcb50a0b50.sql
2026-06-01 20:19:26 -04:00

33 lines
1.1 KiB
PL/PgSQL

CREATE OR REPLACE FUNCTION public.auto_owner_update_from_violation()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $function$
DECLARE
v_title TEXT;
v_content TEXT;
BEGIN
IF TG_OP = 'INSERT' THEN
v_title := 'Violation Issued: ' || COALESCE(NEW.title, NEW.violation_type, 'Untitled');
v_content := 'A new violation has been recorded. Category: ' || COALESCE(NEW.category, 'N/A') || '. Status: ' || COALESCE(NEW.status, 'open') || '.';
ELSIF TG_OP = 'UPDATE' AND OLD.status IS DISTINCT FROM NEW.status THEN
v_title := 'Violation Status Changed: ' || COALESCE(NEW.title, NEW.violation_type, 'Untitled');
v_content := 'Status changed from "' || COALESCE(OLD.status, 'unknown') || '" to "' || COALESCE(NEW.status, 'unknown') || '".';
ELSE
RETURN NEW;
END IF;
INSERT INTO public.owner_updates (association_id, unit_id, title, content, tags, violation_ids)
VALUES (
NEW.association_id,
NEW.unit_id,
v_title,
v_content,
'[{"name":"Violations","color":"#f59e0b"}]'::jsonb,
jsonb_build_array(NEW.id::text)
);
RETURN NEW;
END;
$function$;