-- Onboarding answers and on-site activity, used to build each user's roadmap. -- Nothing personal: just what they want from the site, their level and what they've watched or finished. -- ── learning_profiles ────────────────────────────────────── -- One row per user: their answers to the onboarding questions. Retaking the questions overwrites it. CREATE TABLE IF NOT EXISTS public.learning_profiles ( user_id uuid PRIMARY KEY REFERENCES public.users (id) ON DELETE CASCADE, goals text[] NOT NULL DEFAULT '{}', tracks text[] NOT NULL DEFAULT '{}', level text NOT NULL CHECK (level IN ('Beginner', 'Intermediate', 'Advanced')), weekly_time text NOT NULL CHECK (weekly_time IN ('light', 'steady', 'deep')), format text NOT NULL CHECK (format IN ('video', 'written', 'both')), created_at timestamptz NOT NULL DEFAULT now(), updated_at timestamptz NOT NULL DEFAULT now() ); ALTER TABLE public.learning_profiles ENABLE ROW LEVEL SECURITY; CREATE POLICY "learning_profiles_own" ON public.learning_profiles FOR ALL USING ((select auth.uid()) = user_id) WITH CHECK ((select auth.uid()) = user_id); -- ── tutorial_activity ────────────────────────────────────── -- Which tutorials a user has opened, how often, and which they've marked done on their roadmap. CREATE TABLE IF NOT EXISTS public.tutorial_activity ( user_id uuid NOT NULL REFERENCES public.users (id) ON DELETE CASCADE, tutorial_slug text NOT NULL, view_count integer NOT NULL DEFAULT 0, first_viewed_at timestamptz, last_viewed_at timestamptz, completed_at timestamptz, PRIMARY KEY (user_id, tutorial_slug) ); ALTER TABLE public.tutorial_activity ENABLE ROW LEVEL SECURITY; CREATE POLICY "tutorial_activity_own" ON public.tutorial_activity FOR ALL USING ((select auth.uid()) = user_id) WITH CHECK ((select auth.uid()) = user_id); -- Counts a view for the signed-in user (one call per page open) CREATE OR REPLACE FUNCTION public.record_tutorial_view(p_slug text) RETURNS void LANGUAGE sql SECURITY INVOKER SET search_path = '' AS $$ INSERT INTO public.tutorial_activity (user_id, tutorial_slug, view_count, first_viewed_at, last_viewed_at) VALUES ((select auth.uid()), p_slug, 1, now(), now()) ON CONFLICT (user_id, tutorial_slug) DO UPDATE SET view_count = public.tutorial_activity.view_count + 1, last_viewed_at = now(); $$; REVOKE EXECUTE ON FUNCTION public.record_tutorial_view(text) FROM public, anon; GRANT EXECUTE ON FUNCTION public.record_tutorial_view(text) TO authenticated;