@fayz-ai/plugin-crm 0.8.0 → 0.8.3
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/components/CrmGeneralSettings.d.ts.map +1 -1
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/index.cjs +168 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +169 -34
- package/dist/index.js.map +1 -1
- package/dist/lib/form-answers.d.ts +10 -0
- package/dist/lib/form-answers.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 +2 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/context.d.ts +23 -0
- package/dist/public/context.d.ts.map +1 -0
- package/dist/public/createPublicFormsPlugin.d.ts +38 -0
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
- package/dist/public/data.supabase.d.ts +7 -0
- package/dist/public/data.supabase.d.ts.map +1 -0
- package/dist/public/inbox.d.ts +22 -0
- package/dist/public/inbox.d.ts.map +1 -0
- package/dist/public/index.cjs +306 -0
- package/dist/public/index.cjs.map +1 -0
- package/dist/public/index.d.ts +10 -0
- package/dist/public/index.d.ts.map +1 -0
- package/dist/public/index.js +298 -0
- package/dist/public/index.js.map +1 -0
- package/dist/public/types.d.ts +92 -0
- package/dist/public/types.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadDetailView.d.ts.map +1 -1
- package/dist/views/LeadFormView.d.ts.map +1 -1
- package/dist/views/LeadListView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteFormView.d.ts.map +1 -1
- package/package.json +11 -5
- package/src/components/CrmGeneralSettings.tsx +35 -15
- package/src/data/supabase.ts +47 -4
- package/src/index.ts +9 -0
- package/src/lib/form-answers.tsx +39 -0
- package/src/locales/en.ts +1 -0
- package/src/locales/pt-BR.ts +1 -0
- package/src/migrations/005_public_lead.sql +189 -0
- package/src/migrations/006_lead_enters_pipeline.sql +265 -0
- package/src/migrations/index.ts +461 -1
- package/src/public/context.tsx +69 -0
- package/src/public/createPublicFormsPlugin.ts +188 -0
- package/src/public/data.supabase.ts +86 -0
- package/src/public/inbox.ts +136 -0
- package/src/public/index.ts +30 -0
- package/src/public/types.ts +113 -0
- package/src/views/DealSidebar.tsx +31 -0
- package/src/views/LeadDetailView.tsx +53 -0
- package/src/views/LeadFormView.tsx +10 -0
- package/src/views/LeadListView.tsx +19 -0
- package/src/views/PipelineView.tsx +34 -1
- package/src/views/QuoteFormView.tsx +5 -0
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import React from 'react';
|
|
2
|
+
/** `hair_remaining` / `hairRemaining` → "Hair remaining". Keys that arrive
|
|
3
|
+
* already humanized ("Assunto") come back unchanged. */
|
|
4
|
+
export declare function humanizeKey(key: string): string;
|
|
5
|
+
/** Arrays are joined rather than dropped: a multi-select ("Preocupações") is
|
|
6
|
+
* often the most qualifying answer on the form. */
|
|
7
|
+
export declare function renderFieldValue(value: unknown): React.ReactNode;
|
|
8
|
+
/** Answer entries worth showing, empty values already removed. */
|
|
9
|
+
export declare function answerEntries(fields: unknown): Array<[string, unknown]>;
|
|
10
|
+
//# sourceMappingURL=form-answers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"form-answers.d.ts","sourceRoot":"","sources":["../../src/lib/form-answers.tsx"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAA;AAgBzB;yDACyD;AACzD,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAG/C;AAED;oDACoD;AACpD,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,CAAC,SAAS,CAMhE;AAED,kEAAkE;AAClE,wBAAgB,aAAa,CAAC,MAAM,EAAE,OAAO,GAAG,KAAK,CAAC,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAIvE"}
|
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,CAmSrC,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,CAmSvC,CAAA"}
|
|
@@ -3,6 +3,8 @@ export declare const MIGRATION_001_CRM_BASE = "-- CRM Plugin: Base Tables\n-- Le
|
|
|
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
4
|
export declare const MIGRATION_003_CRM_VIEWS_RLS = "-- CRM plugin \u2014 companion SQL (functions/views/RLS Drizzle doesn't diff).\n-- Tables come from the Drizzle schema (src/schema/); this is everything else the\n-- plugin's data provider depends on: RLS policies + grants + the read-views.\n-- Idempotent. Canonical RLS form: tenant_id IN (SELECT public.user_tenant_ids()).\n\nDO $$\nDECLARE t text;\nBEGIN\n FOR t IN SELECT unnest(ARRAY[\n 'plg_crm_pipelines','plg_crm_pipeline_stages','plg_crm_lead_sources','plg_crm_tags',\n 'plg_crm_deal_extensions','plg_crm_activity_types','plg_crm_activities'\n ])\n LOOP\n EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);\n EXECUTE format('GRANT SELECT, INSERT, UPDATE, DELETE ON public.%I TO authenticated', t);\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_select') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR SELECT TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_select', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_insert') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR INSERT TO authenticated WITH CHECK (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_insert', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_update') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR UPDATE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_update', t);\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_policies WHERE schemaname='public' AND tablename=t AND policyname=t||'_delete') THEN\n EXECUTE format('CREATE POLICY %I ON public.%I FOR DELETE TO authenticated USING (tenant_id IN (SELECT public.user_tenant_ids()))', t||'_delete', t);\n END IF;\n END LOOP;\nEND $$;\n\n-- v_leads: public.people (kind='lead')\nCREATE OR REPLACE VIEW public.v_leads WITH (security_invoker=true) AS\nSELECT\n p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,\n p.metadata->>'company' AS company,\n p.metadata->>'sourceId' AS source_id,\n p.metadata->>'sourceName' AS source_name,\n COALESCE(p.metadata->>'status','new') AS lead_status,\n p.metadata->>'value' AS lead_value,\n p.metadata->>'assignedToId' AS assigned_to_id,\n p.created_at, p.updated_at\nFROM public.people p\nWHERE p.kind = 'lead';\nGRANT SELECT ON public.v_leads TO authenticated;\n\n-- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages\nCREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS\nSELECT\n o.id, o.tenant_id, o.status,\n o.total AS value, o.notes AS title,\n o.party_id AS contact_id, o.assignee_id AS assigned_to_id, o.tags,\n o.metadata->>'contactName' AS contact_name,\n o.created_at, o.updated_at,\n de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,\n de.lead_id, de.lost_reason,\n ps.name AS stage_name, ps.color AS stage_color, ps.\"order\" AS stage_order\nFROM public.orders o\nLEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id\nLEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id\nWHERE o.kind = 'deal';\nGRANT SELECT ON public.v_deals TO authenticated;\n";
|
|
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
|
+
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
|
+
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";
|
|
6
8
|
export declare const MIGRATIONS: Array<{
|
|
7
9
|
id: string;
|
|
8
10
|
sql: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,yyGA6DvC,CAAA;AAED,eAAO,MAAM,mCAAmC,q9CA+B/C,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,yyGA6DvC,CAAA;AAED,eAAO,MAAM,mCAAmC,q9CA+B/C,CAAA;AAED,eAAO,MAAM,yBAAyB,+uOA6LrC,CAAA;AAED,eAAO,MAAM,kCAAkC,g4VAyQ9C,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAQzD,CAAA"}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type ReactNode } from 'react';
|
|
2
|
+
import { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types';
|
|
3
|
+
interface PublicFormsContextValue {
|
|
4
|
+
forms: Map<string, PublicFormDef>;
|
|
5
|
+
submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>;
|
|
6
|
+
}
|
|
7
|
+
export interface PublicFormsProviderProps extends PublicFormsContextValue {
|
|
8
|
+
children: ReactNode;
|
|
9
|
+
}
|
|
10
|
+
export declare function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps): import("react").JSX.Element;
|
|
11
|
+
/** The hook a site's own form component calls. Owns only the submission
|
|
12
|
+
* lifecycle — the markup, the fields and the validation copy stay the site's. */
|
|
13
|
+
export declare function useLeadForm(formId: string): {
|
|
14
|
+
submit: (values: LeadFields) => Promise<LeadSubmitResult | null>;
|
|
15
|
+
reset: () => void;
|
|
16
|
+
submitting: boolean;
|
|
17
|
+
error: LeadSubmitError | null;
|
|
18
|
+
result: LeadSubmitResult | null;
|
|
19
|
+
success: boolean;
|
|
20
|
+
form: PublicFormDef | null;
|
|
21
|
+
};
|
|
22
|
+
export {};
|
|
23
|
+
//# sourceMappingURL=context.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/public/context.tsx"],"names":[],"mappings":"AAAA,OAAO,EAA6D,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AACjG,OAAO,EAAE,eAAe,EAAE,KAAK,UAAU,EAAE,KAAK,gBAAgB,EAAE,KAAK,aAAa,EAAE,MAAM,SAAS,CAAA;AAErG,UAAU,uBAAuB;IAC/B,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IACjC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAA;CAC1E;AAID,MAAM,WAAW,wBAAyB,SAAQ,uBAAuB;IACvE,QAAQ,EAAE,SAAS,CAAA;CACpB;AAED,wBAAgB,mBAAmB,CAAC,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,EAAE,wBAAwB,+BAGxF;AAED;kFACkF;AAClF,wBAAgB,WAAW,CAAC,MAAM,EAAE,MAAM;qBAWvB,UAAU,KAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;;;;;;;EAoC/D"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type FC, type ReactNode } from 'react';
|
|
2
|
+
import type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core';
|
|
3
|
+
import { type LeadAttribution, type LeadFields, type LeadNotifier, type LeadSubmitResult, type PublicFormDef, type PublicLeadDataProvider } from './types';
|
|
4
|
+
export interface PublicFormsOptions {
|
|
5
|
+
/**
|
|
6
|
+
* Tenant the leads land in. REQUIRED — this is the whole point of the
|
|
7
|
+
* abstraction: the site never names a table, only a tenant.
|
|
8
|
+
*/
|
|
9
|
+
tenantId: string;
|
|
10
|
+
/** The forms this site exposes, keyed by id. */
|
|
11
|
+
forms: PublicFormDef[];
|
|
12
|
+
/**
|
|
13
|
+
* Notify the site owner in the Fayz project inbox. Default true; resolves the
|
|
14
|
+
* project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.
|
|
15
|
+
*/
|
|
16
|
+
inbox?: boolean | {
|
|
17
|
+
projectId?: string;
|
|
18
|
+
apiBaseUrl?: string;
|
|
19
|
+
};
|
|
20
|
+
/** Inject a custom transport (tests, or a non-Supabase backend). */
|
|
21
|
+
dataProvider?: PublicLeadDataProvider;
|
|
22
|
+
/** Inject a custom notifier (tests). */
|
|
23
|
+
notifier?: LeadNotifier;
|
|
24
|
+
scope?: PluginScope;
|
|
25
|
+
verticalId?: VerticalId;
|
|
26
|
+
}
|
|
27
|
+
export interface PublicFormsPlugin {
|
|
28
|
+
manifest: PluginManifest;
|
|
29
|
+
Provider: FC<{
|
|
30
|
+
children: ReactNode;
|
|
31
|
+
}>;
|
|
32
|
+
/** Imperative submit, for code paths outside React. */
|
|
33
|
+
submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>;
|
|
34
|
+
}
|
|
35
|
+
/** Reads UTM + page context off the browser. Safe to call during SSR. */
|
|
36
|
+
export declare function readAttribution(): LeadAttribution;
|
|
37
|
+
export declare function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin;
|
|
38
|
+
//# sourceMappingURL=createPublicFormsPlugin.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"createPublicFormsPlugin.d.ts","sourceRoot":"","sources":["../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":"AAaA,OAAO,EAAiB,KAAK,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAI5E,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,sBAAsB,EAC5B,MAAM,SAAS,CAAA;AAEhB,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,KAAK,EAAE,aAAa,EAAE,CAAA;IACtB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7D,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAA;IACrC,wCAAwC;IACxC,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;AAED,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,EAAE,CAAC;QAAE,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAA;IACrC,uDAAuD;IACvD,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACtE;AAED,yEAAyE;AACzE,wBAAgB,eAAe,IAAI,eAAe,CAajD;AAaD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,CAwGtF"}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type PublicLeadDataProvider } from './types';
|
|
2
|
+
export interface SupabasePublicLeadOptions {
|
|
3
|
+
/** The tenant leads land in (RPC arg — required). */
|
|
4
|
+
tenantId: string;
|
|
5
|
+
}
|
|
6
|
+
export declare function createSupabasePublicLeadProvider(options: SupabasePublicLeadOptions): PublicLeadDataProvider;
|
|
7
|
+
//# sourceMappingURL=data.supabase.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"data.supabase.d.ts","sourceRoot":"","sources":["../../src/public/data.supabase.ts"],"names":[],"mappings":"AAcA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAkCxB"}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { LeadNotifier } from './types';
|
|
2
|
+
export interface FayzInboxNotifierOptions {
|
|
3
|
+
/**
|
|
4
|
+
* Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;
|
|
5
|
+
* omit to read that env var automatically.
|
|
6
|
+
*/
|
|
7
|
+
projectId?: string;
|
|
8
|
+
/**
|
|
9
|
+
* API base. Defaults to '/api' (same-origin via Caddy) — see the note above
|
|
10
|
+
* before changing it.
|
|
11
|
+
*/
|
|
12
|
+
apiBaseUrl?: string;
|
|
13
|
+
/** Milliseconds before giving up. The visitor is waiting; keep it short. */
|
|
14
|
+
timeoutMs?: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A notifier that posts to the Fayz project inbox. Returns a no-op notifier
|
|
18
|
+
* (with one loud warning) when no project id is resolvable, so a site running
|
|
19
|
+
* outside Fayz still submits leads normally.
|
|
20
|
+
*/
|
|
21
|
+
export declare function createFayzInboxNotifier(options?: FayzInboxNotifierOptions): LeadNotifier;
|
|
22
|
+
//# sourceMappingURL=inbox.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"inbox.d.ts","sourceRoot":"","sources":["../../src/public/inbox.ts"],"names":[],"mappings":"AAsBA,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,SAAS,CAAA;AAEvD,MAAM,WAAW,wBAAwB;IACvC;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB;;;OAGG;IACH,UAAU,CAAC,EAAE,MAAM,CAAA;IACnB,4EAA4E;IAC5E,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAiDD;;;;GAIG;AACH,wBAAgB,uBAAuB,CAAC,OAAO,GAAE,wBAA6B,GAAG,YAAY,CA4C5F"}
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var react = require('react');
|
|
4
|
+
var core = require('@fayz-ai/core');
|
|
5
|
+
var jsxRuntime = require('react/jsx-runtime');
|
|
6
|
+
|
|
7
|
+
// src/public/createPublicFormsPlugin.ts
|
|
8
|
+
|
|
9
|
+
// src/public/types.ts
|
|
10
|
+
var LeadSubmitError = class extends Error {
|
|
11
|
+
constructor(kind, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "LeadSubmitError";
|
|
14
|
+
this.kind = kind;
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
// src/public/data.supabase.ts
|
|
19
|
+
function getClient() {
|
|
20
|
+
return core.getSupabaseClientOptional() ?? core.getFayzCloudClient();
|
|
21
|
+
}
|
|
22
|
+
function toSubmitError(message) {
|
|
23
|
+
const m = message.toLowerCase();
|
|
24
|
+
if (m.includes("duplicate submission")) {
|
|
25
|
+
return new LeadSubmitError("duplicate", "Recebemos seu contato h\xE1 instantes.");
|
|
26
|
+
}
|
|
27
|
+
if (m.includes("too many submissions")) {
|
|
28
|
+
return new LeadSubmitError("rate_limited", "Muitos envios agora h\xE1 pouco. Tente em instantes.");
|
|
29
|
+
}
|
|
30
|
+
if (m.includes("invalid") || m.includes("required") || m.includes("too many fields") || m.includes("fields too large")) {
|
|
31
|
+
return new LeadSubmitError("validation", message);
|
|
32
|
+
}
|
|
33
|
+
return new LeadSubmitError("unavailable", message);
|
|
34
|
+
}
|
|
35
|
+
function createSupabasePublicLeadProvider(options) {
|
|
36
|
+
const { tenantId } = options;
|
|
37
|
+
return {
|
|
38
|
+
async createLead(input) {
|
|
39
|
+
const client = getClient();
|
|
40
|
+
if (!client) {
|
|
41
|
+
throw new LeadSubmitError(
|
|
42
|
+
"unavailable",
|
|
43
|
+
"[plugin-crm/public] no Supabase client \u2014 register one with setGlobalSupabaseClient."
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
const { data, error } = await client.rpc("create_public_lead", {
|
|
47
|
+
p_tenant_id: tenantId,
|
|
48
|
+
p_name: input.name,
|
|
49
|
+
p_phone: input.phone ?? null,
|
|
50
|
+
p_email: input.email ?? null,
|
|
51
|
+
p_form_id: input.formId,
|
|
52
|
+
p_form_name: input.formName,
|
|
53
|
+
p_fields: input.fields,
|
|
54
|
+
p_notes: input.notes ?? null,
|
|
55
|
+
p_utm: input.attribution
|
|
56
|
+
});
|
|
57
|
+
if (error) throw toSubmitError(error.message);
|
|
58
|
+
const row = Array.isArray(data) ? data[0] : void 0;
|
|
59
|
+
if (!row?.lead_id) {
|
|
60
|
+
throw new LeadSubmitError("unavailable", "Lead n\xE3o foi criado.");
|
|
61
|
+
}
|
|
62
|
+
return { leadId: String(row.lead_id), createdAt: String(row.created_at) };
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// src/public/inbox.ts
|
|
68
|
+
function readEnv(key) {
|
|
69
|
+
try {
|
|
70
|
+
const env = undefined;
|
|
71
|
+
return env?.[key];
|
|
72
|
+
} catch {
|
|
73
|
+
return void 0;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function humanize(key, labels) {
|
|
77
|
+
if (labels?.[key]) return labels[key];
|
|
78
|
+
const spaced = key.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
|
|
79
|
+
return spaced.charAt(0).toUpperCase() + spaced.slice(1);
|
|
80
|
+
}
|
|
81
|
+
function renderValue(value) {
|
|
82
|
+
if (value === null || value === void 0 || value === "") return "\u2014";
|
|
83
|
+
if (Array.isArray(value)) return value.length ? value.join(", ") : "\u2014";
|
|
84
|
+
if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
|
|
85
|
+
return String(value);
|
|
86
|
+
}
|
|
87
|
+
function buildPayload(input) {
|
|
88
|
+
const payload = { Nome: input.leadName };
|
|
89
|
+
if (input.phone) payload["Telefone"] = input.phone;
|
|
90
|
+
if (input.email) payload["E-mail"] = input.email;
|
|
91
|
+
for (const [key, value] of Object.entries(input.fields)) {
|
|
92
|
+
payload[humanize(key, input.labels)] = renderValue(value);
|
|
93
|
+
}
|
|
94
|
+
const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution;
|
|
95
|
+
if (utm_source) payload["Origem"] = utm_source;
|
|
96
|
+
if (utm_medium) payload["M\xEDdia"] = utm_medium;
|
|
97
|
+
if (utm_campaign) payload["Campanha"] = utm_campaign;
|
|
98
|
+
if (landing_page) payload["P\xE1gina"] = landing_page;
|
|
99
|
+
return payload;
|
|
100
|
+
}
|
|
101
|
+
function createFayzInboxNotifier(options = {}) {
|
|
102
|
+
const projectId = options.projectId ?? readEnv("VITE_FAYZ_PROJECT_ID");
|
|
103
|
+
const apiBaseUrl = (options.apiBaseUrl ?? readEnv("VITE_FAYZ_API_BASE_URL") ?? "/api").replace(/\/$/, "");
|
|
104
|
+
const timeoutMs = options.timeoutMs ?? 4e3;
|
|
105
|
+
if (!projectId) {
|
|
106
|
+
let warned = false;
|
|
107
|
+
return {
|
|
108
|
+
async notify() {
|
|
109
|
+
if (!warned && typeof console !== "undefined") {
|
|
110
|
+
warned = true;
|
|
111
|
+
console.warn(
|
|
112
|
+
"[plugin-crm/public] no VITE_FAYZ_PROJECT_ID \u2014 leads are saved to the CRM but the site owner is NOT notified in the Fayz inbox."
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
async notify(input) {
|
|
120
|
+
const controller = typeof AbortController !== "undefined" ? new AbortController() : null;
|
|
121
|
+
const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
|
|
122
|
+
try {
|
|
123
|
+
const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {
|
|
124
|
+
method: "POST",
|
|
125
|
+
headers: { "Content-Type": "application/json" },
|
|
126
|
+
signal: controller?.signal,
|
|
127
|
+
body: JSON.stringify({
|
|
128
|
+
source: "form",
|
|
129
|
+
subject: `Novo lead: ${input.leadName} \u2014 ${input.formName}`,
|
|
130
|
+
payload: buildPayload(input),
|
|
131
|
+
metadata: { formId: input.formId, formName: input.formName, ...input.attribution }
|
|
132
|
+
})
|
|
133
|
+
});
|
|
134
|
+
if (!res.ok) {
|
|
135
|
+
throw new Error(`inbox responded ${res.status}`);
|
|
136
|
+
}
|
|
137
|
+
} finally {
|
|
138
|
+
if (timer) clearTimeout(timer);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
var PublicFormsContext = react.createContext(null);
|
|
144
|
+
function PublicFormsProvider({ forms, submit, children }) {
|
|
145
|
+
const value = react.useMemo(() => ({ forms, submit }), [forms, submit]);
|
|
146
|
+
return /* @__PURE__ */ jsxRuntime.jsx(PublicFormsContext.Provider, { value, children });
|
|
147
|
+
}
|
|
148
|
+
function useLeadForm(formId) {
|
|
149
|
+
const ctx = react.useContext(PublicFormsContext);
|
|
150
|
+
if (!ctx) {
|
|
151
|
+
throw new Error("[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.");
|
|
152
|
+
}
|
|
153
|
+
const [submitting, setSubmitting] = react.useState(false);
|
|
154
|
+
const [error, setError] = react.useState(null);
|
|
155
|
+
const [result, setResult] = react.useState(null);
|
|
156
|
+
const submit = react.useCallback(
|
|
157
|
+
async (values) => {
|
|
158
|
+
if (submitting) return null;
|
|
159
|
+
setSubmitting(true);
|
|
160
|
+
setError(null);
|
|
161
|
+
try {
|
|
162
|
+
const res = await ctx.submit(formId, values);
|
|
163
|
+
setResult(res);
|
|
164
|
+
return res;
|
|
165
|
+
} catch (err) {
|
|
166
|
+
const e = err instanceof LeadSubmitError ? err : new LeadSubmitError("unavailable", err?.message ?? "Falha ao enviar.");
|
|
167
|
+
setError(e);
|
|
168
|
+
return null;
|
|
169
|
+
} finally {
|
|
170
|
+
setSubmitting(false);
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
[ctx, formId, submitting]
|
|
174
|
+
);
|
|
175
|
+
const reset = react.useCallback(() => {
|
|
176
|
+
setError(null);
|
|
177
|
+
setResult(null);
|
|
178
|
+
}, []);
|
|
179
|
+
return {
|
|
180
|
+
submit,
|
|
181
|
+
reset,
|
|
182
|
+
submitting,
|
|
183
|
+
error,
|
|
184
|
+
result,
|
|
185
|
+
success: result !== null,
|
|
186
|
+
form: ctx.forms.get(formId) ?? null
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/public/createPublicFormsPlugin.ts
|
|
191
|
+
function readAttribution() {
|
|
192
|
+
if (typeof window === "undefined") return {};
|
|
193
|
+
const params = new URLSearchParams(window.location.search);
|
|
194
|
+
const pick = (k) => params.get(k) || void 0;
|
|
195
|
+
return {
|
|
196
|
+
utm_source: pick("utm_source"),
|
|
197
|
+
utm_medium: pick("utm_medium"),
|
|
198
|
+
utm_campaign: pick("utm_campaign"),
|
|
199
|
+
utm_term: pick("utm_term"),
|
|
200
|
+
utm_content: pick("utm_content"),
|
|
201
|
+
landing_page: window.location.pathname,
|
|
202
|
+
referrer: document.referrer || void 0
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
function isEmpty(value) {
|
|
206
|
+
if (value === null || value === void 0) return true;
|
|
207
|
+
if (typeof value === "string") return value.trim() === "";
|
|
208
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
209
|
+
return false;
|
|
210
|
+
}
|
|
211
|
+
function stripUndefined(obj) {
|
|
212
|
+
return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
|
|
213
|
+
}
|
|
214
|
+
function createPublicFormsPlugin(options) {
|
|
215
|
+
const { tenantId } = options;
|
|
216
|
+
const formsById = new Map(options.forms.map((f) => [f.id, f]));
|
|
217
|
+
const provider = options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId });
|
|
218
|
+
const notifier = options.notifier ?? (options.inbox === false ? null : createFayzInboxNotifier(typeof options.inbox === "object" ? options.inbox : {}));
|
|
219
|
+
async function submit(formId, values) {
|
|
220
|
+
const form = formsById.get(formId);
|
|
221
|
+
if (!form) {
|
|
222
|
+
throw new LeadSubmitError("validation", `[plugin-crm/public] unknown form "${formId}".`);
|
|
223
|
+
}
|
|
224
|
+
const idMap = { name: "name", phone: "phone", email: "email", ...form.identity };
|
|
225
|
+
const name = String(values[idMap.name] ?? "").trim();
|
|
226
|
+
const phone = idMap.phone ? String(values[idMap.phone] ?? "").trim() : "";
|
|
227
|
+
const email = idMap.email ? String(values[idMap.email] ?? "").trim() : "";
|
|
228
|
+
const notes = idMap.notes ? String(values[idMap.notes] ?? "").trim() : "";
|
|
229
|
+
for (const key of form.required ?? []) {
|
|
230
|
+
if (isEmpty(values[key])) {
|
|
231
|
+
throw new LeadSubmitError("validation", `Campo obrigat\xF3rio: ${form.labels?.[key] ?? key}`);
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
if (!name) throw new LeadSubmitError("validation", "Nome \xE9 obrigat\xF3rio.");
|
|
235
|
+
if (!phone && !email) {
|
|
236
|
+
throw new LeadSubmitError("validation", "Informe telefone ou e-mail.");
|
|
237
|
+
}
|
|
238
|
+
const identityKeys = new Set(Object.values(idMap).filter(Boolean));
|
|
239
|
+
const fields = Object.fromEntries(
|
|
240
|
+
Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v))
|
|
241
|
+
);
|
|
242
|
+
const attribution = readAttribution();
|
|
243
|
+
const { leadId, createdAt } = await provider.createLead(
|
|
244
|
+
stripUndefined({
|
|
245
|
+
formId: form.id,
|
|
246
|
+
formName: form.name,
|
|
247
|
+
name,
|
|
248
|
+
phone: phone || void 0,
|
|
249
|
+
email: email || void 0,
|
|
250
|
+
notes: notes || void 0,
|
|
251
|
+
fields,
|
|
252
|
+
attribution
|
|
253
|
+
})
|
|
254
|
+
);
|
|
255
|
+
let notified = false;
|
|
256
|
+
if (notifier) {
|
|
257
|
+
try {
|
|
258
|
+
await notifier.notify({
|
|
259
|
+
formId: form.id,
|
|
260
|
+
formName: form.name,
|
|
261
|
+
leadName: name,
|
|
262
|
+
phone: phone || void 0,
|
|
263
|
+
email: email || void 0,
|
|
264
|
+
fields,
|
|
265
|
+
labels: form.labels,
|
|
266
|
+
attribution
|
|
267
|
+
});
|
|
268
|
+
notified = true;
|
|
269
|
+
} catch (err) {
|
|
270
|
+
if (typeof console !== "undefined") {
|
|
271
|
+
console.error("[plugin-crm/public] lead saved but inbox notification failed:", err);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
return { leadId, createdAt, notified };
|
|
276
|
+
}
|
|
277
|
+
const Provider = ({ children }) => react.createElement(PublicFormsProvider, { forms: formsById, submit, children });
|
|
278
|
+
Provider.displayName = "PublicFormsProvider";
|
|
279
|
+
const manifest = {
|
|
280
|
+
id: "public-forms",
|
|
281
|
+
name: "Formul\xE1rios",
|
|
282
|
+
icon: "Inbox",
|
|
283
|
+
version: "0.1.0",
|
|
284
|
+
scope: options.scope ?? "universal",
|
|
285
|
+
verticalId: options.verticalId,
|
|
286
|
+
scaffolds: ["website", "landing_page"],
|
|
287
|
+
defaultEnabled: true,
|
|
288
|
+
dependencies: [],
|
|
289
|
+
// Headless: the site owns the markup, so this plugin mounts no route and
|
|
290
|
+
// contributes no navigation. It exists to be registered and provide context.
|
|
291
|
+
navigation: [],
|
|
292
|
+
routes: [],
|
|
293
|
+
widgets: []
|
|
294
|
+
};
|
|
295
|
+
return { manifest, Provider, submit };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
exports.LeadSubmitError = LeadSubmitError;
|
|
299
|
+
exports.PublicFormsProvider = PublicFormsProvider;
|
|
300
|
+
exports.createFayzInboxNotifier = createFayzInboxNotifier;
|
|
301
|
+
exports.createPublicFormsPlugin = createPublicFormsPlugin;
|
|
302
|
+
exports.createSupabasePublicLeadProvider = createSupabasePublicLeadProvider;
|
|
303
|
+
exports.readAttribution = readAttribution;
|
|
304
|
+
exports.useLeadForm = useLeadForm;
|
|
305
|
+
//# sourceMappingURL=index.cjs.map
|
|
306
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +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","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,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,C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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"]}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { createPublicFormsPlugin, readAttribution } from './createPublicFormsPlugin';
|
|
2
|
+
export type { PublicFormsOptions, PublicFormsPlugin } from './createPublicFormsPlugin';
|
|
3
|
+
export { PublicFormsProvider, useLeadForm } from './context';
|
|
4
|
+
export { createSupabasePublicLeadProvider } from './data.supabase';
|
|
5
|
+
export type { SupabasePublicLeadOptions } from './data.supabase';
|
|
6
|
+
export { createFayzInboxNotifier } from './inbox';
|
|
7
|
+
export type { FayzInboxNotifierOptions } from './inbox';
|
|
8
|
+
export { LeadSubmitError } from './types';
|
|
9
|
+
export type { LeadAttribution, LeadFieldValue, LeadFields, LeadNotifier, LeadSubmitErrorKind, LeadSubmitResult, PublicFormDef, PublicLeadDataProvider, } from './types';
|
|
10
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/public/index.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AACpF,YAAY,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAA;AAEtF,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,MAAM,WAAW,CAAA;AAE5D,OAAO,EAAE,gCAAgC,EAAE,MAAM,iBAAiB,CAAA;AAClE,YAAY,EAAE,yBAAyB,EAAE,MAAM,iBAAiB,CAAA;AAEhE,OAAO,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAA;AACjD,YAAY,EAAE,wBAAwB,EAAE,MAAM,SAAS,CAAA;AAEvD,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AACzC,YAAY,EACV,eAAe,EACf,cAAc,EACd,UAAU,EACV,YAAY,EACZ,mBAAmB,EACnB,gBAAgB,EAChB,aAAa,EACb,sBAAsB,GACvB,MAAM,SAAS,CAAA"}
|