Files
cloudlense/website-monitoring-frontend/supabase/migrations/20250813102538_fix_handle_new_user.sql
T
Dennis 14a32bdc0d feat: initialize monorepo with full dev team best practices
- Unified monorepo with backend (Express), frontend (Next.js), and devops
- Backend: ESLint, Prettier, Jest tests (3 passing), health endpoint, .env.example
- Frontend: Fixed build errors, fixed all lint errors (0 remaining), tests passing
- DevOps: Docker Compose with PostgreSQL, backend, frontend + healthchecks
- CI/CD: 3 GitHub Actions workflows (backend, frontend, docker integration)
- DX: Husky pre-commit hooks with smart change detection
- Docs: Root README with architecture, CONTRIBUTING.md, PR template

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-03-06 00:05:50 +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';