-- Triage classification fields on incidents ALTER TABLE incidents ADD COLUMN IF NOT EXISTS is_fatality BOOLEAN NOT NULL DEFAULT false, ADD COLUMN IF NOT EXISTS is_serious_bodily_injury BOOLEAN NOT NULL DEFAULT false, ADD COLUMN IF NOT EXISTS is_dangerous_occurrence BOOLEAN NOT NULL DEFAULT false, ADD COLUMN IF NOT EXISTS is_occupational_disease BOOLEAN NOT NULL DEFAULT false, ADD COLUMN IF NOT EXISTS triage_notes TEXT, ADD COLUMN IF NOT EXISTS triaged_by UUID REFERENCES users(id), ADD COLUMN IF NOT EXISTS triaged_at TIMESTAMPTZ; -- Structured RCA data on investigations ALTER TABLE investigations ADD COLUMN IF NOT EXISTS five_why_steps JSONB, ADD COLUMN IF NOT EXISTS fishbone_categories JSONB; -- Audit log write helper — SECURITY DEFINER so callers cannot bypass RLS CREATE OR REPLACE FUNCTION public.write_audit_log( p_table_name TEXT, p_record_id UUID, p_action TEXT, p_new_value JSONB DEFAULT NULL, p_old_value JSONB DEFAULT NULL ) RETURNS VOID LANGUAGE plpgsql SECURITY DEFINER AS $$ BEGIN INSERT INTO audit_log (table_name, record_id, action, changed_by, new_value, old_value) VALUES (p_table_name, p_record_id, p_action, auth.uid(), p_new_value, p_old_value); END; $$;