Files
cloudlense/frontend/supabase/migrations/20250813102538_fix_handle_new_user.sql
Dennis 50e25e3ee8 refactor: flatten monorepo structure to backend/ frontend/ devops/
Rename subdirectories for a cleaner single-repo layout:
- website-monitoring-backend/  → backend/
- website-monitoring-frontend/ → frontend/
- website-monitoring-devops/   → devops/

Update all references in package.json scripts, CI workflows,
docker-compose, pre-commit hooks, and documentation.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-07 00:25:29 +01:00

67 lines
1.6 KiB
PL/PgSQL

-- Fix the handle_new_user function to use existing organization if provided
CREATE OR REPLACE FUNCTION public.handle_new_user()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public', 'auth'
AS $function$
DECLARE
organization_id UUID;
BEGIN
-- Check if organization_id is provided in metadata
IF NEW.raw_user_meta_data->>'organization_id' IS NOT NULL THEN
-- Use the existing organization
organization_id := (NEW.raw_user_meta_data->>'organization_id')::UUID;
ELSE
-- Create new organization if none provided
INSERT INTO public.organizations (
name,
subscription_tier,
subscription_status
) VALUES (
COALESCE(NEW.raw_user_meta_data->>'organization_name', NEW.raw_user_meta_data->>'name' || '''s Organization'),
'free',
'active'
)
RETURNING id INTO organization_id;
END IF;
-- Create the user profile
INSERT INTO public.users (
id,
email,
name,
organization_id,
role,
is_active,
settings,
created_at,
updated_at
) VALUES (
NEW.id,
NEW.email,
COALESCE(NEW.raw_user_meta_data->>'name', split_part(NEW.email, '@', 1)),
organization_id,
COALESCE(NEW.raw_user_meta_data->>'role', 'owner')::user_role,
true,
jsonb_build_object(
'email_notifications', true,
'notification_frequency', 'instant',
'dashboard_layout', 'default'
),
NOW(),
NOW()
);
RETURN NEW;
EXCEPTION
WHEN others THEN
-- Log the error (will appear in Postgres logs)
RAISE LOG 'Error in handle_new_user: %', SQLERRM;
RETURN NEW;
END;
$function$;
-- Refresh schema cache
NOTIFY pgrst, 'reload schema';