From 219167eebff7c66cc384259d97e9a36ab7340131 Mon Sep 17 00:00:00 2001 From: Kev Date: Sat, 11 Jul 2026 19:54:16 -0400 Subject: [PATCH] =?UTF-8?q?A1:=20migration=20021=20=E2=80=94=20partner=20a?= =?UTF-8?q?ttribution=20(pre-apply=20commit,=20per=20docs/PARTNERS.md)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Fable 5 --- supabase/migrations/021_partner_ref.sql | 46 +++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 supabase/migrations/021_partner_ref.sql diff --git a/supabase/migrations/021_partner_ref.sql b/supabase/migrations/021_partner_ref.sql new file mode 100644 index 0000000..01921f4 --- /dev/null +++ b/supabase/migrations/021_partner_ref.sql @@ -0,0 +1,46 @@ +-- --------------------------------------------------------------- +-- 021 — partner attribution (A1 Session 3, per docs/PARTNERS.md). +-- +-- Adds user_profiles.partner_ref (the external partner code captured from +-- the ?ref= cookie at signup and stored in auth metadata), extends +-- handle_new_user to copy it on profile creation (verified against the +-- LIVE function definition — it inserts (id, email) only; this adds one +-- column and preserves SECURITY DEFINER + search_path), and backfills +-- rows whose auth metadata already carries a ref. +-- +-- Distinct from migration 004's USER-referral system: partner codes are +-- external strings; no dependency on referral_codes tables. +-- --------------------------------------------------------------- + +ALTER TABLE public.user_profiles + ADD COLUMN IF NOT EXISTS partner_ref text; + +CREATE INDEX IF NOT EXISTS idx_user_profiles_partner_ref + ON public.user_profiles(partner_ref) + WHERE partner_ref IS NOT NULL; + +CREATE OR REPLACE FUNCTION public.handle_new_user() +RETURNS trigger +LANGUAGE plpgsql +SECURITY DEFINER +SET search_path TO 'public' +AS $function$ +begin + insert into public.user_profiles (id, email, partner_ref) + values ( + new.id, + new.email, + upper(nullif(new.raw_user_meta_data->>'partner_ref', '')) + ) + on conflict (id) do nothing; + return new; +end; +$function$; + +-- One-time backfill for signups that predate the column. +UPDATE public.user_profiles p +SET partner_ref = upper(u.raw_user_meta_data->>'partner_ref') +FROM auth.users u +WHERE u.id = p.id + AND p.partner_ref IS NULL + AND nullif(u.raw_user_meta_data->>'partner_ref', '') IS NOT NULL;