@fayz-ai/plugin-agenda 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  export declare const MIGRATION_000B_V_BOOKINGS_RENAME = "-- Salon-only unblock: the pre-pools beauty deployment built rep_* report\n-- views on top of its (wider) v_bookings view, so 001's cleanup DROP cannot\n-- run there. Renaming keeps the dependents attached (they track the OID) and\n-- frees the name for 001; 002_v_bookings_compat re-creates v_bookings as a\n-- thin alias for live pre-M5 clients. No-op on fresh pools and on pools whose\n-- v_bookings has no dependents (001's DROP handles those).\n\nDO $rename$\nBEGIN\n IF to_regclass('public.v_bookings') IS NOT NULL\n AND to_regclass('public.v_bookings_legacy_beauty') IS NULL\n AND EXISTS (\n SELECT 1 FROM pg_depend d\n JOIN pg_rewrite rw ON rw.oid = d.objid\n JOIN pg_class dep ON dep.oid = rw.ev_class\n JOIN pg_class ref ON ref.oid = d.refobjid\n WHERE ref.relname = 'v_bookings' AND dep.relname <> 'v_bookings'\n ) THEN\n EXECUTE 'ALTER VIEW public.v_bookings RENAME TO v_bookings_legacy_beauty';\n END IF;\nEND $rename$;\n";
2
2
  export declare const MIGRATION_000C_DEDUPE_CUSTOMER_PHONES = "-- 001 needs the customer-phone upsert key UNIQUE(tenant_id, phone). Converted\n-- pools can carry duplicates (found live on salon: 9 dogfood test records all\n-- sharing the founder's phone). Non-destructive dedupe: per (tenant_id, phone)\n-- customer group keep the row with most appointments (tie: oldest), NULL the\n-- phone on the rest and stash the original in metadata->'dedupedPhone'.\n-- Idempotent: reruns find no groups > 1.\n\nDO $dedupe$\nDECLARE\n r record;\nBEGIN\n IF to_regclass('public.people') IS NULL THEN\n RETURN;\n END IF;\n\n FOR r IN\n SELECT p.id, p.phone\n FROM public.people p\n JOIN LATERAL (\n SELECT count(*) AS appts\n FROM public.appointments a WHERE a.party_id = p.id\n ) ac ON true\n WHERE p.kind = 'customer' AND p.phone IS NOT NULL\n AND p.id NOT IN (\n SELECT DISTINCT ON (p2.tenant_id, p2.phone) p2.id\n FROM public.people p2\n WHERE p2.kind = 'customer' AND p2.phone IS NOT NULL\n ORDER BY p2.tenant_id, p2.phone,\n (SELECT count(*) FROM public.appointments a2 WHERE a2.party_id = p2.id) DESC,\n p2.created_at ASC\n )\n AND (p.tenant_id, p.phone) IN (\n SELECT tenant_id, phone FROM public.people\n WHERE kind = 'customer' AND phone IS NOT NULL\n GROUP BY tenant_id, phone HAVING count(*) > 1\n )\n LOOP\n UPDATE public.people\n SET metadata = COALESCE(metadata, '{}'::jsonb) || jsonb_build_object('dedupedPhone', r.phone),\n phone = NULL\n WHERE id = r.id;\n END LOOP;\nEND $dedupe$;\n";
3
- export declare const MIGRATION_001_PUBLIC_BOOKING = "-- ============================================================================\n-- plugin-agenda 001: booking read model + public (anon) booking surface\n--\n-- Ships the objects the agenda providers reference but the spine (packages/db\n-- migrations 001\u2013010) does not define:\n-- \u00A70 converted-pool cleanup \u2014 drop the pre-rename v_bookings view / indexes\n-- \u00A71 order_items columns the admin provider writes (duration/assignee)\n-- \u00A72 public.v_appointments \u2014 admin read model (authenticated, RLS applies)\n-- \u00A73 public.v_public_services \u2014 anon-readable service catalog\n-- \u00A74 public.get_available_slots \u2014 anon RPC (mirrors the mock algorithm)\n-- \u00A75 public.create_public_booking \u2014 anon RPC (validated, race-safe write)\n--\n-- Core v1 lives directly in PUBLIC (no separate core schema): people (was\n-- persons), appointments (was bookings). This migration is written against public\n-- names and is idempotent + safe on both fresh and converted pools.\n--\n-- Anon-access design: public booking pages run with the publishable key and no\n-- session, so the canonical tenant RLS yields nothing. Anon access is granted\n-- ONLY via the column-whitelisted view (\u00A73) and SECURITY DEFINER RPCs (\u00A74, \u00A75)\n-- with tight input validation and hardcoded statuses.\n-- ============================================================================\n\n-- \u00A70 \u2014 converted-pool cleanup. The pre-industry-pool shape shipped a v_bookings\n-- view and persons_/bookings_-named indexes; drop them so this file re-emits the\n-- canonical v_appointments view + people_/appointments_ indexes without leaving\n-- duplicates. All guarded with IF EXISTS \u2192 no-ops on a fresh pool.\nDROP VIEW IF EXISTS public.v_bookings;\nDROP INDEX IF EXISTS public.persons_tenant_customer_phone;\nDROP INDEX IF EXISTS public.bookings_assignee_time;\n\n-- \u00A71 \u2014 columns the agenda provider writes but 004_archetypes lacks\nALTER TABLE public.order_items\n ADD COLUMN IF NOT EXISTS duration_minutes integer,\n ADD COLUMN IF NOT EXISTS assignee_id uuid REFERENCES public.people(id) ON DELETE SET NULL;\n\n-- Upsert key for public customers (per tenant, by normalized phone)\nCREATE UNIQUE INDEX IF NOT EXISTS people_tenant_customer_phone\n ON public.people(tenant_id, phone)\n WHERE kind = 'customer' AND phone IS NOT NULL;\n\n-- Slot-conflict scan\nCREATE INDEX IF NOT EXISTS appointments_assignee_time\n ON public.appointments(assignee_id, starts_at, ends_at)\n WHERE status NOT IN ('cancelled', 'no_show');\n\n-- \u00A72 \u2014 admin read model (security_invoker \u2192 underlying RLS applies; anon sees 0 rows)\nCREATE OR REPLACE VIEW public.v_appointments\nWITH (security_invoker = true) AS\nSELECT\n b.id, b.tenant_id, b.kind, b.starts_at, b.ends_at, b.status, b.notes,\n b.order_id, b.location_id, b.metadata, b.created_at, b.updated_at,\n b.party_id AS client_id,\n COALESCE(pc.name, b.metadata->>'title') AS client_name,\n pc.phone AS client_phone,\n pc.email AS client_email,\n pc.avatar_url AS client_avatar_url,\n b.assignee_id AS professional_id,\n ps.name AS professional_name,\n ps.avatar_url AS professional_avatar_url,\n l.name AS location_name,\n o.total AS order_total,\n o.status AS order_status,\n (EXTRACT(EPOCH FROM (COALESCE(b.ends_at, b.starts_at) - b.starts_at))::int / 60)\n AS total_duration_minutes\nFROM public.appointments b\nLEFT JOIN public.people pc ON pc.id = b.party_id\nLEFT JOIN public.people ps ON ps.id = b.assignee_id\nLEFT JOIN public.locations l ON l.id = b.location_id\nLEFT JOIN public.orders o ON o.id = b.order_id;\n\nGRANT SELECT ON public.v_appointments TO authenticated, service_role;\nREVOKE SELECT ON public.v_appointments FROM anon;\n\n-- \u00A73 \u2014 anon-readable public catalog (owner-rights view = deliberate, whitelisted)\nCREATE OR REPLACE VIEW public.v_public_services AS\nSELECT\n s.id, s.tenant_id, s.name, s.description, s.price, s.currency,\n COALESCE(s.duration_minutes, 30) AS duration_minutes,\n s.image_url,\n COALESCE((s.metadata->>'sort_order')::int, 0) AS sort_order\nFROM public.services s\nWHERE s.is_active AND s.status = 'active';\n\nGRANT SELECT ON public.v_public_services TO anon, authenticated, service_role;\n\n-- \u00A74 \u2014 availability RPC (mirrors plugin-agenda/src/data/mock.ts getAvailableSlots)\nCREATE OR REPLACE FUNCTION public.get_available_slots(\n p_tenant_id uuid,\n p_date date,\n p_duration_minutes integer,\n p_assignee_id uuid DEFAULT NULL,\n p_slot_interval integer DEFAULT 30\n) RETURNS TABLE (slot_start timestamptz, slot_end timestamptz)\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_tz text;\nBEGIN\n -- tight validation: this function is anon-callable\n IF p_duration_minutes IS NULL OR p_duration_minutes NOT BETWEEN 5 AND 480 THEN\n RAISE EXCEPTION 'invalid duration';\n END IF;\n IF p_slot_interval IS NULL OR p_slot_interval NOT BETWEEN 5 AND 240 THEN\n RAISE EXCEPTION 'invalid interval';\n END IF;\n IF p_date IS NULL OR p_date < current_date OR p_date > current_date + 90 THEN\n RETURN;\n END IF;\n\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RETURN; END IF; -- unknown tenant \u2192 empty, not an error\n\n RETURN QUERY\n WITH day_schedules AS (\n SELECT sc.assignee_id, sc.starts_at AS win_start, sc.ends_at AS win_end\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (p_assignee_id IS NULL OR sc.assignee_id = p_assignee_id)\n AND (\n sc.specific_date = p_date\n OR (sc.specific_date IS NULL AND sc.day_of_week = EXTRACT(dow FROM p_date)::smallint)\n )\n ),\n candidate AS (\n SELECT\n ds.assignee_id,\n gs AS s_start,\n gs + make_interval(mins => p_duration_minutes) AS s_end\n FROM day_schedules ds\n CROSS JOIN LATERAL generate_series(\n (p_date + ds.win_start) AT TIME ZONE v_tz,\n ((p_date + ds.win_end) AT TIME ZONE v_tz) - make_interval(mins => p_duration_minutes),\n make_interval(mins => p_slot_interval)\n ) AS gs\n )\n SELECT DISTINCT c.s_start, c.s_end\n FROM candidate c\n WHERE NOT EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = c.assignee_id\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < c.s_end\n AND COALESCE(b.ends_at, b.starts_at) > c.s_start\n )\n ORDER BY 1;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer) FROM public;\nGRANT EXECUTE ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer)\n TO anon, authenticated, service_role;\n\n-- \u00A75 \u2014 public booking write RPC (validated, race-safe, hardcoded statuses)\nCREATE OR REPLACE FUNCTION public.create_public_booking(\n p_tenant_id uuid,\n p_service_id uuid,\n p_starts_at timestamptz,\n p_name text,\n p_phone text,\n p_email text DEFAULT NULL,\n p_notes text DEFAULT NULL\n) RETURNS TABLE (booking_id uuid, starts_at timestamptz, ends_at timestamptz)\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_service record;\n v_person_id uuid;\n v_assignee uuid;\n v_ends timestamptz;\n v_order uuid;\n v_booking uuid;\n v_phone text;\n v_tz text;\n v_notes text;\nBEGIN\n -- validation: anon-callable, everything tight\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');\n IF length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n v_notes := left(p_notes, 500);\n IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN\n RAISE EXCEPTION 'invalid start';\n END IF;\n\n SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes\n INTO v_service\n FROM services s\n WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id\n AND s.is_active AND s.status = 'active';\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;\n\n v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n -- pick the assignee whose working hours cover the slot\n SELECT sc.assignee_id INTO v_assignee\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (\n sc.specific_date = (p_starts_at AT TIME ZONE v_tz)::date\n OR (sc.specific_date IS NULL\n AND sc.day_of_week = EXTRACT(dow FROM p_starts_at AT TIME ZONE v_tz)::smallint)\n )\n AND (p_starts_at AT TIME ZONE v_tz)::time >= sc.starts_at\n AND (v_ends AT TIME ZONE v_tz)::time <= sc.ends_at\n ORDER BY sc.assignee_id\n LIMIT 1;\n IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;\n\n -- serialize per (tenant, assignee) to kill the double-book race\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));\n\n IF EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = v_assignee\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < v_ends\n AND COALESCE(b.ends_at, b.starts_at) > p_starts_at\n ) THEN\n RAISE EXCEPTION 'slot no longer available';\n END IF;\n\n -- anti-spam: cap open future public bookings per phone per tenant\n IF (\n SELECT count(*) FROM appointments b\n JOIN people p ON p.id = b.party_id\n WHERE b.tenant_id = p_tenant_id\n AND p.phone = v_phone\n AND b.starts_at > now()\n AND b.status = 'scheduled'\n ) >= 3 THEN\n RAISE EXCEPTION 'too many open bookings for this phone';\n END IF;\n\n -- upsert the customer by (tenant, phone) \u2014 matches people_tenant_customer_phone\n INSERT INTO people (tenant_id, kind, name, phone, email, metadata)\n VALUES (p_tenant_id, 'customer', trim(p_name), v_phone, p_email,\n jsonb_build_object('source', 'public_booking'))\n ON CONFLICT (tenant_id, phone) WHERE kind = 'customer' AND phone IS NOT NULL\n DO UPDATE SET\n name = EXCLUDED.name,\n email = COALESCE(EXCLUDED.email, people.email),\n updated_at = now()\n RETURNING id INTO v_person_id;\n\n -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)\n INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)\n VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,\n v_service.price, v_service.price, v_notes,\n jsonb_build_object('source', 'public_booking',\n 'serviceNames', v_service.name,\n 'contactName', trim(p_name)))\n RETURNING id INTO v_order;\n\n INSERT INTO appointments (tenant_id, kind, party_id, assignee_id, order_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,\n p_starts_at, v_ends, 'scheduled', v_notes,\n jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))\n RETURNING id INTO v_booking;\n\n INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,\n sort_order, duration_minutes, assignee_id)\n VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,\n 0, v_service.duration_minutes, v_assignee);\n\n RETURN QUERY SELECT v_booking, p_starts_at, v_ends;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text) FROM public;\nGRANT EXECUTE ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text)\n TO anon, authenticated, service_role;\n";
3
+ export declare const MIGRATION_001_PUBLIC_BOOKING = "-- ============================================================================\n-- plugin-agenda 001: booking read model + public (anon) booking surface\n--\n-- Ships the objects the agenda providers reference but the spine (packages/db\n-- migrations 001\u2013010) does not define:\n-- \u00A70 converted-pool cleanup \u2014 drop the pre-rename v_bookings view / indexes\n-- \u00A71 order_items columns the admin provider writes (duration/assignee)\n-- \u00A72 public.v_appointments \u2014 admin read model (authenticated, RLS applies)\n-- \u00A73 public.v_public_services \u2014 anon-readable service catalog\n-- \u00A74 public.get_available_slots \u2014 anon RPC (mirrors the mock algorithm)\n-- \u00A75 public.create_public_booking \u2014 anon RPC (validated, race-safe write)\n--\n-- Core v1 lives directly in PUBLIC (no separate core schema): people (was\n-- persons), appointments (was bookings). This migration is written against public\n-- names and is idempotent + safe on both fresh and converted pools.\n--\n-- Anon-access design: public booking pages run with the publishable key and no\n-- session, so the canonical tenant RLS yields nothing. Anon access is granted\n-- ONLY via the column-whitelisted view (\u00A73) and SECURITY DEFINER RPCs (\u00A74, \u00A75)\n-- with tight input validation and hardcoded statuses.\n-- ============================================================================\n\n-- \u00A70 \u2014 converted-pool cleanup. The pre-industry-pool shape shipped a v_bookings\n-- view and persons_/bookings_-named indexes; drop them so this file re-emits the\n-- canonical v_appointments view + people_/appointments_ indexes without leaving\n-- duplicates. All guarded with IF EXISTS \u2192 no-ops on a fresh pool.\nDROP VIEW IF EXISTS public.v_bookings;\nDROP INDEX IF EXISTS public.persons_tenant_customer_phone;\nDROP INDEX IF EXISTS public.bookings_assignee_time;\n\n-- \u00A71 \u2014 columns the agenda provider writes but 004_archetypes lacks\nALTER TABLE public.order_items\n ADD COLUMN IF NOT EXISTS duration_minutes integer,\n ADD COLUMN IF NOT EXISTS assignee_id uuid REFERENCES public.people(id) ON DELETE SET NULL;\n\n-- Upsert key for public customers (per tenant, by normalized phone)\nCREATE UNIQUE INDEX IF NOT EXISTS people_tenant_customer_phone\n ON public.people(tenant_id, phone)\n WHERE kind = 'customer' AND phone IS NOT NULL;\n\n-- Slot-conflict scan\nCREATE INDEX IF NOT EXISTS appointments_assignee_time\n ON public.appointments(assignee_id, starts_at, ends_at)\n WHERE status NOT IN ('cancelled', 'no_show');\n\n-- \u00A72 \u2014 admin read model (security_invoker \u2192 underlying RLS applies; anon sees 0 rows)\n-- DROP first: 013 widens this view and CREATE OR REPLACE cannot narrow a live\n-- view on replay (\"cannot drop columns from view\"). 013 replays right after.\nDROP VIEW IF EXISTS public.v_appointments;\nCREATE VIEW public.v_appointments\nWITH (security_invoker = true) AS\nSELECT\n b.id, b.tenant_id, b.kind, b.starts_at, b.ends_at, b.status, b.notes,\n b.order_id, b.location_id, b.metadata, b.created_at, b.updated_at,\n b.party_id AS client_id,\n COALESCE(pc.name, b.metadata->>'title') AS client_name,\n pc.phone AS client_phone,\n pc.email AS client_email,\n pc.avatar_url AS client_avatar_url,\n b.assignee_id AS professional_id,\n ps.name AS professional_name,\n ps.avatar_url AS professional_avatar_url,\n l.name AS location_name,\n o.total AS order_total,\n o.status AS order_status,\n (EXTRACT(EPOCH FROM (COALESCE(b.ends_at, b.starts_at) - b.starts_at))::int / 60)\n AS total_duration_minutes\nFROM public.appointments b\nLEFT JOIN public.people pc ON pc.id = b.party_id\nLEFT JOIN public.people ps ON ps.id = b.assignee_id\nLEFT JOIN public.locations l ON l.id = b.location_id\nLEFT JOIN public.orders o ON o.id = b.order_id;\n\nGRANT SELECT ON public.v_appointments TO authenticated, service_role;\nREVOKE SELECT ON public.v_appointments FROM anon;\n\n-- \u00A73 \u2014 anon-readable public catalog (owner-rights view = deliberate, whitelisted)\n-- DROP first: 010 widens this view (curation columns) \u2014 same replay rule as \u00A72.\nDROP VIEW IF EXISTS public.v_public_services;\nCREATE VIEW public.v_public_services AS\nSELECT\n s.id, s.tenant_id, s.name, s.description, s.price, s.currency,\n COALESCE(s.duration_minutes, 30) AS duration_minutes,\n s.image_url,\n COALESCE((s.metadata->>'sort_order')::int, 0) AS sort_order\nFROM public.services s\nWHERE s.is_active AND s.status = 'active';\n\nGRANT SELECT ON public.v_public_services TO anon, authenticated, service_role;\n\n-- \u00A74 \u2014 availability RPC (mirrors plugin-agenda/src/data/mock.ts getAvailableSlots)\nCREATE OR REPLACE FUNCTION public.get_available_slots(\n p_tenant_id uuid,\n p_date date,\n p_duration_minutes integer,\n p_assignee_id uuid DEFAULT NULL,\n p_slot_interval integer DEFAULT 30\n) RETURNS TABLE (slot_start timestamptz, slot_end timestamptz)\nLANGUAGE plpgsql STABLE SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_tz text;\nBEGIN\n -- tight validation: this function is anon-callable\n IF p_duration_minutes IS NULL OR p_duration_minutes NOT BETWEEN 5 AND 480 THEN\n RAISE EXCEPTION 'invalid duration';\n END IF;\n IF p_slot_interval IS NULL OR p_slot_interval NOT BETWEEN 5 AND 240 THEN\n RAISE EXCEPTION 'invalid interval';\n END IF;\n IF p_date IS NULL OR p_date < current_date OR p_date > current_date + 90 THEN\n RETURN;\n END IF;\n\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RETURN; END IF; -- unknown tenant \u2192 empty, not an error\n\n RETURN QUERY\n WITH day_schedules AS (\n SELECT sc.assignee_id, sc.starts_at AS win_start, sc.ends_at AS win_end\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (p_assignee_id IS NULL OR sc.assignee_id = p_assignee_id)\n AND (\n sc.specific_date = p_date\n OR (sc.specific_date IS NULL AND sc.day_of_week = EXTRACT(dow FROM p_date)::smallint)\n )\n ),\n candidate AS (\n SELECT\n ds.assignee_id,\n gs AS s_start,\n gs + make_interval(mins => p_duration_minutes) AS s_end\n FROM day_schedules ds\n CROSS JOIN LATERAL generate_series(\n (p_date + ds.win_start) AT TIME ZONE v_tz,\n ((p_date + ds.win_end) AT TIME ZONE v_tz) - make_interval(mins => p_duration_minutes),\n make_interval(mins => p_slot_interval)\n ) AS gs\n )\n SELECT DISTINCT c.s_start, c.s_end\n FROM candidate c\n WHERE NOT EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = c.assignee_id\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < c.s_end\n AND COALESCE(b.ends_at, b.starts_at) > c.s_start\n )\n ORDER BY 1;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer) FROM public;\nGRANT EXECUTE ON FUNCTION public.get_available_slots(uuid, date, integer, uuid, integer)\n TO anon, authenticated, service_role;\n\n-- \u00A75 \u2014 public booking write RPC (validated, race-safe, hardcoded statuses)\nCREATE OR REPLACE FUNCTION public.create_public_booking(\n p_tenant_id uuid,\n p_service_id uuid,\n p_starts_at timestamptz,\n p_name text,\n p_phone text,\n p_email text DEFAULT NULL,\n p_notes text DEFAULT NULL\n) RETURNS TABLE (booking_id uuid, starts_at timestamptz, ends_at timestamptz)\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_service record;\n v_person_id uuid;\n v_assignee uuid;\n v_ends timestamptz;\n v_order uuid;\n v_booking uuid;\n v_phone text;\n v_tz text;\n v_notes text;\nBEGIN\n -- validation: anon-callable, everything tight\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');\n IF length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n v_notes := left(p_notes, 500);\n IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN\n RAISE EXCEPTION 'invalid start';\n END IF;\n\n SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes\n INTO v_service\n FROM services s\n WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id\n AND s.is_active AND s.status = 'active';\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;\n\n v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo') INTO v_tz\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n -- pick the assignee whose working hours cover the slot\n SELECT sc.assignee_id INTO v_assignee\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (\n sc.specific_date = (p_starts_at AT TIME ZONE v_tz)::date\n OR (sc.specific_date IS NULL\n AND sc.day_of_week = EXTRACT(dow FROM p_starts_at AT TIME ZONE v_tz)::smallint)\n )\n AND (p_starts_at AT TIME ZONE v_tz)::time >= sc.starts_at\n AND (v_ends AT TIME ZONE v_tz)::time <= sc.ends_at\n ORDER BY sc.assignee_id\n LIMIT 1;\n IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;\n\n -- serialize per (tenant, assignee) to kill the double-book race\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));\n\n IF EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = v_assignee\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < v_ends\n AND COALESCE(b.ends_at, b.starts_at) > p_starts_at\n ) THEN\n RAISE EXCEPTION 'slot no longer available';\n END IF;\n\n -- anti-spam: cap open future public bookings per phone per tenant\n IF (\n SELECT count(*) FROM appointments b\n JOIN people p ON p.id = b.party_id\n WHERE b.tenant_id = p_tenant_id\n AND p.phone = v_phone\n AND b.starts_at > now()\n AND b.status = 'scheduled'\n ) >= 3 THEN\n RAISE EXCEPTION 'too many open bookings for this phone';\n END IF;\n\n -- upsert the customer by (tenant, phone) \u2014 matches people_tenant_customer_phone\n INSERT INTO people (tenant_id, kind, name, phone, email, metadata)\n VALUES (p_tenant_id, 'customer', trim(p_name), v_phone, p_email,\n jsonb_build_object('source', 'public_booking'))\n ON CONFLICT (tenant_id, phone) WHERE kind = 'customer' AND phone IS NOT NULL\n DO UPDATE SET\n name = EXCLUDED.name,\n email = COALESCE(EXCLUDED.email, people.email),\n updated_at = now()\n RETURNING id INTO v_person_id;\n\n -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)\n INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)\n VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,\n v_service.price, v_service.price, v_notes,\n jsonb_build_object('source', 'public_booking',\n 'serviceNames', v_service.name,\n 'contactName', trim(p_name)))\n RETURNING id INTO v_order;\n\n INSERT INTO appointments (tenant_id, kind, party_id, assignee_id, order_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,\n p_starts_at, v_ends, 'scheduled', v_notes,\n jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))\n RETURNING id INTO v_booking;\n\n INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,\n sort_order, duration_minutes, assignee_id)\n VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,\n 0, v_service.duration_minutes, v_assignee);\n\n RETURN QUERY SELECT v_booking, p_starts_at, v_ends;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text) FROM public;\nGRANT EXECUTE ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text)\n TO anon, authenticated, service_role;\n";
4
4
  export declare const MIGRATION_002_V_BOOKINGS_COMPAT = "-- Where 000b preserved the legacy beauty view, re-create v_bookings as a\n-- thin alias over it so live pre-M5 clients that SELECT v_bookings by name\n-- keep their full legacy column set. Dropped for good once the beauty app\n-- ships on v_appointments (M5 follow-up).\n\nDO $compat$\nBEGIN\n IF to_regclass('public.v_bookings_legacy_beauty') IS NOT NULL\n AND to_regclass('public.v_bookings') IS NULL THEN\n EXECUTE 'CREATE VIEW public.v_bookings WITH (security_invoker = true) AS SELECT * FROM public.v_bookings_legacy_beauty';\n EXECUTE 'GRANT SELECT ON public.v_bookings TO authenticated, service_role';\n EXECUTE 'REVOKE SELECT ON public.v_bookings FROM anon';\n END IF;\nEND $compat$;\n";
5
5
  export declare const MIGRATION_003_PUBLIC_CLIENT_KIND = "-- ---------------------------------------------------------------------------\n-- Public booking \u2014 tenant-configurable client kind\n-- ---------------------------------------------------------------------------\n-- 001 hardcoded kind='customer' for people created by create_public_booking.\n-- Verticals whose client archetype uses another kind (school \u2192 'student',\n-- clinic \u2192 whatever the app registers) ended up with people invisible to the\n-- app's own pages/lookups and with entity links resolving to unregistered\n-- routes (#/customers/:id \u2192 not found).\n--\n-- The client kind now comes from TENANT SETTINGS (admin-controlled \u2014 never\n-- from the anon caller): tenants.settings.booking.client_kind\n-- Default remains 'customer', so existing pools/tenants are unaffected until\n-- they opt in:\n-- UPDATE tenants SET settings = jsonb_set(COALESCE(settings,'{}'::jsonb),\n-- '{booking,client_kind}', '\"student\"') WHERE id = '<tenant>';\n--\n-- The upsert no longer relies on the kind-specific partial unique index\n-- (people_tenant_customer_phone) \u2014 a per-(tenant, phone) advisory lock\n-- serializes concurrent first-bookings for any kind. The 001 index stays in\n-- place (harmless, still guards direct customer writes).\n--\n-- Idempotent: CREATE OR REPLACE, same signature as 001.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.create_public_booking(\n p_tenant_id uuid,\n p_service_id uuid,\n p_starts_at timestamptz,\n p_name text,\n p_phone text,\n p_email text DEFAULT NULL,\n p_notes text DEFAULT NULL\n) RETURNS TABLE (booking_id uuid, starts_at timestamptz, ends_at timestamptz)\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_service record;\n v_person_id uuid;\n v_assignee uuid;\n v_ends timestamptz;\n v_order uuid;\n v_booking uuid;\n v_phone text;\n v_tz text;\n v_notes text;\n v_client_kind text;\nBEGIN\n -- validation: anon-callable, everything tight\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');\n IF length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n v_notes := left(p_notes, 500);\n IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN\n RAISE EXCEPTION 'invalid start';\n END IF;\n\n SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes\n INTO v_service\n FROM services s\n WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id\n AND s.is_active AND s.status = 'active';\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;\n\n v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);\n\n -- tenant config: timezone + client kind (admin-set; sanitized, never caller input)\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo'),\n COALESCE(NULLIF(trim(t.settings->'booking'->>'client_kind'), ''), 'customer')\n INTO v_tz, v_client_kind\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n IF v_client_kind !~ '^[a-z_]{2,32}$' THEN v_client_kind := 'customer'; END IF;\n\n -- pick the assignee whose working hours cover the slot\n SELECT sc.assignee_id INTO v_assignee\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (\n sc.specific_date = (p_starts_at AT TIME ZONE v_tz)::date\n OR (sc.specific_date IS NULL\n AND sc.day_of_week = EXTRACT(dow FROM p_starts_at AT TIME ZONE v_tz)::smallint)\n )\n AND (p_starts_at AT TIME ZONE v_tz)::time >= sc.starts_at\n AND (v_ends AT TIME ZONE v_tz)::time <= sc.ends_at\n ORDER BY sc.assignee_id\n LIMIT 1;\n IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;\n\n -- serialize per (tenant, assignee) to kill the double-book race\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));\n\n IF EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = v_assignee\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < v_ends\n AND COALESCE(b.ends_at, b.starts_at) > p_starts_at\n ) THEN\n RAISE EXCEPTION 'slot no longer available';\n END IF;\n\n -- anti-spam: cap open future public bookings per phone per tenant\n IF (\n SELECT count(*) FROM appointments b\n JOIN people p ON p.id = b.party_id\n WHERE b.tenant_id = p_tenant_id\n AND p.phone = v_phone\n AND b.starts_at > now()\n AND b.status = 'scheduled'\n ) >= 3 THEN\n RAISE EXCEPTION 'too many open bookings for this phone';\n END IF;\n\n -- upsert the client by (tenant, kind, phone). Kind is tenant-configured, so\n -- the 001 customer-only partial index can't arbitrate \u2014 a per-(tenant,\n -- phone) advisory lock serializes concurrent first-bookings instead.\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || ':' || v_phone, 1));\n\n SELECT p.id INTO v_person_id\n FROM people p\n WHERE p.tenant_id = p_tenant_id AND p.kind = v_client_kind AND p.phone = v_phone\n ORDER BY p.created_at\n LIMIT 1;\n\n IF v_person_id IS NOT NULL THEN\n UPDATE people SET\n name = trim(p_name),\n email = COALESCE(p_email, people.email),\n updated_at = now()\n WHERE id = v_person_id;\n ELSE\n INSERT INTO people (tenant_id, kind, name, phone, email, metadata)\n VALUES (p_tenant_id, v_client_kind, trim(p_name), v_phone, p_email,\n jsonb_build_object('source', 'public_booking'))\n RETURNING id INTO v_person_id;\n END IF;\n\n -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)\n INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)\n VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,\n v_service.price, v_service.price, v_notes,\n jsonb_build_object('source', 'public_booking',\n 'serviceNames', v_service.name,\n 'contactName', trim(p_name)))\n RETURNING id INTO v_order;\n\n INSERT INTO appointments (tenant_id, kind, party_id, assignee_id, order_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,\n p_starts_at, v_ends, 'scheduled', v_notes,\n jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))\n RETURNING id INTO v_booking;\n\n INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,\n sort_order, duration_minutes, assignee_id)\n VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,\n 0, v_service.duration_minutes, v_assignee);\n\n RETURN QUERY SELECT v_booking, p_starts_at, v_ends;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text) FROM public;\nGRANT EXECUTE ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text)\n TO anon, authenticated, service_role;\n";
6
6
  export declare const MIGRATION_004_PUBLIC_BOOKING_ASSIGNEE = "-- ---------------------------------------------------------------------------\n-- Public booking \u2014 respect the professional the visitor saw\n-- ---------------------------------------------------------------------------\n-- Until now create_public_booking IGNORED which professional the site showed\n-- availability for and re-picked by working hours (ORDER BY assignee_id\n-- LIMIT 1). With several professionals covering the same slot the booking\n-- landed on someone else than displayed (\"Equipe Great DJs\" on the site,\n-- \"Rafa Groove\" in the agenda). New optional p_assignee_id:\n-- * provided \u2192 validate THAT professional's working hours cover the slot and\n-- book them \u2014 never silently reassign (mismatch becomes an explicit error);\n-- * NULL \u2192 auto-pick as before (sites that don't pin a professional).\n-- Conflict check + advisory lock already run against the resolved assignee, so\n-- the double-book guard follows whichever path resolves.\n--\n-- Signature change (8th arg): the old 7-arg function is DROPPED first \u2014\n-- CREATE OR REPLACE with a different signature would create an ambiguous\n-- PostgREST overload instead of replacing.\n-- Includes 003's tenant-configurable client kind. Idempotent.\n-- ---------------------------------------------------------------------------\nDROP FUNCTION IF EXISTS public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text);\n\nCREATE OR REPLACE FUNCTION public.create_public_booking(\n p_tenant_id uuid,\n p_service_id uuid,\n p_starts_at timestamptz,\n p_name text,\n p_phone text,\n p_email text DEFAULT NULL,\n p_notes text DEFAULT NULL,\n p_assignee_id uuid DEFAULT NULL\n) RETURNS TABLE (booking_id uuid, starts_at timestamptz, ends_at timestamptz)\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_service record;\n v_person_id uuid;\n v_assignee uuid;\n v_ends timestamptz;\n v_order uuid;\n v_booking uuid;\n v_phone text;\n v_tz text;\n v_notes text;\n v_client_kind text;\nBEGIN\n -- validation: anon-callable, everything tight\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');\n IF length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n v_notes := left(p_notes, 500);\n IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN\n RAISE EXCEPTION 'invalid start';\n END IF;\n\n SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes\n INTO v_service\n FROM services s\n WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id\n AND s.is_active AND s.status = 'active';\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;\n\n v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);\n\n -- tenant config: timezone + client kind (admin-set; sanitized, never caller input)\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo'),\n COALESCE(NULLIF(trim(t.settings->'booking'->>'client_kind'), ''), 'customer')\n INTO v_tz, v_client_kind\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n IF v_client_kind !~ '^[a-z_]{2,32}$' THEN v_client_kind := 'customer'; END IF;\n\n -- resolve the professional: the one the visitor saw (validated), else the\n -- first whose working hours cover the slot\n SELECT sc.assignee_id INTO v_assignee\n FROM schedules sc\n WHERE sc.tenant_id = p_tenant_id\n AND sc.kind = 'working_hours'\n AND sc.is_active\n AND (p_assignee_id IS NULL OR sc.assignee_id = p_assignee_id)\n AND (\n sc.specific_date = (p_starts_at AT TIME ZONE v_tz)::date\n OR (sc.specific_date IS NULL\n AND sc.day_of_week = EXTRACT(dow FROM p_starts_at AT TIME ZONE v_tz)::smallint)\n )\n AND (p_starts_at AT TIME ZONE v_tz)::time >= sc.starts_at\n AND (v_ends AT TIME ZONE v_tz)::time <= sc.ends_at\n ORDER BY sc.assignee_id\n LIMIT 1;\n IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;\n\n -- serialize per (tenant, assignee) to kill the double-book race\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));\n\n IF EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = v_assignee\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < v_ends\n AND COALESCE(b.ends_at, b.starts_at) > p_starts_at\n ) THEN\n RAISE EXCEPTION 'slot no longer available';\n END IF;\n\n -- anti-spam: cap open future public bookings per phone per tenant\n IF (\n SELECT count(*) FROM appointments b\n JOIN people p ON p.id = b.party_id\n WHERE b.tenant_id = p_tenant_id\n AND p.phone = v_phone\n AND b.starts_at > now()\n AND b.status = 'scheduled'\n ) >= 3 THEN\n RAISE EXCEPTION 'too many open bookings for this phone';\n END IF;\n\n -- upsert the client by (tenant, kind, phone), serialized by advisory lock\n -- (kind is tenant-configured, so the customer-only partial index can't\n -- arbitrate)\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || ':' || v_phone, 1));\n\n SELECT p.id INTO v_person_id\n FROM people p\n WHERE p.tenant_id = p_tenant_id AND p.kind = v_client_kind AND p.phone = v_phone\n ORDER BY p.created_at\n LIMIT 1;\n\n IF v_person_id IS NOT NULL THEN\n UPDATE people SET\n name = trim(p_name),\n email = COALESCE(p_email, people.email),\n updated_at = now()\n WHERE id = v_person_id;\n ELSE\n INSERT INTO people (tenant_id, kind, name, phone, email, metadata)\n VALUES (p_tenant_id, v_client_kind, trim(p_name), v_phone, p_email,\n jsonb_build_object('source', 'public_booking'))\n RETURNING id INTO v_person_id;\n END IF;\n\n -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)\n INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)\n VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,\n v_service.price, v_service.price, v_notes,\n jsonb_build_object('source', 'public_booking',\n 'serviceNames', v_service.name,\n 'contactName', trim(p_name)))\n RETURNING id INTO v_order;\n\n INSERT INTO appointments (tenant_id, kind, party_id, assignee_id, order_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,\n p_starts_at, v_ends, 'scheduled', v_notes,\n jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))\n RETURNING id INTO v_booking;\n\n INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,\n sort_order, duration_minutes, assignee_id)\n VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,\n 0, v_service.duration_minutes, v_assignee);\n\n RETURN QUERY SELECT v_booking, p_starts_at, v_ends;\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text, uuid) FROM public;\nGRANT EXECUTE ON FUNCTION public.create_public_booking(uuid, uuid, timestamptz, text, text, text, text, uuid)\n TO anon, authenticated, service_role;\n";
@@ -12,7 +12,7 @@ export declare const MIGRATION_009_PUBLIC_BOOKING_LOCATION = "-- Public bookings
12
12
  export declare const MIGRATION_010_PUBLIC_SERVICE_CURATION = "-- plugin-agenda 010: curate what the PUBLIC booking page sells.\n--\n-- v_public_services published every active service, so the website catalog was\n-- \"whatever exists in the system\". That conflates two different questions:\n--\n-- \u2022 is this service usable at all? \u2192 services.is_active / status\n-- \u2022 should a stranger be able to book it? \u2192 this flag\n--\n-- Without the split, hiding something from the site means deactivating it \u2014\n-- which also removes it from the internal agenda and orphans its history. The\n-- case that forced this: a school whose public page listed 7 services when it\n-- sells 3, and one of the 4 extras already had real bookings attached.\n--\n-- OPT-OUT on purpose: a service is public unless explicitly marked otherwise.\n-- Opt-in would silently empty every live catalog the moment this ships.\n\nCREATE OR REPLACE VIEW public.v_public_services AS\nSELECT id,\n tenant_id,\n name,\n description,\n price,\n currency,\n COALESCE(duration_minutes, 30) AS duration_minutes,\n image_url,\n COALESCE(((metadata ->> 'sort_order'::text))::integer, 0) AS sort_order\n FROM services s\n WHERE is_active\n AND status = 'active'::text\n -- absent \u2192 public (back-compat). Only an explicit false hides it.\n AND COALESCE((metadata ->> 'bookableOnline'::text)::boolean, true);\n";
13
13
  export declare const MIGRATION_011_DEFAULT_ASSIGNEE = "-- plugin-agenda 011: honour a tenant's default professional.\n--\n-- create_public_booking picks the assignee from whoever's working hours cover\n-- the slot, ordered by assignee_id \u2014 i.e. the lowest UUID wins. That is fine\n-- when the caller names the professional, and wrong when it does not: the\n-- public page confirms \"Equipe Great DJs\" while the booking silently lands on\n-- an unrelated instructor whose UUID happened to sort first.\n--\n-- Clients shipped before p_assignee_id existed still call this with 7 named\n-- args, so the parameter defaults to NULL and every live booking on those sites\n-- is mis-assigned today. Republishing the SDK fixes the caller, but the sites\n-- already deployed cannot be fixed that way \u2014 this can, from the database.\n--\n-- Precedence: explicit arg > tenant default > first covering schedule.\n-- Tenants without the setting keep exactly the previous behaviour.\n\nCREATE OR REPLACE FUNCTION public.create_public_booking(p_tenant_id uuid, p_service_id uuid, p_starts_at timestamp with time zone, p_name text, p_phone text, p_email text DEFAULT NULL::text, p_notes text DEFAULT NULL::text, p_assignee_id uuid DEFAULT NULL::uuid)\n RETURNS TABLE(booking_id uuid, starts_at timestamp with time zone, ends_at timestamp with time zone)\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO 'public'\nAS $function$\nDECLARE\n v_service record;\n v_person_id uuid;\n v_assignee uuid;\n v_requested uuid;\n v_ends timestamptz;\n v_order uuid;\n v_booking uuid;\n v_phone text;\n v_tz text;\n v_notes text;\n v_client_kind text;\nBEGIN\n -- validation: anon-callable, everything tight\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n v_phone := regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g');\n IF length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n IF p_email IS NOT NULL AND (length(p_email) > 254 OR p_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n v_notes := left(p_notes, 500);\n IF p_starts_at IS NULL OR p_starts_at <= now() OR p_starts_at > now() + interval '90 days' THEN\n RAISE EXCEPTION 'invalid start';\n END IF;\n\n SELECT s.id, s.name, s.price, COALESCE(s.duration_minutes, 30) AS duration_minutes\n INTO v_service\n FROM services s\n WHERE s.id = p_service_id AND s.tenant_id = p_tenant_id\n AND s.is_active AND s.status = 'active';\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown service'; END IF;\n\n v_ends := p_starts_at + make_interval(mins => v_service.duration_minutes);\n\n -- tenant config: timezone + client kind (admin-set; sanitized, never caller input)\n SELECT COALESCE(t.settings->>'timezone', 'America/Sao_Paulo'),\n COALESCE(NULLIF(trim(t.settings->'booking'->>'client_kind'), ''), 'customer')\n INTO v_tz, v_client_kind\n FROM tenants t WHERE t.id = p_tenant_id;\n IF v_tz IS NULL THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n IF v_client_kind !~ '^[a-z_]{2,32}$' THEN v_client_kind := 'customer'; END IF;\n\n -- resolve the professional, in order of trust:\n -- 1. the id the caller sent (the one the visitor actually saw)\n -- 2. the tenant's configured default (settings->>'defaultAssigneeId')\n -- 3. whoever's working hours cover the slot\n --\n -- Step 2 is why this migration exists. Older published clients call this with\n -- 7 named args, leaving p_assignee_id NULL, and step 3 then resolved to\n -- \"lowest assignee UUID\" \u2014 an arbitrary instructor who had nothing to do with\n -- the name the site displayed on the confirmation screen. The default gives\n -- those clients a correct answer without waiting for a redeploy.\n v_requested := COALESCE(\n p_assignee_id,\n (SELECT NULLIF(t.settings ->> 'defaultAssigneeId', '')::uuid\n FROM tenants t WHERE t.id = p_tenant_id)\n );\n\n SELECT w.assignee_id INTO v_assignee\n FROM agenda_working_windows(\n p_tenant_id, (p_starts_at AT TIME ZONE v_tz)::date, v_requested) w\n WHERE (p_starts_at AT TIME ZONE v_tz)::time >= w.win_start\n AND (v_ends AT TIME ZONE v_tz)::time <= w.win_end\n ORDER BY w.assignee_id\n LIMIT 1;\n IF v_assignee IS NULL THEN RAISE EXCEPTION 'slot outside working hours'; END IF;\n\n -- serialize per (tenant, assignee) to kill the double-book race\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || v_assignee::text, 0));\n\n IF EXISTS (\n SELECT 1 FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.assignee_id = v_assignee\n AND b.status NOT IN ('cancelled', 'no_show')\n AND b.starts_at < v_ends\n AND COALESCE(b.ends_at, b.starts_at) > p_starts_at\n ) THEN\n RAISE EXCEPTION 'slot no longer available';\n END IF;\n\n -- anti-spam: cap open future public bookings per phone per tenant\n IF (\n SELECT count(*) FROM appointments b\n JOIN people p ON p.id = b.party_id\n WHERE b.tenant_id = p_tenant_id\n AND p.phone = v_phone\n AND b.starts_at > now()\n AND b.status = 'scheduled'\n ) >= 3 THEN\n RAISE EXCEPTION 'too many open bookings for this phone';\n END IF;\n\n -- upsert the client by (tenant, kind, phone), serialized by advisory lock\n -- (kind is tenant-configured, so the customer-only partial index can't\n -- arbitrate)\n PERFORM pg_advisory_xact_lock(hashtextextended(p_tenant_id::text || ':' || v_phone, 1));\n\n SELECT p.id INTO v_person_id\n FROM people p\n WHERE p.tenant_id = p_tenant_id AND p.kind = v_client_kind AND p.phone = v_phone\n ORDER BY p.created_at\n LIMIT 1;\n\n IF v_person_id IS NOT NULL THEN\n UPDATE people SET\n name = trim(p_name),\n email = COALESCE(p_email, people.email),\n updated_at = now()\n WHERE id = v_person_id;\n ELSE\n INSERT INTO people (tenant_id, kind, name, phone, email, metadata)\n VALUES (p_tenant_id, v_client_kind, trim(p_name), v_phone, p_email,\n jsonb_build_object('source', 'public_booking'))\n RETURNING id INTO v_person_id;\n END IF;\n\n -- order + booking + order_item (statuses hardcoded \u2014 caller cannot set)\n INSERT INTO orders (tenant_id, kind, status, party_id, assignee_id, subtotal, total, notes, metadata)\n VALUES (p_tenant_id, 'appointment', 'scheduled', v_person_id, v_assignee,\n v_service.price, v_service.price, v_notes,\n jsonb_build_object('source', 'public_booking',\n 'serviceNames', v_service.name,\n 'contactName', trim(p_name)))\n RETURNING id INTO v_order;\n\n INSERT INTO appointments (tenant_id, kind, party_id, assignee_id, order_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, 'appointment', v_person_id, v_assignee, v_order,\n p_starts_at, v_ends, 'scheduled', v_notes,\n jsonb_build_object('source', 'public_booking', 'serviceNames', v_service.name))\n RETURNING id INTO v_booking;\n\n INSERT INTO order_items (order_id, service_id, name, quantity, unit_price, total,\n sort_order, duration_minutes, assignee_id)\n VALUES (v_order, v_service.id, v_service.name, 1, v_service.price, v_service.price,\n 0, v_service.duration_minutes, v_assignee);\n\n RETURN QUERY SELECT v_booking, p_starts_at, v_ends;\nEND;\n$function$;\n";
14
14
  export declare const MIGRATION_012_DROP_LEGACY_BOOKING_OVERLOAD = "-- plugin-agenda 012: retire the pre-assignee create_public_booking overload.\n--\n-- \u26A0\uFE0F DO NOT APPLY UNTIL @fayz-ai/plugin-agenda IS REPUBLISHED *AND* EVERY LIVE\n-- SITE HAS BEEN REDEPLOYED. Applying early breaks public booking on any\n-- site still serving a bundle that calls the 7-argument signature \u2014 the\n-- call stops resolving and every submission fails.\n--\n-- Some pools carry two overloads side by side:\n-- create_public_booking(uuid,uuid,timestamptz,text,text,text,text)\n-- create_public_booking(uuid,uuid,timestamptz,text,text,text,text,uuid)\n--\n-- Nothing errors when both exist, which is exactly the problem: a stale client\n-- silently resolves to the 7-arg one, which cannot know which professional the\n-- visitor was shown and falls back to \"lowest assignee UUID\". The site confirms\n-- one name, the agenda records another, and no one finds out until someone\n-- compares the two screens.\n--\n-- 011 makes that fallback survivable (tenant default). This makes it\n-- impossible \u2014 but only once no caller needs the old signature.\n--\n-- Verify before running:\n-- 1. npm view @fayz-ai/plugin-agenda version \u2192 the republished version\n-- 2. every deployed bundle greps for p_assignee_id:\n-- curl -s https://<site>/assets/index-*.js | grep -c p_assignee_id\n-- Each must be \u2265 2 (slots + booking). Zero means that site still needs it.\n\nDROP FUNCTION IF EXISTS public.create_public_booking(\n uuid, uuid, timestamptz, text, text, text, text\n);\n";
15
- export declare const MIGRATION_013_NORMALIZE_V_APPOINTMENTS = "-- plugin-agenda 013: one booking read model \u2014 v_appointments.\n--\n-- Three views described the same 34 rows:\n--\n-- v_bookings \u2192 thin alias over the legacy view (002 compat shim)\n-- v_bookings_legacy_beauty \u2192 the pre-pools shape, still feeding 5 rep_* views\n-- v_appointments \u2192 the canonical name, and the only one the SDK reads\n--\n-- The school pool already had only v_appointments; the salon pool carried all\n-- three. Same data, three names, and reports quietly wired to the oldest one.\n--\n-- v_appointments was a strict SUBSET, so it could not simply absorb them. It\n-- gains the 7 columns it lacked \u2014 most importantly `services`, the order_items\n-- aggregate that 4 of the 5 reports depend on. That also retires a documented\n-- N+1: getBookingById fetches order_items in a second round-trip precisely\n-- because this view had no line items (see plugin-agenda/src/data/supabase.ts).\n--\n-- Deliberately NOT copied from the legacy view:\n-- \u2022 total_duration_minutes \u2014 legacy sums order_items durations, the canonical\n-- measures the slot. They disagree, no report reads it, and the SDK relies\n-- on the canonical meaning. Kept as-is.\n-- \u2022 client_name \u2014 the canonical COALESCEs with metadata->>'title' so blocks\n-- and personal events show a label instead of NULL. Kept as-is (an\n-- improvement the legacy shape never had).\n\n-- 1. v_appointments becomes the superset. Columns are APPENDED: CREATE OR\n-- REPLACE VIEW cannot reorder or drop, and the SDK selects '*'.\nCREATE OR REPLACE VIEW public.v_appointments\nWITH (security_invoker = true) AS\n SELECT b.id,\n b.tenant_id,\n b.kind,\n b.starts_at,\n b.ends_at,\n b.status,\n b.notes,\n b.order_id,\n b.location_id,\n b.metadata,\n b.created_at,\n b.updated_at,\n b.party_id AS client_id,\n COALESCE(pc.name, (b.metadata ->> 'title'::text)) AS client_name,\n pc.phone AS client_phone,\n pc.email AS client_email,\n pc.avatar_url AS client_avatar_url,\n b.assignee_id AS professional_id,\n ps.name AS professional_name,\n ps.avatar_url AS professional_avatar_url,\n l.name AS location_name,\n o.total AS order_total,\n o.status AS order_status,\n ((EXTRACT(epoch FROM (COALESCE(b.ends_at, b.starts_at) - b.starts_at)))::integer / 60) AS total_duration_minutes,\n -- appended:\n o.reference_number,\n o.status AS stage,\n (o.metadata ->> 'direction'::text) AS direction,\n ( SELECT json_agg(json_build_object('id', oi.id, 'serviceId', oi.service_id,\n 'name', oi.name, 'durationMinutes', oi.duration_minutes,\n 'price', oi.unit_price, 'assigneeId', oi.assignee_id)\n ORDER BY oi.sort_order)\n FROM order_items oi\n WHERE (oi.order_id = b.order_id)) AS services,\n inv.status AS payment_status,\n inv.paid AS order_paid,\n inv.balance AS order_balance\n FROM (((((appointments b\n LEFT JOIN people pc ON ((pc.id = b.party_id)))\n LEFT JOIN people ps ON ((ps.id = b.assignee_id)))\n LEFT JOIN locations l ON ((l.id = b.location_id)))\n LEFT JOIN orders o ON ((o.id = b.order_id)))\n LEFT JOIN v_invoice_balances inv ON ((inv.invoice_id = b.order_id)));\n\n-- 2. Repoint the reports off the legacy view. Bodies are unchanged\n-- except for the source relation.\n\nCREATE OR REPLACE VIEW public.rep_appointments_by_period AS\nSELECT tenant_id,\n id AS booking_id,\n (starts_at)::date AS date,\n starts_at,\n client_id,\n client_name,\n professional_id,\n professional_name,\n COALESCE(((services -> 0) ->> 'name'::text), ((services -> 0) ->> 'serviceName'::text)) AS service_name,\n status,\n order_total AS revenue,\n created_at,\n updated_at\n FROM v_appointments b;\n\nCREATE OR REPLACE VIEW public.rep_confirmation_queue AS\nSELECT b.tenant_id,\n b.id AS booking_id,\n (b.starts_at)::date AS date,\n b.starts_at,\n b.client_id,\n b.client_name,\n b.professional_id,\n b.professional_name,\n COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,\n COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,\n a.confirmation_channel,\n a.confirmation_sent_at,\n a.confirmed_at,\n b.created_at,\n b.updated_at\n FROM (v_appointments b\n LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))\n WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)));\n\nCREATE OR REPLACE VIEW public.rep_new_clients AS\nSELECT c.tenant_id,\n c.id AS client_id,\n (c.created_at)::date AS date,\n c.name AS client_name,\n c.origin,\n first_booking.service_name AS first_service,\n c.created_at,\n c.updated_at\n FROM (v_clients c\n LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name\n FROM v_appointments b\n WHERE (b.client_id = c.id)\n ORDER BY b.starts_at\n LIMIT 1) first_booking ON (true));\n\nCREATE OR REPLACE VIEW public.rep_revenue_by_professional AS\nSELECT tenant_id,\n (starts_at)::date AS date,\n professional_id,\n COALESCE(professional_name, 'Sem profissional'::text) AS professional_name,\n (count(*))::integer AS appointment_count,\n (COALESCE(sum(NULLIF(order_total, (0)::numeric)), (0)::numeric))::numeric(14,2) AS total_revenue,\n (COALESCE(avg(NULLIF(order_total, (0)::numeric)), (0)::numeric))::numeric(14,2) AS avg_ticket,\n (0)::numeric(14,2) AS commission,\n max(updated_at) AS updated_at\n FROM v_appointments b\n WHERE (status <> ALL (ARRAY['cancelled'::text, 'no_show'::text]))\n GROUP BY tenant_id, ((starts_at)::date), professional_id, COALESCE(professional_name, 'Sem profissional'::text);\n\nCREATE OR REPLACE VIEW public.rep_revenue_by_service AS\nSELECT b.tenant_id,\n (b.starts_at)::date AS date,\n NULLIF((service_item.value ->> 'serviceId'::text), ''::text) AS service_id,\n COALESCE((service_item.value ->> 'name'::text), (service_item.value ->> 'serviceName'::text), 'Sem servico'::text) AS service_name,\n (count(DISTINCT b.id))::integer AS quantity,\n (COALESCE(sum((NULLIF((service_item.value ->> 'price'::text), ''::text))::numeric), (0)::numeric))::numeric(14,2) AS total_revenue,\n (COALESCE(avg((NULLIF((service_item.value ->> 'price'::text), ''::text))::numeric), (0)::numeric))::numeric(14,2) AS avg_ticket,\n max(b.updated_at) AS updated_at\n FROM (v_appointments b\n CROSS JOIN LATERAL jsonb_array_elements(COALESCE((b.services)::jsonb, '[]'::jsonb)) service_item(value))\n WHERE (b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text]))\n GROUP BY b.tenant_id, ((b.starts_at)::date), NULLIF((service_item.value ->> 'serviceId'::text), ''::text), COALESCE((service_item.value ->> 'name'::text), (service_item.value ->> 'serviceName'::text), 'Sem servico'::text);\n\n-- 3. Retire the duplicates. v_bookings goes first: it reads the legacy view.\n-- Nothing in the SDK references either name (checked: only migrations and a\n-- README mention v_bookings).\nDROP VIEW IF EXISTS public.v_bookings;\nDROP VIEW IF EXISTS public.v_bookings_legacy_beauty;\n";
15
+ export declare const MIGRATION_013_NORMALIZE_V_APPOINTMENTS = "-- plugin-agenda 013: one booking read model \u2014 v_appointments.\n--\n-- Three views described the same 34 rows:\n--\n-- v_bookings \u2192 thin alias over the legacy view (002 compat shim)\n-- v_bookings_legacy_beauty \u2192 the pre-pools shape, still feeding 5 rep_* views\n-- v_appointments \u2192 the canonical name, and the only one the SDK reads\n--\n-- The school pool already had only v_appointments; the salon pool carried all\n-- three. Same data, three names, and reports quietly wired to the oldest one.\n--\n-- v_appointments was a strict SUBSET, so it could not simply absorb them. It\n-- gains the 7 columns it lacked \u2014 most importantly `services`, the order_items\n-- aggregate that 4 of the 5 reports depend on. That also retires a documented\n-- N+1: getBookingById fetches order_items in a second round-trip precisely\n-- because this view had no line items (see plugin-agenda/src/data/supabase.ts).\n--\n-- Deliberately NOT copied from the legacy view:\n-- \u2022 total_duration_minutes \u2014 legacy sums order_items durations, the canonical\n-- measures the slot. They disagree, no report reads it, and the SDK relies\n-- on the canonical meaning. Kept as-is.\n-- \u2022 client_name \u2014 the canonical COALESCEs with metadata->>'title' so blocks\n-- and personal events show a label instead of NULL. Kept as-is (an\n-- improvement the legacy shape never had).\n\n-- 1. v_appointments becomes the superset. Columns are APPENDED: CREATE OR\n-- REPLACE VIEW cannot reorder or drop, and the SDK selects '*'.\nCREATE OR REPLACE VIEW public.v_appointments\nWITH (security_invoker = true) AS\n SELECT b.id,\n b.tenant_id,\n b.kind,\n b.starts_at,\n b.ends_at,\n b.status,\n b.notes,\n b.order_id,\n b.location_id,\n b.metadata,\n b.created_at,\n b.updated_at,\n b.party_id AS client_id,\n COALESCE(pc.name, (b.metadata ->> 'title'::text)) AS client_name,\n pc.phone AS client_phone,\n pc.email AS client_email,\n pc.avatar_url AS client_avatar_url,\n b.assignee_id AS professional_id,\n ps.name AS professional_name,\n ps.avatar_url AS professional_avatar_url,\n l.name AS location_name,\n o.total AS order_total,\n o.status AS order_status,\n ((EXTRACT(epoch FROM (COALESCE(b.ends_at, b.starts_at) - b.starts_at)))::integer / 60) AS total_duration_minutes,\n -- appended:\n o.reference_number,\n o.status AS stage,\n (o.metadata ->> 'direction'::text) AS direction,\n ( SELECT json_agg(json_build_object('id', oi.id, 'serviceId', oi.service_id,\n 'name', oi.name, 'durationMinutes', oi.duration_minutes,\n 'price', oi.unit_price, 'assigneeId', oi.assignee_id)\n ORDER BY oi.sort_order)\n FROM order_items oi\n WHERE (oi.order_id = b.order_id)) AS services,\n inv.status AS payment_status,\n inv.paid AS order_paid,\n inv.balance AS order_balance\n FROM (((((appointments b\n LEFT JOIN people pc ON ((pc.id = b.party_id)))\n LEFT JOIN people ps ON ((ps.id = b.assignee_id)))\n LEFT JOIN locations l ON ((l.id = b.location_id)))\n LEFT JOIN orders o ON ((o.id = b.order_id)))\n LEFT JOIN v_invoice_balances inv ON ((inv.invoice_id = b.order_id)));\n\n-- 2. Repoint the reports off the legacy view. Bodies are unchanged\n-- except for the source relation.\n\nCREATE OR REPLACE VIEW public.rep_appointments_by_period AS\nSELECT tenant_id,\n id AS booking_id,\n (starts_at)::date AS date,\n starts_at,\n client_id,\n client_name,\n professional_id,\n professional_name,\n COALESCE(((services -> 0) ->> 'name'::text), ((services -> 0) ->> 'serviceName'::text)) AS service_name,\n status,\n order_total AS revenue,\n created_at,\n updated_at\n FROM v_appointments b;\n\n-- legacy_pre_pools only exists on pools migrated from the pre-pool era; fresh\n-- pools get the same shape with confirmation columns defaulting to pending/NULL.\nDO $$\nBEGIN\n IF to_regclass('legacy_pre_pools.appointments') IS NOT NULL THEN\n EXECUTE $v$\n CREATE OR REPLACE VIEW public.rep_confirmation_queue AS\n SELECT b.tenant_id,\n b.id AS booking_id,\n (b.starts_at)::date AS date,\n b.starts_at,\n b.client_id,\n b.client_name,\n b.professional_id,\n b.professional_name,\n COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,\n COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,\n a.confirmation_channel,\n a.confirmation_sent_at,\n a.confirmed_at,\n b.created_at,\n b.updated_at\n FROM (v_appointments b\n LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))\n WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))\n $v$;\n ELSE\n EXECUTE $v$\n CREATE OR REPLACE VIEW public.rep_confirmation_queue AS\n SELECT b.tenant_id,\n b.id AS booking_id,\n (b.starts_at)::date AS date,\n b.starts_at,\n b.client_id,\n b.client_name,\n b.professional_id,\n b.professional_name,\n COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,\n 'pending'::text AS confirmation_status,\n NULL::text AS confirmation_channel,\n NULL::timestamptz AS confirmation_sent_at,\n NULL::timestamptz AS confirmed_at,\n b.created_at,\n b.updated_at\n FROM v_appointments b\n WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))\n $v$;\n END IF;\nEND $$;\n\n-- v_clients (beauty Ring-2 extension) may not exist on non-salon pools \u2014 the\n-- report only makes sense where it does.\nDO $$\nBEGIN\n IF to_regclass('public.v_clients') IS NULL THEN RETURN; END IF;\n EXECUTE $v$\n CREATE OR REPLACE VIEW public.rep_new_clients AS\n SELECT c.tenant_id,\n c.id AS client_id,\n (c.created_at)::date AS date,\n c.name AS client_name,\n c.origin,\n first_booking.service_name AS first_service,\n c.created_at,\n c.updated_at\n FROM (v_clients c\n LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name\n FROM v_appointments b\n WHERE (b.client_id = c.id)\n ORDER BY b.starts_at\n LIMIT 1) first_booking ON (true))\n $v$;\nEND $$;\n\nCREATE OR REPLACE VIEW public.rep_revenue_by_professional AS\nSELECT tenant_id,\n (starts_at)::date AS date,\n professional_id,\n COALESCE(professional_name, 'Sem profissional'::text) AS professional_name,\n (count(*))::integer AS appointment_count,\n (COALESCE(sum(NULLIF(order_total, (0)::numeric)), (0)::numeric))::numeric(14,2) AS total_revenue,\n (COALESCE(avg(NULLIF(order_total, (0)::numeric)), (0)::numeric))::numeric(14,2) AS avg_ticket,\n (0)::numeric(14,2) AS commission,\n max(updated_at) AS updated_at\n FROM v_appointments b\n WHERE (status <> ALL (ARRAY['cancelled'::text, 'no_show'::text]))\n GROUP BY tenant_id, ((starts_at)::date), professional_id, COALESCE(professional_name, 'Sem profissional'::text);\n\nCREATE OR REPLACE VIEW public.rep_revenue_by_service AS\nSELECT b.tenant_id,\n (b.starts_at)::date AS date,\n NULLIF((service_item.value ->> 'serviceId'::text), ''::text) AS service_id,\n COALESCE((service_item.value ->> 'name'::text), (service_item.value ->> 'serviceName'::text), 'Sem servico'::text) AS service_name,\n (count(DISTINCT b.id))::integer AS quantity,\n (COALESCE(sum((NULLIF((service_item.value ->> 'price'::text), ''::text))::numeric), (0)::numeric))::numeric(14,2) AS total_revenue,\n (COALESCE(avg((NULLIF((service_item.value ->> 'price'::text), ''::text))::numeric), (0)::numeric))::numeric(14,2) AS avg_ticket,\n max(b.updated_at) AS updated_at\n FROM (v_appointments b\n CROSS JOIN LATERAL jsonb_array_elements(COALESCE((b.services)::jsonb, '[]'::jsonb)) service_item(value))\n WHERE (b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text]))\n GROUP BY b.tenant_id, ((b.starts_at)::date), NULLIF((service_item.value ->> 'serviceId'::text), ''::text), COALESCE((service_item.value ->> 'name'::text), (service_item.value ->> 'serviceName'::text), 'Sem servico'::text);\n\n-- 3. Retire the duplicates. v_bookings goes first: it reads the legacy view.\n-- Nothing in the SDK references either name (checked: only migrations and a\n-- README mention v_bookings).\nDROP VIEW IF EXISTS public.v_bookings;\nDROP VIEW IF EXISTS public.v_bookings_legacy_beauty;\n";
16
16
  export declare const MIGRATIONS: Array<{
17
17
  id: string;
18
18
  sql: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,gCAAgC,09BAqB5C,CAAA;AAED,eAAO,MAAM,qCAAqC,giDA2CjD,CAAA;AAED,eAAO,MAAM,4BAA4B,mgZAmSxC,CAAA;AAED,eAAO,MAAM,+BAA+B,0sBAc3C,CAAA;AAED,eAAO,MAAM,gCAAgC,q5OA+K5C,CAAA;AAED,eAAO,MAAM,qCAAqC,oiPAgLjD,CAAA;AAED,eAAO,MAAM,wBAAwB,uzQAwKpC,CAAA;AAED,eAAO,MAAM,iCAAiC,0xRAqL7C,CAAA;AAED,eAAO,MAAM,2CAA2C,i5YAkSvD,CAAA;AAED,eAAO,MAAM,4CAA4C,i8QA4KxD,CAAA;AAED,eAAO,MAAM,qCAAqC,04MAkKjD,CAAA;AAED,eAAO,MAAM,qCAAqC,y2CA+BjD,CAAA;AAED,eAAO,MAAM,8BAA8B,ivOAuK1C,CAAA;AAED,eAAO,MAAM,0CAA0C,6gDA6BtD,CAAA;AAED,eAAO,MAAM,sCAAsC,gxOAiKlD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAgBzD,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,gCAAgC,09BAqB5C,CAAA;AAED,eAAO,MAAM,qCAAqC,giDA2CjD,CAAA;AAED,eAAO,MAAM,4BAA4B,q0ZAwSxC,CAAA;AAED,eAAO,MAAM,+BAA+B,0sBAc3C,CAAA;AAED,eAAO,MAAM,gCAAgC,q5OA+K5C,CAAA;AAED,eAAO,MAAM,qCAAqC,oiPAgLjD,CAAA;AAED,eAAO,MAAM,wBAAwB,uzQAwKpC,CAAA;AAED,eAAO,MAAM,iCAAiC,0xRAqL7C,CAAA;AAED,eAAO,MAAM,2CAA2C,i5YAkSvD,CAAA;AAED,eAAO,MAAM,4CAA4C,i8QA4KxD,CAAA;AAED,eAAO,MAAM,qCAAqC,04MAkKjD,CAAA;AAED,eAAO,MAAM,qCAAqC,y2CA+BjD,CAAA;AAED,eAAO,MAAM,8BAA8B,ivOAuK1C,CAAA;AAED,eAAO,MAAM,0CAA0C,6gDA6BtD,CAAA;AAED,eAAO,MAAM,sCAAsC,2yRAuMlD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAgBzD,CAAA"}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunk3KWNHV5A_cjs = require('../chunk-3KWNHV5A.cjs');
3
+ var chunkRX2HMWXS_cjs = require('../chunk-RX2HMWXS.cjs');
4
4
  var react = require('react');
5
5
  var lucideReact = require('lucide-react');
6
6
  var jsxRuntime = require('react/jsx-runtime');
@@ -8,7 +8,7 @@ var core = require('@fayz-ai/core');
8
8
 
9
9
  // src/public/data.ts
10
10
  function createMockPublicBookingProvider(options) {
11
- const inner = chunk3KWNHV5A_cjs.createMockAgendaProvider({ seed: options.seed });
11
+ const inner = chunkRX2HMWXS_cjs.createMockAgendaProvider({ seed: options.seed });
12
12
  const { services, professionalId } = options;
13
13
  return {
14
14
  async getServices() {
@@ -1306,7 +1306,7 @@ function createPublicBookingPlugin(options) {
1306
1306
  if (options.dataProvider) {
1307
1307
  provider = options.dataProvider;
1308
1308
  } else if (options.tenantId) {
1309
- provider = chunk3KWNHV5A_cjs.createSupabasePublicBookingProvider({ tenantId: options.tenantId });
1309
+ provider = chunkRX2HMWXS_cjs.createSupabasePublicBookingProvider({ tenantId: options.tenantId });
1310
1310
  } else {
1311
1311
  if (typeof console !== "undefined") {
1312
1312
  console.warn(
@@ -1366,7 +1366,7 @@ function createPublicBookingPlugin(options) {
1366
1366
 
1367
1367
  Object.defineProperty(exports, "createSupabasePublicBookingProvider", {
1368
1368
  enumerable: true,
1369
- get: function () { return chunk3KWNHV5A_cjs.createSupabasePublicBookingProvider; }
1369
+ get: function () { return chunkRX2HMWXS_cjs.createSupabasePublicBookingProvider; }
1370
1370
  });
1371
1371
  exports.BookingProvider = BookingProvider;
1372
1372
  exports.BookingWidget = BookingWidget;
@@ -1,5 +1,5 @@
1
- import { createMockAgendaProvider, createSupabasePublicBookingProvider } from '../chunk-YQO6B4G3.js';
2
- export { createSupabasePublicBookingProvider } from '../chunk-YQO6B4G3.js';
1
+ import { createMockAgendaProvider, createSupabasePublicBookingProvider } from '../chunk-Q2PAWBPR.js';
2
+ export { createSupabasePublicBookingProvider } from '../chunk-Q2PAWBPR.js';
3
3
  import { createContext, useState, useEffect, useMemo, useContext, useRef, createElement } from 'react';
4
4
  import { ChevronLeft, ShieldCheck, Clock, ChevronRight, User, Check, Calendar, ChevronDown, Loader2, CreditCard, Plus, QrCode, CalendarCheck, Copy, Video } from 'lucide-react';
5
5
  import { jsx, jsxs } from 'react/jsx-runtime';
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "fayz": {
4
4
  "status": "beta"
5
5
  },
6
- "version": "0.8.3",
6
+ "version": "0.8.4",
7
7
  "description": "Fayz SDK — plugin-agenda plugin",
8
8
  "type": "module",
9
9
  "main": "./dist/index.cjs",
@@ -43,10 +43,10 @@
43
43
  "@tanstack/react-table": "^8.20.0",
44
44
  "@fullcalendar/resource-timegrid": "^6.1.0",
45
45
  "@fullcalendar/list": "^6.1.0",
46
- "@fayz-ai/core": "^0.8.3",
47
- "@fayz-ai/ui": "^0.8.3",
48
- "@fayz-ai/saas": "^0.8.3",
49
- "@fayz-ai/plugin-financial": "^0.8.3"
46
+ "@fayz-ai/core": "^0.8.4",
47
+ "@fayz-ai/ui": "^0.8.4",
48
+ "@fayz-ai/saas": "^0.8.4",
49
+ "@fayz-ai/plugin-financial": "^0.8.4"
50
50
  },
51
51
  "devDependencies": {
52
52
  "@types/react": "^18.3.0",
@@ -44,7 +44,10 @@ CREATE INDEX IF NOT EXISTS appointments_assignee_time
44
44
  WHERE status NOT IN ('cancelled', 'no_show');
45
45
 
46
46
  -- §2 — admin read model (security_invoker → underlying RLS applies; anon sees 0 rows)
47
- CREATE OR REPLACE VIEW public.v_appointments
47
+ -- DROP first: 013 widens this view and CREATE OR REPLACE cannot narrow a live
48
+ -- view on replay ("cannot drop columns from view"). 013 replays right after.
49
+ DROP VIEW IF EXISTS public.v_appointments;
50
+ CREATE VIEW public.v_appointments
48
51
  WITH (security_invoker = true) AS
49
52
  SELECT
50
53
  b.id, b.tenant_id, b.kind, b.starts_at, b.ends_at, b.status, b.notes,
@@ -72,7 +75,9 @@ GRANT SELECT ON public.v_appointments TO authenticated, service_role;
72
75
  REVOKE SELECT ON public.v_appointments FROM anon;
73
76
 
74
77
  -- §3 — anon-readable public catalog (owner-rights view = deliberate, whitelisted)
75
- CREATE OR REPLACE VIEW public.v_public_services AS
78
+ -- DROP first: 010 widens this view (curation columns) — same replay rule as §2.
79
+ DROP VIEW IF EXISTS public.v_public_services;
80
+ CREATE VIEW public.v_public_services AS
76
81
  SELECT
77
82
  s.id, s.tenant_id, s.name, s.description, s.price, s.currency,
78
83
  COALESCE(s.duration_minutes, 30) AS duration_minutes,
@@ -90,41 +90,79 @@ SELECT tenant_id,
90
90
  updated_at
91
91
  FROM v_appointments b;
92
92
 
93
- CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
94
- SELECT b.tenant_id,
95
- b.id AS booking_id,
96
- (b.starts_at)::date AS date,
97
- b.starts_at,
98
- b.client_id,
99
- b.client_name,
100
- b.professional_id,
101
- b.professional_name,
102
- COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
103
- COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,
104
- a.confirmation_channel,
105
- a.confirmation_sent_at,
106
- a.confirmed_at,
107
- b.created_at,
108
- b.updated_at
109
- FROM (v_appointments b
110
- LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))
111
- WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)));
93
+ -- legacy_pre_pools only exists on pools migrated from the pre-pool era; fresh
94
+ -- pools get the same shape with confirmation columns defaulting to pending/NULL.
95
+ DO $$
96
+ BEGIN
97
+ IF to_regclass('legacy_pre_pools.appointments') IS NOT NULL THEN
98
+ EXECUTE $v$
99
+ CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
100
+ SELECT b.tenant_id,
101
+ b.id AS booking_id,
102
+ (b.starts_at)::date AS date,
103
+ b.starts_at,
104
+ b.client_id,
105
+ b.client_name,
106
+ b.professional_id,
107
+ b.professional_name,
108
+ COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
109
+ COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,
110
+ a.confirmation_channel,
111
+ a.confirmation_sent_at,
112
+ a.confirmed_at,
113
+ b.created_at,
114
+ b.updated_at
115
+ FROM (v_appointments b
116
+ LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))
117
+ WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))
118
+ $v$;
119
+ ELSE
120
+ EXECUTE $v$
121
+ CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
122
+ SELECT b.tenant_id,
123
+ b.id AS booking_id,
124
+ (b.starts_at)::date AS date,
125
+ b.starts_at,
126
+ b.client_id,
127
+ b.client_name,
128
+ b.professional_id,
129
+ b.professional_name,
130
+ COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
131
+ 'pending'::text AS confirmation_status,
132
+ NULL::text AS confirmation_channel,
133
+ NULL::timestamptz AS confirmation_sent_at,
134
+ NULL::timestamptz AS confirmed_at,
135
+ b.created_at,
136
+ b.updated_at
137
+ FROM v_appointments b
138
+ WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))
139
+ $v$;
140
+ END IF;
141
+ END $$;
112
142
 
113
- CREATE OR REPLACE VIEW public.rep_new_clients AS
114
- SELECT c.tenant_id,
115
- c.id AS client_id,
116
- (c.created_at)::date AS date,
117
- c.name AS client_name,
118
- c.origin,
119
- first_booking.service_name AS first_service,
120
- c.created_at,
121
- c.updated_at
122
- FROM (v_clients c
123
- LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name
124
- FROM v_appointments b
125
- WHERE (b.client_id = c.id)
126
- ORDER BY b.starts_at
127
- LIMIT 1) first_booking ON (true));
143
+ -- v_clients (beauty Ring-2 extension) may not exist on non-salon pools — the
144
+ -- report only makes sense where it does.
145
+ DO $$
146
+ BEGIN
147
+ IF to_regclass('public.v_clients') IS NULL THEN RETURN; END IF;
148
+ EXECUTE $v$
149
+ CREATE OR REPLACE VIEW public.rep_new_clients AS
150
+ SELECT c.tenant_id,
151
+ c.id AS client_id,
152
+ (c.created_at)::date AS date,
153
+ c.name AS client_name,
154
+ c.origin,
155
+ first_booking.service_name AS first_service,
156
+ c.created_at,
157
+ c.updated_at
158
+ FROM (v_clients c
159
+ LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name
160
+ FROM v_appointments b
161
+ WHERE (b.client_id = c.id)
162
+ ORDER BY b.starts_at
163
+ LIMIT 1) first_booking ON (true))
164
+ $v$;
165
+ END $$;
128
166
 
129
167
  CREATE OR REPLACE VIEW public.rep_revenue_by_professional AS
130
168
  SELECT tenant_id,
@@ -116,7 +116,10 @@ CREATE INDEX IF NOT EXISTS appointments_assignee_time
116
116
  WHERE status NOT IN ('cancelled', 'no_show');
117
117
 
118
118
  -- §2 — admin read model (security_invoker → underlying RLS applies; anon sees 0 rows)
119
- CREATE OR REPLACE VIEW public.v_appointments
119
+ -- DROP first: 013 widens this view and CREATE OR REPLACE cannot narrow a live
120
+ -- view on replay ("cannot drop columns from view"). 013 replays right after.
121
+ DROP VIEW IF EXISTS public.v_appointments;
122
+ CREATE VIEW public.v_appointments
120
123
  WITH (security_invoker = true) AS
121
124
  SELECT
122
125
  b.id, b.tenant_id, b.kind, b.starts_at, b.ends_at, b.status, b.notes,
@@ -144,7 +147,9 @@ GRANT SELECT ON public.v_appointments TO authenticated, service_role;
144
147
  REVOKE SELECT ON public.v_appointments FROM anon;
145
148
 
146
149
  -- §3 — anon-readable public catalog (owner-rights view = deliberate, whitelisted)
147
- CREATE OR REPLACE VIEW public.v_public_services AS
150
+ -- DROP first: 010 widens this view (curation columns) — same replay rule as §2.
151
+ DROP VIEW IF EXISTS public.v_public_services;
152
+ CREATE VIEW public.v_public_services AS
148
153
  SELECT
149
154
  s.id, s.tenant_id, s.name, s.description, s.price, s.currency,
150
155
  COALESCE(s.duration_minutes, 30) AS duration_minutes,
@@ -2042,41 +2047,79 @@ SELECT tenant_id,
2042
2047
  updated_at
2043
2048
  FROM v_appointments b;
2044
2049
 
2045
- CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
2046
- SELECT b.tenant_id,
2047
- b.id AS booking_id,
2048
- (b.starts_at)::date AS date,
2049
- b.starts_at,
2050
- b.client_id,
2051
- b.client_name,
2052
- b.professional_id,
2053
- b.professional_name,
2054
- COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
2055
- COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,
2056
- a.confirmation_channel,
2057
- a.confirmation_sent_at,
2058
- a.confirmed_at,
2059
- b.created_at,
2060
- b.updated_at
2061
- FROM (v_appointments b
2062
- LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))
2063
- WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)));
2064
-
2065
- CREATE OR REPLACE VIEW public.rep_new_clients AS
2066
- SELECT c.tenant_id,
2067
- c.id AS client_id,
2068
- (c.created_at)::date AS date,
2069
- c.name AS client_name,
2070
- c.origin,
2071
- first_booking.service_name AS first_service,
2072
- c.created_at,
2073
- c.updated_at
2074
- FROM (v_clients c
2075
- LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name
2076
- FROM v_appointments b
2077
- WHERE (b.client_id = c.id)
2078
- ORDER BY b.starts_at
2079
- LIMIT 1) first_booking ON (true));
2050
+ -- legacy_pre_pools only exists on pools migrated from the pre-pool era; fresh
2051
+ -- pools get the same shape with confirmation columns defaulting to pending/NULL.
2052
+ DO $$
2053
+ BEGIN
2054
+ IF to_regclass('legacy_pre_pools.appointments') IS NOT NULL THEN
2055
+ EXECUTE $v$
2056
+ CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
2057
+ SELECT b.tenant_id,
2058
+ b.id AS booking_id,
2059
+ (b.starts_at)::date AS date,
2060
+ b.starts_at,
2061
+ b.client_id,
2062
+ b.client_name,
2063
+ b.professional_id,
2064
+ b.professional_name,
2065
+ COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
2066
+ COALESCE(a.confirmation_status, 'pending'::text) AS confirmation_status,
2067
+ a.confirmation_channel,
2068
+ a.confirmation_sent_at,
2069
+ a.confirmed_at,
2070
+ b.created_at,
2071
+ b.updated_at
2072
+ FROM (v_appointments b
2073
+ LEFT JOIN legacy_pre_pools.appointments a ON ((a.booking_id = b.id)))
2074
+ WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))
2075
+ $v$;
2076
+ ELSE
2077
+ EXECUTE $v$
2078
+ CREATE OR REPLACE VIEW public.rep_confirmation_queue AS
2079
+ SELECT b.tenant_id,
2080
+ b.id AS booking_id,
2081
+ (b.starts_at)::date AS date,
2082
+ b.starts_at,
2083
+ b.client_id,
2084
+ b.client_name,
2085
+ b.professional_id,
2086
+ b.professional_name,
2087
+ COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name,
2088
+ 'pending'::text AS confirmation_status,
2089
+ NULL::text AS confirmation_channel,
2090
+ NULL::timestamptz AS confirmation_sent_at,
2091
+ NULL::timestamptz AS confirmed_at,
2092
+ b.created_at,
2093
+ b.updated_at
2094
+ FROM v_appointments b
2095
+ WHERE ((b.status <> ALL (ARRAY['cancelled'::text, 'no_show'::text])) AND (b.starts_at >= (now() - '1 day'::interval)))
2096
+ $v$;
2097
+ END IF;
2098
+ END $$;
2099
+
2100
+ -- v_clients (beauty Ring-2 extension) may not exist on non-salon pools — the
2101
+ -- report only makes sense where it does.
2102
+ DO $$
2103
+ BEGIN
2104
+ IF to_regclass('public.v_clients') IS NULL THEN RETURN; END IF;
2105
+ EXECUTE $v$
2106
+ CREATE OR REPLACE VIEW public.rep_new_clients AS
2107
+ SELECT c.tenant_id,
2108
+ c.id AS client_id,
2109
+ (c.created_at)::date AS date,
2110
+ c.name AS client_name,
2111
+ c.origin,
2112
+ first_booking.service_name AS first_service,
2113
+ c.created_at,
2114
+ c.updated_at
2115
+ FROM (v_clients c
2116
+ LEFT JOIN LATERAL ( SELECT COALESCE(((b.services -> 0) ->> 'name'::text), ((b.services -> 0) ->> 'serviceName'::text)) AS service_name
2117
+ FROM v_appointments b
2118
+ WHERE (b.client_id = c.id)
2119
+ ORDER BY b.starts_at
2120
+ LIMIT 1) first_booking ON (true))
2121
+ $v$;
2122
+ END $$;
2080
2123
 
2081
2124
  CREATE OR REPLACE VIEW public.rep_revenue_by_professional AS
2082
2125
  SELECT tenant_id,
@@ -11,7 +11,7 @@
11
11
  // Shipped by plugins/plugin-agenda/src/migrations/001_public_booking.sql.
12
12
  // ---------------------------------------------------------------------------
13
13
 
14
- import { getFayzCloudClient, getSupabaseClientOptional } from '@fayz-ai/core'
14
+ import { getSupabaseClientOptional } from '@fayz-ai/core'
15
15
  import type { TimeSlot } from '../types'
16
16
  import type { PublicService } from './types'
17
17
  import type { PublicBookingDataProvider } from './data'
@@ -26,10 +26,10 @@ interface SupabaseLikeClient {
26
26
  rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>
27
27
  }
28
28
 
29
- // App-registered client (BYO backend) wins; otherwise Fayz Cloud — the shared
30
- // hosted project every tenantId-only app books against by default.
31
29
  function getClient(): SupabaseLikeClient {
32
- return (getSupabaseClientOptional() ?? getFayzCloudClient()) as SupabaseLikeClient
30
+ const client = getSupabaseClientOptional()
31
+ if (!client) throw new Error('No Supabase client registered — call setGlobalSupabaseClient() at app startup.')
32
+ return client as SupabaseLikeClient
33
33
  }
34
34
 
35
35
  /** Digits-only phone (RPC normalizes again server-side; keep the dial code). */