@fayz-ai/plugin-crm 0.8.3 → 0.8.5

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 (84) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/BoardFilters.d.ts +23 -0
  3. package/dist/components/BoardFilters.d.ts.map +1 -0
  4. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  5. package/dist/components/TagChips.d.ts +16 -0
  6. package/dist/components/TagChips.d.ts.map +1 -0
  7. package/dist/data/mock.d.ts +5 -0
  8. package/dist/data/mock.d.ts.map +1 -1
  9. package/dist/data/supabase.d.ts +6 -0
  10. package/dist/data/supabase.d.ts.map +1 -1
  11. package/dist/data/types.d.ts +12 -2
  12. package/dist/data/types.d.ts.map +1 -1
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1136 -164
  16. package/dist/index.js.map +1 -1
  17. package/dist/lib/access.d.ts +8 -0
  18. package/dist/lib/access.d.ts.map +1 -0
  19. package/dist/locales/en.d.ts.map +1 -1
  20. package/dist/locales/pt-BR.d.ts.map +1 -1
  21. package/dist/migrations/index.d.ts +9 -1
  22. package/dist/migrations/index.d.ts.map +1 -1
  23. package/dist/public/context.d.ts +3 -3
  24. package/dist/public/context.d.ts.map +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  26. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  27. package/dist/public/data.supabase.d.ts.map +1 -1
  28. package/dist/public/index.js +31 -7
  29. package/dist/public/index.js.map +1 -1
  30. package/dist/public/types.d.ts +27 -0
  31. package/dist/public/types.d.ts.map +1 -1
  32. package/dist/registries.d.ts +11 -0
  33. package/dist/registries.d.ts.map +1 -1
  34. package/dist/store.d.ts +12 -2
  35. package/dist/store.d.ts.map +1 -1
  36. package/dist/types.d.ts +51 -2
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts +6 -1
  39. package/dist/views/ActivityListView.d.ts.map +1 -1
  40. package/dist/views/DealSidebar.d.ts.map +1 -1
  41. package/dist/views/LeadDetailView.d.ts.map +1 -1
  42. package/dist/views/PipelineView.d.ts.map +1 -1
  43. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  44. package/dist/views/QuoteListView.d.ts.map +1 -1
  45. package/package.json +15 -14
  46. package/src/CrmPage.tsx +1 -1
  47. package/src/cascade.ts +2 -0
  48. package/src/components/BoardFilters.tsx +190 -0
  49. package/src/components/QuoteStatusDropdown.tsx +15 -3
  50. package/src/components/TagChips.tsx +80 -0
  51. package/src/data/mock.ts +140 -7
  52. package/src/data/supabase.ts +256 -11
  53. package/src/data/types.ts +14 -3
  54. package/src/index.ts +179 -3
  55. package/src/lib/access.ts +11 -0
  56. package/src/locales/en.ts +13 -0
  57. package/src/locales/pt-BR.ts +18 -5
  58. package/src/migrations/003_crm_views_rls.sql +10 -2
  59. package/src/migrations/007_activity_log.sql +55 -0
  60. package/src/migrations/008_view_field_aliases.sql +43 -0
  61. package/src/migrations/009_deal_archived_status.sql +30 -0
  62. package/src/migrations/010_quote_archived_status.sql +40 -0
  63. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  64. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  65. package/src/migrations/013_tag_slugs.sql +177 -0
  66. package/src/migrations/014_public_lead_tags.sql +172 -0
  67. package/src/migrations/index.ts +833 -3
  68. package/src/public/context.tsx +4 -4
  69. package/src/public/createPublicFormsPlugin.ts +72 -2
  70. package/src/public/data.supabase.ts +3 -2
  71. package/src/public/types.ts +28 -0
  72. package/src/registries.ts +44 -11
  73. package/src/store.ts +135 -38
  74. package/src/types.ts +59 -2
  75. package/src/views/ActivityListView.tsx +79 -11
  76. package/src/views/DealSidebar.tsx +48 -39
  77. package/src/views/LeadDetailView.tsx +29 -10
  78. package/src/views/PipelineView.tsx +112 -11
  79. package/src/views/QuoteDetailView.tsx +7 -3
  80. package/src/views/QuoteListView.tsx +26 -12
  81. package/dist/index.cjs +0 -4759
  82. package/dist/index.cjs.map +0 -1
  83. package/dist/public/index.cjs +0 -306
  84. package/dist/public/index.cjs.map +0 -1
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Single resolver for "can this user archive CRM records?" (deals, leads).
3
+ * One feature/action pair resolved in ONE place — call sites render or hide
4
+ * the affordance off this boolean and never repeat the check. Degrades to
5
+ * allow under a bare host shell (useAccessOptional's contract).
6
+ */
7
+ export declare function useCanArchive(): boolean;
8
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../../src/lib/access.ts"],"names":[],"mappings":"AAEA;;;;;GAKG;AACH,wBAAgB,aAAa,IAAI,OAAO,CAEvC"}
@@ -1 +1 @@
1
- {"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../src/locales/en.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAmSrC,CAAA"}
1
+ {"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../src/locales/en.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAgTrC,CAAA"}
@@ -1 +1 @@
1
- {"version":3,"file":"pt-BR.d.ts","sourceRoot":"","sources":["../../src/locales/pt-BR.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAmSvC,CAAA"}
1
+ {"version":3,"file":"pt-BR.d.ts","sourceRoot":"","sources":["../../src/locales/pt-BR.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAgTvC,CAAA"}
@@ -1,10 +1,18 @@
1
1
  export declare const MIGRATION_000_PLG_RENAME = "-- 000_plg_rename.sql \u2014 rename legacy CRM tables to the plg_crm_* convention for\n-- pools provisioned before the industry-pool rename. Guarded: only fires when the\n-- legacy name exists and the target does not, so fresh pools skip every branch and\n-- the create-table migrations below build clean.\nDO $$\nBEGIN\n IF to_regclass('public.crm_activities') IS NOT NULL AND to_regclass('public.plg_crm_activities') IS NULL THEN\n ALTER TABLE public.crm_activities RENAME TO plg_crm_activities;\n END IF;\n IF to_regclass('public.crm_tags') IS NOT NULL AND to_regclass('public.plg_crm_tags') IS NULL THEN\n ALTER TABLE public.crm_tags RENAME TO plg_crm_tags;\n END IF;\n IF to_regclass('public.crm_activity_types') IS NOT NULL AND to_regclass('public.plg_crm_activity_types') IS NULL THEN\n ALTER TABLE public.crm_activity_types RENAME TO plg_crm_activity_types;\n END IF;\n IF to_regclass('public.pipelines') IS NOT NULL AND to_regclass('public.plg_crm_pipelines') IS NULL THEN\n ALTER TABLE public.pipelines RENAME TO plg_crm_pipelines;\n END IF;\n IF to_regclass('public.pipeline_stages') IS NOT NULL AND to_regclass('public.plg_crm_pipeline_stages') IS NULL THEN\n ALTER TABLE public.pipeline_stages RENAME TO plg_crm_pipeline_stages;\n END IF;\n IF to_regclass('public.deal_extensions') IS NOT NULL AND to_regclass('public.plg_crm_deal_extensions') IS NULL THEN\n ALTER TABLE public.deal_extensions RENAME TO plg_crm_deal_extensions;\n END IF;\n IF to_regclass('public.lead_sources') IS NOT NULL AND to_regclass('public.plg_crm_lead_sources') IS NULL THEN\n ALTER TABLE public.lead_sources RENAME TO plg_crm_lead_sources;\n END IF;\nEND $$;\n";
2
2
  export declare const MIGRATION_001_CRM_BASE = "-- CRM Plugin: Base Tables\n-- Leads use public.people (kind='lead')\n-- Deals use public.orders (kind='deal')\n-- Quotes use public.orders (kind='quote') + public.order_items\n-- These are plugin-specific extension tables\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_pipelines (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n is_default boolean DEFAULT false,\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);\nALTER TABLE public.plg_crm_pipelines ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_pipelines_tenant ON public.plg_crm_pipelines(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_pipeline_stages (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n pipeline_id uuid NOT NULL REFERENCES public.plg_crm_pipelines(id) ON DELETE CASCADE,\n name text NOT NULL,\n \"order\" integer NOT NULL DEFAULT 0,\n color text DEFAULT '#6366f1',\n probability numeric(5,2) DEFAULT 0,\n is_won boolean DEFAULT false,\n is_lost boolean DEFAULT false,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_pipeline_stages ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_pipeline_stages_tenant ON public.plg_crm_pipeline_stages(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_pipeline_stages_pipeline ON public.plg_crm_pipeline_stages(pipeline_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_lead_sources (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_lead_sources ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_lead_sources_tenant ON public.plg_crm_lead_sources(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_tags (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n color text DEFAULT '#6366f1',\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_tags ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant ON public.plg_crm_tags(tenant_id);\n\n-- Deal extension: links public.orders (kind='deal') to pipeline stage\nCREATE TABLE IF NOT EXISTS public.plg_crm_deal_extensions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n order_id uuid NOT NULL REFERENCES public.orders(id) ON DELETE CASCADE,\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n pipeline_id uuid REFERENCES public.plg_crm_pipelines(id),\n stage_id uuid REFERENCES public.plg_crm_pipeline_stages(id),\n probability numeric(5,2) DEFAULT 0,\n expected_close_date date,\n lead_id uuid REFERENCES public.people(id),\n lost_reason text,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_deal_extensions ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_tenant ON public.plg_crm_deal_extensions(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_order ON public.plg_crm_deal_extensions(order_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_stage ON public.plg_crm_deal_extensions(stage_id);\n";
3
3
  export declare const MIGRATION_002_ACTIVITIES = "-- CRM Plugin: Activities & Tasks\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_activity_types (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n name text NOT NULL,\n is_active boolean NOT NULL DEFAULT true,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_activity_types ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_activity_types_tenant ON public.plg_crm_activity_types(tenant_id);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_activities (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,\n deal_id uuid REFERENCES public.orders(id),\n lead_id uuid REFERENCES public.people(id),\n contact_id uuid REFERENCES public.people(id),\n contact_name text,\n activity_type text NOT NULL,\n title text NOT NULL,\n description text,\n due_date date,\n completed_at timestamptz,\n assigned_to_id uuid,\n assigned_to_name text,\n created_at timestamptz NOT NULL DEFAULT now()\n);\nALTER TABLE public.plg_crm_activities ENABLE ROW LEVEL SECURITY;\nCREATE INDEX IF NOT EXISTS idx_plg_crm_activities_tenant ON public.plg_crm_activities(tenant_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_activities_deal ON public.plg_crm_activities(deal_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_activities_lead ON public.plg_crm_activities(lead_id);\nCREATE INDEX IF NOT EXISTS idx_plg_crm_activities_due ON public.plg_crm_activities(tenant_id, due_date);\n";
4
- export declare const MIGRATION_003_CRM_VIEWS_RLS = "-- CRM plugin \u2014 companion SQL (functions/views/RLS Drizzle doesn't diff).\n-- Tables come from the Drizzle schema (src/schema/); this is everything else the\n-- plugin's data provider depends on: RLS policies + grants + the read-views.\n-- Idempotent. Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).\n\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_crm_pipelines','plg_crm_pipeline_stages','plg_crm_lead_sources','plg_crm_tags',\n 'plg_crm_deal_extensions','plg_crm_activity_types','plg_crm_activities'\n ])\n LOOP\n EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);\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||'_select') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);\n END IF;\n END LOOP;\nEND $$;\n\n-- v_leads: public.people (kind='lead')\nCREATE OR REPLACE VIEW public.v_leads WITH (security_invoker=true) AS\nSELECT\n p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,\n p.metadata->>'company' AS company,\n p.metadata->>'sourceId' AS source_id,\n p.metadata->>'sourceName' AS source_name,\n COALESCE(p.metadata->>'status','new') AS lead_status,\n p.metadata->>'value' AS lead_value,\n p.metadata->>'assignedToId' AS assigned_to_id,\n p.created_at, p.updated_at\nFROM public.people p\nWHERE p.kind = 'lead';\nGRANT SELECT ON public.v_leads TO authenticated;\n\n-- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages\nCREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS\nSELECT\n o.id, o.tenant_id, o.status,\n o.total AS value, o.notes AS title,\n o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,\n o.metadata->>'contactName' AS contact_name,\n o.created_at, o.updated_at,\n de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,\n de.lead_id, de.lost_reason,\n ps.name AS stage_name, ps.color AS stage_color, ps.\"order\" AS stage_order\nFROM public.orders o\nLEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id\nLEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id\nWHERE o.kind = 'deal';\nGRANT SELECT ON public.v_deals TO authenticated;\n";
4
+ export declare const MIGRATION_003_CRM_VIEWS_RLS = "-- CRM plugin \u2014 companion SQL (functions/views/RLS Drizzle doesn't diff).\n-- Tables come from the Drizzle schema (src/schema/); this is everything else the\n-- plugin's data provider depends on: RLS policies + grants + the read-views.\n-- Idempotent. Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).\n\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_crm_pipelines','plg_crm_pipeline_stages','plg_crm_lead_sources','plg_crm_tags',\n 'plg_crm_deal_extensions','plg_crm_activity_types','plg_crm_activities'\n ])\n LOOP\n EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);\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||'_select') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);\n END IF;\n END LOOP;\nEND $$;\n\n-- v_leads: public.people (kind='lead')\n-- DROP first: 005 widens this view (form_id/custom_fields/utm), and CREATE OR\n-- REPLACE cannot narrow a live view \u2014 replaying 003 on a pool that already ran\n-- 005 would fail with \"cannot drop columns from view\". 005 replays right after\n-- and widens it again, so the net result is unchanged.\nDROP VIEW IF EXISTS public.v_leads;\nCREATE VIEW public.v_leads WITH (security_invoker=true) AS\nSELECT\n p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,\n p.metadata->>'company' AS company,\n p.metadata->>'sourceId' AS source_id,\n p.metadata->>'sourceName' AS source_name,\n COALESCE(p.metadata->>'status','new') AS lead_status,\n p.metadata->>'value' AS lead_value,\n p.metadata->>'assignedToId' AS assigned_to_id,\n p.created_at, p.updated_at\nFROM public.people p\nWHERE p.kind = 'lead';\nGRANT SELECT ON public.v_leads TO authenticated;\n\n-- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages\n-- DROP first for the same reason as v_leads above: 008 appends the `stage`\n-- alias, and CREATE OR REPLACE cannot narrow a live view on replay.\nDROP VIEW IF EXISTS public.v_deals;\nCREATE VIEW public.v_deals WITH (security_invoker=true) AS\nSELECT\n o.id, o.tenant_id, o.status,\n o.total AS value, o.notes AS title,\n o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,\n o.metadata->>'contactName' AS contact_name,\n o.created_at, o.updated_at,\n de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,\n de.lead_id, de.lost_reason,\n ps.name AS stage_name, ps.color AS stage_color, ps.\"order\" AS stage_order\nFROM public.orders o\nLEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id\nLEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id\nWHERE o.kind = 'deal';\nGRANT SELECT ON public.v_deals TO authenticated;\n";
5
5
  export declare const MIGRATION_004_SEED_DEFAULT_PIPELINE = "-- CRM plugin \u2014 seed: default \"Sales Pipeline\" + canonical stages.\n-- The pipeline board (#/sales/pipeline) reads public.plg_crm_pipelines / plg_crm_pipeline_stages\n-- directly; a fresh tenant has zero rows and the board renders blank. This\n-- backfills the default pipeline (matching the plugin's mock/offline provider)\n-- for every tenant that has none. Idempotent \u2014 tenants with a pipeline are skipped.\n-- Plugin-owned so EVERY app gets it on install (not re-authored per app).\n\nDO $$\nDECLARE\n t_id uuid;\n p_id uuid;\nBEGIN\n FOR t_id IN (\n SELECT id FROM public.tenants\n WHERE id NOT IN (SELECT tenant_id FROM public.plg_crm_pipelines)\n )\n LOOP\n INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)\n VALUES (t_id, 'Sales Pipeline', true, true)\n RETURNING id INTO p_id;\n\n INSERT INTO public.plg_crm_pipeline_stages (tenant_id, pipeline_id, name, \"order\", color, probability, is_won, is_lost) VALUES\n (t_id, p_id, 'New', 0, '#6366f1', 10, false, false),\n (t_id, p_id, 'Contacted', 1, '#3b82f6', 25, false, false),\n (t_id, p_id, 'Qualified', 2, '#f59e0b', 50, false, false),\n (t_id, p_id, 'Proposal', 3, '#f97316', 75, false, false),\n (t_id, p_id, 'Negotiation', 4, '#8b5cf6', 90, false, false),\n (t_id, p_id, 'Won', 5, '#22c55e', 100, true, false),\n (t_id, p_id, 'Lost', 6, '#ef4444', 0, false, true);\n END LOOP;\nEND $$;\n";
6
6
  export declare const MIGRATION_005_PUBLIC_LEAD = "-- plugin-crm 005: anon-safe lead capture from public sites.\n--\n-- The counterpart of agenda's create_public_booking: a marketing site posts a\n-- form and a lead lands in the CRM of the right tenant. Same shape of trust \u2014\n-- the caller is an anonymous browser holding only a publishable key, so every\n-- decision that matters (which tenant, which status, whether it is spam) is\n-- made here and cannot be set by the caller.\n--\n-- Why p_fields jsonb: every landing page asks something different (hair\n-- coverage on one, discount coupon on another, subject/message on a third).\n-- Modelling those as columns means a migration per campaign \u2014 the site this was\n-- built for already had 22 columns on its lead table. They go to people.metadata\n-- under 'fields', which v_leads already reads from, so a new form ships with\n-- zero schema change.\n\nCREATE OR REPLACE FUNCTION public.create_public_lead(\n p_tenant_id uuid,\n p_name text,\n p_phone text DEFAULT NULL,\n p_email text DEFAULT NULL,\n p_form_id text DEFAULT NULL,\n p_form_name text DEFAULT NULL,\n p_fields jsonb DEFAULT '{}'::jsonb,\n p_notes text DEFAULT NULL,\n p_utm jsonb DEFAULT '{}'::jsonb\n)\nRETURNS TABLE(lead_id uuid, created_at timestamptz)\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $function$\nDECLARE\n v_person_id uuid;\n v_phone text;\n v_email text;\n v_fields jsonb;\n v_utm jsonb;\n v_recent int;\nBEGIN\n -- ---------------------------------------------------------------------\n -- validation: anon-callable, so everything is checked here\n -- ---------------------------------------------------------------------\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n\n v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');\n IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n\n v_email := NULLIF(trim(COALESCE(p_email, '')), '');\n IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n\n -- a lead with no way to reach them back is not a lead\n IF v_phone IS NULL AND v_email IS NULL THEN\n RAISE EXCEPTION 'phone or email required';\n END IF;\n\n PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n -- ---------------------------------------------------------------------\n -- custom fields: object-only, bounded, and scalars only.\n -- Bounding the payload keeps a hostile caller from parking documents in\n -- the CRM; flattening nested values keeps the detail panel renderable.\n -- ---------------------------------------------------------------------\n v_fields := COALESCE(p_fields, '{}'::jsonb);\n IF jsonb_typeof(v_fields) <> 'object' THEN\n RAISE EXCEPTION 'fields must be an object';\n END IF;\n IF length(v_fields::text) > 8000 THEN\n RAISE EXCEPTION 'fields too large';\n END IF;\n IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN\n RAISE EXCEPTION 'too many fields';\n END IF;\n\n v_utm := COALESCE(p_utm, '{}'::jsonb);\n IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN\n RAISE EXCEPTION 'invalid utm';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is\n -- a double-click or a bot, not two inquiries. Repeat interest days later IS\n -- a new lead, so this window stays deliberately short.\n -- ---------------------------------------------------------------------\n SELECT count(*) INTO v_recent\n FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '5 minutes'\n AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')\n AND (\n (v_phone IS NOT NULL AND p.phone = v_phone)\n OR (v_email IS NOT NULL AND p.email = v_email)\n );\n IF v_recent > 0 THEN\n RAISE EXCEPTION 'duplicate submission';\n END IF;\n\n -- burst cap per tenant: a flood is never legitimate marketing traffic\n IF (\n SELECT count(*) FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '1 minute'\n ) >= 20 THEN\n RAISE EXCEPTION 'too many submissions';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- the lead. status/kind are hardcoded \u2014 the caller cannot promote itself\n -- into a customer or land pre-qualified.\n -- ---------------------------------------------------------------------\n INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)\n VALUES (\n p_tenant_id,\n 'lead',\n trim(p_name),\n v_phone,\n v_email,\n left(p_notes, 2000),\n ARRAY[]::text[],\n true,\n jsonb_strip_nulls(\n jsonb_build_object(\n 'status', 'new',\n 'source', 'public_form',\n 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),\n 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),\n 'fields', v_fields,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END\n )\n )\n )\n RETURNING id, people.created_at INTO v_person_id, created_at;\n\n lead_id := v_person_id;\n RETURN NEXT;\nEND;\n$function$;\n\n-- anon: the whole point. authenticated too, so a logged-in visitor on the same\n-- site takes the identical path.\nGRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb)\n TO anon, authenticated;\n\n-- Leads are read through v_leads, which is tenant-scoped by RLS on people.\n-- No anon SELECT is granted here: a public form writes, it never reads back.\nCREATE INDEX IF NOT EXISTS idx_people_lead_tenant_created\n ON public.people (tenant_id, created_at DESC)\n WHERE kind = 'lead';\n\n-- ---------------------------------------------------------------------------\n-- v_leads gains the custom-field payload.\n--\n-- Without this the whole abstraction is write-only: a form's answers reach\n-- people.metadata and no CRM screen can read them back. Columns are APPENDED\n-- (CREATE OR REPLACE VIEW cannot reorder or drop), and the view keeps\n-- security_invoker=true so people's RLS still scopes rows per tenant.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE VIEW public.v_leads\nWITH (security_invoker = true) AS\nSELECT id,\n tenant_id,\n name,\n email,\n phone,\n notes,\n tags,\n is_active,\n (metadata ->> 'company'::text) AS company,\n (metadata ->> 'sourceId'::text) AS source_id,\n (metadata ->> 'sourceName'::text) AS source_name,\n COALESCE((metadata ->> 'status'::text), 'new'::text) AS lead_status,\n (metadata ->> 'value'::text) AS lead_value,\n (metadata ->> 'assignedToId'::text) AS assigned_to_id,\n created_at,\n updated_at,\n -- appended:\n (metadata ->> 'formId'::text) AS form_id,\n COALESCE(metadata -> 'fields'::text, '{}'::jsonb) AS custom_fields,\n COALESCE(metadata -> 'utm'::text, '{}'::jsonb) AS utm\n FROM people p\n WHERE (kind = 'lead'::text);\n";
7
7
  export declare const MIGRATION_006_LEAD_ENTERS_PIPELINE = "-- plugin-crm 006: every lead lands on the board, guaranteed by the database.\n--\n-- The bug this closes: the leads LIST reads v_leads (public.people WHERE\n-- kind='lead') while the PIPELINE reads v_deals (public.orders WHERE kind='deal'\n-- + plg_crm_deal_extensions). A lead is a person; a card is an order. Nothing\n-- created the second from the first \u2014 create_public_lead never touches orders \u2014\n-- so form leads landed in the list and the board stayed empty. Forever, not\n-- intermittently. plg_crm_deal_extensions.lead_id has existed since 001 and was\n-- NULL on every row in the pool: the link was designed and never wired.\n--\n-- Why a TRIGGER and not application code: a lead reaches people through at\n-- least four independent writers today \u2014 the anon RPC create_public_lead, the\n-- agent's generic createRecord, CSV import, and the CRM's own form. Putting the\n-- board insert in any one of them leaves the other three silently broken, and\n-- the next writer added leaves a fifth. Here it cannot be forgotten or bypassed,\n-- including by a direct SQL insert.\n--\n-- Idempotent by construction: a UNIQUE index on deal_extensions.lead_id means a\n-- second attempt for the same lead is a no-op, so re-running the backfill or\n-- replaying the migration cannot double-card anyone.\n\n-- ---------------------------------------------------------------------------\n-- 1. One card per lead, enforced by the database rather than by the trigger\n-- remembering to check.\n-- ---------------------------------------------------------------------------\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_deal_extensions_lead_idx\n ON public.plg_crm_deal_extensions (lead_id) WHERE lead_id IS NOT NULL;\n\n-- ---------------------------------------------------------------------------\n-- 1b. The default board, as a callable function instead of 004's one-shot loop.\n-- Same pipeline and stages 004 seeds; idempotent per tenant.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.crm_seed_default_pipeline(p_tenant_id uuid)\nRETURNS uuid\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $$\nDECLARE\n v_pipeline uuid;\nBEGIN\n SELECT id INTO v_pipeline\n FROM public.plg_crm_pipelines\n WHERE tenant_id = p_tenant_id\n ORDER BY is_default DESC, created_at ASC\n LIMIT 1;\n IF v_pipeline IS NOT NULL THEN\n RETURN v_pipeline;\n END IF;\n\n INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)\n VALUES (p_tenant_id, 'Sales Pipeline', true, true)\n RETURNING id INTO v_pipeline;\n\n INSERT INTO public.plg_crm_pipeline_stages\n (tenant_id, pipeline_id, name, \"order\", color, probability, is_won, is_lost)\n VALUES\n (p_tenant_id, v_pipeline, 'New', 0, '#6366f1', 10, false, false),\n (p_tenant_id, v_pipeline, 'Contacted', 1, '#3b82f6', 25, false, false),\n (p_tenant_id, v_pipeline, 'Qualified', 2, '#f59e0b', 50, false, false),\n (p_tenant_id, v_pipeline, 'Proposal', 3, '#f97316', 75, false, false),\n (p_tenant_id, v_pipeline, 'Negotiation', 4, '#8b5cf6', 90, false, false),\n (p_tenant_id, v_pipeline, 'Won', 5, '#22c55e', 100, true, false),\n (p_tenant_id, v_pipeline, 'Lost', 6, '#ef4444', 0, false, true);\n\n RETURN v_pipeline;\nEND;\n$$;\n\n-- ---------------------------------------------------------------------------\n-- 2. The lead \u2192 card projection, shared by the trigger and the backfill so the\n-- two can never drift apart.\n--\n-- Placement is the tenant's DEFAULT pipeline, lowest `order` stage that is\n-- neither won nor lost (the \"New\" column). A tenant with no pipeline yet is\n-- skipped rather than failing: the lead must still be captured \u2014 losing a\n-- real customer enquiry because a board was not configured would be a far\n-- worse bug than a missing card. 004 seeds a default pipeline for every\n-- tenant, so this is the empty-tenant edge, not the normal path.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.crm_place_lead_on_board(p_lead_id uuid)\nRETURNS uuid\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $$\nDECLARE\n v_lead public.people%ROWTYPE;\n v_pipeline uuid;\n v_stage uuid;\n v_prob numeric;\n v_order_id uuid;\nBEGIN\n SELECT * INTO v_lead FROM public.people WHERE id = p_lead_id;\n IF NOT FOUND OR v_lead.kind <> 'lead' THEN\n RETURN NULL;\n END IF;\n\n -- Already on the board (re-run, or a card made by hand): nothing to do.\n IF EXISTS (SELECT 1 FROM public.plg_crm_deal_extensions WHERE lead_id = p_lead_id) THEN\n RETURN NULL;\n END IF;\n\n SELECT id INTO v_pipeline\n FROM public.plg_crm_pipelines\n WHERE tenant_id = v_lead.tenant_id\n ORDER BY is_default DESC, created_at ASC\n LIMIT 1;\n\n -- No board yet? Build the default one and carry on.\n --\n -- 004 seeds the default pipeline as a ONE-SHOT backfill with no trigger, so\n -- every tenant created after it ran has none \u2014 3 of the 8 tenants in this pool\n -- were in that state. Their board renders blank no matter how many leads\n -- arrive, and it would punch a hole straight through the guarantee this\n -- migration exists to make: a lead in such a tenant would be captured and then\n -- silently skipped for want of a stage to sit in.\n --\n -- Seeded here, on demand, rather than from a trigger on public.tenants: the\n -- board is the CRM's own concern, and a plugin has no business attaching\n -- itself to tenant creation in a core table.\n IF v_pipeline IS NULL THEN\n v_pipeline := public.crm_seed_default_pipeline(v_lead.tenant_id);\n END IF;\n IF v_pipeline IS NULL THEN\n RETURN NULL;\n END IF;\n\n SELECT id, probability INTO v_stage, v_prob\n FROM public.plg_crm_pipeline_stages\n WHERE pipeline_id = v_pipeline AND NOT is_won AND NOT is_lost\n ORDER BY \"order\" ASC\n LIMIT 1;\n IF v_stage IS NULL THEN\n RETURN NULL;\n END IF;\n\n -- The card's money value comes from the lead when the form captured one;\n -- 0 otherwise. `notes` is the deal TITLE (v_deals maps o.notes -> title), so\n -- it carries the lead's name, not the lead's message.\n INSERT INTO public.orders (\n tenant_id, kind, status, total, currency, party_id, notes, tags, metadata\n ) VALUES (\n v_lead.tenant_id,\n 'deal',\n 'open',\n COALESCE((v_lead.metadata ->> 'value')::numeric, 0),\n 'BRL',\n v_lead.id,\n v_lead.name,\n COALESCE(v_lead.tags, '{}'),\n jsonb_build_object(\n 'contactName', v_lead.name,\n 'createdFrom', 'lead',\n -- Which form produced it, when there was one: lets the board be filtered\n -- by campaign without re-joining people.\n 'formId', v_lead.metadata ->> 'formId'\n )\n )\n RETURNING id INTO v_order_id;\n\n INSERT INTO public.plg_crm_deal_extensions (\n order_id, tenant_id, pipeline_id, stage_id, probability, lead_id\n ) VALUES (\n v_order_id, v_lead.tenant_id, v_pipeline, v_stage, COALESCE(v_prob, 0), v_lead.id\n )\n -- Concurrent inserts for the same lead: the unique index above turns the\n -- loser into a no-op instead of an error the trigger would propagate back to\n -- the form submission.\n ON CONFLICT (lead_id) WHERE lead_id IS NOT NULL DO NOTHING;\n\n RETURN v_order_id;\nEND;\n$$;\n\nCOMMENT ON FUNCTION public.crm_place_lead_on_board(uuid) IS\n 'Projects a people row of kind=lead onto the tenant default pipeline as an orders(kind=deal) + deal_extension. Idempotent per lead.';\n\n-- ---------------------------------------------------------------------------\n-- 3. The trigger. AFTER INSERT so a failure here can never roll back the lead\n-- itself, and EXCEPTION-guarded for the same reason: capturing the enquiry\n-- is the part that must not fail. A board that missed a card is recoverable\n-- (step 4 re-runs); a lost lead is not.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.crm_lead_to_board()\nRETURNS trigger\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $$\nBEGIN\n IF NEW.kind = 'lead' THEN\n BEGIN\n PERFORM public.crm_place_lead_on_board(NEW.id);\n EXCEPTION WHEN OTHERS THEN\n RAISE WARNING 'crm_lead_to_board: lead % captured but not placed on the board: %', NEW.id, SQLERRM;\n END;\n END IF;\n RETURN NULL;\nEND;\n$$;\n\nDROP TRIGGER IF EXISTS people_lead_to_board ON public.people;\nCREATE TRIGGER people_lead_to_board\n AFTER INSERT ON public.people\n FOR EACH ROW\n WHEN (NEW.kind = 'lead')\n EXECUTE FUNCTION public.crm_lead_to_board();\n\n-- A person PROMOTED to lead later (kind edited from contact/customer) must land\n-- on the board too \u2014 otherwise the guarantee holds only for the insert path.\nDROP TRIGGER IF EXISTS people_promoted_to_lead_to_board ON public.people;\nCREATE TRIGGER people_promoted_to_lead_to_board\n AFTER UPDATE OF kind ON public.people\n FOR EACH ROW\n WHEN (NEW.kind = 'lead' AND OLD.kind IS DISTINCT FROM 'lead')\n EXECUTE FUNCTION public.crm_lead_to_board();\n\n-- ---------------------------------------------------------------------------\n-- 4. Realtime, so an open board updates itself instead of waiting for a reload.\n--\n-- The trigger above writes the card with no client involved, so the browser\n-- has nothing to react to unless the change is streamed. The pool's\n-- supabase_realtime publication was EMPTY \u2014 every .subscribe() in the SDK\n-- was silently receiving nothing \u2014 so the table is added explicitly rather\n-- than assumed. FOR EACH ROW replica identity stays default (PK): the\n-- handler refetches the board, so the payload's contents are irrelevant.\n-- ---------------------------------------------------------------------------\nDO $$\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN\n CREATE PUBLICATION supabase_realtime;\n END IF;\n IF NOT EXISTS (\n SELECT 1 FROM pg_publication_tables\n WHERE pubname = 'supabase_realtime'\n AND schemaname = 'public'\n AND tablename = 'plg_crm_deal_extensions'\n ) THEN\n ALTER PUBLICATION supabase_realtime ADD TABLE public.plg_crm_deal_extensions;\n END IF;\nEND $$;\n\n-- ---------------------------------------------------------------------------\n-- 5. Backfill every lead that predates the trigger. Idempotent via step 2's\n-- own guard, so replaying this migration adds nothing.\n-- ---------------------------------------------------------------------------\nDO $$\nDECLARE\n r record;\n n int := 0;\nBEGIN\n FOR r IN\n SELECT p.id\n FROM public.people p\n LEFT JOIN public.plg_crm_deal_extensions de ON de.lead_id = p.id\n WHERE p.kind = 'lead' AND de.id IS NULL\n ORDER BY p.created_at\n LOOP\n IF public.crm_place_lead_on_board(r.id) IS NOT NULL THEN\n n := n + 1;\n END IF;\n END LOOP;\n RAISE NOTICE 'crm 006 backfill: % lead(s) placed on the board', n;\nEND $$;\n";
8
+ export declare const MIGRATION_007_ACTIVITY_LOG = "-- CRM plugin \u2014 activity log foundation.\n-- Activity types become tenant-editable (icon column) and upsertable by the\n-- provider's lazy per-tenant seed (unique tenant+name). System timeline events\n-- (lead_created, stage_changed, quote_*\u2026) are written by the data provider\n-- into plg_crm_activities with completed_at = now(); they are product-defined\n-- and do NOT live in the types catalog.\n-- Idempotent / replay-safe.\n\nALTER TABLE public.plg_crm_activity_types ADD COLUMN IF NOT EXISTS icon text;\n\n-- Guarded: a pre-existing pool could hold duplicate names; skip rather than fail.\nDO $$\nBEGIN\n CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_crm_activity_types_tenant_name\n ON public.plg_crm_activity_types(tenant_id, name);\nEXCEPTION WHEN OTHERS THEN\n RAISE NOTICE 'skipping uq_plg_crm_activity_types_tenant_name: %', SQLERRM;\nEND $$;\n\n-- Backfill: records created BEFORE auto-logging existed get their timeline\n-- events retroactively (stamped at the record's created_at), so the Activities\n-- view isn't empty on day one. Idempotent via NOT EXISTS per record+type.\nINSERT INTO public.plg_crm_activities\n (tenant_id, lead_id, contact_name, activity_type, title, completed_at, created_at)\nSELECT p.tenant_id, p.id, p.name, 'lead_created', p.name, p.created_at, p.created_at\nFROM public.people p\nWHERE p.kind = 'lead'\n AND NOT EXISTS (\n SELECT 1 FROM public.plg_crm_activities a\n WHERE a.lead_id = p.id AND a.activity_type = 'lead_created'\n );\n\nINSERT INTO public.plg_crm_activities\n (tenant_id, deal_id, contact_name, activity_type, title, completed_at, created_at)\nSELECT o.tenant_id, o.id, o.metadata->>'contactName', 'deal_created',\n COALESCE(NULLIF(o.notes, ''), 'Deal'), o.created_at, o.created_at\nFROM public.orders o\nWHERE o.kind = 'deal'\n AND NOT EXISTS (\n SELECT 1 FROM public.plg_crm_activities a\n WHERE a.deal_id = o.id AND a.activity_type = 'deal_created'\n );\n\nINSERT INTO public.plg_crm_activities\n (tenant_id, contact_name, activity_type, title, description, completed_at, created_at)\nSELECT o.tenant_id, o.metadata->>'contactName', 'quote_created',\n COALESCE(o.reference_number, 'Quote'), o.metadata->>'contactName',\n o.created_at, o.created_at\nFROM public.orders o\nWHERE o.kind = 'quote'\n AND NOT EXISTS (\n SELECT 1 FROM public.plg_crm_activities a\n WHERE a.activity_type = 'quote_created' AND a.title = COALESCE(o.reference_number, 'Quote')\n AND a.tenant_id = o.tenant_id\n );\n";
9
+ export declare const MIGRATION_008_VIEW_FIELD_ALIASES = "-- CRM plugin \u2014 agent-ergonomic view aliases.\n-- The assistant's first guess for a groupBy/filter field is the natural name\n-- ('stage', 'status'), not the qualified one ('stage_name', 'lead_status') \u2014\n-- each miss costs a failed tool round. CREATE OR REPLACE can only APPEND\n-- columns, so the aliases land at the end; existing consumers are untouched.\n-- Idempotent.\n\nCREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS\nSELECT\n o.id, o.tenant_id, o.status,\n o.total AS value, o.notes AS title,\n o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,\n o.metadata->>'contactName' AS contact_name,\n o.created_at, o.updated_at,\n de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,\n de.lead_id, de.lost_reason,\n ps.name AS stage_name, ps.color AS stage_color, ps.\"order\" AS stage_order,\n ps.name AS stage\nFROM public.orders o\nLEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id\nLEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id\nWHERE o.kind = 'deal';\nGRANT SELECT ON public.v_deals TO authenticated;\n\n-- v_leads: current definition is 005's widened shape \u2014 append `status`.\nCREATE OR REPLACE VIEW public.v_leads\nWITH (security_invoker = true) AS\nSELECT\n p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,\n p.metadata->>'company' AS company,\n p.metadata->>'sourceId' AS source_id,\n p.metadata->>'sourceName' AS source_name,\n COALESCE(p.metadata->>'status','new') AS lead_status,\n p.metadata->>'value' AS lead_value,\n p.metadata->>'assignedToId' AS assigned_to_id,\n p.created_at, p.updated_at,\n p.metadata->>'formId' AS form_id,\n COALESCE(p.metadata->'fields', '{}'::jsonb) AS custom_fields,\n COALESCE(p.metadata->'utm', '{}'::jsonb) AS utm,\n COALESCE(p.metadata->>'status','new') AS status\nFROM public.people p\nWHERE p.kind = 'lead';\nGRANT SELECT ON public.v_leads TO authenticated;\n";
10
+ export declare const MIGRATION_009_DEAL_ARCHIVED_STATUS = "-- CRM plugin \u2014 allow status='archived' for deals.\n-- A beauty-era legacy migration (20260617000006) added orders_kind_status_valid\n-- whitelisting per-kind statuses; the deal branch predates archiving and\n-- rejected the soft-remove write. Recreate the check with 'archived' included,\n-- ONLY where the constraint exists (other pools: no-op). NOT VALID kept from\n-- the original \u2014 existing rows are not re-validated. Idempotent via the\n-- 'archived' probe.\n\nDO $$\nDECLARE def text;\nBEGIN\n SELECT pg_get_constraintdef(oid) INTO def\n FROM pg_constraint\n WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;\n IF def IS NULL OR def LIKE '%archived%' THEN RETURN; END IF;\n\n ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;\n ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (\n status IS NULL OR\n CASE kind\n WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted')\n WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')\n WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')\n WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')\n WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n ELSE true\n END\n ) NOT VALID;\nEND $$;\n";
11
+ export declare const MIGRATION_010_QUOTE_ARCHIVED_STATUS = "-- CRM plugin \u2014 allow status='archived' for quotes (follow-up to 009, which\n-- covered deals). Recreates orders_kind_status_valid with 'archived' in BOTH\n-- branches, only where the constraint exists (other pools: no-op). Idempotent:\n-- skips when 'archived' already appears twice (deal + quote branches).\n\nDO $$\nDECLARE def text;\nBEGIN\n SELECT pg_get_constraintdef(oid) INTO def\n FROM pg_constraint\n WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;\n IF def IS NULL THEN RETURN; END IF;\n IF (length(def) - length(replace(def, 'archived', ''))) / length('archived') >= 2 THEN RETURN; END IF;\n\n ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;\n ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (\n status IS NULL OR\n CASE kind\n WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted', 'archived')\n WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')\n WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')\n WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')\n WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n ELSE true\n END\n ) NOT VALID;\nEND $$;\n\n-- Backfill: deals stuck at total=0 whose quotes hold the real number take the\n-- LATEST quote's total (the same sync the provider now does on quote create/\n-- update). Idempotent \u2014 once totals are non-zero the predicate no longer bites.\nUPDATE public.orders d SET total = q.total\nFROM (\n SELECT DISTINCT ON ((metadata->>'dealId')) metadata->>'dealId' AS deal_id, total\n FROM public.orders\n WHERE kind = 'quote' AND metadata->>'dealId' IS NOT NULL AND total > 0\n ORDER BY (metadata->>'dealId'), created_at DESC\n) q\nWHERE d.id::text = q.deal_id AND d.kind = 'deal' AND COALESCE(d.total, 0) = 0;\n";
12
+ export declare const MIGRATION_011_AGENT_RPC_UPDATE_LEAD = "-- ============================================================================\n-- plugin-crm 011: agent_crm_update_lead \u2014 mover o status de um lead (e corrigir\n-- seus dados) pelo agente.\n--\n-- Lacuna que isso fecha: o CRM n\u00E3o tinha NENHUMA escrita pelo agente. Pedido\n-- real (\"acabei de mandar a proposta pra ele, ent\u00E3o atualiza o status\") ca\u00EDa no\n-- updateRecord gen\u00E9rico, que bate em v_leads \u2014 uma view sobre people \u2014, e o\n-- assistente s\u00F3 sabia dizer \"essa entidade \u00E9 somente leitura\". Mudar status de\n-- lead \u00E9 a a\u00E7\u00E3o mais frequente de um CRM; sem ela o agente \u00E9 s\u00F3 um relat\u00F3rio.\n--\n-- Sobre o feature id: `sales`, n\u00E3o `crm.leads`. Duas raz\u00F5es, ambas medidas em\n-- pool real. (1) agent_guard concatena feature || '.' || action sem normalizar,\n-- e nenhum pool guarda `crm.leads.edit` \u2014 beauty guarda `crm_leads.edit`,\n-- great-djs n\u00E3o guarda nenhum dos dois. (2) `sales.edit` existe nos dois, e \u00E9 o\n-- que a pr\u00F3pria tool declara em `permission`. Servidor e cliente checando\n-- features diferentes \u00E9 bug por constru\u00E7\u00E3o.\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.agent_crm_update_lead(\n p_tenant_id uuid,\n p_actor_user_id uuid,\n p_payload jsonb\n) RETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_denial jsonb;\n v_id uuid;\n v_row record;\n v_status text;\n v_patch jsonb := '{}'::jsonb;\n v_meta jsonb := '{}'::jsonb;\n v_touched boolean := false;\nBEGIN\n BEGIN\n v_id := (p_payload->>'lead_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);\n END;\n IF v_id IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error',\n 'lead_id is required \u2014 search the leads first and reuse the id from the result');\n END IF;\n\n SELECT p.id, p.name, p.email, p.phone, p.notes, p.metadata, p.kind\n INTO v_row\n FROM people p\n WHERE p.id = v_id AND p.tenant_id = p_tenant_id AND p.kind = 'lead';\n IF NOT FOUND THEN\n RETURN jsonb_build_object('ok', false, 'error', 'unknown lead for this tenant');\n END IF;\n\n v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'edit');\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n -- Status is a CLOSED set. The model reached for 'proposta_enviada', which no\n -- board column renders \u2014 an invalid status writes a lead nobody can find, so\n -- the allowed values come back in the error for it to self-correct.\n v_status := nullif(trim(lower(p_payload->>'status')), '');\n IF v_status IS NOT NULL THEN\n IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN\n RETURN jsonb_build_object(\n 'ok', false,\n 'error', format('unknown lead status %L', v_status),\n 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'),\n 'hint', 'A sent proposal is usually \"qualified\"; a closed sale is \"converted\".');\n END IF;\n v_meta := v_meta || jsonb_build_object('status', v_status);\n v_touched := true;\n END IF;\n\n -- Top-level columns.\n IF p_payload ? 'name' AND nullif(trim(p_payload->>'name'), '') IS NOT NULL THEN\n v_patch := v_patch || jsonb_build_object('name', trim(p_payload->>'name'));\n v_touched := true;\n END IF;\n IF p_payload ? 'email' THEN\n v_patch := v_patch || jsonb_build_object('email', nullif(trim(p_payload->>'email'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'phone' THEN\n v_patch := v_patch || jsonb_build_object('phone', nullif(trim(p_payload->>'phone'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'notes' THEN\n v_patch := v_patch || jsonb_build_object('notes', left(p_payload->>'notes', 2000));\n v_touched := true;\n END IF;\n\n -- Metadata-backed columns of v_leads.\n IF p_payload ? 'company' THEN\n v_meta := v_meta || jsonb_build_object('company', nullif(trim(p_payload->>'company'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'value' THEN\n v_meta := v_meta || jsonb_build_object('value', p_payload->>'value');\n v_touched := true;\n END IF;\n IF p_payload ? 'assigned_to_id' THEN\n v_meta := v_meta || jsonb_build_object('assignedToId', nullif(trim(p_payload->>'assigned_to_id'), ''));\n v_touched := true;\n END IF;\n\n IF NOT v_touched THEN\n RETURN jsonb_build_object('ok', false, 'error',\n 'nothing to change: send status, name, email, phone, company, value, assigned_to_id or notes');\n END IF;\n\n UPDATE people p SET\n name = COALESCE(v_patch->>'name', p.name),\n email = CASE WHEN v_patch ? 'email' THEN v_patch->>'email' ELSE p.email END,\n phone = CASE WHEN v_patch ? 'phone' THEN v_patch->>'phone' ELSE p.phone END,\n notes = CASE WHEN v_patch ? 'notes' THEN v_patch->>'notes' ELSE p.notes END,\n metadata = COALESCE(p.metadata, '{}'::jsonb) || v_meta,\n updated_at = now()\n WHERE p.id = v_id AND p.tenant_id = p_tenant_id;\n\n INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.updateLead', 'lead', v_id::text,\n jsonb_build_object('payload', p_payload,\n 'previous', jsonb_build_object(\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'status', COALESCE(v_row.metadata->>'status', 'new'))));\n\n SELECT l.id, l.name, l.email, l.phone, l.company, l.status\n INTO v_row\n FROM v_leads l WHERE l.id = v_id;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'company', v_row.company,\n 'status', v_row.status\n )\n );\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM public;\nREVOKE EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM anon;\nGRANT EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb)\n TO authenticated, service_role;\n";
13
+ export declare const MIGRATION_012_AGENT_RPC_CREATE_LEAD = "-- ============================================================================\n-- plugin-crm 012: agent_crm_create_lead \u2014 abrir um lead pelo agente.\n--\n-- Par do 011. Sem ele, \"cria um lead Noronha em stage qualified\" ca\u00EDa no\n-- createRecord gen\u00E9rico, batia no read_only de v_leads, e o modelo \u2014 vendo que\n-- existia updateLead \u2014 chamava a tool de EDI\u00C7\u00C3O com `lead_id: \"N/A\"`. Faltando\n-- o create, ele improvisa com o que tem.\n--\n-- Deduplica\u00E7\u00E3o \u00E9 parte do contrato, n\u00E3o extra: e-mail ou telefone que j\u00E1 existem\n-- no tenant devolvem o lead existente com `deduped: true` em vez de abrir um\n-- segundo. Um CRM com o mesmo contato duas vezes \u00E9 pior que um CRM vazio.\n--\n-- Feature `sales` pelo mesmo motivo do 011 \u2014 \u00E9 a que existe em todo pool e a que\n-- a tool declara.\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.agent_crm_create_lead(\n p_tenant_id uuid,\n p_actor_user_id uuid,\n p_payload jsonb\n) RETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_denial jsonb;\n v_used int;\n v_name text;\n v_email text;\n v_phone text;\n v_status text;\n v_meta jsonb;\n v_existing record;\n v_id uuid;\n v_row record;\nBEGIN\n v_name := nullif(trim(p_payload->>'name'), '');\n v_email := lower(nullif(trim(p_payload->>'email'), ''));\n v_phone := nullif(regexp_replace(coalesce(p_payload->>'phone', ''), '\\D', '', 'g'), '');\n IF v_name IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error', 'name is required to open a lead');\n END IF;\n\n v_status := coalesce(nullif(trim(lower(p_payload->>'status')), ''), 'new');\n IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN\n RETURN jsonb_build_object(\n 'ok', false,\n 'error', format('unknown lead status %L', v_status),\n 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'));\n END IF;\n\n -- \u2500\u2500 authorization: role \u2192 plan \u2192 leads cap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n SELECT count(*) INTO v_used FROM people p\n WHERE p.tenant_id = p_tenant_id AND p.kind = 'lead';\n v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create', 'leads', v_used, 1);\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n -- \u2500\u2500 dedupe before writing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_email IS NOT NULL OR v_phone IS NOT NULL THEN\n SELECT p.id, p.name INTO v_existing\n FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND (\n (v_email IS NOT NULL AND lower(p.email) = v_email)\n OR (v_phone IS NOT NULL AND regexp_replace(coalesce(p.phone, ''), '\\D', '', 'g') = v_phone)\n )\n LIMIT 1;\n IF FOUND THEN\n RETURN jsonb_build_object(\n 'ok', true,\n 'deduped', true,\n 'id', v_existing.id,\n 'message', format('%L already exists as a lead with that e-mail/phone \u2014 returning it instead of creating a second one. Use updateLead to change it.', v_existing.name),\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_existing.id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_existing.name));\n END IF;\n END IF;\n\n v_meta := jsonb_strip_nulls(jsonb_build_object(\n 'status', v_status,\n 'source', 'agent',\n 'company', nullif(trim(p_payload->>'company'), ''),\n 'value', nullif(trim(p_payload->>'value'), ''),\n 'sourceName', nullif(trim(p_payload->>'source_name'), ''),\n 'assignedToId', nullif(trim(p_payload->>'assigned_to_id'), '')\n ));\n\n INSERT INTO people (tenant_id, kind, name, email, phone, notes, is_active, metadata)\n VALUES (p_tenant_id, 'lead', v_name,\n nullif(trim(p_payload->>'email'), ''),\n nullif(trim(p_payload->>'phone'), ''),\n left(p_payload->>'notes', 2000),\n true, v_meta)\n RETURNING id INTO v_id;\n\n INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.createLead', 'lead', v_id::text,\n jsonb_build_object('payload', p_payload));\n\n SELECT l.id, l.name, l.email, l.phone, l.company, l.status\n INTO v_row\n FROM v_leads l WHERE l.id = v_id;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'company', v_row.company,\n 'status', v_row.status\n )\n );\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM public;\nREVOKE EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM anon;\nGRANT EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb)\n TO authenticated, service_role;\n";
14
+ export declare const MIGRATION_013_TAG_SLUGS = "-- plugin-crm 013: tags ganham um SLUG, que passa a ser o contrato.\n--\n-- people.tags e orders.tags sempre foram text[] livre, e plg_crm_tags sempre\n-- foi um cadastro solto: nada ligava um ao outro. Na pr\u00E1tica isso d\u00E1 os dois\n-- problemas cl\u00E1ssicos de tag em CRM \u2014 \"Live Agosto\", \"live agosto\" e \"Live\n-- Agosto \" viram tr\u00EAs tags, e renomear a tag no cadastro \u00F3rf\u00E3 todo registro que\n-- j\u00E1 carregava o nome antigo.\n--\n-- O slug resolve os dois: o ARRAY guarda slug (est\u00E1vel, normalizado), e o\n-- cadastro guarda label + cor para exibi\u00E7\u00E3o. Renomear passa a ser cosm\u00E9tico.\n--\n-- Slug DESCONHECIDO continua v\u00E1lido de prop\u00F3sito: uma campanha precisa poder\n-- marcar leads hoje, sem esperar algu\u00E9m cadastrar a tag. A UI mostra o slug\n-- num chip neutro at\u00E9 o cadastro existir. Vocabul\u00E1rio controlado que degrada,\n-- em vez de vocabul\u00E1rio que bloqueia.\n\n-- ---------------------------------------------------------------------------\n-- Normalizador. Sem depender da extens\u00E3o unaccent (nem todo pool a tem):\n-- translate() cobre o portugu\u00EAs, que \u00E9 o que estas tags carregam.\n-- IMMUTABLE porque \u00E9 usado em \u00EDndice/generated abaixo.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.crm_tag_slug(p_input text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nSET search_path TO 'public'\nAS $function$\n SELECT NULLIF(\n -- 4. colapsa h\u00EDfens repetidos e apara as pontas\n trim(BOTH '-' FROM regexp_replace(\n -- 3. tudo que n\u00E3o for [a-z0-9:] vira h\u00EDfen (':' sobrevive: \u00E9 o separador\n -- de namespace das tags autom\u00E1ticas, ex. 'camp:black-friday')\n regexp_replace(\n -- 2. min\u00FAscula\n lower(\n -- 1. tira acento\n translate(\n COALESCE(p_input, ''),\n '\u00E1\u00E0\u00E2\u00E3\u00E4\u00E9\u00E8\u00EA\u00EB\u00ED\u00EC\u00EE\u00EF\u00F3\u00F2\u00F4\u00F5\u00F6\u00FA\u00F9\u00FB\u00FC\u00E7\u00F1\u00C1\u00C0\u00C2\u00C3\u00C4\u00C9\u00C8\u00CA\u00CB\u00CD\u00CC\u00CE\u00CF\u00D3\u00D2\u00D4\u00D5\u00D6\u00DA\u00D9\u00DB\u00DC\u00C7\u00D1',\n 'aaaaaeeeeiiiiooooouuuucnAAAAAEEEEIIIIOOOOOUUUUCN'\n )\n ),\n '[^a-z0-9:]+', '-', 'g'\n ),\n '-{2,}', '-', 'g'\n )),\n ''\n );\n$function$;\n\nCOMMENT ON FUNCTION public.crm_tag_slug(text) IS\n 'Normaliza um r\u00F3tulo de tag para o slug que people.tags/orders.tags guardam. Preserva \":\" como separador de namespace (camp:, src:).';\n\n-- ---------------------------------------------------------------------------\n-- Cadastro de tags: slug + backfill a partir do nome.\n-- ---------------------------------------------------------------------------\nALTER TABLE public.plg_crm_tags\n ADD COLUMN IF NOT EXISTS slug text;\n\nUPDATE public.plg_crm_tags\n SET slug = public.crm_tag_slug(name)\n WHERE slug IS NULL;\n\n-- Duas linhas com o mesmo nome no mesmo tenant colidiriam no \u00EDndice \u00FAnico.\n-- Desempata pela mais antiga (a que os registros provavelmente j\u00E1 referenciam)\n-- e sufixa as demais, em vez de falhar a migration.\nWITH dupes AS (\n SELECT id, row_number() OVER (PARTITION BY tenant_id, slug ORDER BY created_at, id) AS rn\n FROM public.plg_crm_tags\n WHERE slug IS NOT NULL\n)\nUPDATE public.plg_crm_tags t\n SET slug = t.slug || '-' || d.rn\n FROM dupes d\n WHERE d.id = t.id AND d.rn > 1;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant_slug\n ON public.plg_crm_tags (tenant_id, slug);\n\n-- Um cadastro sem slug n\u00E3o serve para nada (nunca casa com um registro), ent\u00E3o\n-- o slug passa a ser derivado do nome quando o cliente n\u00E3o manda um.\nCREATE OR REPLACE FUNCTION public.plg_crm_tags_fill_slug()\nRETURNS trigger\nLANGUAGE plpgsql\nSET search_path TO 'public'\nAS $function$\nBEGIN\n NEW.slug := COALESCE(public.crm_tag_slug(NEW.slug), public.crm_tag_slug(NEW.name));\n RETURN NEW;\nEND;\n$function$;\n\nDROP TRIGGER IF EXISTS trg_plg_crm_tags_fill_slug ON public.plg_crm_tags;\nCREATE TRIGGER trg_plg_crm_tags_fill_slug\n BEFORE INSERT OR UPDATE OF name, slug ON public.plg_crm_tags\n FOR EACH ROW EXECUTE FUNCTION public.plg_crm_tags_fill_slug();\n\n-- ---------------------------------------------------------------------------\n-- O cadastro passa a se alimentar do que \u00E9 REALMENTE usado.\n--\n-- At\u00E9 aqui plg_crm_tags s\u00F3 existia como tela: o `seedData` do registry alimenta\n-- o provider mock, nunca o banco, ent\u00E3o /settings/crm/_properties/tags lia uma\n-- tabela vazia em todo tenant \u2014 e continuaria vazia mesmo com campanhas\n-- marcando leads. Registrar na escrita inverte isso: a tag aparece no cadastro\n-- porque foi usada, e o operador entra depois s\u00F3 para renomear ou trocar a cor.\n--\n-- Alternativa descartada: semear VIP/Hot Lead/Follow-up em todo tenant. Isso\n-- enche o cadastro de vocabul\u00E1rio que ningu\u00E9m escolheu e que n\u00E3o corresponde a\n-- nenhum registro.\n-- ---------------------------------------------------------------------------\n\n-- Cor est\u00E1vel por slug: a mesma tag sai da mesma cor em qualquer tenant, e o\n-- operador pode sobrescrever depois. Paleta com contraste suficiente em chip.\nCREATE OR REPLACE FUNCTION public.crm_tag_default_color(p_slug text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $function$\n SELECT (ARRAY[\n '#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#14b8a6'\n ])[(abs(hashtext(COALESCE(p_slug, ''))) % 8) + 1];\n$function$;\n\n-- R\u00F3tulo leg\u00EDvel a partir do slug: 'camp:black-friday' -> 'Black Friday'.\n-- O namespace some do r\u00F3tulo (a cor e o filtro j\u00E1 o distinguem) \u2014 quem l\u00EA o\n-- card quer ver a campanha, n\u00E3o o prefixo.\nCREATE OR REPLACE FUNCTION public.crm_tag_humanize(p_slug text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $function$\n SELECT initcap(replace(regexp_replace(COALESCE(p_slug, ''), '^[a-z]+:', ''), '-', ' '));\n$function$;\n\nCREATE OR REPLACE FUNCTION public.crm_register_tags(p_tenant_id uuid, p_slugs text[])\nRETURNS void\nLANGUAGE sql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $function$\n INSERT INTO public.plg_crm_tags (tenant_id, name, slug, color, is_active)\n SELECT p_tenant_id,\n public.crm_tag_humanize(s),\n s,\n public.crm_tag_default_color(s),\n true\n FROM unnest(COALESCE(p_slugs, '{}'::text[])) AS s\n WHERE s IS NOT NULL AND s <> ''\n ON CONFLICT (tenant_id, slug) DO NOTHING;\n$function$;\n\n-- INTERNA de prop\u00F3sito: \u00E9 SECURITY DEFINER e recebe o tenant do caller, ent\u00E3o\n-- exposta ela deixaria qualquer um semear cadastro no tenant alheio. S\u00F3 \u00E9\n-- alcan\u00E7\u00E1vel de dentro de outra fun\u00E7\u00E3o DEFINER que j\u00E1 validou o tenant \u2014 hoje,\n-- create_public_lead. O caminho do ADMIN n\u00E3o passa por aqui: ele faz upsert\n-- direto em plg_crm_tags, onde a RLS da tabela j\u00E1 faz a autoriza\u00E7\u00E3o certa.\nREVOKE ALL ON FUNCTION public.crm_register_tags(uuid, text[]) FROM public, anon, authenticated;\n\n-- Backfill: tudo que J\u00C1 est\u00E1 em people.tags / orders.tags vira cadastro, para a\n-- tela n\u00E3o nascer vazia num tenant que j\u00E1 vinha usando tags.\nDO $$\nDECLARE\n r record;\nBEGIN\n FOR r IN\n SELECT tenant_id, array_agg(DISTINCT public.crm_tag_slug(tag)) AS slugs\n FROM (\n SELECT tenant_id, unnest(tags) AS tag FROM public.people WHERE tags IS NOT NULL\n UNION ALL\n SELECT tenant_id, unnest(tags) AS tag FROM public.orders WHERE tags IS NOT NULL\n ) used\n WHERE public.crm_tag_slug(tag) IS NOT NULL\n GROUP BY tenant_id\n LOOP\n PERFORM public.crm_register_tags(r.tenant_id, r.slugs);\n END LOOP;\nEND $$;\n";
15
+ export declare const MIGRATION_014_PUBLIC_LEAD_TAGS = "-- plugin-crm 014: o formul\u00E1rio p\u00FAblico passa a poder marcar o lead.\n--\n-- create_public_lead gravava `ARRAY[]::text[]` fixo \u2014 n\u00E3o existia caminho para\n-- uma landing page dizer \"este lead veio da Turma Delas\". Sem isso, tag em CRM\n-- vira trabalho manual: algu\u00E9m abre o card e digita de onde veio, que \u00E9\n-- exatamente o que a atribui\u00E7\u00E3o autom\u00E1tica deveria evitar.\n--\n-- O caller \u00E9 um browser an\u00F4nimo, ent\u00E3o nada do que ele manda \u00E9 confi\u00E1vel: os\n-- slugs s\u00E3o normalizados, deduplicados e limitados AQUI. O site pede tags; o\n-- banco decide o que de fato entra.\n--\n-- A propaga\u00E7\u00E3o para o card do funil j\u00E1 existe: o trigger de\n-- 006_lead_enters_pipeline copia people.tags para orders.tags ao criar o deal.\n\n-- A assinatura ganha p_tags. A antiga precisa SAIR: com as duas no cat\u00E1logo o\n-- PostgREST n\u00E3o resolve a chamada sem tags (duas candidatas, mesmos nomes de\n-- par\u00E2metro) e devolve PGRST203.\nDROP FUNCTION IF EXISTS public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb);\n\nCREATE OR REPLACE FUNCTION public.create_public_lead(\n p_tenant_id uuid,\n p_name text,\n p_phone text DEFAULT NULL,\n p_email text DEFAULT NULL,\n p_form_id text DEFAULT NULL,\n p_form_name text DEFAULT NULL,\n p_fields jsonb DEFAULT '{}'::jsonb,\n p_notes text DEFAULT NULL,\n p_utm jsonb DEFAULT '{}'::jsonb,\n p_tags text[] DEFAULT '{}'::text[]\n)\nRETURNS TABLE(lead_id uuid, created_at timestamptz)\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $function$\nDECLARE\n v_person_id uuid;\n v_phone text;\n v_email text;\n v_fields jsonb;\n v_utm jsonb;\n v_tags text[];\n v_recent int;\nBEGIN\n -- ---------------------------------------------------------------------\n -- validation: anon-callable, so everything is checked here\n -- ---------------------------------------------------------------------\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n\n v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');\n IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n\n v_email := NULLIF(trim(COALESCE(p_email, '')), '');\n IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n\n -- a lead with no way to reach them back is not a lead\n IF v_phone IS NULL AND v_email IS NULL THEN\n RAISE EXCEPTION 'phone or email required';\n END IF;\n\n PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n -- ---------------------------------------------------------------------\n -- custom fields: object-only, bounded, and scalars only.\n -- ---------------------------------------------------------------------\n v_fields := COALESCE(p_fields, '{}'::jsonb);\n IF jsonb_typeof(v_fields) <> 'object' THEN\n RAISE EXCEPTION 'fields must be an object';\n END IF;\n IF length(v_fields::text) > 8000 THEN\n RAISE EXCEPTION 'fields too large';\n END IF;\n IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN\n RAISE EXCEPTION 'too many fields';\n END IF;\n\n v_utm := COALESCE(p_utm, '{}'::jsonb);\n IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN\n RAISE EXCEPTION 'invalid utm';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- tags: normalizadas e limitadas aqui. Um slug ruim \u00E9 DESCARTADO em vez de\n -- derrubar a submiss\u00E3o \u2014 perder um lead por causa de um r\u00F3tulo de campanha\n -- mal formatado seria trocar o essencial pelo acess\u00F3rio. Teto de 10 evita\n -- que uma querystring hostil vire um card com cinquenta chips.\n -- ---------------------------------------------------------------------\n SELECT array_agg(s) INTO v_tags FROM (\n SELECT DISTINCT public.crm_tag_slug(t) AS s\n FROM unnest(COALESCE(p_tags, '{}'::text[])) AS t\n WHERE public.crm_tag_slug(t) IS NOT NULL\n AND length(public.crm_tag_slug(t)) <= 48\n LIMIT 10\n ) normalized;\n v_tags := COALESCE(v_tags, '{}'::text[]);\n\n -- ---------------------------------------------------------------------\n -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is\n -- a double-click or a bot, not two inquiries.\n -- ---------------------------------------------------------------------\n SELECT count(*) INTO v_recent\n FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '5 minutes'\n AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')\n AND (\n (v_phone IS NOT NULL AND p.phone = v_phone)\n OR (v_email IS NOT NULL AND p.email = v_email)\n );\n IF v_recent > 0 THEN\n RAISE EXCEPTION 'duplicate submission';\n END IF;\n\n -- burst cap per tenant: a flood is never legitimate marketing traffic\n IF (\n SELECT count(*) FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '1 minute'\n ) >= 20 THEN\n RAISE EXCEPTION 'too many submissions';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- the lead. status/kind are hardcoded \u2014 the caller cannot promote itself\n -- into a customer or land pre-qualified.\n -- ---------------------------------------------------------------------\n INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)\n VALUES (\n p_tenant_id,\n 'lead',\n trim(p_name),\n v_phone,\n v_email,\n left(p_notes, 2000),\n v_tags,\n true,\n jsonb_strip_nulls(\n jsonb_build_object(\n 'status', 'new',\n 'source', 'public_form',\n 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),\n 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),\n 'fields', v_fields,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END\n )\n )\n )\n RETURNING id, people.created_at INTO v_person_id, created_at;\n\n -- O cadastro de tags se alimenta do que foi usado, para a tela de settings\n -- refletir a realidade sem ningu\u00E9m pr\u00E9-preencher nada.\n IF array_length(v_tags, 1) > 0 THEN\n PERFORM public.crm_register_tags(p_tenant_id, v_tags);\n END IF;\n\n lead_id := v_person_id;\n RETURN NEXT;\nEND;\n$function$;\n\nGRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[])\n TO anon, authenticated;\n";
8
16
  export declare const MIGRATIONS: Array<{
9
17
  id: string;
10
18
  sql: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,yyGA6DvC,CAAA;AAED,eAAO,MAAM,mCAAmC,q9CA+B/C,CAAA;AAED,eAAO,MAAM,yBAAyB,+uOA6LrC,CAAA;AAED,eAAO,MAAM,kCAAkC,g4VAyQ9C,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAQzD,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,kyHAqEvC,CAAA;AAED,eAAO,MAAM,mCAAmC,q9CA+B/C,CAAA;AAED,eAAO,MAAM,yBAAyB,+uOA6LrC,CAAA;AAED,eAAO,MAAM,kCAAkC,g4VAyQ9C,CAAA;AAED,eAAO,MAAM,0BAA0B,q9EAuDtC,CAAA;AAED,eAAO,MAAM,gCAAgC,g9DA2C5C,CAAA;AAED,eAAO,MAAM,kCAAkC,qlDA8B9C,CAAA;AAED,eAAO,MAAM,mCAAmC,0nEAwC/C,CAAA;AAED,eAAO,MAAM,mCAAmC,i8MAyJ/C,CAAA;AAED,eAAO,MAAM,mCAAmC,6gLAgI/C,CAAA;AAED,eAAO,MAAM,uBAAuB,0tPAiLnC,CAAA;AAED,eAAO,MAAM,8BAA8B,urNA4K1C,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAgBzD,CAAA"}
@@ -1,8 +1,8 @@
1
1
  import { type ReactNode } from 'react';
2
- import { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types';
2
+ import { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types';
3
3
  interface PublicFormsContextValue {
4
4
  forms: Map<string, PublicFormDef>;
5
- submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>;
5
+ submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>;
6
6
  }
7
7
  export interface PublicFormsProviderProps extends PublicFormsContextValue {
8
8
  children: ReactNode;
@@ -11,7 +11,7 @@ export declare function PublicFormsProvider({ forms, submit, children }: PublicF
11
11
  /** The hook a site's own form component calls. Owns only the submission
12
12
  * lifecycle — the markup, the fields and the validation copy stay the site's. */
13
13
  export declare function useLeadForm(formId: string): {
14
- submit: (values: LeadFields) => Promise<LeadSubmitResult | null>;
14
+ submit: (values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult | null>;
15
15
  reset: () => void;
16
16
  submitting: boolean;
17
17
  error: LeadSubmitError | null;
@@ -1 +1 @@
1
- {"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/public/context.tsx"],"names":[],"mappings":"AAAA,O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C,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,wBAAwB,+BAGxF;AAED;kFACkF;AAClF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM;qBAWvB,UAAU,YAAY,iBAAiB,KAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;;;;;;;EAoC5F"}
@@ -1,6 +1,6 @@
1
1
  import { type FC, type ReactNode } from 'react';
2
2
  import type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core';
3
- import { type LeadAttribution, type LeadFields, type LeadNotifier, type LeadSubmitResult, type PublicFormDef, type PublicLeadDataProvider } from './types';
3
+ import { type LeadAttribution, type LeadFields, type LeadNotifier, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef, type PublicLeadDataProvider } from './types';
4
4
  export interface PublicFormsOptions {
5
5
  /**
6
6
  * Tenant the leads land in. REQUIRED — this is the whole point of the
@@ -21,6 +21,22 @@ export interface PublicFormsOptions {
21
21
  dataProvider?: PublicLeadDataProvider;
22
22
  /** Inject a custom notifier (tests). */
23
23
  notifier?: LeadNotifier;
24
+ /**
25
+ * Marca o lead com a campanha que o trouxe, lendo a UTM da URL.
26
+ *
27
+ * Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag
28
+ * automática e tag curada convivem no mesmo array, e sem prefixo a primeira
29
+ * engole a segunda — em seis meses ninguém sabe mais quais tags alguém
30
+ * escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,
31
+ * relatar e limpar cada grupo separadamente.
32
+ *
33
+ * `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica
34
+ * desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.
35
+ */
36
+ campaignTags?: boolean | {
37
+ campaign?: boolean;
38
+ source?: boolean;
39
+ };
24
40
  scope?: PluginScope;
25
41
  verticalId?: VerticalId;
26
42
  }
@@ -30,7 +46,7 @@ export interface PublicFormsPlugin {
30
46
  children: ReactNode;
31
47
  }>;
32
48
  /** Imperative submit, for code paths outside React. */
33
- submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>;
49
+ submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>;
34
50
  }
35
51
  /** Reads UTM + page context off the browser. Safe to call during SSR. */
36
52
  export declare function readAttribution(): LeadAttribution;
@@ -1 +1 @@
1
- {"version":3,"file":"createPublicFormsPlugin.d.ts","sourceRoot":"","sources":["../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":"AAaA,OAAO,EAAiB,KAAK,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAI5E,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,sBAAsB,EAC5B,MAAM,SAAS,CAAA;AAEhB,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,KAAK,EAAE,aAAa,EAAE,CAAA;IACtB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7D,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAA;IACrC,wCAAwC;IACxC,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,EAAE,CAAC;QAAE,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAA;IACrC,uDAAuD;IACvD,MAAM,CAAC,MAAM,EAAE,MAAM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AAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,EAAE,CAAC;QAAE,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAA;IACrC,uDAAuD;IACvD,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACnG;AAED,yEAAyE;AACzE,wBAAgB,eAAe,IAAI,eAAe,CAajD;AAaD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,CA8GtF"}
@@ -1 +1 @@
1
- {"version":3,"file":"data.supabase.d.ts","sourceRoot":"","sources":["../../src/public/data.supabase.ts"],"names":[],"mappings":"AAcA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAkCxB"}
1
+ {"version":3,"file":"data.supabase.d.ts","sourceRoot":"","sources":["../../src/public/data.supabase.ts"],"names":[],"mappings":"AAcA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAmCxB"}
@@ -1,5 +1,5 @@
1
1
  import { createContext, useMemo, useContext, useState, useCallback, createElement } from 'react';
2
- import { getSupabaseClientOptional, getFayzCloudClient } from '@fayz-ai/core';
2
+ import { getSupabaseClientOptional } from '@fayz-ai/core';
3
3
  import { jsx } from 'react/jsx-runtime';
4
4
 
5
5
  // src/public/createPublicFormsPlugin.ts
@@ -15,7 +15,7 @@ var LeadSubmitError = class extends Error {
15
15
 
16
16
  // src/public/data.supabase.ts
17
17
  function getClient() {
18
- return getSupabaseClientOptional() ?? getFayzCloudClient();
18
+ return getSupabaseClientOptional();
19
19
  }
20
20
  function toSubmitError(message) {
21
21
  const m = message.toLowerCase();
@@ -50,7 +50,8 @@ function createSupabasePublicLeadProvider(options) {
50
50
  p_form_name: input.formName,
51
51
  p_fields: input.fields,
52
52
  p_notes: input.notes ?? null,
53
- p_utm: input.attribution
53
+ p_utm: input.attribution,
54
+ p_tags: input.tags ?? []
54
55
  });
55
56
  if (error) throw toSubmitError(error.message);
56
57
  const row = Array.isArray(data) ? data[0] : void 0;
@@ -152,12 +153,12 @@ function useLeadForm(formId) {
152
153
  const [error, setError] = useState(null);
153
154
  const [result, setResult] = useState(null);
154
155
  const submit = useCallback(
155
- async (values) => {
156
+ async (values, options) => {
156
157
  if (submitting) return null;
157
158
  setSubmitting(true);
158
159
  setError(null);
159
160
  try {
160
- const res = await ctx.submit(formId, values);
161
+ const res = await ctx.submit(formId, values, options);
161
162
  setResult(res);
162
163
  return res;
163
164
  } catch (err) {
@@ -186,6 +187,27 @@ function useLeadForm(formId) {
186
187
  }
187
188
 
188
189
  // src/public/createPublicFormsPlugin.ts
190
+ var MAX_TAGS = 10;
191
+ function slugify(input) {
192
+ return input.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9:]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
193
+ }
194
+ function resolveTags(formTags, callTags, attribution, campaignTags) {
195
+ const cfg = campaignTags === false ? { campaign: false, source: false } : campaignTags === true || campaignTags === void 0 ? { campaign: true, source: false } : { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false };
196
+ const out = [];
197
+ for (const raw of [...formTags ?? [], ...callTags ?? []]) {
198
+ const slug = slugify(raw);
199
+ if (slug) out.push(slug);
200
+ }
201
+ if (cfg.campaign && attribution.utm_campaign) {
202
+ const slug = slugify(attribution.utm_campaign);
203
+ if (slug) out.push(`camp:${slug}`);
204
+ }
205
+ if (cfg.source && attribution.utm_source) {
206
+ const slug = slugify(attribution.utm_source);
207
+ if (slug) out.push(`src:${slug}`);
208
+ }
209
+ return [...new Set(out)].slice(0, MAX_TAGS);
210
+ }
189
211
  function readAttribution() {
190
212
  if (typeof window === "undefined") return {};
191
213
  const params = new URLSearchParams(window.location.search);
@@ -214,7 +236,7 @@ function createPublicFormsPlugin(options) {
214
236
  const formsById = new Map(options.forms.map((f) => [f.id, f]));
215
237
  const provider = options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId });
216
238
  const notifier = options.notifier ?? (options.inbox === false ? null : createFayzInboxNotifier(typeof options.inbox === "object" ? options.inbox : {}));
217
- async function submit(formId, values) {
239
+ async function submit(formId, values, submitOptions) {
218
240
  const form = formsById.get(formId);
219
241
  if (!form) {
220
242
  throw new LeadSubmitError("validation", `[plugin-crm/public] unknown form "${formId}".`);
@@ -238,6 +260,7 @@ function createPublicFormsPlugin(options) {
238
260
  Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v))
239
261
  );
240
262
  const attribution = readAttribution();
263
+ const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags);
241
264
  const { leadId, createdAt } = await provider.createLead(
242
265
  stripUndefined({
243
266
  formId: form.id,
@@ -247,7 +270,8 @@ function createPublicFormsPlugin(options) {
247
270
  email: email || void 0,
248
271
  notes: notes || void 0,
249
272
  fields,
250
- attribution
273
+ attribution,
274
+ tags: tags.length ? tags : void 0
251
275
  })
252
276
  );
253
277
  let notified = false;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/public/types.ts","../../src/public/data.supabase.ts","../../src/public/inbox.ts","../../src/public/context.tsx","../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":";;;;;;;AAiEO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,C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,EAAW,CAAC,SAAA,EAAW,cAAc,CAAA;AAAA,IACrC,cAAA,EAAgB,IAAA;AAAA,IAChB,cAAc,EAAC;AAAA;AAAA;AAAA,IAGf,YAAY,EAAC;AAAA,IACb,QAAQ,EAAC;AAAA,IACT,SAAS;AAAC,GACZ;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,EAAO;AACtC","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Public lead capture — types\n//\n// The contract between a marketing site's own form UI and the CRM. Sites keep\n// their bespoke layout and copy; all they hand over is a bag of values. Where\n// that lands (which tenant, which table, what status) is decided by the SDK and\n// the RPC behind it, never by the site.\n// ---------------------------------------------------------------------------\n\n/** What a form field may carry. Scalars and scalar lists — anything a checkbox\n * group, a select or a text input produces. Files are out of scope: a lead\n * form links to an upload, it does not embed one. */\nexport type LeadFieldValue = string | number | boolean | null | string[] | number[]\n\n/** The values a site collects, keyed by field id. Free-form on purpose: a new\n * landing page adds keys without touching the schema. */\nexport type LeadFields = Record<string, LeadFieldValue>\n\n/**\n * One form the site exposes. Registered up-front so submissions carry a stable\n * id (attribution) and a human name (what the operator reads in the CRM).\n */\nexport interface PublicFormDef {\n /** Stable id — the attribution key. Keep it stable across redesigns. */\n id: string\n /** Human name shown as the lead's source in the CRM. */\n name: string\n /**\n * Field ids that must be present and non-empty for the submission to be\n * attempted. Contact reachability (phone or email) is enforced server-side\n * regardless of what is declared here.\n */\n required?: string[]\n /**\n * Maps this form's field ids onto the lead's identity columns. Everything NOT\n * mapped stays in `fields` as a custom field.\n *\n * Defaults to { name: 'name', phone: 'phone', email: 'email' }.\n */\n identity?: {\n name?: string\n phone?: string\n email?: string\n /** Field whose value becomes the lead's free-text note. */\n notes?: string\n }\n /** Labels for custom fields, so the CRM shows \"Faixa etária\" not \"age_range\". */\n labels?: Record<string, string>\n}\n\n/** Result of a submission — enough for the site to show its own success state. */\nexport interface LeadSubmitResult {\n leadId: string\n createdAt: string\n /** False when the CRM write succeeded but the inbox notification did not. */\n notified: boolean\n}\n\n/** Thrown for problems the site should surface differently than a crash. */\nexport type LeadSubmitErrorKind =\n | 'validation' // missing required field / no contact channel\n | 'duplicate' // same contact, same form, seconds apart\n | 'rate_limited' // burst cap tripped\n | 'unavailable' // backend not configured or unreachable\n\nexport class LeadSubmitError extends Error {\n readonly kind: LeadSubmitErrorKind\n constructor(kind: LeadSubmitErrorKind, message: string) {\n super(message)\n this.name = 'LeadSubmitError'\n this.kind = kind\n }\n}\n\n/** UTM/attribution captured from the browser, merged into every submission. */\nexport interface LeadAttribution {\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n utm_term?: string\n utm_content?: string\n /** Path the form was submitted from. */\n landing_page?: string\n referrer?: string\n}\n\n/** The transport a submission goes through. Swappable for tests. */\nexport interface PublicLeadDataProvider {\n createLead(input: {\n formId: string\n formName: string\n name: string\n phone?: string\n email?: string\n notes?: string\n fields: LeadFields\n attribution: LeadAttribution\n }): Promise<{ leadId: string; createdAt: string }>\n}\n\n/** Notifies the site's admin that a lead arrived. */\nexport interface LeadNotifier {\n notify(input: {\n formId: string\n formName: string\n leadName: string\n phone?: string\n email?: string\n fields: LeadFields\n labels?: Record<string, string>\n attribution: LeadAttribution\n }): Promise<void>\n}\n","// ---------------------------------------------------------------------------\n// Supabase implementation of PublicLeadDataProvider — anon-safe.\n//\n// Public marketing pages run with the publishable (anon) key and NO user\n// session, so canonical tenant RLS yields nothing. This provider touches only\n// the one object designed for anon access:\n// - public.create_public_lead (SECURITY DEFINER RPC: validates, caps spam,\n// writes people[kind=lead] with the custom fields in metadata)\n// Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.\n//\n// The RPC never reads back — a form writes, it does not query the CRM.\n// ---------------------------------------------------------------------------\n\nimport { getFayzCloudClient, getSupabaseClientOptional } from '@fayz-ai/core'\nimport { LeadSubmitError, type PublicLeadDataProvider } from './types'\n\nexport interface SupabasePublicLeadOptions {\n /** The tenant leads land in (RPC arg — required). */\n tenantId: string\n}\n\ninterface SupabaseLikeClient {\n rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>\n}\n\nfunction getClient(): SupabaseLikeClient | null {\n return (getSupabaseClientOptional() ?? getFayzCloudClient()) as SupabaseLikeClient | null\n}\n\n/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */\nfunction toSubmitError(message: string): LeadSubmitError {\n const m = message.toLowerCase()\n if (m.includes('duplicate submission')) {\n return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')\n }\n if (m.includes('too many submissions')) {\n return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')\n }\n if (\n m.includes('invalid') ||\n m.includes('required') ||\n m.includes('too many fields') ||\n m.includes('fields too large')\n ) {\n return new LeadSubmitError('validation', message)\n }\n return new LeadSubmitError('unavailable', message)\n}\n\nexport function createSupabasePublicLeadProvider(\n options: SupabasePublicLeadOptions,\n): PublicLeadDataProvider {\n const { tenantId } = options\n\n return {\n async createLead(input) {\n const client = getClient()\n if (!client) {\n throw new LeadSubmitError(\n 'unavailable',\n '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',\n )\n }\n\n const { data, error } = await client.rpc('create_public_lead', {\n p_tenant_id: tenantId,\n p_name: input.name,\n p_phone: input.phone ?? null,\n p_email: input.email ?? null,\n p_form_id: input.formId,\n p_form_name: input.formName,\n p_fields: input.fields,\n p_notes: input.notes ?? null,\n p_utm: input.attribution,\n })\n\n if (error) throw toSubmitError(error.message)\n\n const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined\n if (!row?.lead_id) {\n throw new LeadSubmitError('unavailable', 'Lead não foi criado.')\n }\n return { leadId: String(row.lead_id), createdAt: String(row.created_at) }\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Fayz inbox notifier — tells the site's owner a lead just arrived.\n//\n// The Fayz platform already ships a public ingest endpoint built for exactly\n// this (\"Deployed user-sites POST here\"): it stores an InboxRecord against the\n// project and emails the project owner. We only have to speak to it.\n//\n// POST <base>/public/projects/:projectId/inbox\n// { source, subject, payload, metadata }\n//\n// SAME-ORIGIN BY DEFAULT. In production the API's CORS allowlist is a single\n// origin (the editor), so a cross-origin POST from a published site would be\n// refused at preflight. Fayz's Caddy proxies `/api/*` to the API \"regardless of\n// host\", so a published site — custom domain included — reaches it same-origin\n// with no preflight at all. Hence the default base '/api' (relative). Only pass\n// an absolute base when the site is NOT served by Fayz, and expect to widen\n// CORS on the API before it works.\n//\n// Best-effort by contract: the lead is already safe in the CRM by the time this\n// runs. A failed notification is logged and swallowed — never a failed form.\n// ---------------------------------------------------------------------------\n\nimport type { LeadNotifier, LeadFields } from './types'\n\nexport interface FayzInboxNotifierOptions {\n /**\n * Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;\n * omit to read that env var automatically.\n */\n projectId?: string\n /**\n * API base. Defaults to '/api' (same-origin via Caddy) — see the note above\n * before changing it.\n */\n apiBaseUrl?: string\n /** Milliseconds before giving up. The visitor is waiting; keep it short. */\n timeoutMs?: number\n}\n\nfunction readEnv(key: string): string | undefined {\n try {\n const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env\n return env?.[key]\n } catch {\n return undefined\n }\n}\n\n/** \"age_range\" → \"Age range\", unless the form gave us a real label. */\nfunction humanize(key: string, labels?: Record<string, string>): string {\n if (labels?.[key]) return labels[key]\n const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\nfunction renderValue(value: unknown): string {\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value)) return value.length ? value.join(', ') : '—'\n if (typeof value === 'boolean') return value ? 'Sim' : 'Não'\n return String(value)\n}\n\n/**\n * Builds the flat, already-humanized payload the inbox renders. The editor\n * shows this verbatim, so it must read like a message — not like a database row.\n */\nfunction buildPayload(\n input: Parameters<LeadNotifier['notify']>[0],\n): Record<string, string> {\n const payload: Record<string, string> = { Nome: input.leadName }\n if (input.phone) payload['Telefone'] = input.phone\n if (input.email) payload['E-mail'] = input.email\n\n for (const [key, value] of Object.entries(input.fields as LeadFields)) {\n payload[humanize(key, input.labels)] = renderValue(value)\n }\n\n const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution\n if (utm_source) payload['Origem'] = utm_source\n if (utm_medium) payload['Mídia'] = utm_medium\n if (utm_campaign) payload['Campanha'] = utm_campaign\n if (landing_page) payload['Página'] = landing_page\n\n return payload\n}\n\n/**\n * A notifier that posts to the Fayz project inbox. Returns a no-op notifier\n * (with one loud warning) when no project id is resolvable, so a site running\n * outside Fayz still submits leads normally.\n */\nexport function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {\n const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')\n const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\\/$/, '')\n const timeoutMs = options.timeoutMs ?? 4000\n\n if (!projectId) {\n let warned = false\n return {\n async notify() {\n if (!warned && typeof console !== 'undefined') {\n warned = true\n console.warn(\n '[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +\n 'site owner is NOT notified in the Fayz inbox.',\n )\n }\n },\n }\n }\n\n return {\n async notify(input) {\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null\n try {\n const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: controller?.signal,\n body: JSON.stringify({\n source: 'form',\n subject: `Novo lead: ${input.leadName} — ${input.formName}`,\n payload: buildPayload(input),\n metadata: { formId: input.formId, formName: input.formName, ...input.attribution },\n }),\n })\n if (!res.ok) {\n throw new Error(`inbox responded ${res.status}`)\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n },\n }\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'\nimport { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types'\n\ninterface PublicFormsContextValue {\n forms: Map<string, PublicFormDef>\n submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>\n}\n\nconst PublicFormsContext = createContext<PublicFormsContextValue | null>(null)\n\nexport interface PublicFormsProviderProps extends PublicFormsContextValue {\n children: ReactNode\n}\n\nexport function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {\n const value = useMemo(() => ({ forms, submit }), [forms, submit])\n return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>\n}\n\n/** The hook a site's own form component calls. Owns only the submission\n * lifecycle — the markup, the fields and the validation copy stay the site's. */\nexport function useLeadForm(formId: string) {\n const ctx = useContext(PublicFormsContext)\n if (!ctx) {\n throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')\n }\n\n const [submitting, setSubmitting] = useState(false)\n const [error, setError] = useState<LeadSubmitError | null>(null)\n const [result, setResult] = useState<LeadSubmitResult | null>(null)\n\n const submit = useCallback(\n async (values: LeadFields): Promise<LeadSubmitResult | null> => {\n if (submitting) return null\n setSubmitting(true)\n setError(null)\n try {\n const res = await ctx.submit(formId, values)\n setResult(res)\n return res\n } catch (err) {\n const e =\n err instanceof LeadSubmitError\n ? err\n : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')\n setError(e)\n return null\n } finally {\n setSubmitting(false)\n }\n },\n [ctx, formId, submitting],\n )\n\n const reset = useCallback(() => {\n setError(null)\n setResult(null)\n }, [])\n\n return {\n submit,\n reset,\n submitting,\n error,\n result,\n success: result !== null,\n form: ctx.forms.get(formId) ?? null,\n }\n}\n","// ---------------------------------------------------------------------------\n// Public forms plugin — \"the site collects, the SDK decides where it goes\".\n//\n// Headless on purpose. Marketing sites have bespoke, brand-heavy forms; taking\n// over their markup would be a downgrade. So this ships no UI: a site keeps its\n// own inputs and calls submit() with a plain object of values.\n//\n// Every submission fans out to two places, in this order:\n// 1. the tenant's CRM (create_public_lead) — the record of truth\n// 2. the Fayz project inbox — so the site owner is told, and gets the email\n// Step 2 is best-effort: a notification outage must never cost a lead.\n// ---------------------------------------------------------------------------\n\nimport { createElement, type FC, type ReactNode } from 'react'\nimport type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'\nimport { createSupabasePublicLeadProvider } from './data.supabase'\nimport { createFayzInboxNotifier } from './inbox'\nimport { PublicFormsProvider } from './context'\nimport {\n LeadSubmitError,\n type LeadAttribution,\n type LeadFields,\n type LeadNotifier,\n type LeadSubmitResult,\n type PublicFormDef,\n type PublicLeadDataProvider,\n} from './types'\n\nexport interface PublicFormsOptions {\n /**\n * Tenant the leads land in. REQUIRED — this is the whole point of the\n * abstraction: the site never names a table, only a tenant.\n */\n tenantId: string\n /** The forms this site exposes, keyed by id. */\n forms: PublicFormDef[]\n /**\n * Notify the site owner in the Fayz project inbox. Default true; resolves the\n * project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.\n */\n inbox?: boolean | { projectId?: string; apiBaseUrl?: string }\n /** Inject a custom transport (tests, or a non-Supabase backend). */\n dataProvider?: PublicLeadDataProvider\n /** Inject a custom notifier (tests). */\n notifier?: LeadNotifier\n scope?: PluginScope\n verticalId?: VerticalId\n}\n\nexport interface PublicFormsPlugin {\n manifest: PluginManifest\n Provider: FC<{ children: ReactNode }>\n /** Imperative submit, for code paths outside React. */\n submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>\n}\n\n/** Reads UTM + page context off the browser. Safe to call during SSR. */\nexport function readAttribution(): LeadAttribution {\n if (typeof window === 'undefined') return {}\n const params = new URLSearchParams(window.location.search)\n const pick = (k: string) => params.get(k) || undefined\n return {\n utm_source: pick('utm_source'),\n utm_medium: pick('utm_medium'),\n utm_campaign: pick('utm_campaign'),\n utm_term: pick('utm_term'),\n utm_content: pick('utm_content'),\n landing_page: window.location.pathname,\n referrer: document.referrer || undefined,\n }\n}\n\nfunction isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T\n}\n\nexport function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {\n const { tenantId } = options\n const formsById = new Map(options.forms.map((f) => [f.id, f]))\n\n const provider: PublicLeadDataProvider =\n options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })\n\n const notifier: LeadNotifier | null =\n options.notifier ??\n (options.inbox === false\n ? null\n : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))\n\n async function submit(formId: string, values: LeadFields): Promise<LeadSubmitResult> {\n const form = formsById.get(formId)\n if (!form) {\n throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form \"${formId}\".`)\n }\n\n // Identity fields are pulled OUT of the bag; whatever remains is custom.\n const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }\n const name = String(values[idMap.name] ?? '').trim()\n const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''\n const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''\n const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''\n\n for (const key of form.required ?? []) {\n if (isEmpty(values[key])) {\n throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)\n }\n }\n if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')\n if (!phone && !email) {\n throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')\n }\n\n const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])\n const fields: LeadFields = Object.fromEntries(\n Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),\n )\n\n const attribution = readAttribution()\n\n // 1. CRM — if this throws, the submission failed and the site says so.\n const { leadId, createdAt } = await provider.createLead(\n stripUndefined({\n formId: form.id,\n formName: form.name,\n name,\n phone: phone || undefined,\n email: email || undefined,\n notes: notes || undefined,\n fields,\n attribution,\n }),\n )\n\n // 2. Inbox — the lead is already safe; never fail the form over a notice.\n let notified = false\n if (notifier) {\n try {\n await notifier.notify({\n formId: form.id,\n formName: form.name,\n leadName: name,\n phone: phone || undefined,\n email: email || undefined,\n fields,\n labels: form.labels,\n attribution,\n })\n notified = true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)\n }\n }\n }\n\n return { leadId, createdAt, notified }\n }\n\n const Provider: FC<{ children: ReactNode }> = ({ children }) =>\n createElement(PublicFormsProvider, { forms: formsById, submit, children })\n Provider.displayName = 'PublicFormsProvider'\n\n const manifest: PluginManifest = {\n id: 'public-forms',\n name: 'Formulários',\n icon: 'Inbox',\n version: '0.1.0',\n scope: options.scope ?? 'universal',\n verticalId: options.verticalId,\n scaffolds: ['website', 'landing_page'],\n defaultEnabled: true,\n dependencies: [],\n // Headless: the site owns the markup, so this plugin mounts no route and\n // contributes no navigation. It exists to be registered and provide context.\n navigation: [],\n routes: [],\n widgets: [],\n }\n\n return { manifest, Provider, submit }\n}\n"]}
1
+ {"version":3,"sources":["../../src/public/types.ts","../../src/public/data.supabase.ts","../../src/public/inbox.ts","../../src/public/context.tsx","../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":";;;;;;;AA2FO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;;;ACzEA,SAAS,SAAA,GAAuC;AAC9C,EAAA,OAAO,yBAAA,EAA0B;AACnC;AAGA,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,CAAA,GAAI,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EAAQ,QAAA,EAAU,CAAA;AAC3E,EAAA,QAAA,CAAS,WAAA,GAAc,qBAAA;AAEvB,EAAA,MAAM,QAAA,GAA2B;AAAA,IAC/B,EAAA,EAAI,cAAA;AAAA,IACJ,IAAA,EAAM,gBAAA;AAAA,IACN,IAAA,EAAM,OAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,KAAA,EAAO,QAAQ,KAAA,IAAS,WAAA;AAAA,IACxB,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,SAAA,EAAW,CAAC,SAAA,EAAW,cAAc,CAAA;AAAA,IACrC,cAAA,EAAgB,IAAA;AAAA,IAChB,cAAc,EAAC;AAAA;AAAA;AAAA,IAGf,YAAY,EAAC;AAAA,IACb,QAAQ,EAAC;AAAA,IACT,SAAS;AAAC,GACZ;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,EAAO;AACtC","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Public lead capture — types\n//\n// The contract between a marketing site's own form UI and the CRM. Sites keep\n// their bespoke layout and copy; all they hand over is a bag of values. Where\n// that lands (which tenant, which table, what status) is decided by the SDK and\n// the RPC behind it, never by the site.\n// ---------------------------------------------------------------------------\n\n/** What a form field may carry. Scalars and scalar lists — anything a checkbox\n * group, a select or a text input produces. Files are out of scope: a lead\n * form links to an upload, it does not embed one. */\nexport type LeadFieldValue = string | number | boolean | null | string[] | number[]\n\n/** The values a site collects, keyed by field id. Free-form on purpose: a new\n * landing page adds keys without touching the schema. */\nexport type LeadFields = Record<string, LeadFieldValue>\n\n/**\n * One form the site exposes. Registered up-front so submissions carry a stable\n * id (attribution) and a human name (what the operator reads in the CRM).\n */\nexport interface PublicFormDef {\n /** Stable id — the attribution key. Keep it stable across redesigns. */\n id: string\n /** Human name shown as the lead's source in the CRM. */\n name: string\n /**\n * Field ids that must be present and non-empty for the submission to be\n * attempted. Contact reachability (phone or email) is enforced server-side\n * regardless of what is declared here.\n */\n required?: string[]\n /**\n * Maps this form's field ids onto the lead's identity columns. Everything NOT\n * mapped stays in `fields` as a custom field.\n *\n * Defaults to { name: 'name', phone: 'phone', email: 'email' }.\n */\n identity?: {\n name?: string\n phone?: string\n email?: string\n /** Field whose value becomes the lead's free-text note. */\n notes?: string\n }\n /** Labels for custom fields, so the CRM shows \"Faixa etária\" not \"age_range\". */\n labels?: Record<string, string>\n /**\n * Tags every lead from this form carries into the CRM, and from there onto\n * the card no funil (o trigger de lead→deal copia).\n *\n * Isto é o vocabulário CURADO: o que a landing page É (\"aluno-novo\",\n * \"parceria\"), não de qual campanha veio. Escreva em slug; o servidor\n * normaliza de qualquer jeito (minúscula, sem acento, hifenizado) e descarta\n * o que não der para normalizar em vez de derrubar o envio.\n *\n * Máximo de 10 tags por lead, somando estas e as automáticas.\n */\n tags?: string[]\n}\n\n/**\n * O que a PÁGINA decide na hora do envio, e o formulário não sabe de antemão.\n *\n * Existe porque uma landing page costuma ter mais de uma porta de entrada para\n * o mesmo formulário (a home e uma campanha específica levam ao mesmo\n * `/quero-ser-aluno`). Sem isto, distinguir as duas exigiria declarar um\n * formulário por porta, e cada um vira uma \"origem\" diferente no CRM para o que\n * é o mesmo formulário.\n */\nexport interface LeadSubmitOptions {\n /** Somadas às `tags` do formulário e às automáticas da campanha. */\n tags?: string[]\n}\n\n/** Result of a submission — enough for the site to show its own success state. */\nexport interface LeadSubmitResult {\n leadId: string\n createdAt: string\n /** False when the CRM write succeeded but the inbox notification did not. */\n notified: boolean\n}\n\n/** Thrown for problems the site should surface differently than a crash. */\nexport type LeadSubmitErrorKind =\n | 'validation' // missing required field / no contact channel\n | 'duplicate' // same contact, same form, seconds apart\n | 'rate_limited' // burst cap tripped\n | 'unavailable' // backend not configured or unreachable\n\nexport class LeadSubmitError extends Error {\n readonly kind: LeadSubmitErrorKind\n constructor(kind: LeadSubmitErrorKind, message: string) {\n super(message)\n this.name = 'LeadSubmitError'\n this.kind = kind\n }\n}\n\n/** UTM/attribution captured from the browser, merged into every submission. */\nexport interface LeadAttribution {\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n utm_term?: string\n utm_content?: string\n /** Path the form was submitted from. */\n landing_page?: string\n referrer?: string\n}\n\n/** The transport a submission goes through. Swappable for tests. */\nexport interface PublicLeadDataProvider {\n createLead(input: {\n formId: string\n formName: string\n name: string\n phone?: string\n email?: string\n notes?: string\n fields: LeadFields\n attribution: LeadAttribution\n /** Slugs já resolvidos (curados do formulário + automáticos da campanha). */\n tags?: string[]\n }): Promise<{ leadId: string; createdAt: string }>\n}\n\n/** Notifies the site's admin that a lead arrived. */\nexport interface LeadNotifier {\n notify(input: {\n formId: string\n formName: string\n leadName: string\n phone?: string\n email?: string\n fields: LeadFields\n labels?: Record<string, string>\n attribution: LeadAttribution\n }): Promise<void>\n}\n","// ---------------------------------------------------------------------------\n// Supabase implementation of PublicLeadDataProvider — anon-safe.\n//\n// Public marketing pages run with the publishable (anon) key and NO user\n// session, so canonical tenant RLS yields nothing. This provider touches only\n// the one object designed for anon access:\n// - public.create_public_lead (SECURITY DEFINER RPC: validates, caps spam,\n// writes people[kind=lead] with the custom fields in metadata)\n// Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.\n//\n// The RPC never reads back — a form writes, it does not query the CRM.\n// ---------------------------------------------------------------------------\n\nimport { getSupabaseClientOptional } from '@fayz-ai/core'\nimport { LeadSubmitError, type PublicLeadDataProvider } from './types'\n\nexport interface SupabasePublicLeadOptions {\n /** The tenant leads land in (RPC arg — required). */\n tenantId: string\n}\n\ninterface SupabaseLikeClient {\n rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>\n}\n\nfunction getClient(): SupabaseLikeClient | null {\n return getSupabaseClientOptional() as SupabaseLikeClient | null\n}\n\n/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */\nfunction toSubmitError(message: string): LeadSubmitError {\n const m = message.toLowerCase()\n if (m.includes('duplicate submission')) {\n return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')\n }\n if (m.includes('too many submissions')) {\n return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')\n }\n if (\n m.includes('invalid') ||\n m.includes('required') ||\n m.includes('too many fields') ||\n m.includes('fields too large')\n ) {\n return new LeadSubmitError('validation', message)\n }\n return new LeadSubmitError('unavailable', message)\n}\n\nexport function createSupabasePublicLeadProvider(\n options: SupabasePublicLeadOptions,\n): PublicLeadDataProvider {\n const { tenantId } = options\n\n return {\n async createLead(input) {\n const client = getClient()\n if (!client) {\n throw new LeadSubmitError(\n 'unavailable',\n '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',\n )\n }\n\n const { data, error } = await client.rpc('create_public_lead', {\n p_tenant_id: tenantId,\n p_name: input.name,\n p_phone: input.phone ?? null,\n p_email: input.email ?? null,\n p_form_id: input.formId,\n p_form_name: input.formName,\n p_fields: input.fields,\n p_notes: input.notes ?? null,\n p_utm: input.attribution,\n p_tags: input.tags ?? [],\n })\n\n if (error) throw toSubmitError(error.message)\n\n const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined\n if (!row?.lead_id) {\n throw new LeadSubmitError('unavailable', 'Lead não foi criado.')\n }\n return { leadId: String(row.lead_id), createdAt: String(row.created_at) }\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Fayz inbox notifier — tells the site's owner a lead just arrived.\n//\n// The Fayz platform already ships a public ingest endpoint built for exactly\n// this (\"Deployed user-sites POST here\"): it stores an InboxRecord against the\n// project and emails the project owner. We only have to speak to it.\n//\n// POST <base>/public/projects/:projectId/inbox\n// { source, subject, payload, metadata }\n//\n// SAME-ORIGIN BY DEFAULT. In production the API's CORS allowlist is a single\n// origin (the editor), so a cross-origin POST from a published site would be\n// refused at preflight. Fayz's Caddy proxies `/api/*` to the API \"regardless of\n// host\", so a published site — custom domain included — reaches it same-origin\n// with no preflight at all. Hence the default base '/api' (relative). Only pass\n// an absolute base when the site is NOT served by Fayz, and expect to widen\n// CORS on the API before it works.\n//\n// Best-effort by contract: the lead is already safe in the CRM by the time this\n// runs. A failed notification is logged and swallowed — never a failed form.\n// ---------------------------------------------------------------------------\n\nimport type { LeadNotifier, LeadFields } from './types'\n\nexport interface FayzInboxNotifierOptions {\n /**\n * Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;\n * omit to read that env var automatically.\n */\n projectId?: string\n /**\n * API base. Defaults to '/api' (same-origin via Caddy) — see the note above\n * before changing it.\n */\n apiBaseUrl?: string\n /** Milliseconds before giving up. The visitor is waiting; keep it short. */\n timeoutMs?: number\n}\n\nfunction readEnv(key: string): string | undefined {\n try {\n const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env\n return env?.[key]\n } catch {\n return undefined\n }\n}\n\n/** \"age_range\" → \"Age range\", unless the form gave us a real label. */\nfunction humanize(key: string, labels?: Record<string, string>): string {\n if (labels?.[key]) return labels[key]\n const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\nfunction renderValue(value: unknown): string {\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value)) return value.length ? value.join(', ') : '—'\n if (typeof value === 'boolean') return value ? 'Sim' : 'Não'\n return String(value)\n}\n\n/**\n * Builds the flat, already-humanized payload the inbox renders. The editor\n * shows this verbatim, so it must read like a message — not like a database row.\n */\nfunction buildPayload(\n input: Parameters<LeadNotifier['notify']>[0],\n): Record<string, string> {\n const payload: Record<string, string> = { Nome: input.leadName }\n if (input.phone) payload['Telefone'] = input.phone\n if (input.email) payload['E-mail'] = input.email\n\n for (const [key, value] of Object.entries(input.fields as LeadFields)) {\n payload[humanize(key, input.labels)] = renderValue(value)\n }\n\n const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution\n if (utm_source) payload['Origem'] = utm_source\n if (utm_medium) payload['Mídia'] = utm_medium\n if (utm_campaign) payload['Campanha'] = utm_campaign\n if (landing_page) payload['Página'] = landing_page\n\n return payload\n}\n\n/**\n * A notifier that posts to the Fayz project inbox. Returns a no-op notifier\n * (with one loud warning) when no project id is resolvable, so a site running\n * outside Fayz still submits leads normally.\n */\nexport function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {\n const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')\n const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\\/$/, '')\n const timeoutMs = options.timeoutMs ?? 4000\n\n if (!projectId) {\n let warned = false\n return {\n async notify() {\n if (!warned && typeof console !== 'undefined') {\n warned = true\n console.warn(\n '[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +\n 'site owner is NOT notified in the Fayz inbox.',\n )\n }\n },\n }\n }\n\n return {\n async notify(input) {\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null\n try {\n const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: controller?.signal,\n body: JSON.stringify({\n source: 'form',\n subject: `Novo lead: ${input.leadName} — ${input.formName}`,\n payload: buildPayload(input),\n metadata: { formId: input.formId, formName: input.formName, ...input.attribution },\n }),\n })\n if (!res.ok) {\n throw new Error(`inbox responded ${res.status}`)\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n },\n }\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'\nimport { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types'\n\ninterface PublicFormsContextValue {\n forms: Map<string, PublicFormDef>\n submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>\n}\n\nconst PublicFormsContext = createContext<PublicFormsContextValue | null>(null)\n\nexport interface PublicFormsProviderProps extends PublicFormsContextValue {\n children: ReactNode\n}\n\nexport function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {\n const value = useMemo(() => ({ forms, submit }), [forms, submit])\n return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>\n}\n\n/** The hook a site's own form component calls. Owns only the submission\n * lifecycle — the markup, the fields and the validation copy stay the site's. */\nexport function useLeadForm(formId: string) {\n const ctx = useContext(PublicFormsContext)\n if (!ctx) {\n throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')\n }\n\n const [submitting, setSubmitting] = useState(false)\n const [error, setError] = useState<LeadSubmitError | null>(null)\n const [result, setResult] = useState<LeadSubmitResult | null>(null)\n\n const submit = useCallback(\n async (values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult | null> => {\n if (submitting) return null\n setSubmitting(true)\n setError(null)\n try {\n const res = await ctx.submit(formId, values, options)\n setResult(res)\n return res\n } catch (err) {\n const e =\n err instanceof LeadSubmitError\n ? err\n : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')\n setError(e)\n return null\n } finally {\n setSubmitting(false)\n }\n },\n [ctx, formId, submitting],\n )\n\n const reset = useCallback(() => {\n setError(null)\n setResult(null)\n }, [])\n\n return {\n submit,\n reset,\n submitting,\n error,\n result,\n success: result !== null,\n form: ctx.forms.get(formId) ?? null,\n }\n}\n","// ---------------------------------------------------------------------------\n// Public forms plugin — \"the site collects, the SDK decides where it goes\".\n//\n// Headless on purpose. Marketing sites have bespoke, brand-heavy forms; taking\n// over their markup would be a downgrade. So this ships no UI: a site keeps its\n// own inputs and calls submit() with a plain object of values.\n//\n// Every submission fans out to two places, in this order:\n// 1. the tenant's CRM (create_public_lead) — the record of truth\n// 2. the Fayz project inbox — so the site owner is told, and gets the email\n// Step 2 is best-effort: a notification outage must never cost a lead.\n// ---------------------------------------------------------------------------\n\nimport { createElement, type FC, type ReactNode } from 'react'\nimport type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'\nimport { createSupabasePublicLeadProvider } from './data.supabase'\nimport { createFayzInboxNotifier } from './inbox'\nimport { PublicFormsProvider } from './context'\nimport {\n LeadSubmitError,\n type LeadAttribution,\n type LeadFields,\n type LeadNotifier,\n type LeadSubmitOptions,\n type LeadSubmitResult,\n type PublicFormDef,\n type PublicLeadDataProvider,\n} from './types'\n\nexport interface PublicFormsOptions {\n /**\n * Tenant the leads land in. REQUIRED — this is the whole point of the\n * abstraction: the site never names a table, only a tenant.\n */\n tenantId: string\n /** The forms this site exposes, keyed by id. */\n forms: PublicFormDef[]\n /**\n * Notify the site owner in the Fayz project inbox. Default true; resolves the\n * project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.\n */\n inbox?: boolean | { projectId?: string; apiBaseUrl?: string }\n /** Inject a custom transport (tests, or a non-Supabase backend). */\n dataProvider?: PublicLeadDataProvider\n /** Inject a custom notifier (tests). */\n notifier?: LeadNotifier\n /**\n * Marca o lead com a campanha que o trouxe, lendo a UTM da URL.\n *\n * Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag\n * automática e tag curada convivem no mesmo array, e sem prefixo a primeira\n * engole a segunda — em seis meses ninguém sabe mais quais tags alguém\n * escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,\n * relatar e limpar cada grupo separadamente.\n *\n * `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica\n * desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.\n */\n campaignTags?: boolean | { campaign?: boolean; source?: boolean }\n scope?: PluginScope\n verticalId?: VerticalId\n}\n\n/** Teto por lead — o mesmo que o RPC aplica; aparar aqui evita mandar lixo. */\nconst MAX_TAGS = 10\n\n/**\n * Slug normalizado. O servidor normaliza de novo (é ele quem manda), mas fazer\n * aqui também mantém `camp:` legível e evita gastar as 10 vagas com duplicata.\n */\nfunction slugify(input: string): string {\n return input\n .normalize('NFD')\n // Marcas combinantes: o NFD separa o acento da letra, e este range remove\n // só o acento. Escapado em vez de literal — o caractere cru é invisível no\n // editor e some em qualquer copy-paste.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9:]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\n/** Tags curadas do formulário + as automáticas da campanha, deduplicadas. */\nfunction resolveTags(\n formTags: string[] | undefined,\n callTags: string[] | undefined,\n attribution: LeadAttribution,\n campaignTags: PublicFormsOptions['campaignTags'],\n): string[] {\n const cfg =\n campaignTags === false\n ? { campaign: false, source: false }\n : campaignTags === true || campaignTags === undefined\n ? { campaign: true, source: false }\n : { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false }\n\n const out: string[] = []\n for (const raw of [...(formTags ?? []), ...(callTags ?? [])]) {\n const slug = slugify(raw)\n if (slug) out.push(slug)\n }\n if (cfg.campaign && attribution.utm_campaign) {\n const slug = slugify(attribution.utm_campaign)\n if (slug) out.push(`camp:${slug}`)\n }\n if (cfg.source && attribution.utm_source) {\n const slug = slugify(attribution.utm_source)\n if (slug) out.push(`src:${slug}`)\n }\n return [...new Set(out)].slice(0, MAX_TAGS)\n}\n\nexport interface PublicFormsPlugin {\n manifest: PluginManifest\n Provider: FC<{ children: ReactNode }>\n /** Imperative submit, for code paths outside React. */\n submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>\n}\n\n/** Reads UTM + page context off the browser. Safe to call during SSR. */\nexport function readAttribution(): LeadAttribution {\n if (typeof window === 'undefined') return {}\n const params = new URLSearchParams(window.location.search)\n const pick = (k: string) => params.get(k) || undefined\n return {\n utm_source: pick('utm_source'),\n utm_medium: pick('utm_medium'),\n utm_campaign: pick('utm_campaign'),\n utm_term: pick('utm_term'),\n utm_content: pick('utm_content'),\n landing_page: window.location.pathname,\n referrer: document.referrer || undefined,\n }\n}\n\nfunction isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T\n}\n\nexport function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {\n const { tenantId } = options\n const formsById = new Map(options.forms.map((f) => [f.id, f]))\n\n const provider: PublicLeadDataProvider =\n options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })\n\n const notifier: LeadNotifier | null =\n options.notifier ??\n (options.inbox === false\n ? null\n : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))\n\n async function submit(\n formId: string,\n values: LeadFields,\n submitOptions?: LeadSubmitOptions,\n ): Promise<LeadSubmitResult> {\n const form = formsById.get(formId)\n if (!form) {\n throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form \"${formId}\".`)\n }\n\n // Identity fields are pulled OUT of the bag; whatever remains is custom.\n const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }\n const name = String(values[idMap.name] ?? '').trim()\n const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''\n const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''\n const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''\n\n for (const key of form.required ?? []) {\n if (isEmpty(values[key])) {\n throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)\n }\n }\n if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')\n if (!phone && !email) {\n throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')\n }\n\n const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])\n const fields: LeadFields = Object.fromEntries(\n Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),\n )\n\n const attribution = readAttribution()\n const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags)\n\n // 1. CRM — if this throws, the submission failed and the site says so.\n const { leadId, createdAt } = await provider.createLead(\n stripUndefined({\n formId: form.id,\n formName: form.name,\n name,\n phone: phone || undefined,\n email: email || undefined,\n notes: notes || undefined,\n fields,\n attribution,\n tags: tags.length ? tags : undefined,\n }),\n )\n\n // 2. Inbox — the lead is already safe; never fail the form over a notice.\n let notified = false\n if (notifier) {\n try {\n await notifier.notify({\n formId: form.id,\n formName: form.name,\n leadName: name,\n phone: phone || undefined,\n email: email || undefined,\n fields,\n labels: form.labels,\n attribution,\n })\n notified = true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)\n }\n }\n }\n\n return { leadId, createdAt, notified }\n }\n\n const Provider: FC<{ children: ReactNode }> = ({ children }) =>\n createElement(PublicFormsProvider, { forms: formsById, submit, children })\n Provider.displayName = 'PublicFormsProvider'\n\n const manifest: PluginManifest = {\n id: 'public-forms',\n name: 'Formulários',\n icon: 'Inbox',\n version: '0.1.0',\n scope: options.scope ?? 'universal',\n verticalId: options.verticalId,\n scaffolds: ['website', 'landing_page'],\n defaultEnabled: true,\n dependencies: [],\n // Headless: the site owns the markup, so this plugin mounts no route and\n // contributes no navigation. It exists to be registered and provide context.\n navigation: [],\n routes: [],\n widgets: [],\n }\n\n return { manifest, Provider, submit }\n}\n"]}