-- Fix: event_departments has no created_by column. -- Use auth.uid() instead of NEW.created_by in the auto-create trigger. CREATE OR REPLACE FUNCTION public.create_department_dashboard() RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path = '' AS $$ DECLARE dash_id uuid; checklist_id uuid; note_id uuid; current_user_id uuid := auth.uid(); BEGIN INSERT INTO public.department_dashboards (department_id, created_by) VALUES (NEW.id, current_user_id) RETURNING id INTO dash_id; INSERT INTO public.dashboard_panels (dashboard_id, module_type, position, config) VALUES (dash_id, 'kanban', 0, '{}'), (dash_id, 'files', 1, '{}'), (dash_id, 'checklist', 2, '{}'), (dash_id, 'notes', 3, '{}'); INSERT INTO public.department_checklists (department_id, title, created_by) VALUES (NEW.id, 'Getting Started', current_user_id) RETURNING id INTO checklist_id; INSERT INTO public.department_checklist_items (checklist_id, title, position) VALUES (checklist_id, 'Set up department goals', 0), (checklist_id, 'Assign team members', 1), (checklist_id, 'Create initial tasks', 2); INSERT INTO public.department_notes (department_id, title, content, created_by) VALUES (NEW.id, 'Welcome', 'Welcome to your department! Use this space for notes and documentation.', current_user_id); RETURN NEW; END; $$;