@fayz-ai/plugin-crm 0.8.1 → 0.8.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cascade.d.ts.map +1 -1
- package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
- package/dist/data/mock.d.ts +5 -0
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/supabase.d.ts +6 -0
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/types.d.ts +9 -1
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.cjs +698 -103
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +701 -106
- package/dist/index.js.map +1 -1
- package/dist/lib/access.d.ts +8 -0
- package/dist/lib/access.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +5 -1
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/index.cjs +1 -1
- package/dist/public/index.cjs.map +1 -1
- package/dist/public/index.js +2 -2
- package/dist/public/index.js.map +1 -1
- package/dist/registries.d.ts +11 -0
- package/dist/registries.d.ts.map +1 -1
- package/dist/store.d.ts +5 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +14 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/views/ActivityListView.d.ts +6 -1
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadDetailView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteDetailView.d.ts.map +1 -1
- package/dist/views/QuoteListView.d.ts.map +1 -1
- package/package.json +5 -5
- package/src/CrmPage.tsx +1 -1
- package/src/cascade.ts +2 -0
- package/src/components/QuoteStatusDropdown.tsx +15 -3
- package/src/data/mock.ts +110 -4
- package/src/data/supabase.ts +186 -8
- package/src/data/types.ts +9 -1
- package/src/index.ts +85 -3
- package/src/lib/access.ts +11 -0
- package/src/locales/en.ts +4 -0
- package/src/locales/pt-BR.ts +9 -5
- package/src/migrations/003_crm_views_rls.sql +10 -2
- package/src/migrations/007_activity_log.sql +55 -0
- package/src/migrations/008_view_field_aliases.sql +43 -0
- package/src/migrations/009_deal_archived_status.sql +30 -0
- package/src/migrations/010_quote_archived_status.sql +40 -0
- package/src/migrations/index.ts +191 -3
- package/src/public/data.supabase.ts +2 -2
- package/src/registries.ts +32 -8
- package/src/store.ts +76 -0
- package/src/types.ts +19 -2
- package/src/views/ActivityListView.tsx +79 -11
- package/src/views/DealSidebar.tsx +39 -33
- package/src/views/LeadDetailView.tsx +29 -10
- package/src/views/PipelineView.tsx +22 -4
- package/src/views/QuoteDetailView.tsx +7 -3
- package/src/views/QuoteListView.tsx +26 -12
|
@@ -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"}
|
package/dist/locales/en.d.ts.map
CHANGED
|
@@ -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,
|
|
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,CAuSrC,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,
|
|
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,CAuSvC,CAAA"}
|
|
@@ -1,10 +1,14 @@
|
|
|
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')\
|
|
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";
|
|
8
12
|
export declare const MIGRATIONS: Array<{
|
|
9
13
|
id: string;
|
|
10
14
|
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,
|
|
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,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAYzD,CAAA"}
|
package/dist/public/index.cjs
CHANGED
|
@@ -17,7 +17,7 @@ var LeadSubmitError = class extends Error {
|
|
|
17
17
|
|
|
18
18
|
// src/public/data.supabase.ts
|
|
19
19
|
function getClient() {
|
|
20
|
-
return core.getSupabaseClientOptional()
|
|
20
|
+
return core.getSupabaseClientOptional();
|
|
21
21
|
}
|
|
22
22
|
function toSubmitError(message) {
|
|
23
23
|
const m = message.toLowerCase();
|
|
@@ -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":["getSupabaseClientOptional","getFayzCloudClient","createContext","useMemo","jsx","use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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.cjs","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":["getSupabaseClientOptional","createContext","useMemo","jsx","useContext","useState","useCallback","createElement"],"mappings":";;;;;;;;;AAiEO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CA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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.cjs","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 { 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 })\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"]}
|
package/dist/public/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createContext, useMemo, useContext, useState, useCallback, createElement } from 'react';
|
|
2
|
-
import { getSupabaseClientOptional
|
|
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()
|
|
18
|
+
return getSupabaseClientOptional();
|
|
19
19
|
}
|
|
20
20
|
function toSubmitError(message) {
|
|
21
21
|
const m = message.toLowerCase();
|
package/dist/public/index.js.map
CHANGED
|
@@ -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,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;;;AC/CA,SAAS,SAAA,GAAuC;AAC9C,EAAA,OAAQ,yBAAA,MAA+B,kBAAA,EAAmB;AAC5D;AAGA,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,CAAE,QAAA,CAAS,sBAAsB,CAAA,EAAG;AACtC,IAAA,OAAO,IAAI,eAAA,CAAgB,WAAA,EAAa,wCAAqC,CAAA;AAAA,EAC/E;AACA,EAAA,IAAI,CAAA,CAAE,QAAA,CAAS,sBAAsB,CAAA,EAAG;AACtC,IAAA,OAAO,IAAI,eAAA,CAAgB,cAAA,EAAgB,sDAAmD,CAAA;AAAA,EAChG;AACA,EAAA,IACE,CAAA,CAAE,QAAA,CAAS,SAAS,CAAA,IACpB,EAAE,QAAA,CAAS,UAAU,CAAA,IACrB,CAAA,CAAE,SAAS,iBAAiB,CAAA,IAC5B,CAAA,CAAE,QAAA,CAAS,kBAAkB,CAAA,EAC7B;AACA,IAAA,OAAO,IAAI,eAAA,CAAgB,YAAA,EAAc,OAAO,CAAA;AAAA,EAClD;AACA,EAAA,OAAO,IAAI,eAAA,CAAgB,aAAA,EAAe,OAAO,CAAA;AACnD;AAEO,SAAS,iCACd,OAAA,EACwB;AACxB,EAAA,MAAM,EAAE,UAAS,GAAI,OAAA;AAErB,EAAA,OAAO;AAAA,IACL,MAAM,WAAW,KAAA,EAAO;AACtB,MA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,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\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":";;;;;;;AAiEO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAA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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 { 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 })\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"]}
|
package/dist/registries.d.ts
CHANGED
|
@@ -1,3 +1,14 @@
|
|
|
1
1
|
import type { PluginRegistryDef } from '@fayz-ai/core';
|
|
2
|
+
export declare const DEFAULT_ACTIVITY_TYPES: Array<{
|
|
3
|
+
value: string;
|
|
4
|
+
label: string;
|
|
5
|
+
icon?: string;
|
|
6
|
+
}>;
|
|
2
7
|
export declare const crmRegistries: PluginRegistryDef[];
|
|
8
|
+
/** Registries with the app's activity-type set replacing the default seed. */
|
|
9
|
+
export declare function buildCrmRegistries(activityTypes?: Array<{
|
|
10
|
+
value: string;
|
|
11
|
+
label: string;
|
|
12
|
+
icon?: string;
|
|
13
|
+
}>): PluginRegistryDef[];
|
|
3
14
|
//# sourceMappingURL=registries.d.ts.map
|
package/dist/registries.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"registries.d.ts","sourceRoot":"","sources":["../src/registries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;
|
|
1
|
+
{"version":3,"file":"registries.d.ts","sourceRoot":"","sources":["../src/registries.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAA;AAsEtD,eAAO,MAAM,sBAAsB,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAOzF,CAAA;AAED,eAAO,MAAM,aAAa,EAAE,iBAAiB,EAwD5C,CAAA;AAED,8EAA8E;AAC9E,wBAAgB,kBAAkB,CAChC,aAAa,CAAC,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC,GACrE,iBAAiB,EAAE,CAYrB"}
|
package/dist/store.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface CrmUIState {
|
|
|
27
27
|
fetchDeals(query: DealQuery): Promise<void>;
|
|
28
28
|
fetchDealsByStage(pipelineId: string): Promise<void>;
|
|
29
29
|
fetchActivities(query: ActivityQuery): Promise<void>;
|
|
30
|
+
/** Re-fetch the timeline with the last query — writes append system events. */
|
|
31
|
+
refreshActivities(): Promise<void>;
|
|
30
32
|
fetchQuotes(query: QuoteQuery): Promise<void>;
|
|
31
33
|
createLead(input: CreateLeadInput): Promise<Lead>;
|
|
32
34
|
createDeal(input: CreateDealInput): Promise<Deal>;
|
|
@@ -38,6 +40,9 @@ export interface CrmUIState {
|
|
|
38
40
|
rejectQuote(id: string, reason: string): Promise<Quote>;
|
|
39
41
|
expireQuote(id: string): Promise<Quote>;
|
|
40
42
|
moveDealToStage(dealId: string, stageId: string): Promise<void>;
|
|
43
|
+
archiveDeal(dealId: string): Promise<void>;
|
|
44
|
+
archiveLead(leadId: string): Promise<void>;
|
|
45
|
+
archiveQuote(quoteId: string): Promise<void>;
|
|
41
46
|
}
|
|
42
47
|
export declare function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>;
|
|
43
48
|
//# sourceMappingURL=store.d.ts.map
|
package/dist/store.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../src/store.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAA;AAG5D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AACnD,OAAO,KAAK,EACV,QAAQ,EAAE,aAAa,EAAE,IAAI,EAAE,IAAI,EAAE,QAAQ,EAAE,KAAK,EACpD,UAAU,EAAE,WAAW,EACvB,SAAS,EAAE,SAAS,EAAE,aAAa,EAAE,UAAU,EAC/C,eAAe,EAAE,eAAe,EAAE,mBAAmB,EAAE,gBAAgB,EACxE,MAAM,SAAS,CAAA;AAEhB,MAAM,WAAW,UAAU;IACzB,SAAS,EAAE,QAAQ,EAAE,CAAA;IACrB,MAAM,EAAE,aAAa,EAAE,CAAA;IACvB,KAAK,EAAE,IAAI,EAAE,CAAA;IACb,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,OAAO,CAAA;IACrB,KAAK,EAAE,IAAI,EAAE,CAAA;IACb,UAAU,EAAE,MAAM,CAAA;IAClB,YAAY,EAAE,OAAO,CAAA;IACrB,YAAY,EAAE,GAAG,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAA;IACjC,UAAU,EAAE,QAAQ,EAAE,CAAA;IACtB,eAAe,EAAE,MAAM,CAAA;IACvB,iBAAiB,EAAE,OAAO,CAAA;IAC1B,MAAM,EAAE,KAAK,EAAE,CAAA;IACf,WAAW,EAAE,MAAM,CAAA;IACnB,aAAa,EAAE,OAAO,CA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AAW,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;IACvD,WAAW,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAA;IACvC,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC/D,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1C,WAAW,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;IAC1C,YAAY,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAC7C;AAED,wBAAgB,cAAc,CAAC,QAAQ,EAAE,eAAe,GAAG,QAAQ,CAAC,UAAU,CAAC,CA0Y9E"}
|
package/dist/types.d.ts
CHANGED
|
@@ -1,7 +1,19 @@
|
|
|
1
1
|
export type LeadStatus = 'new' | 'contacted' | 'qualified' | 'unqualified' | 'converted' | 'lost';
|
|
2
|
-
export type DealStatus = 'open' | 'won' | 'lost';
|
|
3
|
-
export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired';
|
|
2
|
+
export type DealStatus = 'open' | 'won' | 'lost' | 'archived';
|
|
3
|
+
export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired' | 'archived';
|
|
4
4
|
export type ActivityType = 'call' | 'email' | 'meeting' | 'note' | 'task' | 'whatsapp' | (string & {});
|
|
5
|
+
/** System timeline events auto-logged by the data provider at every CRM write.
|
|
6
|
+
* Product-defined (not tenant-editable); manual interaction TYPES live in the
|
|
7
|
+
* activity-types registry and are editable in settings. */
|
|
8
|
+
export declare const SYSTEM_ACTIVITY_TYPES: readonly ["lead_created", "lead_converted", "lead_archived", "deal_created", "stage_changed", "deal_won", "deal_lost", "deal_archived", "quote_created", "quote_sent", "quote_approved", "quote_rejected", "quote_archived"];
|
|
9
|
+
export type SystemActivityType = (typeof SYSTEM_ACTIVITY_TYPES)[number];
|
|
10
|
+
/** A tenant-editable manual interaction type (activity-types registry row). */
|
|
11
|
+
export interface ActivityTypeDef {
|
|
12
|
+
id: string;
|
|
13
|
+
name: string;
|
|
14
|
+
icon?: string;
|
|
15
|
+
isActive: boolean;
|
|
16
|
+
}
|
|
5
17
|
export interface Pipeline {
|
|
6
18
|
id: string;
|
|
7
19
|
name: string;
|