@fayz-ai/plugin-agenda 0.27.11 → 0.27.12

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.
Files changed (45) hide show
  1. package/dist/AgendaGeneralSettings-YBI43RB6.js +96 -0
  2. package/dist/AgendaGeneralSettings-YBI43RB6.js.map +1 -0
  3. package/dist/AgendaMessageTemplates-46ZLTFLM.js +31 -0
  4. package/dist/AgendaMessageTemplates-46ZLTFLM.js.map +1 -0
  5. package/dist/AgendaPage-43OXQDZE.js +3174 -0
  6. package/dist/AgendaPage-43OXQDZE.js.map +1 -0
  7. package/dist/CheckinPage-SGWK2TQZ.js +904 -0
  8. package/dist/CheckinPage-SGWK2TQZ.js.map +1 -0
  9. package/dist/ConfirmationsView-DZJSYBXA.js +361 -0
  10. package/dist/ConfirmationsView-DZJSYBXA.js.map +1 -0
  11. package/dist/MyClientsTodayWidget-ZGTXJJKN.js +127 -0
  12. package/dist/MyClientsTodayWidget-ZGTXJJKN.js.map +1 -0
  13. package/dist/PersonAttendanceBlock-PHZVHFQ4.js +105 -0
  14. package/dist/PersonAttendanceBlock-PHZVHFQ4.js.map +1 -0
  15. package/dist/PersonAttendancesWidget-3NTWBGCU.js +1278 -0
  16. package/dist/PersonAttendancesWidget-3NTWBGCU.js.map +1 -0
  17. package/dist/PersonServicesWidget-4RJGKX3K.js +80 -0
  18. package/dist/PersonServicesWidget-4RJGKX3K.js.map +1 -0
  19. package/dist/chunk-37INOUNW.js +20 -0
  20. package/dist/chunk-37INOUNW.js.map +1 -0
  21. package/dist/chunk-A2VD5DVN.js +12 -0
  22. package/dist/chunk-A2VD5DVN.js.map +1 -0
  23. package/dist/chunk-HGJI2JR6.js +169 -0
  24. package/dist/chunk-HGJI2JR6.js.map +1 -0
  25. package/dist/chunk-VFQPXKXP.js +11 -0
  26. package/dist/chunk-VFQPXKXP.js.map +1 -0
  27. package/dist/chunk-WNANVT4F.js +2386 -0
  28. package/dist/chunk-WNANVT4F.js.map +1 -0
  29. package/dist/chunk-X7PKHXT6.js +18 -0
  30. package/dist/chunk-X7PKHXT6.js.map +1 -0
  31. package/dist/chunk-XTNSK4RJ.js +12 -0
  32. package/dist/chunk-XTNSK4RJ.js.map +1 -0
  33. package/dist/components/PersonAttendanceBlock.d.ts.map +1 -1
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +2530 -19553
  36. package/dist/index.js.map +1 -1
  37. package/dist/migrations/integrations-google-calendar.browser.js +15 -0
  38. package/dist/migrations/integrations-google-calendar.browser.js.map +1 -0
  39. package/dist/migrations/integrations-google-calendar.js +1992 -0
  40. package/dist/migrations/integrations-google-calendar.js.map +1 -0
  41. package/dist/migrations/main.browser.js +29 -0
  42. package/dist/migrations/main.browser.js.map +1 -0
  43. package/dist/migrations/main.js +6440 -0
  44. package/dist/migrations/main.js.map +1 -0
  45. package/package.json +13 -7
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/integrations/google-calendar/migrations/index.ts"],"names":[],"mappings":";AAIO,IAAM,6BAAA,GAAgC,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAmGtC,IAAM,w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AkB,GAAA,EAAK,wBAAA,EAAyB;AAAA,EACtD,EAAE,EAAA,EAAI,uBAAA,EAAyB,GAAA,EAAK,+BAAA,EAAgC;AAAA,EACpE,EAAE,EAAA,EAAI,6BAAA,EAA+B,GAAA,EAAK,qCAAA,EAAsC;AAAA,EAChF,EAAE,EAAA,EAAI,+BAAA,EAAiC,GAAA,EAAK,uCAAA,EAAwC;AAAA,EACpF,EAAE,EAAA,EAAI,6BAAA,EAA+B,GAAA,EAAK,qCAAA,EAAsC;AAAA,EAChF,EAAE,EAAA,EAAI,uBAAA,EAAyB,GAAA,EAAK,+BAAA,EAAgC;AAAA,EACpE,EAAE,EAAA,EAAI,+BAAA,EAAiC,GAAA,EAAK,uCAAA;AAC9C","file":"integrations-google-calendar.js","sourcesContent":["// AUTO-GENERATED from 001_google_calendar.sql, 002_smart_sync.sql, 003_plg_rename.sql, 004_drop_oauth_tokens.sql, 005_outbound_vault_delivery.sql, 006_webhook_deliveries_outbox.sql, 007_credential_free_install.sql, 008_the_outbound_half.sql, 009_the_service_runs_the_sync.sql — regenerate with scripts/embed-migrations.mjs\n// SQL files are the source of truth; this inline copy lets the manifest declare\n// migrations as data. Do not edit by hand — run the embed script instead.\n\nexport const MIGRATION_001_GOOGLE_CALENDAR = `-- ---------------------------------------------------------------------------\n-- Google Calendar integration (bidirectional) — connection + audit + triggers\n-- ---------------------------------------------------------------------------\n-- Outbound (Fayz booking → Google event) fires from a trigger on public.appointments\n-- via pg_net to the google-calendar-sync edge function (push_event). Inbound\n-- (Google → booking) runs on a pg_cron schedule (pull_events) and/or a Google\n-- watch-channel webhook. The booking↔event link is stored on\n-- public.appointments.metadata.googleCalendarEventId (no schema change there).\n\n-- Plugin-owned tables carry the platform \\`plg_<plugin>_\\` prefix (DATA-MODEL.md\n-- Ring 1). Legacy pools provisioned under the old \\`calendar_*\\` names are migrated\n-- by 003_plg_rename.sql; fresh installs are born with the prefixed names here.\nCREATE TABLE IF NOT EXISTS public.plg_calendar_integrations (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n provider text NOT NULL DEFAULT 'google',\n oauth_refresh_token text,\n oauth_access_token text,\n token_expires_at timestamptz,\n calendar_id text NOT NULL DEFAULT 'primary',\n -- Incremental pull cursor + Google watch channel bookkeeping.\n sync_token text,\n channel_id text,\n channel_resource_id text,\n channel_expires_at timestamptz,\n active boolean NOT NULL DEFAULT true,\n last_sync_at timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (tenant_id, provider)\n);\nALTER TABLE public.plg_calendar_integrations ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_integrations_tenant ON public.plg_calendar_integrations(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_calendar_sync_log (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n direction text NOT NULL, -- inbound | outbound\n trigger text, -- on-write | scheduled | webhook | manual\n status text NOT NULL DEFAULT 'success', -- success | partial | error\n fetched integer NOT NULL DEFAULT 0,\n written integer NOT NULL DEFAULT 0,\n error text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_calendar_sync_log ENABLE ROW LEVEL SECURITY;\n\n-- RLS: tenant isolation.\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY['plg_calendar_integrations','plg_calendar_sync_log'])\n LOOP\n EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON public.%I TO authenticated', t);\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_rls') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR ALL TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids())) WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_rls', t);\n END IF;\n END LOOP;\nEND $$;\n\n-- ---------------------------------------------------------------------------\n-- Outbound trigger: booking change → edge function (push_event).\n-- Requires pg_net + a configured function URL. Set once per project:\n-- ALTER DATABASE postgres SET app.gcal_sync_url = 'https://<ref>.functions.supabase.co/google-calendar-sync';\n-- ALTER DATABASE postgres SET app.gcal_service_key = '<service-role-key>';\n-- Safe to skip in environments without pg_net — outbound also works via the\n-- client-side withGoogleCalendarSync() decorator.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.fn_gcal_push_booking() RETURNS trigger\nLANGUAGE plpgsql SECURITY DEFINER AS $$\nDECLARE\n url text := current_setting('app.gcal_sync_url', true);\n key text := current_setting('app.gcal_service_key', true);\n rec record := COALESCE(NEW, OLD);\n op text := lower(TG_OP);\nBEGIN\n IF url IS NULL OR url = '' THEN RETURN COALESCE(NEW, OLD); END IF;\n PERFORM net.http_post(\n url := url,\n headers := jsonb_build_object('Content-Type', 'application/json', 'Authorization', 'Bearer ' || COALESCE(key, '')),\n body := jsonb_build_object('action', 'push_event', 'op', op, 'bookingId', rec.id, 'tenantId', rec.tenant_id)\n );\n RETURN COALESCE(NEW, OLD);\nEND $$;\n\nDROP TRIGGER IF EXISTS trg_gcal_push ON public.appointments;\nCREATE TRIGGER trg_gcal_push\n AFTER INSERT OR UPDATE OR DELETE ON public.appointments\n FOR EACH ROW EXECUTE FUNCTION public.fn_gcal_push_booking();\n\n-- Inbound schedule (optional): pull external changes every 10 minutes.\n-- SELECT cron.schedule('gcal-pull', '*/10 * * * *', $$\n-- SELECT net.http_post(\n-- url := current_setting('app.gcal_sync_url'),\n-- headers := jsonb_build_object('Content-Type','application/json','Authorization','Bearer '||current_setting('app.gcal_service_key')),\n-- body := jsonb_build_object('action','pull_events'));\n-- $$);\n`\n\nexport const MIGRATION_002_SMART_SYNC = `-- ---------------------------------------------------------------------------\n-- Google Calendar SMART SYNC — multi-calendar de-para + loop-safe two-way sync\n-- ---------------------------------------------------------------------------\n-- Builds on 001_google_calendar.sql. Where 001 modelled a single calendar per\n-- tenant (plg_calendar_integrations, one outbound trigger, a pull template), 002\n-- makes the sync vertical-agnostic and bidirectional-safe:\n--\n-- §1 public.plg_calendar_channels — de-para: one Google calendar → one sync\n-- target (whole tenant / assignee / service\n-- / location), per direction + import mode\n-- §2 fn_gcal_push_booking (REPLACE)— loop-prevention guard + correlation id\n-- §3 plg_calendar_sync_log — correlation_id + channel_id_ref columns\n-- §4 inbound write functions — the ONLY path Google→booking writes take\n-- (gcal_import_event / gcal_apply_event_patch\n-- / gcal_unlink_channel), SECURITY DEFINER,\n-- service_role-only\n-- §5 get_available_slots (REPLACE) — tenant-wide imported blocks now also\n-- remove slots for every professional\n-- §6 pg_cron template — per-channel pull\n--\n-- Idempotent / re-runnable: IF NOT EXISTS, CREATE OR REPLACE, DROP … IF EXISTS.\n-- Written against the canonical public names (appointments uses starts_at/ends_at,\n-- metadata jsonb, party_id/assignee_id — see packages/db 004_archetypes.sql).\n-- ---------------------------------------------------------------------------\n\n-- ===========================================================================\n-- §1 — plg_calendar_channels: multi-calendar de-para (vertical-agnostic)\n-- target_kind NULL → whole tenant agenda (agency-os): every professional\n-- target_kind 'assignee' → calendar maps to one professional (school: teacher)\n-- target_kind 'service' | 'location' → clinic-style mapping\n-- import_mode 'block' → inbound events become opaque busy blocks\n-- import_mode 'appointment' → inbound events become real appointments\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_channels (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n integration_id uuid NOT NULL REFERENCES public.plg_calendar_integrations(id) ON DELETE CASCADE,\n tenant_id uuid NOT NULL,\n google_calendar_id text NOT NULL,\n summary text,\n color text,\n direction text NOT NULL DEFAULT 'bidirectional'\n CHECK (direction IN ('inbound','outbound','bidirectional','off')),\n target_kind text CHECK (target_kind IN ('assignee','service','location')),\n target_id uuid,\n import_mode text NOT NULL DEFAULT 'block'\n CHECK (import_mode IN ('block','appointment')),\n sync_token text,\n channel_id text,\n resource_id text,\n channel_expires_at timestamptz,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (integration_id, google_calendar_id)\n);\n\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_channels_tenant ON public.plg_calendar_channels(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_channels_integration ON public.plg_calendar_channels(integration_id);\n\nALTER TABLE public.plg_calendar_channels ENABLE ROW LEVEL SECURITY;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_calendar_channels TO authenticated;\n-- service_role bypasses RLS, but this table is born after 004's blanket grant,\n-- so grant it explicitly (the inbound functions run as definer/service_role).\nGRANT ALL ON public.plg_calendar_channels TO service_role;\n\nDROP TRIGGER IF EXISTS plg_calendar_channels_updated_at ON public.plg_calendar_channels;\nCREATE TRIGGER plg_calendar_channels_updated_at BEFORE UPDATE ON public.plg_calendar_channels\n FOR EACH ROW EXECUTE FUNCTION public.handle_updated_at();\n\n-- RLS: tenant isolation (padrão 001) + explicit service_role FOR ALL policy\n-- (matches the vigente service_role policy pattern from 001_core payment_events).\nDROP POLICY IF EXISTS plg_calendar_channels_rls ON public.plg_calendar_channels;\nCREATE POLICY plg_calendar_channels_rls ON public.plg_calendar_channels\n FOR ALL TO authenticated\n USING (tenant_id IN (SELECT public.user_tenant_ids()))\n WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()));\n\nDROP POLICY IF EXISTS plg_calendar_channels_service ON public.plg_calendar_channels;\nCREATE POLICY plg_calendar_channels_service ON public.plg_calendar_channels\n FOR ALL TO service_role USING (true) WITH CHECK (true);\n\n-- ===========================================================================\n-- §2 — Outbound trigger with loop-prevention + correlation id.\n-- CREATE OR REPLACE of 001's fn_gcal_push_booking. Same pg_net → edge function\n-- payload (app.gcal_sync_url / app.gcal_service_key), but now:\n-- * SKIP the push when the write itself came from the Google sync, detected by\n-- the TRANSACTION-LOCAL GUC app.booking_origin = 'google' — set by every §4\n-- writer via set_config(..., true) and gone when the transaction ends.\n-- This is what stops the Google→booking→Google→… echo loop.\n-- Deliberately NOT a persistent metadata check: a sticky marker\n-- (metadata.syncOrigin) would permanently mute pushes for imported events,\n-- so a later admin edit would never reach Google. metadata.syncOrigin is\n-- kept by §4 as provenance only — this trigger does not read it.\n-- * carry a correlation_id so both directions can be stitched in the sync log\n-- (from GUC app.booking_correlation_id, else a fresh uuid — design ported\n-- from PR #7).\n-- ===========================================================================\nCREATE OR REPLACE FUNCTION public.fn_gcal_push_booking() RETURNS trigger\nLANGUAGE plpgsql SECURITY DEFINER AS $$\nDECLARE\n url text := current_setting('app.gcal_sync_url', true);\n key text := current_setting('app.gcal_service_key', true);\n rec record := COALESCE(NEW, OLD);\n op text := lower(TG_OP);\n corr text := NULLIF(current_setting('app.booking_correlation_id', true), '');\nBEGIN\n -- Loop guard: never bounce a Google-originated write back to Google.\n -- Transaction-local GUC only (see §2 header for why not persistent metadata).\n IF current_setting('app.booking_origin', true) = 'google' THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n IF url IS NULL OR url = '' THEN RETURN COALESCE(NEW, OLD); END IF;\n\n PERFORM net.http_post(\n url := url,\n headers := jsonb_build_object('Content-Type', 'application/json',\n 'Authorization', 'Bearer ' || COALESCE(key, '')),\n body := jsonb_build_object(\n 'action', 'push_event',\n 'op', op,\n 'bookingId', rec.id,\n 'tenantId', rec.tenant_id,\n 'correlationId', COALESCE(corr, gen_random_uuid()::text)\n )\n );\n RETURN COALESCE(NEW, OLD);\nEND $$;\n\n-- Re-assert the trigger (idempotent; unchanged from 001).\nDROP TRIGGER IF EXISTS trg_gcal_push ON public.appointments;\nCREATE TRIGGER trg_gcal_push\n AFTER INSERT OR UPDATE OR DELETE ON public.appointments\n FOR EACH ROW EXECUTE FUNCTION public.fn_gcal_push_booking();\n\n-- ===========================================================================\n-- §3 — sync log: correlate the two directions + reference the source channel.\n-- ===========================================================================\nALTER TABLE public.plg_calendar_sync_log\n ADD COLUMN IF NOT EXISTS correlation_id uuid;\nALTER TABLE public.plg_calendar_sync_log\n ADD COLUMN IF NOT EXISTS channel_id_ref uuid\n REFERENCES public.plg_calendar_channels(id) ON DELETE SET NULL;\n-- Unlinked future events seen during a pull (import-wizard candidates), so the\n-- log can show \"N eventos aguardando import\" without re-hitting Google.\nALTER TABLE public.plg_calendar_sync_log\n ADD COLUMN IF NOT EXISTS discovered integer;\n\n-- ===========================================================================\n-- §4 — Inbound write path (Google → booking). THE single entry point used by\n-- the edge function (scheduled pull, webhook, and the import wizard). All three\n-- functions are SECURITY DEFINER with SET search_path = public and are granted\n-- to service_role ONLY (anon/authenticated explicitly revoked) — they bypass the\n-- tenant RLS on purpose and must never be reachable from the anon/authenticated\n-- PostgREST surface. Every writer sets the TRANSACTION-LOCAL GUC\n-- app.booking_origin='google' (set_config ..., true) so §2's trigger suppresses\n-- the echo for THIS write only; metadata.syncOrigin is provenance, not a guard.\n-- ===========================================================================\n\n-- gcal_import_event: create (or idempotently update) a booking from a Google\n-- event, honouring the channel's import_mode + target mapping.\n-- kind = 'block' | 'appointment' (from channel.import_mode)\n-- assignee_id = channel.target_id when target_kind='assignee', else NULL\n-- (NULL = tenant-wide → blocks every professional, see §5)\n-- location_id = channel.target_id when target_kind='location', else NULL\n-- status = 'scheduled'\n-- No order is created — an external import is not a sale. Idempotent on\n-- (tenant_id, metadata.googleCalendarEventId): update in place if seen before.\nCREATE OR REPLACE FUNCTION public.gcal_import_event(\n p_tenant_id uuid,\n p_channel_id uuid,\n p_event_id text,\n p_etag text,\n p_summary text,\n p_starts_at timestamptz,\n p_ends_at timestamptz,\n p_all_day boolean,\n p_description text DEFAULT NULL\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_ch record;\n v_kind text;\n v_assignee uuid;\n v_location uuid;\n v_ends timestamptz;\n v_meta jsonb;\n v_existing uuid;\n v_appt uuid;\nBEGIN\n IF p_tenant_id IS NULL OR p_event_id IS NULL OR p_starts_at IS NULL THEN\n RAISE EXCEPTION 'gcal_import_event: tenant, event id and start are required';\n END IF;\n\n -- Transaction-local: §2's trigger skips the echo for this write only.\n PERFORM set_config('app.booking_origin', 'google', true);\n\n -- Resolve the channel mapping (must belong to the same tenant).\n SELECT c.import_mode, c.target_kind, c.target_id\n INTO v_ch\n FROM plg_calendar_channels c\n WHERE c.id = p_channel_id AND c.tenant_id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'gcal_import_event: unknown channel for tenant'; END IF;\n\n v_kind := CASE WHEN v_ch.import_mode = 'appointment' THEN 'appointment' ELSE 'block' END;\n v_assignee := CASE WHEN v_ch.target_kind = 'assignee' THEN v_ch.target_id ELSE NULL END;\n v_location := CASE WHEN v_ch.target_kind = 'location' THEN v_ch.target_id ELSE NULL END;\n\n -- All-day events without an explicit end block the whole day so §5 excludes it.\n v_ends := COALESCE(\n p_ends_at,\n CASE WHEN COALESCE(p_all_day, false) THEN p_starts_at + interval '1 day' ELSE p_starts_at END\n );\n\n v_meta := jsonb_build_object(\n 'syncOrigin', 'google',\n 'googleCalendarEventId', p_event_id,\n 'gcalEtag', p_etag,\n 'gcalChannelId', p_channel_id::text,\n 'allDay', COALESCE(p_all_day, false),\n 'title', p_summary,\n 'source', 'google_import'\n );\n\n -- Idempotency: has this event already been imported for the tenant?\n SELECT b.id INTO v_existing\n FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.metadata->>'googleCalendarEventId' = p_event_id\n LIMIT 1;\n\n IF v_existing IS NOT NULL THEN\n UPDATE appointments b\n SET kind = v_kind,\n assignee_id = v_assignee,\n location_id = v_location,\n starts_at = p_starts_at,\n ends_at = v_ends,\n status = 'scheduled',\n notes = COALESCE(p_description, p_summary),\n metadata = COALESCE(b.metadata, '{}'::jsonb) || v_meta,\n updated_at = now()\n WHERE b.id = v_existing\n RETURNING b.id INTO v_appt;\n ELSE\n INSERT INTO appointments (tenant_id, kind, assignee_id, location_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, v_kind, v_assignee, v_location,\n p_starts_at, v_ends, 'scheduled', COALESCE(p_description, p_summary), v_meta)\n RETURNING id INTO v_appt;\n END IF;\n\n RETURN v_appt;\nEND $$;\n\n-- gcal_apply_event_patch: apply an inbound reschedule/cancel to an already-linked\n-- booking. Located by metadata.googleCalendarEventId. Echo suppression: if the\n-- stored gcalEtag already equals the incoming etag, this is our own write coming\n-- back — skip and return NULL. Every real write re-stamps syncOrigin='google'.\nCREATE OR REPLACE FUNCTION public.gcal_apply_event_patch(\n p_tenant_id uuid,\n p_event_id text,\n p_etag text,\n p_starts_at timestamptz,\n p_ends_at timestamptz,\n p_summary text,\n p_cancelled boolean\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_appt uuid;\n v_curr_etag text;\nBEGIN\n IF p_tenant_id IS NULL OR p_event_id IS NULL THEN\n RAISE EXCEPTION 'gcal_apply_event_patch: tenant and event id are required';\n END IF;\n\n -- Transaction-local: §2's trigger skips the echo for this write only.\n PERFORM set_config('app.booking_origin', 'google', true);\n\n SELECT b.id, b.metadata->>'gcalEtag'\n INTO v_appt, v_curr_etag\n FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.metadata->>'googleCalendarEventId' = p_event_id\n LIMIT 1;\n\n IF v_appt IS NULL THEN RETURN NULL; END IF; -- not linked here\n IF p_etag IS NOT NULL AND p_etag = v_curr_etag THEN\n RETURN NULL; -- echo: nothing changed\n END IF;\n\n IF COALESCE(p_cancelled, false) THEN\n UPDATE appointments b\n SET status = 'cancelled',\n metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('syncOrigin', 'google', 'gcalEtag', p_etag),\n updated_at = now()\n WHERE b.id = v_appt;\n ELSE\n UPDATE appointments b\n SET starts_at = COALESCE(p_starts_at, b.starts_at),\n ends_at = COALESCE(p_ends_at, b.ends_at),\n notes = COALESCE(p_summary, b.notes),\n metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('syncOrigin', 'google',\n 'gcalEtag', p_etag,\n 'title', COALESCE(p_summary, b.metadata->>'title')),\n updated_at = now()\n WHERE b.id = v_appt;\n END IF;\n\n RETURN v_appt;\nEND $$;\n\n-- gcal_stamp_outbound: after the edge function creates the Google event for an\n-- outbound push, it stamps the fresh event id/etag back onto the appointment.\n-- Bookkeeping only — must not re-fire §2's trigger, hence the GUC. Does NOT set\n-- metadata.syncOrigin (the booking's provenance is still the app/site).\nCREATE OR REPLACE FUNCTION public.gcal_stamp_outbound(\n p_tenant_id uuid,\n p_booking_id uuid,\n p_event_id text,\n p_etag text DEFAULT NULL,\n p_calendar_id text DEFAULT NULL\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_id uuid;\nBEGIN\n IF p_tenant_id IS NULL OR p_booking_id IS NULL OR p_event_id IS NULL THEN\n RAISE EXCEPTION 'gcal_stamp_outbound: tenant, booking and event id are required';\n END IF;\n\n -- Transaction-local: §2's trigger skips the echo for this write only.\n PERFORM set_config('app.booking_origin', 'google', true);\n\n UPDATE appointments b\n SET metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('googleCalendarEventId', p_event_id,\n 'gcalEtag', p_etag,\n 'gcalSyncedAt', now())\n || CASE WHEN p_calendar_id IS NULL THEN '{}'::jsonb\n ELSE jsonb_build_object('gcalCalendarId', p_calendar_id) END,\n updated_at = now()\n WHERE b.id = p_booking_id AND b.tenant_id = p_tenant_id\n RETURNING b.id INTO v_id;\n RETURN v_id;\nEND $$;\n\n-- gcal_unlink_channel: forget the incremental cursor + Google watch bookkeeping\n-- for a channel (used on disconnect / re-watch). Leaves the mapping row in place.\nCREATE OR REPLACE FUNCTION public.gcal_unlink_channel(\n p_channel_id uuid\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_id uuid;\nBEGIN\n UPDATE plg_calendar_channels c\n SET sync_token = NULL,\n channel_id = NULL,\n resource_id = NULL,\n channel_expires_at = NULL,\n updated_at = now()\n WHERE c.id = p_channel_id\n RETURNING c.id INTO v_id;\n RETURN v_id;\nEND $$;\n\n-- Lock the inbound writers to service_role only.\nDO $$\nDECLARE fn text;\nBEGIN\n FOR fn IN SELECT unnest(ARRAY[\n 'public.gcal_import_event(uuid, uuid, text, text, text, timestamptz, timestamptz, boolean, text)',\n 'public.gcal_apply_event_patch(uuid, text, text, timestamptz, timestamptz, text, boolean)',\n 'public.gcal_stamp_outbound(uuid, uuid, text, text, text)',\n 'public.gcal_unlink_channel(uuid)'\n ])\n LOOP\n EXECUTE format('REVOKE ALL ON FUNCTION %s FROM public, anon, authenticated', fn);\n EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO service_role', fn);\n END LOOP;\nEND $$;\n\n-- ===========================================================================\n-- §5 — get_available_slots: imported Google blocks must remove availability.\n-- CREATE OR REPLACE keeping the EXACT signature (anon + admin both call it, and\n-- it is graded on the same shape as plugin-agenda/src/migrations/001_public_booking.sql).\n--\n-- Conceptual diff vs 001 — ONE condition in the overlap NOT EXISTS:\n-- before: AND b.assignee_id = c.assignee_id\n-- after: AND (b.assignee_id = c.assignee_id\n-- OR (b.assignee_id IS NULL AND b.kind = 'block'))\n-- Rationale: a tenant-wide BLOCK imported from Google (target_kind NULL →\n-- assignee_id IS NULL, kind 'block', see §4) must busy-out the slot for EVERY\n-- professional. Restricted to kind='block' so an unassigned admin appointment\n-- keeps the 001 behaviour (blocks nobody). Per-assignee rows keep matching on\n-- assignee_id.\n-- Everything else is byte-identical to 001: the status filter already covers\n-- \"any non-cancelled kind\" (no_show also excluded), and the p_assignee_id-NULL\n-- fan-out across staff via day_schedules is preserved untouched.\n-- ===========================================================================\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 → 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 -- SMART SYNC: match this professional's own bookings OR any tenant-wide\n -- BLOCK (assignee_id IS NULL AND kind='block', e.g. imported from Google\n -- with a whole-tenant channel) — the latter busies the slot for every\n -- professional. Assignee-less rows of other kinds (an unassigned admin\n -- appointment) keep the 001 behaviour and do not block anyone.\n AND (b.assignee_id = c.assignee_id\n OR (b.assignee_id IS NULL AND b.kind = 'block'))\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-- ===========================================================================\n-- §6 — Inbound schedule (optional) — per-channel incremental pull.\n-- Supersedes the single-calendar template in 001. Enable once per project after\n-- setting app.gcal_sync_url / app.gcal_service_key (see 001 header). The edge\n-- function fans out over active channels, using each channel's sync_token cursor:\n--\n-- SELECT cron.schedule('gcal-pull', '*/10 * * * *', $CRON$\n-- SELECT net.http_post(\n-- url := current_setting('app.gcal_sync_url'),\n-- headers := jsonb_build_object(\n-- 'Content-Type','application/json',\n-- 'Authorization','Bearer '||current_setting('app.gcal_service_key')),\n-- body := jsonb_build_object('action','pull_events'))\n-- $CRON$);\n--\n-- Or drive one row per channel from SQL (tighter scoping / per-channel cadence):\n--\n-- SELECT cron.schedule('gcal-pull-'||ch.id::text, '*/10 * * * *', format($CRON$\n-- SELECT net.http_post(\n-- url := current_setting('app.gcal_sync_url'),\n-- headers := jsonb_build_object(\n-- 'Content-Type','application/json',\n-- 'Authorization','Bearer '||current_setting('app.gcal_service_key')),\n-- body := jsonb_build_object('action','pull_events','channelId',%L))\n-- $CRON$, ch.id))\n-- FROM public.plg_calendar_channels ch\n-- WHERE ch.is_active AND ch.direction IN ('inbound','bidirectional');\n-- ===========================================================================\n`\n\nexport const MIGRATION_003_PLG_RENAME = `-- ---------------------------------------------------------------------------\n-- 003_plg_rename.sql — standardize the Google Calendar connector objects onto\n-- the platform \\`plg_<plugin>_\\` prefix (DATA-MODEL.md Ring 1).\n--\n-- calendar_integrations → plg_calendar_integrations\n-- calendar_channels → plg_calendar_channels\n-- calendar_sync_log → plg_calendar_sync_log\n--\n-- Legacy-pool remediation ONLY: 001/002 now create the prefixed names directly,\n-- so fresh installs never reach a rename branch. Fully idempotent and guarded —\n-- every RENAME fires only when the old object exists and the new one does not,\n-- so re-running (or running on an already-prefixed pool) is a no-op.\n--\n-- A table RENAME preserves its data, RLS state, policies, grants, indexes,\n-- constraints and triggers (they follow the table), so §1 only renames the\n-- table + the explicitly-named indexes. §2 then re-points the SECURITY DEFINER\n-- gcal_* functions whose bodies hard-code the old table names.\n-- ---------------------------------------------------------------------------\n\n-- ===========================================================================\n-- §1 — Guarded table + index renames.\n-- ===========================================================================\nDO $$\nBEGIN\n IF to_regclass('public.calendar_integrations') IS NOT NULL\n AND to_regclass('public.plg_calendar_integrations') IS NULL THEN\n ALTER TABLE public.calendar_integrations RENAME TO plg_calendar_integrations;\n END IF;\n\n IF to_regclass('public.calendar_channels') IS NOT NULL\n AND to_regclass('public.plg_calendar_channels') IS NULL THEN\n ALTER TABLE public.calendar_channels RENAME TO plg_calendar_channels;\n END IF;\n\n IF to_regclass('public.calendar_sync_log') IS NOT NULL\n AND to_regclass('public.plg_calendar_sync_log') IS NULL THEN\n ALTER TABLE public.calendar_sync_log RENAME TO plg_calendar_sync_log;\n END IF;\n\n -- Named indexes do not follow a table rename automatically.\n IF to_regclass('public.idx_calendar_integrations_tenant') IS NOT NULL\n AND to_regclass('public.idx_plg_calendar_integrations_tenant') IS NULL THEN\n ALTER INDEX public.idx_calendar_integrations_tenant RENAME TO idx_plg_calendar_integrations_tenant;\n END IF;\n\n IF to_regclass('public.idx_calendar_channels_tenant') IS NOT NULL\n AND to_regclass('public.idx_plg_calendar_channels_tenant') IS NULL THEN\n ALTER INDEX public.idx_calendar_channels_tenant RENAME TO idx_plg_calendar_channels_tenant;\n END IF;\n\n IF to_regclass('public.idx_calendar_channels_integration') IS NOT NULL\n AND to_regclass('public.idx_plg_calendar_channels_integration') IS NULL THEN\n ALTER INDEX public.idx_calendar_channels_integration RENAME TO idx_plg_calendar_channels_integration;\n END IF;\nEND $$;\n\n-- ===========================================================================\n-- §2 — Re-point the inbound SECURITY DEFINER writers at the prefixed names.\n-- These bodies are byte-identical to 002_smart_sync.sql except the calendar_*\n-- table references, which now read plg_calendar_*. gcal_apply_event_patch and\n-- gcal_stamp_outbound only touch public.appointments (unaffected by the rename)\n-- and are re-asserted here for completeness so all four writers stay in step.\n-- ===========================================================================\n\nCREATE OR REPLACE FUNCTION public.gcal_import_event(\n p_tenant_id uuid,\n p_channel_id uuid,\n p_event_id text,\n p_etag text,\n p_summary text,\n p_starts_at timestamptz,\n p_ends_at timestamptz,\n p_all_day boolean,\n p_description text DEFAULT NULL\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_ch record;\n v_kind text;\n v_assignee uuid;\n v_location uuid;\n v_ends timestamptz;\n v_meta jsonb;\n v_existing uuid;\n v_appt uuid;\nBEGIN\n IF p_tenant_id IS NULL OR p_event_id IS NULL OR p_starts_at IS NULL THEN\n RAISE EXCEPTION 'gcal_import_event: tenant, event id and start are required';\n END IF;\n\n PERFORM set_config('app.booking_origin', 'google', true);\n\n SELECT c.import_mode, c.target_kind, c.target_id\n INTO v_ch\n FROM plg_calendar_channels c\n WHERE c.id = p_channel_id AND c.tenant_id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'gcal_import_event: unknown channel for tenant'; END IF;\n\n v_kind := CASE WHEN v_ch.import_mode = 'appointment' THEN 'appointment' ELSE 'block' END;\n v_assignee := CASE WHEN v_ch.target_kind = 'assignee' THEN v_ch.target_id ELSE NULL END;\n v_location := CASE WHEN v_ch.target_kind = 'location' THEN v_ch.target_id ELSE NULL END;\n\n v_ends := COALESCE(\n p_ends_at,\n CASE WHEN COALESCE(p_all_day, false) THEN p_starts_at + interval '1 day' ELSE p_starts_at END\n );\n\n v_meta := jsonb_build_object(\n 'syncOrigin', 'google',\n 'googleCalendarEventId', p_event_id,\n 'gcalEtag', p_etag,\n 'gcalChannelId', p_channel_id::text,\n 'allDay', COALESCE(p_all_day, false),\n 'title', p_summary,\n 'source', 'google_import'\n );\n\n SELECT b.id INTO v_existing\n FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.metadata->>'googleCalendarEventId' = p_event_id\n LIMIT 1;\n\n IF v_existing IS NOT NULL THEN\n UPDATE appointments b\n SET kind = v_kind,\n assignee_id = v_assignee,\n location_id = v_location,\n starts_at = p_starts_at,\n ends_at = v_ends,\n status = 'scheduled',\n notes = COALESCE(p_description, p_summary),\n metadata = COALESCE(b.metadata, '{}'::jsonb) || v_meta,\n updated_at = now()\n WHERE b.id = v_existing\n RETURNING b.id INTO v_appt;\n ELSE\n INSERT INTO appointments (tenant_id, kind, assignee_id, location_id,\n starts_at, ends_at, status, notes, metadata)\n VALUES (p_tenant_id, v_kind, v_assignee, v_location,\n p_starts_at, v_ends, 'scheduled', COALESCE(p_description, p_summary), v_meta)\n RETURNING id INTO v_appt;\n END IF;\n\n RETURN v_appt;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.gcal_apply_event_patch(\n p_tenant_id uuid,\n p_event_id text,\n p_etag text,\n p_starts_at timestamptz,\n p_ends_at timestamptz,\n p_summary text,\n p_cancelled boolean\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_appt uuid;\n v_curr_etag text;\nBEGIN\n IF p_tenant_id IS NULL OR p_event_id IS NULL THEN\n RAISE EXCEPTION 'gcal_apply_event_patch: tenant and event id are required';\n END IF;\n\n PERFORM set_config('app.booking_origin', 'google', true);\n\n SELECT b.id, b.metadata->>'gcalEtag'\n INTO v_appt, v_curr_etag\n FROM appointments b\n WHERE b.tenant_id = p_tenant_id\n AND b.metadata->>'googleCalendarEventId' = p_event_id\n LIMIT 1;\n\n IF v_appt IS NULL THEN RETURN NULL; END IF;\n IF p_etag IS NOT NULL AND p_etag = v_curr_etag THEN\n RETURN NULL;\n END IF;\n\n IF COALESCE(p_cancelled, false) THEN\n UPDATE appointments b\n SET status = 'cancelled',\n metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('syncOrigin', 'google', 'gcalEtag', p_etag),\n updated_at = now()\n WHERE b.id = v_appt;\n ELSE\n UPDATE appointments b\n SET starts_at = COALESCE(p_starts_at, b.starts_at),\n ends_at = COALESCE(p_ends_at, b.ends_at),\n notes = COALESCE(p_summary, b.notes),\n metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('syncOrigin', 'google',\n 'gcalEtag', p_etag,\n 'title', COALESCE(p_summary, b.metadata->>'title')),\n updated_at = now()\n WHERE b.id = v_appt;\n END IF;\n\n RETURN v_appt;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.gcal_stamp_outbound(\n p_tenant_id uuid,\n p_booking_id uuid,\n p_event_id text,\n p_etag text DEFAULT NULL,\n p_calendar_id text DEFAULT NULL\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_id uuid;\nBEGIN\n IF p_tenant_id IS NULL OR p_booking_id IS NULL OR p_event_id IS NULL THEN\n RAISE EXCEPTION 'gcal_stamp_outbound: tenant, booking and event id are required';\n END IF;\n\n PERFORM set_config('app.booking_origin', 'google', true);\n\n UPDATE appointments b\n SET metadata = COALESCE(b.metadata, '{}'::jsonb)\n || jsonb_build_object('googleCalendarEventId', p_event_id,\n 'gcalEtag', p_etag,\n 'gcalSyncedAt', now())\n || CASE WHEN p_calendar_id IS NULL THEN '{}'::jsonb\n ELSE jsonb_build_object('gcalCalendarId', p_calendar_id) END,\n updated_at = now()\n WHERE b.id = p_booking_id AND b.tenant_id = p_tenant_id\n RETURNING b.id INTO v_id;\n RETURN v_id;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.gcal_unlink_channel(\n p_channel_id uuid\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_id uuid;\nBEGIN\n UPDATE plg_calendar_channels c\n SET sync_token = NULL,\n channel_id = NULL,\n resource_id = NULL,\n channel_expires_at = NULL,\n updated_at = now()\n WHERE c.id = p_channel_id\n RETURNING c.id INTO v_id;\n RETURN v_id;\nEND $$;\n\n-- Re-assert the service_role-only lock (idempotent; matches 002 §4).\nDO $$\nDECLARE fn text;\nBEGIN\n FOR fn IN SELECT unnest(ARRAY[\n 'public.gcal_import_event(uuid, uuid, text, text, text, timestamptz, timestamptz, boolean, text)',\n 'public.gcal_apply_event_patch(uuid, text, text, timestamptz, timestamptz, text, boolean)',\n 'public.gcal_stamp_outbound(uuid, uuid, text, text, text)',\n 'public.gcal_unlink_channel(uuid)'\n ])\n LOOP\n EXECUTE format('REVOKE ALL ON FUNCTION %s FROM public, anon, authenticated', fn);\n EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO service_role', fn);\n END LOOP;\nEND $$;\n`\n\nexport const MIGRATION_004_DROP_OAUTH_TOKENS = `-- ============================================================================\n-- Google Calendar 004: the credential leaves the tenant database, and the\n-- outbound trigger stops being able to break a booking write.\n--\n-- §1 credential drop oauth_refresh_token + oauth_access_token\n-- §2 outbound anti-loop, safe no-op, delete context, correlation id\n-- §3 realtime publish public.appointments so the calendar repaints\n--\n-- Additive and idempotent: no table is created, no policy is rewritten, and the\n-- tenant RLS from 001 already covers everything touched here.\n-- ============================================================================\n\n-- §1 ── credential ───────────────────────────────────────────────────────────\n-- THE EXPOSURE THIS CLOSES: 001 stored \\`oauth_refresh_token text\\` and\n-- \\`oauth_access_token text\\` on public.plg_calendar_integrations. That table is\n-- read from the browser with the publishable key under tenant RLS — and the\n-- connector read it with \\`select('*')\\` — so a Google refresh token was readable\n-- by ANY authenticated member of the tenant, reception included. A refresh token\n-- is not a session: it is durable access to the owner's entire calendar, mail-\n-- adjacent metadata and every calendar shared with them. And a pool is one\n-- Supabase project serving N tenants, so anything running there with\n-- service_role read every clinic's Google grant at once.\n--\n-- This is the third connector to make the same move, and the worst of the three.\n-- RankLayer had nothing to replace its key with (it pushes IN and authenticates\n-- against the platform); PlugBank's credential is meant to move to the platform\n-- (FAY-1360 — as of 2026-08-12 its api_token is still a plaintext pool column).\n-- Google Calendar is PlugBank's case: the grant still has to exist, it just must\n-- not exist HERE. The destination is the platform's ConnectorConnection store\n-- (encrypted; exists, unused), with the sync function redeeming per call — that\n-- is FAY-1359, and it has NOT happened.\n--\n-- ⚠ REPO AHEAD OF POOL (verified 2026-08-12, FAY-1379): this file has NOT been\n-- applied to the live salon pool. plg_calendar_integrations there still carries\n-- both token columns with a real clinic's grant, and the DEPLOYED\n-- google-calendar-sync (v16) still reads and writes them. Applying this drop\n-- before FAY-1359's ordered rollout (function reads both homes → data migrated\n-- → function reads only the new home → drop) severs the clinic's sync. Do not\n-- \\`db apply\\` this to a pool outside that sequence.\n--\n-- \\`token_expires_at\\` deliberately stays. It is a timestamp, not a credential,\n-- and it is the only non-secret signal that a grant exists — which is what the\n-- browser needs in order to draw a connected/disconnected badge without ever\n-- being handed the thing it is reporting on. See ../credentials.ts.\n--\n-- ROTATE any token a pool already stored. Nothing is live on this connector yet,\n-- but DROP COLUMN is a catalog change: the old values stay in the heap until the\n-- next table rewrite, so a grant that ever reached a pool must be revoked at\n-- Google rather than assumed gone.\n\nDO $$\nBEGIN\n IF to_regclass('public.plg_calendar_integrations') IS NOT NULL THEN\n ALTER TABLE public.plg_calendar_integrations DROP COLUMN IF EXISTS oauth_refresh_token;\n ALTER TABLE public.plg_calendar_integrations DROP COLUMN IF EXISTS oauth_access_token;\n END IF;\n -- Pools converted before 003 renamed the tables carry the legacy name.\n IF to_regclass('public.calendar_integrations') IS NOT NULL THEN\n ALTER TABLE public.calendar_integrations DROP COLUMN IF EXISTS oauth_refresh_token;\n ALTER TABLE public.calendar_integrations DROP COLUMN IF EXISTS oauth_access_token;\n END IF;\nEND $$;\n\n-- §2 ── outbound trigger ─────────────────────────────────────────────────────\n-- Three defects in 001's fn_gcal_push_booking, in order of how badly they hurt:\n--\n-- 1. NO ANTI-LOOP. An inbound Google event is written to public.appointments by\n-- the sync function, which fires this trigger, which pushes the same change\n-- back to Google, which changes the event, which the next pull reads as new.\n-- The symptom a customer reports is an appointment that will not stop moving.\n-- The sync function sets \\`app.booking_origin = 'google'\\` for the duration of\n-- its transaction; a write carrying that marker is never echoed back.\n--\n-- 2. A MISSING PREREQUISITE COULD BREAK THE BOOKING. 001 returned early on an\n-- empty URL but not on an empty key, so a half-configured pool sent an\n-- unauthenticated pg_net request; and any error raised in here aborts the\n-- INSERT that fired it. An integration that is not set up must degrade to\n-- \"Google is not updated\", never to \"the appointment could not be saved\".\n-- Every exit path below returns the row.\n--\n-- 3. A DELETE ARRIVED WITH NOTHING TO DELETE. AFTER DELETE can still read OLD,\n-- but pg_net delivers asynchronously — by the time the function runs, the row\n-- is gone and it cannot look up which Google event to remove. The linked ids\n-- now travel in the payload.\n--\n-- The early returns are not enough on their own: on a pool where the settings\n-- are present but pg_net is not installed, the PERFORM itself raises \\`schema\n-- \"net\" does not exist\\` and takes the INSERT down with it. So the delivery is\n-- wrapped too. Swallowing a delivery error is safe here because pg_net only\n-- ENQUEUES — anything it could tell us is already visible as \"nothing has\n-- synced\" in plg_calendar_sync_log and in the connector's derived health.\n--\n-- The Supabase service-role key still reaches this trigger through the\n-- \\`app.gcal_service_key\\` database setting that 001 introduced. That is a lesser\n-- exposure than the one closed in §1 (a GUC is not reachable through PostgREST,\n-- so no browser can read it) but it is still a pool-wide credential in the\n-- database, and it is NOT fixed here. FAY-1372 shipped the RLS half (a\n-- tenant-scoped claim narrows user_tenant_ids); nothing mints such a token for\n-- this trigger yet, and the function still runs on service_role (FAY-1378).\n-- Left as a named debt rather than moved to a third hiding place.\n\nCREATE OR REPLACE FUNCTION public.fn_gcal_push_booking() RETURNS trigger\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public, extensions, net\nAS $$\nDECLARE\n url text := current_setting('app.gcal_sync_url', true);\n key text := current_setting('app.gcal_service_key', true);\n rec record := COALESCE(NEW, OLD);\n op text := lower(TG_OP);\n corr text := NULLIF(current_setting('app.booking_correlation_id', true), '');\nBEGIN\n -- (1) Inbound Google writes mark themselves. Never echo them back.\n IF current_setting('app.booking_origin', true) = 'google' THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n -- (2) Not configured is not an error. Diagnostics report the connector as\n -- incomplete; the appointment is saved either way.\n IF NULLIF(url, '') IS NULL OR NULLIF(key, '') IS NULL THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n BEGIN\n PERFORM net.http_post(\n url := url,\n headers := jsonb_build_object(\n 'Content-Type', 'application/json',\n 'Authorization', 'Bearer ' || key\n ),\n body := jsonb_build_object(\n 'action', 'push_event',\n 'op', op,\n 'bookingId', rec.id,\n 'tenantId', rec.tenant_id,\n -- (3) Carried so a delete can still be honoured after the row is gone.\n 'googleEventId', rec.metadata->>'googleCalendarEventId',\n 'calendarId', rec.metadata->>'gcalCalendarId',\n 'correlationId', COALESCE(corr, gen_random_uuid()::text)\n )\n );\n EXCEPTION WHEN OTHERS THEN\n -- Missing pg_net, a bad URL, a full queue: the appointment is still saved.\n RAISE WARNING 'gcal push skipped for booking %: %', rec.id, SQLERRM;\n END;\n\n RETURN COALESCE(NEW, OLD);\nEND $$;\n\n-- §3 ── realtime ─────────────────────────────────────────────────────────────\n-- The calendar screen subscribes to public.appointments so a booking written by\n-- the sync function repaints the grid the manager is looking at, instead of\n-- waiting for them to reload the tab. Additive and guarded: a pool without the\n-- supabase_realtime publication is left alone, and re-running adds nothing.\nDO $$\nBEGIN\n IF EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime')\n AND NOT EXISTS (\n SELECT 1 FROM pg_publication_tables\n WHERE pubname = 'supabase_realtime' AND schemaname = 'public' AND tablename = 'appointments'\n )\n THEN\n ALTER PUBLICATION supabase_realtime ADD TABLE public.appointments;\n END IF;\nEND $$;\n`\n\nexport const MIGRATION_005_OUTBOUND_VAULT_DELIVERY = `-- ============================================================================\n-- Google Calendar 005: the outbound credential moves to Vault, and stops being\n-- the service-role key. The Authorization header stays.\n--\n-- §1 trigger fn_gcal_push_booking reads Vault, falls back to the old GUCs\n-- §2 cleanup clear app.gcal_service_key ONLY where Vault already covers it\n--\n-- Additive and idempotent: a CREATE OR REPLACE plus a guarded, conditional\n-- catalog cleanup.\n--\n-- WRITTEN AGAINST THE DEPLOYED POOL, NOT AGAINST THIS FOLDER. The repo and\n-- cluster-salon-br-01 (gphxclpkbtbucoqclbco) had drifted: \\`004\\` here still reads\n-- \\`app.gcal_service_key\\`, while the pool has been on Vault since 2026-07-28 and\n-- the deployed function is four features ahead of \\`functions/\\`. Everything below\n-- was checked against the live database and the live function source, because\n-- the previous attempt at this file was derived from the repo alone and would\n-- have broken a real clinic. See FAY-1379 for the drift itself.\n-- ============================================================================\n\n-- §1 ── the credential ───────────────────────────────────────────────────────\n-- THE EXPOSURE THIS CLOSES, precisely: \\`001\\` told operators to run\n-- ALTER DATABASE postgres SET app.gcal_service_key = '<service-role-key>';\n-- and every version of this trigger in the repo since (\\`001\\`, \\`002 §2\\`,\n-- \\`004 §2\\`) reads it back with current_setting(). A pool is ONE Supabase project\n-- serving N tenants and service_role bypasses RLS by definition, so that setting\n-- is unrestricted read/write over every tenant in the cluster, in plain text in\n-- pg_db_role_setting and in every pg_dump taken since.\n--\n-- It is closed by making the credential BOTH narrow and encrypted, not by\n-- removing it: the header is the only thing authorising the push. The deployed\n-- function checks it (\\`isServiceRequest\\` compares the bearer against\n-- GCAL_OUTBOUND_SECRET, then against the service-role key) and \\`push_event\\` is a\n-- service action with no user path, so a request with no Authorization header is\n-- rejected with \\`400 Unknown action: push_event\\`. Because pg_net is\n-- fire-and-forget that rejection is INVISIBLE — the clinic would simply stop\n-- appearing in Google Calendar. Removing the header is therefore not a security\n-- improvement, it is a silent outage. It was tried and reverted.\n--\n-- So: \\`gcal_outbound_secret\\` in Vault. Encrypted at rest, outside pg_dump's\n-- plaintext, readable only by a definer function like this one, and — the part\n-- that matters — it authorises exactly one thing, calling this connector's edge\n-- function. Losing it does not hand anyone another tenant's data. This is the\n-- shape the pool has been running since 2026-07-28; \\`005\\` is the repo catching\n-- up, so a pool provisioned fresh from this folder is born with it instead of\n-- being told to paste a service-role key into a database setting.\n--\n-- THE FALLBACK IS DELIBERATE. A pool that followed \\`001\\` and has no Vault secret\n-- keeps working off the old GUCs, loudly. The alternative — read Vault only —\n-- silently disarms the push on exactly the pools that did what the docs told\n-- them to, which is the failure this file exists to avoid.\n--\n-- WHAT THIS DOES NOT FIX: the edge function still builds its Supabase client\n-- with SUPABASE_SERVICE_ROLE_KEY, so the FUNCTION still reads every tenant in\n-- the pool. That is not reachable from SQL and does not close here: it closes\n-- when the platform mints a short-lived tenant-scoped token (FAY-1353) that\n-- packages/db/migrations/028_tenant_scoped_token.sql already teaches every\n-- policy to honour through user_tenant_ids(). See docs/platform/DECISIONS.md,\n-- 2026-08-11 — \"a connector's privilege comes from its token\".\n--\n-- ROTATE the service-role key of any pool that ever ran \\`001\\`'s setup line: it\n-- was plain text at rest and in every backup taken since, so §2 clearing it is\n-- not the same as it never having been there.\n\nCREATE OR REPLACE FUNCTION public.fn_gcal_push_booking() RETURNS trigger\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public, extensions, net, vault\nAS $$\nDECLARE\n url text;\n key text;\n legacy boolean := false;\n rec record := COALESCE(NEW, OLD);\n op text := lower(TG_OP);\n corr text := NULLIF(current_setting('app.booking_correlation_id', true), '');\nBEGIN\n -- Unchanged from 004: inbound Google writes mark themselves, and a write\n -- carrying that marker is never echoed back.\n IF current_setting('app.booking_origin', true) = 'google' THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n -- Vault first. Wrapped because a pool without the vault extension must\n -- degrade to the fallback, not abort the booking write.\n BEGIN\n SELECT decrypted_secret INTO url\n FROM vault.decrypted_secrets WHERE name = 'gcal_sync_url'\n ORDER BY created_at DESC LIMIT 1;\n SELECT decrypted_secret INTO key\n FROM vault.decrypted_secrets WHERE name = 'gcal_outbound_secret'\n ORDER BY created_at DESC LIMIT 1;\n EXCEPTION WHEN OTHERS THEN\n url := NULL;\n key := NULL;\n END;\n\n -- Legacy pools provisioned per 001's header keep working, and say so.\n IF NULLIF(url, '') IS NULL OR NULLIF(key, '') IS NULL THEN\n url := COALESCE(NULLIF(url, ''), current_setting('app.gcal_sync_url', true));\n key := COALESCE(NULLIF(key, ''), current_setting('app.gcal_service_key', true));\n legacy := NULLIF(key, '') IS NOT NULL;\n END IF;\n\n -- Not configured is not an error: an unconfigured pool degrades to \"Google is\n -- not updated\", never to \"the appointment could not be saved\".\n IF NULLIF(url, '') IS NULL OR NULLIF(key, '') IS NULL THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n IF legacy THEN\n RAISE WARNING 'gcal outbound is still using app.gcal_service_key; move it to the vault secret gcal_outbound_secret and rotate the service-role key';\n END IF;\n\n BEGIN\n PERFORM net.http_post(\n url := url,\n headers := jsonb_build_object(\n 'Content-Type', 'application/json',\n -- REQUIRED. The deployed function authorises push_event on this header\n -- alone; without it every push 400s, silently, forever.\n 'Authorization', 'Bearer ' || key\n ),\n body := jsonb_build_object(\n 'action', 'push_event',\n 'op', op,\n 'bookingId', rec.id,\n 'tenantId', rec.tenant_id,\n -- Carried so a delete can still be honoured after the row is gone.\n 'googleEventId', rec.metadata->>'googleCalendarEventId',\n 'calendarId', rec.metadata->>'gcalCalendarId',\n 'correlationId', COALESCE(corr, gen_random_uuid()::text)\n )\n );\n EXCEPTION WHEN OTHERS THEN\n -- Missing pg_net, a bad URL, a full queue: the appointment is still saved.\n -- The deployed trigger lacks this wrapper; 004 added it here after a pool\n -- with the settings present but the extension missing took an INSERT down.\n RAISE WARNING 'gcal push skipped for booking %: %', rec.id, SQLERRM;\n END;\n\n RETURN COALESCE(NEW, OLD);\nEND $$;\n\n-- §2 ── cleanup ──────────────────────────────────────────────────────────────\n-- Redefining the function stops the key being PREFERRED; it does not stop it\n-- being STORED. Settings live in pg_db_role_setting per (database, role), so the\n-- sweep is driven off the catalog rather than off the one ALTER DATABASE form\n-- \\`001\\` happened to show.\n--\n-- CONDITIONAL ON PURPOSE: the setting is cleared only where Vault already\n-- supplies \\`gcal_outbound_secret\\`, i.e. only where §1 provably never needs the\n-- fallback. Anywhere else it is left in place and reported, because clearing it\n-- there would disarm the push with no error anyone can see. On the live pool\n-- this loop finds nothing — the setting is not present on any role or database —\n-- and that is the expected result, not a failure.\nDO $$\nDECLARE\n r record;\n has_vault boolean := false;\nBEGIN\n BEGIN\n SELECT EXISTS (\n SELECT 1 FROM vault.decrypted_secrets\n WHERE name = 'gcal_outbound_secret' AND NULLIF(decrypted_secret, '') IS NOT NULL\n ) INTO has_vault;\n EXCEPTION WHEN OTHERS THEN\n has_vault := false;\n END;\n\n FOR r IN\n SELECT d.datname, a.rolname\n FROM pg_db_role_setting s\n LEFT JOIN pg_database d ON d.oid = s.setdatabase\n LEFT JOIN pg_roles a ON a.oid = s.setrole\n WHERE EXISTS (\n SELECT 1 FROM unnest(s.setconfig) AS c WHERE c LIKE 'app.gcal_service_key=%'\n )\n LOOP\n IF NOT has_vault THEN\n RAISE WARNING 'app.gcal_service_key is still set (database %, role %) and is the ONLY outbound credential — create the vault secret gcal_outbound_secret first, then re-run this migration',\n r.datname, r.rolname;\n CONTINUE;\n END IF;\n BEGIN\n IF r.rolname IS NULL THEN\n EXECUTE format('ALTER DATABASE %I RESET app.gcal_service_key', r.datname);\n ELSIF r.datname IS NULL THEN\n EXECUTE format('ALTER ROLE %I RESET app.gcal_service_key', r.rolname);\n ELSE\n EXECUTE format('ALTER ROLE %I IN DATABASE %I RESET app.gcal_service_key', r.rolname, r.datname);\n END IF;\n EXCEPTION WHEN OTHERS THEN\n RAISE WARNING 'could not clear app.gcal_service_key (database %, role %): % — clear it by hand, and rotate the key either way',\n r.datname, r.rolname, SQLERRM;\n END;\n END LOOP;\nEND $$;\n`\n\nexport const MIGRATION_006_WEBHOOK_DELIVERIES_OUTBOX = `-- ---------------------------------------------------------------------------\n-- Google Calendar WEBHOOK INTAKE — delivery ledger + automation outbox\n-- ---------------------------------------------------------------------------\n-- RECONSTRUCTED FROM THE LIVE SCHEMA on 2026-08-12 (FAY-1379). These objects\n-- existed in pool gphxclpkbtbucoqclbco and in NO migration in any repo: they\n-- were applied by hand alongside the google-calendar-webhook deployment. A pool\n-- provisioned from this repo could not run that function — the SELECT of\n-- plg_calendar_channels.webhook_token_hash failed before any gate ran, and both\n-- INSERT targets were missing. This file closes that hole.\n--\n-- Written to be applied to a pool that ALREADY has them: every statement is\n-- IF NOT EXISTS / DROP-then-CREATE, and re-running it must be a no-op.\n--\n-- §1 plg_calendar_channels — the three webhook columns\n-- §2 plg_calendar_webhook_deliveries — one row per Google notification\n-- §3 plg_calendar_automation_outbox — domain events for the automations lane\n--\n-- Read by: functions/google-calendar-webhook/index.ts (§1 gate, §2 idempotency,\n-- §3 emit) and functions/google-calendar-sync/index.ts (§1 watch bookkeeping,\n-- §3 emit on inbound import/patch).\n-- ---------------------------------------------------------------------------\n\n-- ===========================================================================\n-- §1 — Watch-channel authentication state on plg_calendar_channels.\n-- Added by ALTER in the pool (they sit after created_at/updated_at), so they\n-- are added the same way here rather than folded into 002's CREATE TABLE —\n-- 002 has already run everywhere and its checksum must not move.\n--\n-- webhook_token_hash: SHA-256 of the token handed to Google at watch_start. The\n-- token itself is never stored, so a dump of this table does not let anyone\n-- forge a notification. The webhook re-hashes what arrives and compares in\n-- constant time.\n-- last_webhook_message_number: high-water mark of Google's monotonic per-channel\n-- counter — the replay guard. bigint because it outgrows int4.\n-- ===========================================================================\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS webhook_token_hash text;\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS last_webhook_message_number bigint;\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS last_webhook_at timestamptz;\n\n-- ===========================================================================\n-- §2 — plg_calendar_webhook_deliveries: one row per accepted notification.\n--\n-- The row IS the idempotency mechanism, not a log of one: the webhook inserts\n-- before doing any work and reads 23505 as \"already handled\", returning 204.\n-- Hence two unique keys, both present in the pool and both reproduced —\n-- (channel_ref, message_number) is the constraint the FK cascade protects, and\n-- (google_channel_id, message_number) catches a replay arriving after the\n-- channel row was recreated with the same Google channel id.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_webhook_deliveries (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL,\n channel_ref uuid NOT NULL REFERENCES public.plg_calendar_channels(id) ON DELETE CASCADE,\n google_channel_id text NOT NULL,\n resource_id text,\n message_number bigint NOT NULL,\n resource_state text,\n status text NOT NULL DEFAULT 'pending'\n CHECK (status IN ('pending','processing','processed','failed','ignored')),\n error text,\n received_at timestamptz NOT NULL DEFAULT now(),\n processed_at timestamptz,\n created_at timestamptz DEFAULT now(),\n UNIQUE (channel_ref, message_number)\n);\n\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_calendar_webhook_delivery_message\n ON public.plg_calendar_webhook_deliveries (google_channel_id, message_number);\n\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_webhook_deliveries_tenant_created\n ON public.plg_calendar_webhook_deliveries (tenant_id, created_at DESC);\n\n-- Two partial indexes over the same predicate on different sort columns. Both\n-- are in the pool (evidence of two overlapping hand-applied scripts) and both\n-- are reproduced so this file matches the live schema exactly; consolidating\n-- them is a separate change with its own reasoning.\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_webhook_pending\n ON public.plg_calendar_webhook_deliveries (status, received_at)\n WHERE status IN ('pending','failed');\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_webhook_deliveries_pending\n ON public.plg_calendar_webhook_deliveries (status, created_at)\n WHERE status IN ('pending','failed');\n\nALTER TABLE public.plg_calendar_webhook_deliveries ENABLE ROW LEVEL SECURITY;\n\n-- Read-only for the app. Every write comes from the webhook function running as\n-- service_role, which bypasses RLS — there is no authenticated INSERT/UPDATE\n-- grant, so a browser cannot forge or retire a delivery.\nGRANT SELECT ON public.plg_calendar_webhook_deliveries TO authenticated;\nGRANT ALL ON public.plg_calendar_webhook_deliveries TO service_role;\n\nDROP POLICY IF EXISTS plg_calendar_webhook_deliveries_read ON public.plg_calendar_webhook_deliveries;\nCREATE POLICY plg_calendar_webhook_deliveries_read ON public.plg_calendar_webhook_deliveries\n FOR SELECT TO authenticated\n USING (tenant_id IN (SELECT public.user_tenant_ids()));\n\n-- ===========================================================================\n-- §3 — plg_calendar_automation_outbox: calendar facts, for the automations lane.\n--\n-- Transactional outbox: the sync/webhook functions record WHAT happened and\n-- return; a consumer drains it. idempotency_key is unique per tenant so a\n-- replayed Google delivery or a re-run pull upserts onto the same row instead\n-- of firing an automation twice — that key is what the functions pass as\n-- onConflict, so it is load-bearing and not merely a hygiene constraint.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_automation_outbox (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL,\n source text NOT NULL DEFAULT 'google_calendar',\n event_type text NOT NULL,\n aggregate_type text NOT NULL,\n aggregate_id text,\n idempotency_key text NOT NULL,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n status text NOT NULL DEFAULT 'pending'\n CHECK (status IN ('pending','processing','processed','failed','ignored')),\n attempts integer NOT NULL DEFAULT 0,\n last_error text,\n occurred_at timestamptz NOT NULL DEFAULT now(),\n -- available_at is the retry clock: a failed row is re-eligible once it passes.\n available_at timestamptz NOT NULL DEFAULT now(),\n processed_at timestamptz,\n error text,\n created_at timestamptz DEFAULT now(),\n UNIQUE (tenant_id, idempotency_key)\n);\n\n-- Redundant with the UNIQUE constraint's own index, and present in the pool for\n-- the same overlapping-scripts reason as §2. Reproduced, not tidied.\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_calendar_automation_outbox_idempotency\n ON public.plg_calendar_automation_outbox (tenant_id, idempotency_key);\n\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_automation_pending\n ON public.plg_calendar_automation_outbox (status, available_at)\n WHERE status IN ('pending','failed');\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_automation_outbox_pending\n ON public.plg_calendar_automation_outbox (status, available_at, created_at)\n WHERE status IN ('pending','failed');\n\nALTER TABLE public.plg_calendar_automation_outbox ENABLE ROW LEVEL SECURITY;\n\nGRANT SELECT ON public.plg_calendar_automation_outbox TO authenticated;\nGRANT ALL ON public.plg_calendar_automation_outbox TO service_role;\n\nDROP POLICY IF EXISTS plg_calendar_automation_outbox_read ON public.plg_calendar_automation_outbox;\nCREATE POLICY plg_calendar_automation_outbox_read ON public.plg_calendar_automation_outbox\n FOR SELECT TO authenticated\n USING (tenant_id IN (SELECT public.user_tenant_ids()));\n`\n\nexport const MIGRATION_007_CREDENTIAL_FREE_INSTALL = `-- ---------------------------------------------------------------------------\n-- Google Calendar — a credential-free install, from zero\n-- ---------------------------------------------------------------------------\n-- FAY-1359/1360. On 2026-08-12 the five plg_calendar_* tables were DROPPED from\n-- the beauty pool (gphxclpkbtbucoqclbco) together with both edge functions,\n-- because plg_calendar_integrations held the tenant's Google refresh token in an\n-- open column. A pool is one database for N clinics, so that column was one\n-- backup, one dump or one service_role key away from being every clinic's\n-- calendar.\n--\n-- This file is what a pool runs to have the connector back. It is deliberately\n-- SELF-CONTAINED rather than \"001 through 006 again\":\n--\n-- * 001 CREATEs the credential columns and 004 drops them. A pool restored by\n-- replaying the chain therefore holds a refresh-token column for the length\n-- of that replay, and holds it forever if the replay stops early — which is\n-- exactly what a half-applied ledger does. There is no ordering of those\n-- files in which the column never exists; there is this file, in which it\n-- never exists.\n-- * The beauty pool's ledger and its schema had already parted company (it\n-- recorded shop/0006b while tables up to 0043 were applied by hand). A\n-- recovery that depends on the ledger being right is not a recovery.\n--\n-- Re-runnable, and a near no-op on a pool that ran 001–006: every statement is\n-- IF NOT EXISTS / DROP-then-CREATE, and §5 drops the credential columns if it\n-- finds them rather than assuming 004 ran.\n--\n-- §1 plg_calendar_integrations — per-tenant sync state. NO credential.\n-- §2 plg_calendar_channels — the de-para, incl. the webhook columns\n-- §3 plg_calendar_sync_log — run history\n-- §4 plg_calendar_webhook_deliveries + plg_calendar_automation_outbox\n-- §5 the gate: this schema must not be able to hold a Google grant\n--\n-- WHAT OWNS WHAT, after this file (FAY-1388):\n-- the PLATFORM owns the credential — which Google account, authorized by\n-- whom, and the refresh token, in the vault, reachable only by redemption;\n-- plg_connections owns \"is this connector on for this tenant\", written by the\n-- app when consent comes back;\n-- these tables own the SYNC STATE — which calendars map to what, how far the\n-- cursor got, what Google last told us. Nothing here is a secret, and\n-- nothing here can be traded for access to anyone's calendar.\n-- ---------------------------------------------------------------------------\n\n-- ===========================================================================\n-- §1 — plg_calendar_integrations: one row per tenant, sync state only.\n--\n-- Same shape as 001 MINUS oauth_refresh_token, oauth_access_token and\n-- token_expires_at. There is no column here to put a token in, which is the\n-- property this migration exists to establish — see §5, which enforces it.\n--\n-- No FK to plg_connections on purpose. That table is the connector framework's\n-- and this one is the calendar's; a FK would make the connector's row a\n-- prerequisite for reading a cursor, and the two planes are meant to be able to\n-- fail independently.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_integrations (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n provider text NOT NULL DEFAULT 'google',\n calendar_id text NOT NULL DEFAULT 'primary',\n -- Incremental pull cursor + legacy single-calendar watch bookkeeping.\n sync_token text,\n channel_id text,\n channel_resource_id text,\n channel_expires_at timestamptz,\n active boolean NOT NULL DEFAULT true,\n last_sync_at timestamptz,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (tenant_id, provider)\n);\nALTER TABLE public.plg_calendar_integrations ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_integrations_tenant\n ON public.plg_calendar_integrations(tenant_id);\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_calendar_integrations TO authenticated;\nGRANT ALL ON public.plg_calendar_integrations TO service_role;\n\n-- ===========================================================================\n-- §2 — plg_calendar_channels: the de-para, with 006's webhook columns folded in.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_channels (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n integration_id uuid NOT NULL REFERENCES public.plg_calendar_integrations(id) ON DELETE CASCADE,\n tenant_id uuid NOT NULL,\n google_calendar_id text NOT NULL,\n summary text,\n color text,\n direction text NOT NULL DEFAULT 'bidirectional'\n CHECK (direction IN ('inbound','outbound','bidirectional','off')),\n target_kind text CHECK (target_kind IN ('assignee','service','location')),\n target_id uuid,\n import_mode text NOT NULL DEFAULT 'block'\n CHECK (import_mode IN ('block','appointment')),\n sync_token text,\n channel_id text,\n resource_id text,\n channel_expires_at timestamptz,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n UNIQUE (integration_id, google_calendar_id)\n);\n\n-- The webhook's authentication state. \\`webhook_token_hash\\` is a SHA-256 of the\n-- token handed to Google — the token itself is never stored, so reading this\n-- table does not let anyone forge a notification. Added by ALTER as well as in\n-- the CREATE above, for the pool that already has the table from 002.\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS webhook_token_hash text;\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS last_webhook_message_number bigint;\nALTER TABLE public.plg_calendar_channels\n ADD COLUMN IF NOT EXISTS last_webhook_at timestamptz;\n\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_channels_tenant\n ON public.plg_calendar_channels(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_channels_integration\n ON public.plg_calendar_channels(integration_id);\n\nALTER TABLE public.plg_calendar_channels ENABLE ROW LEVEL SECURITY;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_calendar_channels TO authenticated;\nGRANT ALL ON public.plg_calendar_channels TO service_role;\n\nDROP TRIGGER IF EXISTS plg_calendar_channels_updated_at ON public.plg_calendar_channels;\nCREATE TRIGGER plg_calendar_channels_updated_at BEFORE UPDATE ON public.plg_calendar_channels\n FOR EACH ROW EXECUTE FUNCTION public.handle_updated_at();\n\n-- ===========================================================================\n-- §3 — plg_calendar_sync_log: what already happened, per run.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_sync_log (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n direction text NOT NULL, -- inbound | outbound\n trigger text, -- on-write | scheduled | webhook | manual\n status text NOT NULL DEFAULT 'success', -- success | partial | error\n fetched integer NOT NULL DEFAULT 0,\n written integer NOT NULL DEFAULT 0,\n error text,\n correlation_id uuid,\n channel_id_ref uuid,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_calendar_sync_log ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_calendar_sync_log ADD COLUMN IF NOT EXISTS correlation_id uuid;\nALTER TABLE public.plg_calendar_sync_log ADD COLUMN IF NOT EXISTS channel_id_ref uuid;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_calendar_sync_log TO authenticated;\nGRANT ALL ON public.plg_calendar_sync_log TO service_role;\n\n-- RLS: tenant isolation for the three tables the app reads and writes.\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_calendar_integrations',\n 'plg_calendar_channels',\n 'plg_calendar_sync_log'\n ])\n LOOP\n IF NOT EXISTS (\n SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_rls'\n ) THEN\n EXECUTE format(\n 'CREATE POLICY %I ON public.%I FOR ALL TO authenticated '\n 'USING (tenant_id IN (SELECT public.user_tenant_ids())) '\n 'WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))',\n t||'_rls', t);\n END IF;\n IF NOT EXISTS (\n SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_service'\n ) THEN\n EXECUTE format(\n 'CREATE POLICY %I ON public.%I FOR ALL TO service_role USING (true) WITH CHECK (true)',\n t||'_service', t);\n END IF;\n END LOOP;\nEND $$;\n\n-- ===========================================================================\n-- §4 — Webhook intake: the delivery ledger and the automation outbox.\n--\n-- The delivery row IS the idempotency mechanism: the webhook inserts before\n-- doing any work and reads a 23505 as \"already handled\". Google retries hard,\n-- so this is what stops one notification becoming two appointments.\n-- ===========================================================================\nCREATE TABLE IF NOT EXISTS public.plg_calendar_webhook_deliveries (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL,\n channel_ref uuid NOT NULL REFERENCES public.plg_calendar_channels(id) ON DELETE CASCADE,\n google_channel_id text NOT NULL,\n resource_id text,\n message_number bigint NOT NULL,\n resource_state text,\n status text NOT NULL DEFAULT 'pending'\n CHECK (status IN ('pending','processing','processed','failed','ignored')),\n error text,\n received_at timestamptz NOT NULL DEFAULT now(),\n processed_at timestamptz,\n created_at timestamptz DEFAULT now(),\n UNIQUE (channel_ref, message_number)\n);\n\n-- Catches a replay that arrives after the channel row was recreated with the\n-- same Google channel id — the FK-scoped constraint above cannot see that.\nCREATE UNIQUE INDEX IF NOT EXISTS uq_plg_calendar_webhook_delivery_message\n ON public.plg_calendar_webhook_deliveries (google_channel_id, message_number);\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_webhook_deliveries_tenant_created\n ON public.plg_calendar_webhook_deliveries (tenant_id, created_at DESC);\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_webhook_deliveries_pending\n ON public.plg_calendar_webhook_deliveries (status, created_at)\n WHERE status IN ('pending','failed');\n\nALTER TABLE public.plg_calendar_webhook_deliveries ENABLE ROW LEVEL SECURITY;\n-- Read-only for the app: every write comes from the webhook function as\n-- service_role, so a browser cannot forge or retire a delivery.\nGRANT SELECT ON public.plg_calendar_webhook_deliveries TO authenticated;\nGRANT ALL ON public.plg_calendar_webhook_deliveries TO service_role;\n\nDROP POLICY IF EXISTS plg_calendar_webhook_deliveries_read ON public.plg_calendar_webhook_deliveries;\nCREATE POLICY plg_calendar_webhook_deliveries_read ON public.plg_calendar_webhook_deliveries\n FOR SELECT TO authenticated\n USING (tenant_id IN (SELECT public.user_tenant_ids()));\n\nCREATE TABLE IF NOT EXISTS public.plg_calendar_automation_outbox (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL,\n source text NOT NULL DEFAULT 'google_calendar',\n event_type text NOT NULL,\n aggregate_type text NOT NULL,\n aggregate_id text,\n idempotency_key text NOT NULL,\n payload jsonb NOT NULL DEFAULT '{}'::jsonb,\n status text NOT NULL DEFAULT 'pending'\n CHECK (status IN ('pending','processing','processed','failed','ignored')),\n attempts integer NOT NULL DEFAULT 0,\n last_error text,\n occurred_at timestamptz NOT NULL DEFAULT now(),\n -- available_at is the retry clock: a failed row is re-eligible once it passes.\n available_at timestamptz NOT NULL DEFAULT now(),\n processed_at timestamptz,\n error text,\n created_at timestamptz DEFAULT now(),\n UNIQUE (tenant_id, idempotency_key)\n);\n\nCREATE INDEX IF NOT EXISTS idx_plg_calendar_automation_outbox_pending\n ON public.plg_calendar_automation_outbox (status, available_at, created_at)\n WHERE status IN ('pending','failed');\n\nALTER TABLE public.plg_calendar_automation_outbox ENABLE ROW LEVEL SECURITY;\nGRANT SELECT ON public.plg_calendar_automation_outbox TO authenticated;\nGRANT ALL ON public.plg_calendar_automation_outbox TO service_role;\n\nDROP POLICY IF EXISTS plg_calendar_automation_outbox_read ON public.plg_calendar_automation_outbox;\nCREATE POLICY plg_calendar_automation_outbox_read ON public.plg_calendar_automation_outbox\n FOR SELECT TO authenticated\n USING (tenant_id IN (SELECT public.user_tenant_ids()));\n\n-- ===========================================================================\n-- §5 — The gate.\n--\n-- Everything above is a CREATE, and a CREATE says nothing about a pool that\n-- already has the old shape. This block is the part that actually removes the\n-- hole: it drops the three credential columns wherever it finds them — the\n-- pool 004 never reached, the pool restored from an old backup, the pool\n-- someone re-provisioned from 001 — and then refuses to finish if any survived.\n--\n-- The RAISE matters more than the DROP. A migration that silently tolerated a\n-- token column is how this schema kept one for months.\n-- ===========================================================================\nDO $$\nDECLARE\n leftover text;\nBEGIN\n ALTER TABLE IF EXISTS public.plg_calendar_integrations DROP COLUMN IF EXISTS oauth_refresh_token;\n ALTER TABLE IF EXISTS public.plg_calendar_integrations DROP COLUMN IF EXISTS oauth_access_token;\n ALTER TABLE IF EXISTS public.plg_calendar_integrations DROP COLUMN IF EXISTS token_expires_at;\n\n SELECT string_agg(table_name || '.' || column_name, ', ')\n INTO leftover\n FROM information_schema.columns\n WHERE table_schema = 'public'\n AND table_name LIKE 'plg_calendar%'\n AND (\n column_name LIKE '%refresh_token%'\n OR column_name LIKE '%access_token%'\n OR column_name IN ('oauth_token', 'client_secret', 'api_key')\n );\n\n IF leftover IS NOT NULL THEN\n RAISE EXCEPTION\n 'Google Calendar schema still holds credential columns: %. The grant belongs in the platform vault (FAY-1359); redeem it at run time instead.',\n leftover;\n END IF;\nEND $$;\n\n-- Dropping the columns does not erase what was in them: Postgres leaves the old\n-- values in the heap until the next table rewrite. Any grant that ever reached a\n-- pool must be REVOKED AT GOOGLE, not assumed gone — which is also why every\n-- tenant re-consents after this file runs.\n`\n\nexport const MIGRATION_008_THE_OUTBOUND_HALF = `-- ---------------------------------------------------------------------------\n-- Google Calendar — the outbound half that 007 does not install\n-- ---------------------------------------------------------------------------\n-- 007 is the credential-free install: it creates the five plg_calendar_* tables\n-- from zero, with no column a Google grant could ever sit in. What it does NOT\n-- create is the trigger on public.appointments that pushes a booking OUT to\n-- Google, because that trigger never lived in those tables.\n--\n-- Only 001 and 002 create \\`trg_gcal_push\\`, and 001 is the file whose credential\n-- columns 007 exists to prevent. So there is no ordering of the existing files\n-- that gives a fresh pool the outbound direction without also giving it, for a\n-- while, a plaintext refresh-token column.\n--\n-- The result on a pool installed by 007 alone: Google → Fayz works, Fayz →\n-- Google is silent. Not an error, not a warning — appointments simply never\n-- reach the calendar. Discovered on cluster-squash-test after 007 came up green\n-- and the tables were correct.\n--\n-- This file is the missing half, and nothing else:\n--\n-- §1 public.fn_gcal_push_booking — verbatim the definition 005 settled on:\n-- vault first (\\`gcal_sync_url\\` + \\`gcal_outbound_secret\\`), the legacy GUC\n-- only as a fallback that WARNs, and a no-op when neither is configured.\n-- Reproduced rather than referenced because 005 cannot run here: it\n-- replaces a function 001 created, and 001 is the file we are avoiding.\n-- §2 trg_gcal_push on public.appointments — the shape 002 re-asserts.\n--\n-- A pool that already ran 001→006 gets an identical function and an identical\n-- trigger, which is why this is safe to apply anywhere: every statement is\n-- CREATE OR REPLACE / DROP-then-CREATE.\n--\n-- WITHOUT THE VAULT SECRETS THIS IS INERT ON PURPOSE. The function reads\n-- \\`gcal_sync_url\\` and \\`gcal_outbound_secret\\` from the vault and returns without\n-- pushing when they are absent, so installing the trigger before the secrets\n-- exist cannot break an INSERT into appointments — the most load-bearing table\n-- the agenda has.\n--\n-- Idempotent and replay-safe.\n-- ---------------------------------------------------------------------------\n\n-- ===========================================================================\n-- §1 — the push, as 005 defined it\n-- ===========================================================================\nCREATE OR REPLACE FUNCTION public.fn_gcal_push_booking() RETURNS trigger\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path = public, extensions, net, vault\nAS $$\nDECLARE\n url text;\n key text;\n legacy boolean := false;\n rec record := COALESCE(NEW, OLD);\n op text := lower(TG_OP);\n corr text := NULLIF(current_setting('app.booking_correlation_id', true), '');\nBEGIN\n -- Unchanged from 004: inbound Google writes mark themselves, and a write\n -- carrying that marker is never echoed back.\n IF current_setting('app.booking_origin', true) = 'google' THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n -- Vault first. Wrapped because a pool without the vault extension must\n -- degrade to the fallback, not abort the booking write.\n BEGIN\n SELECT decrypted_secret INTO url\n FROM vault.decrypted_secrets WHERE name = 'gcal_sync_url'\n ORDER BY created_at DESC LIMIT 1;\n SELECT decrypted_secret INTO key\n FROM vault.decrypted_secrets WHERE name = 'gcal_outbound_secret'\n ORDER BY created_at DESC LIMIT 1;\n EXCEPTION WHEN OTHERS THEN\n url := NULL;\n key := NULL;\n END;\n\n -- Legacy pools provisioned per 001's header keep working, and say so.\n IF NULLIF(url, '') IS NULL OR NULLIF(key, '') IS NULL THEN\n url := COALESCE(NULLIF(url, ''), current_setting('app.gcal_sync_url', true));\n key := COALESCE(NULLIF(key, ''), current_setting('app.gcal_service_key', true));\n legacy := NULLIF(key, '') IS NOT NULL;\n END IF;\n\n -- Not configured is not an error: an unconfigured pool degrades to \"Google is\n -- not updated\", never to \"the appointment could not be saved\".\n IF NULLIF(url, '') IS NULL OR NULLIF(key, '') IS NULL THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n IF legacy THEN\n RAISE WARNING 'gcal outbound is still using app.gcal_service_key; move it to the vault secret gcal_outbound_secret and rotate the service-role key';\n END IF;\n\n -- Does THIS tenant have a calendar at all?\n --\n -- Added here, not inherited from 005. The vault secrets are per POOL and the\n -- integration is per TENANT, so without this every appointment write in the\n -- pool posted to the sync function — including for tenants that never\n -- connected Google. On the cluster this was installed against that is 354.989\n -- appointments across several tenants, all of them paying for an HTTP round\n -- trip whose only possible answer is \"no integration\".\n --\n -- The function would have answered correctly; the cost is the asking. Indexed\n -- by tenant (idx_plg_calendar_integrations_tenant), so the guard is a lookup,\n -- not a scan.\n --\n -- A tenant who DISCONNECTS stops pushing from that moment, which means a\n -- booking deleted afterwards leaves its Google event behind. That is the right\n -- trade: the alternative is pushing on behalf of someone who revoked us.\n IF NOT EXISTS (\n SELECT 1 FROM public.plg_calendar_integrations i\n WHERE i.tenant_id = rec.tenant_id AND i.active\n ) THEN\n RETURN COALESCE(NEW, OLD);\n END IF;\n\n BEGIN\n PERFORM net.http_post(\n url := url,\n headers := jsonb_build_object(\n 'Content-Type', 'application/json',\n -- REQUIRED. The deployed function authorises push_event on this header\n -- alone; without it every push 400s, silently, forever.\n 'Authorization', 'Bearer ' || key\n ),\n body := jsonb_build_object(\n 'action', 'push_event',\n 'op', op,\n 'bookingId', rec.id,\n 'tenantId', rec.tenant_id,\n -- Carried so a delete can still be honoured after the row is gone.\n 'googleEventId', rec.metadata->>'googleCalendarEventId',\n 'calendarId', rec.metadata->>'gcalCalendarId',\n 'correlationId', COALESCE(corr, gen_random_uuid()::text)\n )\n );\n EXCEPTION WHEN OTHERS THEN\n -- Missing pg_net, a bad URL, a full queue: the appointment is still saved.\n -- The deployed trigger lacks this wrapper; 004 added it here after a pool\n -- with the settings present but the extension missing took an INSERT down.\n RAISE WARNING 'gcal push skipped for booking %: %', rec.id, SQLERRM;\n END;\n\n RETURN COALESCE(NEW, OLD);\nEND $$;\n\n-- §2 ── cleanup ──────────────────────────────────────────────────────────────\n-- Redefining the function stops the key being PREFERRED; it does not stop it\n-- being STORED. Settings live in pg_db_role_setting per (database, role), so the\n-- sweep is driven off the catalog rather than off the one ALTER DATABASE form\n-- \\`001\\` happened to show.\n--\n-- CONDITIONAL ON PURPOSE: the setting is cleared only where Vault already\n-- supplies \\`gcal_outbound_secret\\`, i.e. only where §1 provably never needs the\n-- fallback. Anywhere else it is left in place and reported, because clearing it\n-- there would disarm the push with no error anyone can see. On the live pool\n-- this loop finds nothing — the setting is not present on any role or database —\n-- and that is the expected result, not a failure.\nDO $$\nDECLARE\n r record;\n has_vault boolean := false;\nBEGIN\n BEGIN\n SELECT EXISTS (\n SELECT 1 FROM vault.decrypted_secrets\n WHERE name = 'gcal_outbound_secret' AND NULLIF(decrypted_secret, '') IS NOT NULL\n ) INTO has_vault;\n EXCEPTION WHEN OTHERS THEN\n has_vault := false;\n END;\n\n FOR r IN\n SELECT d.datname, a.rolname\n FROM pg_db_role_setting s\n LEFT JOIN pg_database d ON d.oid = s.setdatabase\n LEFT JOIN pg_roles a ON a.oid = s.setrole\n WHERE EXISTS (\n SELECT 1 FROM unnest(s.setconfig) AS c WHERE c LIKE 'app.gcal_service_key=%'\n )\n LOOP\n IF NOT has_vault THEN\n RAISE WARNING 'app.gcal_service_key is still set (database %, role %) and is the ONLY outbound credential — create the vault secret gcal_outbound_secret first, then re-run this migration',\n r.datname, r.rolname;\n CONTINUE;\n END IF;\n BEGIN\n IF r.rolname IS NULL THEN\n EXECUTE format('ALTER DATABASE %I RESET app.gcal_service_key', r.datname);\n ELSIF r.datname IS NULL THEN\n EXECUTE format('ALTER ROLE %I RESET app.gcal_service_key', r.rolname);\n ELSE\n EXECUTE format('ALTER ROLE %I IN DATABASE %I RESET app.gcal_service_key', r.rolname, r.datname);\n END IF;\n EXCEPTION WHEN OTHERS THEN\n RAISE WARNING 'could not clear app.gcal_service_key (database %, role %): % — clear it by hand, and rotate the key either way',\n r.datname, r.rolname, SQLERRM;\n END;\n END LOOP;\nEND $$;\n\n-- ===========================================================================\n-- §2 — the trigger 007 left out\n--\n-- AFTER INSERT OR UPDATE OR DELETE: a booking that is moved or cancelled has to\n-- reach Google too, and a trigger that only fired on INSERT would leave the\n-- calendar showing an appointment the CRM no longer has.\n-- ===========================================================================\nDROP TRIGGER IF EXISTS trg_gcal_push ON public.appointments;\nCREATE TRIGGER trg_gcal_push\n AFTER INSERT OR UPDATE OR DELETE ON public.appointments\n FOR EACH ROW EXECUTE FUNCTION public.fn_gcal_push_booking();\n\nCOMMENT ON FUNCTION public.fn_gcal_push_booking() IS\n 'Pushes a booking to Google Calendar over pg_net, authorised by the vault secret gcal_outbound_secret. Inert while the vault secrets are absent (008).';\n`\n\nexport const MIGRATION_009_THE_SERVICE_RUNS_THE_SYNC = `-- ============================================================================\n-- google-calendar 009_the_service_runs_the_sync — the Google Calendar data\n-- plane moves to the integration service (ADR 0003 phase 2, wave 3).\n--\n-- User actions run AS the verified caller and machine actions (a booking push,\n-- a webhook pull, watch renewal) AS the store's owner, both under RLS: the\n-- integrations, channels and sync log already admit a member. What only a\n-- machine writes gets the service role, table by table, with an explicit\n-- policy: the webhook delivery log and the automation outbox. And the four\n-- server-only RPCs the sync calls (002/003: service_role only) get EXECUTE for\n-- the service role, where they exist on the cluster.\n--\n-- Guarded: the role is an operator step, and a cluster may not have the RPCs.\n-- Replay-safe.\n-- ============================================================================\n\nDO $$\nDECLARE\n t text;\n f text;\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'fayz_integration') THEN\n RETURN;\n END IF;\n\n FOREACH t IN ARRAY ARRAY['plg_calendar_webhook_deliveries', 'plg_calendar_automation_outbox'] LOOP\n IF to_regclass('public.' || t) IS NULL THEN CONTINUE; END IF;\n EXECUTE format('GRANT SELECT, INSERT, UPDATE ON public.%I TO fayz_integration', t);\n EXECUTE format('DROP POLICY IF EXISTS %I ON public.%I', t || '_service', t);\n EXECUTE format('CREATE POLICY %I ON public.%I FOR ALL TO fayz_integration USING (true) WITH CHECK (true)', t || '_service', t);\n END LOOP;\n\n -- The webhook resolves a channel by its Google channel id before it knows the\n -- tenant: a read of the channels table, and nothing else on it.\n IF to_regclass('public.plg_calendar_channels') IS NOT NULL THEN\n GRANT SELECT ON public.plg_calendar_channels TO fayz_integration;\n DROP POLICY IF EXISTS plg_calendar_channels_service_read ON public.plg_calendar_channels;\n CREATE POLICY plg_calendar_channels_service_read ON public.plg_calendar_channels FOR SELECT TO fayz_integration USING (true);\n END IF;\n\n FOREACH f IN ARRAY ARRAY[\n 'public.gcal_import_event(uuid, uuid, text, text, text, timestamptz, timestamptz, boolean, text)',\n 'public.gcal_apply_event_patch(uuid, text, text, timestamptz, timestamptz, text, boolean)',\n 'public.gcal_stamp_outbound(uuid, uuid, text, text, text)',\n 'public.gcal_unlink_channel(uuid)'\n ] LOOP\n IF to_regprocedure(f) IS NOT NULL THEN\n EXECUTE format('GRANT EXECUTE ON FUNCTION %s TO fayz_integration', f);\n END IF;\n END LOOP;\nEND $$;\n`\n\nexport const MIGRATIONS: Array<{ id: string; sql: string }> = [\n { id: \"001_google_calendar\", sql: MIGRATION_001_GOOGLE_CALENDAR },\n { id: \"002_smart_sync\", sql: MIGRATION_002_SMART_SYNC },\n { id: \"003_plg_rename\", sql: MIGRATION_003_PLG_RENAME },\n { id: \"004_drop_oauth_tokens\", sql: MIGRATION_004_DROP_OAUTH_TOKENS },\n { id: \"005_outbound_vault_delivery\", sql: MIGRATION_005_OUTBOUND_VAULT_DELIVERY },\n { id: \"006_webhook_deliveries_outbox\", sql: MIGRATION_006_WEBHOOK_DELIVERIES_OUTBOX },\n { id: \"007_credential_free_install\", sql: MIGRATION_007_CREDENTIAL_FREE_INSTALL },\n { id: \"008_the_outbound_half\", sql: MIGRATION_008_THE_OUTBOUND_HALF },\n { id: \"009_the_service_runs_the_sync\", sql: MIGRATION_009_THE_SERVICE_RUNS_THE_SYNC },\n]\n"]}
@@ -0,0 +1,29 @@
1
+ // node_modules/.cache/fayz-migration-stubs/main.ts
2
+ var MIGRATION_000_BASELINE = "";
3
+ var MIGRATION_001_THE_CONNECTOR_DEFINERS_KEEP_A_PINNED_PATH = "";
4
+ var MIGRATION_002_THE_APPOINTMENT_NAMES_THE_UNIT = "";
5
+ var MIGRATION_003_THE_CLIENT_ARRIVES_BEFORE_BEING_SERVED = "";
6
+ var MIGRATION_004_THE_APPOINTMENT_CARRIES_ITS_UNIT = "";
7
+ var MIGRATION_005_THE_QUEUE_KNOWS_HOW_LONG_SHE_WAITED = "";
8
+ var MIGRATION_006_THE_AGENDA_STOPS_PRICING_EVERY_INVOICE = "";
9
+ var MIGRATION_007_O_CASCADE_LEVOU_A_AGENDA_JUNTO = "";
10
+ var MIGRATION_008_A_AGENDA_DO_V1_ATRAVESSA = "";
11
+ var MIGRATION_009_O_EXECUTOR_SE_ACHA_PELO_PEDIDO = "";
12
+ var MIGRATION_010_A_GRADE_DO_V1_ATRAVESSA = "";
13
+ var MIGRATION_011_A_SALA_ENTRA_NO_COMPROMISSO = "";
14
+ var MIGRATION_012_A_SALA_SEM_NOME_TAMBEM_E_UMA_SALA = "";
15
+ var MIGRATION_013_O_SELO_DO_ATENDIMENTO_TEM_ONDE_MORAR = "";
16
+ var MIGRATION_014_A_CONFIGURACAO_NAO_E_UMA_TABELA = "";
17
+ var MIGRATION_015_O_FERIADO_TAMBEM_TEM_OBSERVACAO_E_ETIQUETA = "";
18
+ var MIGRATION_016_A_VEZ_E_UM_FATO = "";
19
+ var MIGRATION_017_A_EQUIPE_DO_DIA_APARECE = "";
20
+ var MIGRATION_018_O_AGENDAMENTO_QUE_SE_REPETE = "";
21
+ var MIGRATION_019_A_SERIE_NASCE_NUMA_VIAGEM_SO = "";
22
+ var MIGRATION_020_A_LISTA_DA_VEZ_SE_LIGA_NO_CADASTRO_DA_UNIDADE = "";
23
+ var MIGRATION_021_A_VEZ_POR_AREA = "";
24
+ var MIGRATION_022_A_CHAVE_DA_FILA_E_CONFIGURACAO_DA_UNIDADE = "";
25
+ var MIGRATIONS = [];
26
+
27
+ export { MIGRATIONS, MIGRATION_000_BASELINE, MIGRATION_001_THE_CONNECTOR_DEFINERS_KEEP_A_PINNED_PATH, MIGRATION_002_THE_APPOINTMENT_NAMES_THE_UNIT, MIGRATION_003_THE_CLIENT_ARRIVES_BEFORE_BEING_SERVED, MIGRATION_004_THE_APPOINTMENT_CARRIES_ITS_UNIT, MIGRATION_005_THE_QUEUE_KNOWS_HOW_LONG_SHE_WAITED, MIGRATION_006_THE_AGENDA_STOPS_PRICING_EVERY_INVOICE, MIGRATION_007_O_CASCADE_LEVOU_A_AGENDA_JUNTO, MIGRATION_008_A_AGENDA_DO_V1_ATRAVESSA, MIGRATION_009_O_EXECUTOR_SE_ACHA_PELO_PEDIDO, MIGRATION_010_A_GRADE_DO_V1_ATRAVESSA, MIGRATION_011_A_SALA_ENTRA_NO_COMPROMISSO, MIGRATION_012_A_SALA_SEM_NOME_TAMBEM_E_UMA_SALA, MIGRATION_013_O_SELO_DO_ATENDIMENTO_TEM_ONDE_MORAR, MIGRATION_014_A_CONFIGURACAO_NAO_E_UMA_TABELA, MIGRATION_015_O_FERIADO_TAMBEM_TEM_OBSERVACAO_E_ETIQUETA, MIGRATION_016_A_VEZ_E_UM_FATO, MIGRATION_017_A_EQUIPE_DO_DIA_APARECE, MIGRATION_018_O_AGENDAMENTO_QUE_SE_REPETE, MIGRATION_019_A_SERIE_NASCE_NUMA_VIAGEM_SO, MIGRATION_020_A_LISTA_DA_VEZ_SE_LIGA_NO_CADASTRO_DA_UNIDADE, MIGRATION_021_A_VEZ_POR_AREA, MIGRATION_022_A_CHAVE_DA_FILA_E_CONFIGURACAO_DA_UNIDADE };
28
+ //# sourceMappingURL=main.browser.js.map
29
+ //# sourceMappingURL=main.browser.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../node_modules/.cache/fayz-migration-stubs/main.ts"],"names":[],"mappings":";AAEO,IAAM,sBAAA,GAAyB;AAC/B,IAAM,uDAAA,GAA0D;AAChE,IAAM,4CAAA,GAA+C;AACrD,IAAM,oDAAA,GAAuD;AAC7D,IAAM,8CAAA,GAAiD;AACvD,IAAM,iDAAA,GAAoD;AAC1D,IAAM,oDAAA,GAAuD;AAC7D,IAAM,4CAAA,GAA+C;AACrD,IAAM,sCAAA,GAAyC;AAC/C,IAAM,4CAAA,GAA+C;AACrD,IAAM,qCAAA,GAAwC;AAC9C,IAAM,yCAAA,GAA4C;AAClD,IAAM,+CAAA,GAAkD;AACxD,IAAM,kDAAA,GAAqD;AAC3D,IAAM,6CAAA,GAAgD;AACtD,IAAM,wDAAA,GAA2D;AACjE,IAAM,6BAAA,GAAgC;AACtC,IAAM,qCAAA,GAAwC;AAC9C,IAAM,yCAAA,GAA4C;AAClD,IAAM,0CAAA,GAA6C;AACnD,IAAM,2DAAA,GAA8D;AACpE,IAAM,4BAAA,GAA+B;AACrC,IAAM,uDAAA,GAA0D;AAChE,IAAM,aAAiD","file":"main.browser.js","sourcesContent":["// GENERATED by scripts/tsup-migrations.mjs — the browser build of a\n// migrations barrel: the same names, no SQL. See that script for why.\nexport const MIGRATION_000_BASELINE = ''\nexport const MIGRATION_001_THE_CONNECTOR_DEFINERS_KEEP_A_PINNED_PATH = ''\nexport const MIGRATION_002_THE_APPOINTMENT_NAMES_THE_UNIT = ''\nexport const MIGRATION_003_THE_CLIENT_ARRIVES_BEFORE_BEING_SERVED = ''\nexport const MIGRATION_004_THE_APPOINTMENT_CARRIES_ITS_UNIT = ''\nexport const MIGRATION_005_THE_QUEUE_KNOWS_HOW_LONG_SHE_WAITED = ''\nexport const MIGRATION_006_THE_AGENDA_STOPS_PRICING_EVERY_INVOICE = ''\nexport const MIGRATION_007_O_CASCADE_LEVOU_A_AGENDA_JUNTO = ''\nexport const MIGRATION_008_A_AGENDA_DO_V1_ATRAVESSA = ''\nexport const MIGRATION_009_O_EXECUTOR_SE_ACHA_PELO_PEDIDO = ''\nexport const MIGRATION_010_A_GRADE_DO_V1_ATRAVESSA = ''\nexport const MIGRATION_011_A_SALA_ENTRA_NO_COMPROMISSO = ''\nexport const MIGRATION_012_A_SALA_SEM_NOME_TAMBEM_E_UMA_SALA = ''\nexport const MIGRATION_013_O_SELO_DO_ATENDIMENTO_TEM_ONDE_MORAR = ''\nexport const MIGRATION_014_A_CONFIGURACAO_NAO_E_UMA_TABELA = ''\nexport const MIGRATION_015_O_FERIADO_TAMBEM_TEM_OBSERVACAO_E_ETIQUETA = ''\nexport const MIGRATION_016_A_VEZ_E_UM_FATO = ''\nexport const MIGRATION_017_A_EQUIPE_DO_DIA_APARECE = ''\nexport const MIGRATION_018_O_AGENDAMENTO_QUE_SE_REPETE = ''\nexport const MIGRATION_019_A_SERIE_NASCE_NUMA_VIAGEM_SO = ''\nexport const MIGRATION_020_A_LISTA_DA_VEZ_SE_LIGA_NO_CADASTRO_DA_UNIDADE = ''\nexport const MIGRATION_021_A_VEZ_POR_AREA = ''\nexport const MIGRATION_022_A_CHAVE_DA_FILA_E_CONFIGURACAO_DA_UNIDADE = ''\nexport const MIGRATIONS: Array<{ id: string; sql: string }> = []\n"]}