@fayz-ai/plugin-crm 0.8.4 → 0.9.0-next.0
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/BoardFilters.d.ts +23 -0
- package/dist/components/BoardFilters.d.ts.map +1 -0
- package/dist/components/TagChips.d.ts +16 -0
- package/dist/components/TagChips.d.ts.map +1 -0
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/types.d.ts +4 -2
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +461 -84
- package/dist/index.js.map +1 -1
- 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 +4 -0
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/public/context.d.ts +3 -3
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +18 -2
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/data.supabase.d.ts.map +1 -1
- package/dist/public/index.js +29 -5
- package/dist/public/index.js.map +1 -1
- package/dist/public/types.d.ts +27 -0
- package/dist/public/types.d.ts.map +1 -1
- package/dist/registries.d.ts.map +1 -1
- package/dist/store.d.ts +7 -2
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +37 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/package.json +15 -14
- package/src/components/BoardFilters.tsx +190 -0
- package/src/components/TagChips.tsx +80 -0
- package/src/data/mock.ts +31 -4
- package/src/data/supabase.ts +72 -5
- package/src/data/types.ts +6 -3
- package/src/index.ts +94 -0
- package/src/locales/en.ts +9 -0
- package/src/locales/pt-BR.ts +9 -0
- package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
- package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
- package/src/migrations/013_tag_slugs.sql +177 -0
- package/src/migrations/014_public_lead_tags.sql +172 -0
- package/src/migrations/index.ts +643 -1
- package/src/public/context.tsx +4 -4
- package/src/public/createPublicFormsPlugin.ts +72 -2
- package/src/public/data.supabase.ts +1 -0
- package/src/public/types.ts +28 -0
- package/src/registries.ts +12 -3
- package/src/store.ts +78 -57
- package/src/types.ts +40 -0
- package/src/views/DealSidebar.tsx +9 -6
- package/src/views/PipelineView.tsx +92 -9
- package/dist/index.cjs +0 -5354
- package/dist/index.cjs.map +0 -1
- package/dist/public/index.cjs +0 -306
- package/dist/public/index.cjs.map +0 -1
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,CAgTrC,CAAA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pt-BR.d.ts","sourceRoot":"","sources":["../../src/locales/pt-BR.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"pt-BR.d.ts","sourceRoot":"","sources":["../../src/locales/pt-BR.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAgTvC,CAAA"}
|
|
@@ -9,6 +9,10 @@ export declare const MIGRATION_007_ACTIVITY_LOG = "-- CRM plugin \u2014 activity
|
|
|
9
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
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
11
|
export declare const MIGRATION_010_QUOTE_ARCHIVED_STATUS = "-- CRM plugin \u2014 allow status='archived' for quotes (follow-up to 009, which\n-- covered deals). Recreates orders_kind_status_valid with 'archived' in BOTH\n-- branches, only where the constraint exists (other pools: no-op). Idempotent:\n-- skips when 'archived' already appears twice (deal + quote branches).\n\nDO $$\nDECLARE def text;\nBEGIN\n SELECT pg_get_constraintdef(oid) INTO def\n FROM pg_constraint\n WHERE conname = 'orders_kind_status_valid' AND conrelid = 'public.orders'::regclass;\n IF def IS NULL THEN RETURN; END IF;\n IF (length(def) - length(replace(def, 'archived', ''))) / length('archived') >= 2 THEN RETURN; END IF;\n\n ALTER TABLE public.orders DROP CONSTRAINT orders_kind_status_valid;\n ALTER TABLE public.orders ADD CONSTRAINT orders_kind_status_valid CHECK (\n status IS NULL OR\n CASE kind\n WHEN 'quote' THEN status IN ('draft', 'sent', 'approved', 'rejected', 'expired', 'converted', 'archived')\n WHEN 'deal' THEN status IN ('open', 'won', 'lost', 'archived')\n WHEN 'appointment' THEN status IN ('scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid')\n WHEN 'service_order' THEN status IN ('draft', 'scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'invoiced', 'paid')\n WHEN 'invoice_receivable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n WHEN 'invoice_payable' THEN status IN ('open', 'paid', 'partial', 'overdue', 'cancelled')\n ELSE true\n END\n ) NOT VALID;\nEND $$;\n\n-- Backfill: deals stuck at total=0 whose quotes hold the real number take the\n-- LATEST quote's total (the same sync the provider now does on quote create/\n-- update). Idempotent \u2014 once totals are non-zero the predicate no longer bites.\nUPDATE public.orders d SET total = q.total\nFROM (\n SELECT DISTINCT ON ((metadata->>'dealId')) metadata->>'dealId' AS deal_id, total\n FROM public.orders\n WHERE kind = 'quote' AND metadata->>'dealId' IS NOT NULL AND total > 0\n ORDER BY (metadata->>'dealId'), created_at DESC\n) q\nWHERE d.id::text = q.deal_id AND d.kind = 'deal' AND COALESCE(d.total, 0) = 0;\n";
|
|
12
|
+
export declare const MIGRATION_011_AGENT_RPC_UPDATE_LEAD = "-- ============================================================================\n-- plugin-crm 011: agent_crm_update_lead \u2014 mover o status de um lead (e corrigir\n-- seus dados) pelo agente.\n--\n-- Lacuna que isso fecha: o CRM n\u00E3o tinha NENHUMA escrita pelo agente. Pedido\n-- real (\"acabei de mandar a proposta pra ele, ent\u00E3o atualiza o status\") ca\u00EDa no\n-- updateRecord gen\u00E9rico, que bate em v_leads \u2014 uma view sobre people \u2014, e o\n-- assistente s\u00F3 sabia dizer \"essa entidade \u00E9 somente leitura\". Mudar status de\n-- lead \u00E9 a a\u00E7\u00E3o mais frequente de um CRM; sem ela o agente \u00E9 s\u00F3 um relat\u00F3rio.\n--\n-- Sobre o feature id: `sales`, n\u00E3o `crm.leads`. Duas raz\u00F5es, ambas medidas em\n-- pool real. (1) agent_guard concatena feature || '.' || action sem normalizar,\n-- e nenhum pool guarda `crm.leads.edit` \u2014 beauty guarda `crm_leads.edit`,\n-- great-djs n\u00E3o guarda nenhum dos dois. (2) `sales.edit` existe nos dois, e \u00E9 o\n-- que a pr\u00F3pria tool declara em `permission`. Servidor e cliente checando\n-- features diferentes \u00E9 bug por constru\u00E7\u00E3o.\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.agent_crm_update_lead(\n p_tenant_id uuid,\n p_actor_user_id uuid,\n p_payload jsonb\n) RETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_denial jsonb;\n v_id uuid;\n v_row record;\n v_status text;\n v_patch jsonb := '{}'::jsonb;\n v_meta jsonb := '{}'::jsonb;\n v_touched boolean := false;\nBEGIN\n BEGIN\n v_id := (p_payload->>'lead_id')::uuid;\n EXCEPTION WHEN OTHERS THEN\n RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);\n END;\n IF v_id IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error',\n 'lead_id is required \u2014 search the leads first and reuse the id from the result');\n END IF;\n\n SELECT p.id, p.name, p.email, p.phone, p.notes, p.metadata, p.kind\n INTO v_row\n FROM people p\n WHERE p.id = v_id AND p.tenant_id = p_tenant_id AND p.kind = 'lead';\n IF NOT FOUND THEN\n RETURN jsonb_build_object('ok', false, 'error', 'unknown lead for this tenant');\n END IF;\n\n v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'edit');\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n -- Status is a CLOSED set. The model reached for 'proposta_enviada', which no\n -- board column renders \u2014 an invalid status writes a lead nobody can find, so\n -- the allowed values come back in the error for it to self-correct.\n v_status := nullif(trim(lower(p_payload->>'status')), '');\n IF v_status IS NOT NULL THEN\n IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN\n RETURN jsonb_build_object(\n 'ok', false,\n 'error', format('unknown lead status %L', v_status),\n 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'),\n 'hint', 'A sent proposal is usually \"qualified\"; a closed sale is \"converted\".');\n END IF;\n v_meta := v_meta || jsonb_build_object('status', v_status);\n v_touched := true;\n END IF;\n\n -- Top-level columns.\n IF p_payload ? 'name' AND nullif(trim(p_payload->>'name'), '') IS NOT NULL THEN\n v_patch := v_patch || jsonb_build_object('name', trim(p_payload->>'name'));\n v_touched := true;\n END IF;\n IF p_payload ? 'email' THEN\n v_patch := v_patch || jsonb_build_object('email', nullif(trim(p_payload->>'email'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'phone' THEN\n v_patch := v_patch || jsonb_build_object('phone', nullif(trim(p_payload->>'phone'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'notes' THEN\n v_patch := v_patch || jsonb_build_object('notes', left(p_payload->>'notes', 2000));\n v_touched := true;\n END IF;\n\n -- Metadata-backed columns of v_leads.\n IF p_payload ? 'company' THEN\n v_meta := v_meta || jsonb_build_object('company', nullif(trim(p_payload->>'company'), ''));\n v_touched := true;\n END IF;\n IF p_payload ? 'value' THEN\n v_meta := v_meta || jsonb_build_object('value', p_payload->>'value');\n v_touched := true;\n END IF;\n IF p_payload ? 'assigned_to_id' THEN\n v_meta := v_meta || jsonb_build_object('assignedToId', nullif(trim(p_payload->>'assigned_to_id'), ''));\n v_touched := true;\n END IF;\n\n IF NOT v_touched THEN\n RETURN jsonb_build_object('ok', false, 'error',\n 'nothing to change: send status, name, email, phone, company, value, assigned_to_id or notes');\n END IF;\n\n UPDATE people p SET\n name = COALESCE(v_patch->>'name', p.name),\n email = CASE WHEN v_patch ? 'email' THEN v_patch->>'email' ELSE p.email END,\n phone = CASE WHEN v_patch ? 'phone' THEN v_patch->>'phone' ELSE p.phone END,\n notes = CASE WHEN v_patch ? 'notes' THEN v_patch->>'notes' ELSE p.notes END,\n metadata = COALESCE(p.metadata, '{}'::jsonb) || v_meta,\n updated_at = now()\n WHERE p.id = v_id AND p.tenant_id = p_tenant_id;\n\n INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.updateLead', 'lead', v_id::text,\n jsonb_build_object('payload', p_payload,\n 'previous', jsonb_build_object(\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'status', COALESCE(v_row.metadata->>'status', 'new'))));\n\n SELECT l.id, l.name, l.email, l.phone, l.company, l.status\n INTO v_row\n FROM v_leads l WHERE l.id = v_id;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'company', v_row.company,\n 'status', v_row.status\n )\n );\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM public;\nREVOKE EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM anon;\nGRANT EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb)\n TO authenticated, service_role;\n";
|
|
13
|
+
export declare const MIGRATION_012_AGENT_RPC_CREATE_LEAD = "-- ============================================================================\n-- plugin-crm 012: agent_crm_create_lead \u2014 abrir um lead pelo agente.\n--\n-- Par do 011. Sem ele, \"cria um lead Noronha em stage qualified\" ca\u00EDa no\n-- createRecord gen\u00E9rico, batia no read_only de v_leads, e o modelo \u2014 vendo que\n-- existia updateLead \u2014 chamava a tool de EDI\u00C7\u00C3O com `lead_id: \"N/A\"`. Faltando\n-- o create, ele improvisa com o que tem.\n--\n-- Deduplica\u00E7\u00E3o \u00E9 parte do contrato, n\u00E3o extra: e-mail ou telefone que j\u00E1 existem\n-- no tenant devolvem o lead existente com `deduped: true` em vez de abrir um\n-- segundo. Um CRM com o mesmo contato duas vezes \u00E9 pior que um CRM vazio.\n--\n-- Feature `sales` pelo mesmo motivo do 011 \u2014 \u00E9 a que existe em todo pool e a que\n-- a tool declara.\n-- ============================================================================\n\nCREATE OR REPLACE FUNCTION public.agent_crm_create_lead(\n p_tenant_id uuid,\n p_actor_user_id uuid,\n p_payload jsonb\n) RETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path = public\nAS $$\nDECLARE\n v_denial jsonb;\n v_used int;\n v_name text;\n v_email text;\n v_phone text;\n v_status text;\n v_meta jsonb;\n v_existing record;\n v_id uuid;\n v_row record;\nBEGIN\n v_name := nullif(trim(p_payload->>'name'), '');\n v_email := lower(nullif(trim(p_payload->>'email'), ''));\n v_phone := nullif(regexp_replace(coalesce(p_payload->>'phone', ''), '\\D', '', 'g'), '');\n IF v_name IS NULL THEN\n RETURN jsonb_build_object('ok', false, 'error', 'name is required to open a lead');\n END IF;\n\n v_status := coalesce(nullif(trim(lower(p_payload->>'status')), ''), 'new');\n IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN\n RETURN jsonb_build_object(\n 'ok', false,\n 'error', format('unknown lead status %L', v_status),\n 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'));\n END IF;\n\n -- \u2500\u2500 authorization: role \u2192 plan \u2192 leads cap \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n SELECT count(*) INTO v_used FROM people p\n WHERE p.tenant_id = p_tenant_id AND p.kind = 'lead';\n v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create', 'leads', v_used, 1);\n IF v_denial IS NOT NULL THEN\n RETURN jsonb_build_object('ok', false, 'denial', v_denial);\n END IF;\n\n -- \u2500\u2500 dedupe before writing \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n IF v_email IS NOT NULL OR v_phone IS NOT NULL THEN\n SELECT p.id, p.name INTO v_existing\n FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND (\n (v_email IS NOT NULL AND lower(p.email) = v_email)\n OR (v_phone IS NOT NULL AND regexp_replace(coalesce(p.phone, ''), '\\D', '', 'g') = v_phone)\n )\n LIMIT 1;\n IF FOUND THEN\n RETURN jsonb_build_object(\n 'ok', true,\n 'deduped', true,\n 'id', v_existing.id,\n 'message', format('%L already exists as a lead with that e-mail/phone \u2014 returning it instead of creating a second one. Use updateLead to change it.', v_existing.name),\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_existing.id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_existing.name));\n END IF;\n END IF;\n\n v_meta := jsonb_strip_nulls(jsonb_build_object(\n 'status', v_status,\n 'source', 'agent',\n 'company', nullif(trim(p_payload->>'company'), ''),\n 'value', nullif(trim(p_payload->>'value'), ''),\n 'sourceName', nullif(trim(p_payload->>'source_name'), ''),\n 'assignedToId', nullif(trim(p_payload->>'assigned_to_id'), '')\n ));\n\n INSERT INTO people (tenant_id, kind, name, email, phone, notes, is_active, metadata)\n VALUES (p_tenant_id, 'lead', v_name,\n nullif(trim(p_payload->>'email'), ''),\n nullif(trim(p_payload->>'phone'), ''),\n left(p_payload->>'notes', 2000),\n true, v_meta)\n RETURNING id INTO v_id;\n\n INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)\n VALUES (p_tenant_id, p_actor_user_id, 'agent.createLead', 'lead', v_id::text,\n jsonb_build_object('payload', p_payload));\n\n SELECT l.id, l.name, l.email, l.phone, l.company, l.status\n INTO v_row\n FROM v_leads l WHERE l.id = v_id;\n\n RETURN jsonb_build_object(\n 'ok', true,\n 'id', v_id,\n 'record', jsonb_build_object(\n 'ref', jsonb_build_object('id', v_id, 'resource', 'people',\n 'archetype', 'person:lead', 'entityKey', 'crm:leads'),\n 'name', v_row.name,\n 'email', v_row.email,\n 'phone', v_row.phone,\n 'company', v_row.company,\n 'status', v_row.status\n )\n );\nEND;\n$$;\n\nREVOKE ALL ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM public;\nREVOKE EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM anon;\nGRANT EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb)\n TO authenticated, service_role;\n";
|
|
14
|
+
export declare const MIGRATION_013_TAG_SLUGS = "-- plugin-crm 013: tags ganham um SLUG, que passa a ser o contrato.\n--\n-- people.tags e orders.tags sempre foram text[] livre, e plg_crm_tags sempre\n-- foi um cadastro solto: nada ligava um ao outro. Na pr\u00E1tica isso d\u00E1 os dois\n-- problemas cl\u00E1ssicos de tag em CRM \u2014 \"Live Agosto\", \"live agosto\" e \"Live\n-- Agosto \" viram tr\u00EAs tags, e renomear a tag no cadastro \u00F3rf\u00E3 todo registro que\n-- j\u00E1 carregava o nome antigo.\n--\n-- O slug resolve os dois: o ARRAY guarda slug (est\u00E1vel, normalizado), e o\n-- cadastro guarda label + cor para exibi\u00E7\u00E3o. Renomear passa a ser cosm\u00E9tico.\n--\n-- Slug DESCONHECIDO continua v\u00E1lido de prop\u00F3sito: uma campanha precisa poder\n-- marcar leads hoje, sem esperar algu\u00E9m cadastrar a tag. A UI mostra o slug\n-- num chip neutro at\u00E9 o cadastro existir. Vocabul\u00E1rio controlado que degrada,\n-- em vez de vocabul\u00E1rio que bloqueia.\n\n-- ---------------------------------------------------------------------------\n-- Normalizador. Sem depender da extens\u00E3o unaccent (nem todo pool a tem):\n-- translate() cobre o portugu\u00EAs, que \u00E9 o que estas tags carregam.\n-- IMMUTABLE porque \u00E9 usado em \u00EDndice/generated abaixo.\n-- ---------------------------------------------------------------------------\nCREATE OR REPLACE FUNCTION public.crm_tag_slug(p_input text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nSET search_path TO 'public'\nAS $function$\n SELECT NULLIF(\n -- 4. colapsa h\u00EDfens repetidos e apara as pontas\n trim(BOTH '-' FROM regexp_replace(\n -- 3. tudo que n\u00E3o for [a-z0-9:] vira h\u00EDfen (':' sobrevive: \u00E9 o separador\n -- de namespace das tags autom\u00E1ticas, ex. 'camp:black-friday')\n regexp_replace(\n -- 2. min\u00FAscula\n lower(\n -- 1. tira acento\n translate(\n COALESCE(p_input, ''),\n '\u00E1\u00E0\u00E2\u00E3\u00E4\u00E9\u00E8\u00EA\u00EB\u00ED\u00EC\u00EE\u00EF\u00F3\u00F2\u00F4\u00F5\u00F6\u00FA\u00F9\u00FB\u00FC\u00E7\u00F1\u00C1\u00C0\u00C2\u00C3\u00C4\u00C9\u00C8\u00CA\u00CB\u00CD\u00CC\u00CE\u00CF\u00D3\u00D2\u00D4\u00D5\u00D6\u00DA\u00D9\u00DB\u00DC\u00C7\u00D1',\n 'aaaaaeeeeiiiiooooouuuucnAAAAAEEEEIIIIOOOOOUUUUCN'\n )\n ),\n '[^a-z0-9:]+', '-', 'g'\n ),\n '-{2,}', '-', 'g'\n )),\n ''\n );\n$function$;\n\nCOMMENT ON FUNCTION public.crm_tag_slug(text) IS\n 'Normaliza um r\u00F3tulo de tag para o slug que people.tags/orders.tags guardam. Preserva \":\" como separador de namespace (camp:, src:).';\n\n-- ---------------------------------------------------------------------------\n-- Cadastro de tags: slug + backfill a partir do nome.\n-- ---------------------------------------------------------------------------\nALTER TABLE public.plg_crm_tags\n ADD COLUMN IF NOT EXISTS slug text;\n\nUPDATE public.plg_crm_tags\n SET slug = public.crm_tag_slug(name)\n WHERE slug IS NULL;\n\n-- Duas linhas com o mesmo nome no mesmo tenant colidiriam no \u00EDndice \u00FAnico.\n-- Desempata pela mais antiga (a que os registros provavelmente j\u00E1 referenciam)\n-- e sufixa as demais, em vez de falhar a migration.\nWITH dupes AS (\n SELECT id, row_number() OVER (PARTITION BY tenant_id, slug ORDER BY created_at, id) AS rn\n FROM public.plg_crm_tags\n WHERE slug IS NOT NULL\n)\nUPDATE public.plg_crm_tags t\n SET slug = t.slug || '-' || d.rn\n FROM dupes d\n WHERE d.id = t.id AND d.rn > 1;\n\nCREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant_slug\n ON public.plg_crm_tags (tenant_id, slug);\n\n-- Um cadastro sem slug n\u00E3o serve para nada (nunca casa com um registro), ent\u00E3o\n-- o slug passa a ser derivado do nome quando o cliente n\u00E3o manda um.\nCREATE OR REPLACE FUNCTION public.plg_crm_tags_fill_slug()\nRETURNS trigger\nLANGUAGE plpgsql\nSET search_path TO 'public'\nAS $function$\nBEGIN\n NEW.slug := COALESCE(public.crm_tag_slug(NEW.slug), public.crm_tag_slug(NEW.name));\n RETURN NEW;\nEND;\n$function$;\n\nDROP TRIGGER IF EXISTS trg_plg_crm_tags_fill_slug ON public.plg_crm_tags;\nCREATE TRIGGER trg_plg_crm_tags_fill_slug\n BEFORE INSERT OR UPDATE OF name, slug ON public.plg_crm_tags\n FOR EACH ROW EXECUTE FUNCTION public.plg_crm_tags_fill_slug();\n\n-- ---------------------------------------------------------------------------\n-- O cadastro passa a se alimentar do que \u00E9 REALMENTE usado.\n--\n-- At\u00E9 aqui plg_crm_tags s\u00F3 existia como tela: o `seedData` do registry alimenta\n-- o provider mock, nunca o banco, ent\u00E3o /settings/crm/_properties/tags lia uma\n-- tabela vazia em todo tenant \u2014 e continuaria vazia mesmo com campanhas\n-- marcando leads. Registrar na escrita inverte isso: a tag aparece no cadastro\n-- porque foi usada, e o operador entra depois s\u00F3 para renomear ou trocar a cor.\n--\n-- Alternativa descartada: semear VIP/Hot Lead/Follow-up em todo tenant. Isso\n-- enche o cadastro de vocabul\u00E1rio que ningu\u00E9m escolheu e que n\u00E3o corresponde a\n-- nenhum registro.\n-- ---------------------------------------------------------------------------\n\n-- Cor est\u00E1vel por slug: a mesma tag sai da mesma cor em qualquer tenant, e o\n-- operador pode sobrescrever depois. Paleta com contraste suficiente em chip.\nCREATE OR REPLACE FUNCTION public.crm_tag_default_color(p_slug text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $function$\n SELECT (ARRAY[\n '#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#14b8a6'\n ])[(abs(hashtext(COALESCE(p_slug, ''))) % 8) + 1];\n$function$;\n\n-- R\u00F3tulo leg\u00EDvel a partir do slug: 'camp:black-friday' -> 'Black Friday'.\n-- O namespace some do r\u00F3tulo (a cor e o filtro j\u00E1 o distinguem) \u2014 quem l\u00EA o\n-- card quer ver a campanha, n\u00E3o o prefixo.\nCREATE OR REPLACE FUNCTION public.crm_tag_humanize(p_slug text)\nRETURNS text\nLANGUAGE sql\nIMMUTABLE\nAS $function$\n SELECT initcap(replace(regexp_replace(COALESCE(p_slug, ''), '^[a-z]+:', ''), '-', ' '));\n$function$;\n\nCREATE OR REPLACE FUNCTION public.crm_register_tags(p_tenant_id uuid, p_slugs text[])\nRETURNS void\nLANGUAGE sql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $function$\n INSERT INTO public.plg_crm_tags (tenant_id, name, slug, color, is_active)\n SELECT p_tenant_id,\n public.crm_tag_humanize(s),\n s,\n public.crm_tag_default_color(s),\n true\n FROM unnest(COALESCE(p_slugs, '{}'::text[])) AS s\n WHERE s IS NOT NULL AND s <> ''\n ON CONFLICT (tenant_id, slug) DO NOTHING;\n$function$;\n\n-- INTERNA de prop\u00F3sito: \u00E9 SECURITY DEFINER e recebe o tenant do caller, ent\u00E3o\n-- exposta ela deixaria qualquer um semear cadastro no tenant alheio. S\u00F3 \u00E9\n-- alcan\u00E7\u00E1vel de dentro de outra fun\u00E7\u00E3o DEFINER que j\u00E1 validou o tenant \u2014 hoje,\n-- create_public_lead. O caminho do ADMIN n\u00E3o passa por aqui: ele faz upsert\n-- direto em plg_crm_tags, onde a RLS da tabela j\u00E1 faz a autoriza\u00E7\u00E3o certa.\nREVOKE ALL ON FUNCTION public.crm_register_tags(uuid, text[]) FROM public, anon, authenticated;\n\n-- Backfill: tudo que J\u00C1 est\u00E1 em people.tags / orders.tags vira cadastro, para a\n-- tela n\u00E3o nascer vazia num tenant que j\u00E1 vinha usando tags.\nDO $$\nDECLARE\n r record;\nBEGIN\n FOR r IN\n SELECT tenant_id, array_agg(DISTINCT public.crm_tag_slug(tag)) AS slugs\n FROM (\n SELECT tenant_id, unnest(tags) AS tag FROM public.people WHERE tags IS NOT NULL\n UNION ALL\n SELECT tenant_id, unnest(tags) AS tag FROM public.orders WHERE tags IS NOT NULL\n ) used\n WHERE public.crm_tag_slug(tag) IS NOT NULL\n GROUP BY tenant_id\n LOOP\n PERFORM public.crm_register_tags(r.tenant_id, r.slugs);\n END LOOP;\nEND $$;\n";
|
|
15
|
+
export declare const MIGRATION_014_PUBLIC_LEAD_TAGS = "-- plugin-crm 014: o formul\u00E1rio p\u00FAblico passa a poder marcar o lead.\n--\n-- create_public_lead gravava `ARRAY[]::text[]` fixo \u2014 n\u00E3o existia caminho para\n-- uma landing page dizer \"este lead veio da Turma Delas\". Sem isso, tag em CRM\n-- vira trabalho manual: algu\u00E9m abre o card e digita de onde veio, que \u00E9\n-- exatamente o que a atribui\u00E7\u00E3o autom\u00E1tica deveria evitar.\n--\n-- O caller \u00E9 um browser an\u00F4nimo, ent\u00E3o nada do que ele manda \u00E9 confi\u00E1vel: os\n-- slugs s\u00E3o normalizados, deduplicados e limitados AQUI. O site pede tags; o\n-- banco decide o que de fato entra.\n--\n-- A propaga\u00E7\u00E3o para o card do funil j\u00E1 existe: o trigger de\n-- 006_lead_enters_pipeline copia people.tags para orders.tags ao criar o deal.\n\n-- A assinatura ganha p_tags. A antiga precisa SAIR: com as duas no cat\u00E1logo o\n-- PostgREST n\u00E3o resolve a chamada sem tags (duas candidatas, mesmos nomes de\n-- par\u00E2metro) e devolve PGRST203.\nDROP FUNCTION IF EXISTS public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb);\n\nCREATE OR REPLACE FUNCTION public.create_public_lead(\n p_tenant_id uuid,\n p_name text,\n p_phone text DEFAULT NULL,\n p_email text DEFAULT NULL,\n p_form_id text DEFAULT NULL,\n p_form_name text DEFAULT NULL,\n p_fields jsonb DEFAULT '{}'::jsonb,\n p_notes text DEFAULT NULL,\n p_utm jsonb DEFAULT '{}'::jsonb,\n p_tags text[] DEFAULT '{}'::text[]\n)\nRETURNS TABLE(lead_id uuid, created_at timestamptz)\nLANGUAGE plpgsql\nSECURITY DEFINER\nSET search_path TO 'public'\nAS $function$\nDECLARE\n v_person_id uuid;\n v_phone text;\n v_email text;\n v_fields jsonb;\n v_utm jsonb;\n v_tags text[];\n v_recent int;\nBEGIN\n -- ---------------------------------------------------------------------\n -- validation: anon-callable, so everything is checked here\n -- ---------------------------------------------------------------------\n IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN\n RAISE EXCEPTION 'invalid name';\n END IF;\n\n v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');\n IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN\n RAISE EXCEPTION 'invalid phone';\n END IF;\n\n v_email := NULLIF(trim(COALESCE(p_email, '')), '');\n IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN\n RAISE EXCEPTION 'invalid email';\n END IF;\n\n -- a lead with no way to reach them back is not a lead\n IF v_phone IS NULL AND v_email IS NULL THEN\n RAISE EXCEPTION 'phone or email required';\n END IF;\n\n PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n -- ---------------------------------------------------------------------\n -- custom fields: object-only, bounded, and scalars only.\n -- ---------------------------------------------------------------------\n v_fields := COALESCE(p_fields, '{}'::jsonb);\n IF jsonb_typeof(v_fields) <> 'object' THEN\n RAISE EXCEPTION 'fields must be an object';\n END IF;\n IF length(v_fields::text) > 8000 THEN\n RAISE EXCEPTION 'fields too large';\n END IF;\n IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN\n RAISE EXCEPTION 'too many fields';\n END IF;\n\n v_utm := COALESCE(p_utm, '{}'::jsonb);\n IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN\n RAISE EXCEPTION 'invalid utm';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- tags: normalizadas e limitadas aqui. Um slug ruim \u00E9 DESCARTADO em vez de\n -- derrubar a submiss\u00E3o \u2014 perder um lead por causa de um r\u00F3tulo de campanha\n -- mal formatado seria trocar o essencial pelo acess\u00F3rio. Teto de 10 evita\n -- que uma querystring hostil vire um card com cinquenta chips.\n -- ---------------------------------------------------------------------\n SELECT array_agg(s) INTO v_tags FROM (\n SELECT DISTINCT public.crm_tag_slug(t) AS s\n FROM unnest(COALESCE(p_tags, '{}'::text[])) AS t\n WHERE public.crm_tag_slug(t) IS NOT NULL\n AND length(public.crm_tag_slug(t)) <= 48\n LIMIT 10\n ) normalized;\n v_tags := COALESCE(v_tags, '{}'::text[]);\n\n -- ---------------------------------------------------------------------\n -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is\n -- a double-click or a bot, not two inquiries.\n -- ---------------------------------------------------------------------\n SELECT count(*) INTO v_recent\n FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '5 minutes'\n AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')\n AND (\n (v_phone IS NOT NULL AND p.phone = v_phone)\n OR (v_email IS NOT NULL AND p.email = v_email)\n );\n IF v_recent > 0 THEN\n RAISE EXCEPTION 'duplicate submission';\n END IF;\n\n -- burst cap per tenant: a flood is never legitimate marketing traffic\n IF (\n SELECT count(*) FROM people p\n WHERE p.tenant_id = p_tenant_id\n AND p.kind = 'lead'\n AND p.created_at > now() - interval '1 minute'\n ) >= 20 THEN\n RAISE EXCEPTION 'too many submissions';\n END IF;\n\n -- ---------------------------------------------------------------------\n -- the lead. status/kind are hardcoded \u2014 the caller cannot promote itself\n -- into a customer or land pre-qualified.\n -- ---------------------------------------------------------------------\n INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)\n VALUES (\n p_tenant_id,\n 'lead',\n trim(p_name),\n v_phone,\n v_email,\n left(p_notes, 2000),\n v_tags,\n true,\n jsonb_strip_nulls(\n jsonb_build_object(\n 'status', 'new',\n 'source', 'public_form',\n 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),\n 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),\n 'fields', v_fields,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END\n )\n )\n )\n RETURNING id, people.created_at INTO v_person_id, created_at;\n\n -- O cadastro de tags se alimenta do que foi usado, para a tela de settings\n -- refletir a realidade sem ningu\u00E9m pr\u00E9-preencher nada.\n IF array_length(v_tags, 1) > 0 THEN\n PERFORM public.crm_register_tags(p_tenant_id, v_tags);\n END IF;\n\n lead_id := v_person_id;\n RETURN NEXT;\nEND;\n$function$;\n\nGRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[])\n TO anon, authenticated;\n";
|
|
12
16
|
export declare const MIGRATIONS: Array<{
|
|
13
17
|
id: string;
|
|
14
18
|
sql: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,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,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,wBAAwB,0pDA4BpC,CAAA;AAED,eAAO,MAAM,sBAAsB,skHAyElC,CAAA;AAED,eAAO,MAAM,wBAAwB,whDAiCpC,CAAA;AAED,eAAO,MAAM,2BAA2B,kyHAqEvC,CAAA;AAED,eAAO,MAAM,mCAAmC,q9CA+B/C,CAAA;AAED,eAAO,MAAM,yBAAyB,+uOA6LrC,CAAA;AAED,eAAO,MAAM,kCAAkC,g4VAyQ9C,CAAA;AAED,eAAO,MAAM,0BAA0B,q9EAuDtC,CAAA;AAED,eAAO,MAAM,gCAAgC,g9DA2C5C,CAAA;AAED,eAAO,MAAM,kCAAkC,qlDA8B9C,CAAA;AAED,eAAO,MAAM,mCAAmC,0nEAwC/C,CAAA;AAED,eAAO,MAAM,mCAAmC,i8MAyJ/C,CAAA;AAED,eAAO,MAAM,mCAAmC,6gLAgI/C,CAAA;AAED,eAAO,MAAM,uBAAuB,0tPAiLnC,CAAA;AAED,eAAO,MAAM,8BAA8B,urNA4K1C,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAgBzD,CAAA"}
|
package/dist/public/context.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { type ReactNode } from 'react';
|
|
2
|
-
import { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types';
|
|
2
|
+
import { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types';
|
|
3
3
|
interface PublicFormsContextValue {
|
|
4
4
|
forms: Map<string, PublicFormDef>;
|
|
5
|
-
submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>;
|
|
5
|
+
submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>;
|
|
6
6
|
}
|
|
7
7
|
export interface PublicFormsProviderProps extends PublicFormsContextValue {
|
|
8
8
|
children: ReactNode;
|
|
@@ -11,7 +11,7 @@ export declare function PublicFormsProvider({ forms, submit, children }: PublicF
|
|
|
11
11
|
/** The hook a site's own form component calls. Owns only the submission
|
|
12
12
|
* lifecycle — the markup, the fields and the validation copy stay the site's. */
|
|
13
13
|
export declare function useLeadForm(formId: string): {
|
|
14
|
-
submit: (values: LeadFields) => Promise<LeadSubmitResult | null>;
|
|
14
|
+
submit: (values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult | null>;
|
|
15
15
|
reset: () => void;
|
|
16
16
|
submitting: boolean;
|
|
17
17
|
error: LeadSubmitError | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context.d.ts","sourceRoot":"","sources":["../../src/public/context.tsx"],"names":[],"mappings":"AAAA,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;
|
|
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,iBAAiB,EAAE,KAAK,gBAAgB,EAAE,KAAK,aAAa,EAAE,MAAM,SAAS,CAAA;AAE7H,UAAU,uBAAuB;IAC/B,KAAK,EAAE,GAAG,CAAC,MAAM,EAAE,aAAa,CAAC,CAAA;IACjC,MAAM,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,iBAAiB,KAAK,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACvG;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,YAAY,iBAAiB,KAAG,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;;;;;;;EAoC5F"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type FC, type ReactNode } from 'react';
|
|
2
2
|
import type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core';
|
|
3
|
-
import { type LeadAttribution, type LeadFields, type LeadNotifier, type LeadSubmitResult, type PublicFormDef, type PublicLeadDataProvider } from './types';
|
|
3
|
+
import { type LeadAttribution, type LeadFields, type LeadNotifier, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef, type PublicLeadDataProvider } from './types';
|
|
4
4
|
export interface PublicFormsOptions {
|
|
5
5
|
/**
|
|
6
6
|
* Tenant the leads land in. REQUIRED — this is the whole point of the
|
|
@@ -21,6 +21,22 @@ export interface PublicFormsOptions {
|
|
|
21
21
|
dataProvider?: PublicLeadDataProvider;
|
|
22
22
|
/** Inject a custom notifier (tests). */
|
|
23
23
|
notifier?: LeadNotifier;
|
|
24
|
+
/**
|
|
25
|
+
* Marca o lead com a campanha que o trouxe, lendo a UTM da URL.
|
|
26
|
+
*
|
|
27
|
+
* Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag
|
|
28
|
+
* automática e tag curada convivem no mesmo array, e sem prefixo a primeira
|
|
29
|
+
* engole a segunda — em seis meses ninguém sabe mais quais tags alguém
|
|
30
|
+
* escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,
|
|
31
|
+
* relatar e limpar cada grupo separadamente.
|
|
32
|
+
*
|
|
33
|
+
* `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica
|
|
34
|
+
* desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.
|
|
35
|
+
*/
|
|
36
|
+
campaignTags?: boolean | {
|
|
37
|
+
campaign?: boolean;
|
|
38
|
+
source?: boolean;
|
|
39
|
+
};
|
|
24
40
|
scope?: PluginScope;
|
|
25
41
|
verticalId?: VerticalId;
|
|
26
42
|
}
|
|
@@ -30,7 +46,7 @@ export interface PublicFormsPlugin {
|
|
|
30
46
|
children: ReactNode;
|
|
31
47
|
}>;
|
|
32
48
|
/** Imperative submit, for code paths outside React. */
|
|
33
|
-
submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>;
|
|
49
|
+
submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>;
|
|
34
50
|
}
|
|
35
51
|
/** Reads UTM + page context off the browser. Safe to call during SSR. */
|
|
36
52
|
export declare function readAttribution(): LeadAttribution;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"createPublicFormsPlugin.d.ts","sourceRoot":"","sources":["../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":"AAaA,OAAO,EAAiB,KAAK,EAAE,EAAE,KAAK,SAAS,EAAE,MAAM,OAAO,CAAA;AAC9D,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAI5E,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,gBAAgB,EACrB,KAAK,aAAa,EAClB,KAAK,sBAAsB,EAC5B,MAAM,SAAS,CAAA;AAEhB,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,EAAE,MAAM,CAAA;IAChB,gDAAgD;IAChD,KAAK,EAAE,aAAa,EAAE,CAAA;IACtB;;;OAGG;IACH,KAAK,CAAC,EAAE,OAAO,GAAG;QAAE,SAAS,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAA;IAC7D,oEAAoE;IACpE,YAAY,CAAC,EAAE,sBAAsB,CAAA;IACrC,wCAAwC;IACxC,QAAQ,CAAC,EAAE,YAAY,CAAA;IACvB,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;
|
|
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,YAA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mB,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,
|
|
1
|
+
{"version":3,"file":"data.supabase.d.ts","sourceRoot":"","sources":["../../src/public/data.supabase.ts"],"names":[],"mappings":"AAcA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,SAAS,CAAA;AAEtE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAmCxB"}
|
package/dist/public/index.js
CHANGED
|
@@ -50,7 +50,8 @@ function createSupabasePublicLeadProvider(options) {
|
|
|
50
50
|
p_form_name: input.formName,
|
|
51
51
|
p_fields: input.fields,
|
|
52
52
|
p_notes: input.notes ?? null,
|
|
53
|
-
p_utm: input.attribution
|
|
53
|
+
p_utm: input.attribution,
|
|
54
|
+
p_tags: input.tags ?? []
|
|
54
55
|
});
|
|
55
56
|
if (error) throw toSubmitError(error.message);
|
|
56
57
|
const row = Array.isArray(data) ? data[0] : void 0;
|
|
@@ -152,12 +153,12 @@ function useLeadForm(formId) {
|
|
|
152
153
|
const [error, setError] = useState(null);
|
|
153
154
|
const [result, setResult] = useState(null);
|
|
154
155
|
const submit = useCallback(
|
|
155
|
-
async (values) => {
|
|
156
|
+
async (values, options) => {
|
|
156
157
|
if (submitting) return null;
|
|
157
158
|
setSubmitting(true);
|
|
158
159
|
setError(null);
|
|
159
160
|
try {
|
|
160
|
-
const res = await ctx.submit(formId, values);
|
|
161
|
+
const res = await ctx.submit(formId, values, options);
|
|
161
162
|
setResult(res);
|
|
162
163
|
return res;
|
|
163
164
|
} catch (err) {
|
|
@@ -186,6 +187,27 @@ function useLeadForm(formId) {
|
|
|
186
187
|
}
|
|
187
188
|
|
|
188
189
|
// src/public/createPublicFormsPlugin.ts
|
|
190
|
+
var MAX_TAGS = 10;
|
|
191
|
+
function slugify(input) {
|
|
192
|
+
return input.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9:]+/g, "-").replace(/-{2,}/g, "-").replace(/^-+|-+$/g, "");
|
|
193
|
+
}
|
|
194
|
+
function resolveTags(formTags, callTags, attribution, campaignTags) {
|
|
195
|
+
const cfg = campaignTags === false ? { campaign: false, source: false } : campaignTags === true || campaignTags === void 0 ? { campaign: true, source: false } : { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false };
|
|
196
|
+
const out = [];
|
|
197
|
+
for (const raw of [...formTags ?? [], ...callTags ?? []]) {
|
|
198
|
+
const slug = slugify(raw);
|
|
199
|
+
if (slug) out.push(slug);
|
|
200
|
+
}
|
|
201
|
+
if (cfg.campaign && attribution.utm_campaign) {
|
|
202
|
+
const slug = slugify(attribution.utm_campaign);
|
|
203
|
+
if (slug) out.push(`camp:${slug}`);
|
|
204
|
+
}
|
|
205
|
+
if (cfg.source && attribution.utm_source) {
|
|
206
|
+
const slug = slugify(attribution.utm_source);
|
|
207
|
+
if (slug) out.push(`src:${slug}`);
|
|
208
|
+
}
|
|
209
|
+
return [...new Set(out)].slice(0, MAX_TAGS);
|
|
210
|
+
}
|
|
189
211
|
function readAttribution() {
|
|
190
212
|
if (typeof window === "undefined") return {};
|
|
191
213
|
const params = new URLSearchParams(window.location.search);
|
|
@@ -214,7 +236,7 @@ function createPublicFormsPlugin(options) {
|
|
|
214
236
|
const formsById = new Map(options.forms.map((f) => [f.id, f]));
|
|
215
237
|
const provider = options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId });
|
|
216
238
|
const notifier = options.notifier ?? (options.inbox === false ? null : createFayzInboxNotifier(typeof options.inbox === "object" ? options.inbox : {}));
|
|
217
|
-
async function submit(formId, values) {
|
|
239
|
+
async function submit(formId, values, submitOptions) {
|
|
218
240
|
const form = formsById.get(formId);
|
|
219
241
|
if (!form) {
|
|
220
242
|
throw new LeadSubmitError("validation", `[plugin-crm/public] unknown form "${formId}".`);
|
|
@@ -238,6 +260,7 @@ function createPublicFormsPlugin(options) {
|
|
|
238
260
|
Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v))
|
|
239
261
|
);
|
|
240
262
|
const attribution = readAttribution();
|
|
263
|
+
const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags);
|
|
241
264
|
const { leadId, createdAt } = await provider.createLead(
|
|
242
265
|
stripUndefined({
|
|
243
266
|
formId: form.id,
|
|
@@ -247,7 +270,8 @@ function createPublicFormsPlugin(options) {
|
|
|
247
270
|
email: email || void 0,
|
|
248
271
|
notes: notes || void 0,
|
|
249
272
|
fields,
|
|
250
|
-
attribution
|
|
273
|
+
attribution,
|
|
274
|
+
tags: tags.length ? tags : void 0
|
|
251
275
|
})
|
|
252
276
|
);
|
|
253
277
|
let notified = false;
|
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,OAAO,yBAAA,EAA0B;AACnC;AAGA,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,CAAA,GAAI,QAAQ,WAAA,EAAY;AAC9B,EAAA,IAAI,CAAA,CAAE,QAAA,CAAS,sBAAsB,CAA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AAA,UACf,QAAA,EAAU,IAAA;AAAA,UACV,OAAO,KAAA,IAAS,KAAA,CAAA;AAAA,UAChB,OAAO,KAAA,IAAS,KAAA,CAAA;AAAA,UAChB,MAAA;AAAA,UACA,QAAQ,IAAA,CAAK,MAAA;AAAA,UACb;AAAA,SACD,CAAA;AACD,QAAA,QAAA,GAAW,IAAA;AAAA,MACb,SAAS,GAAA,EAAK;AACZ,QAAA,IAAI,OAAO,YAAY,WAAA,EAAa;AAClC,UAAA,OAAA,CAAQ,KAAA,CAAM,iEAAiE,GAAG,CAAA;AAAA,QACpF;AAAA,MACF;AAAA,IACF;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,SAAA,EAAW,QAAA,EAAS;AAAA,EACvC;AAEA,EAAA,MAAM,QAAA,GAAwC,CAAC,EAAE,QAAA,EAAS,KACxD,aAAA,CAAc,mBAAA,EAAqB,EAAE,KAAA,EAAO,SAAA,EAAW,MAAA,EAAQ,QAAA,EAAU,CAAA;AAC3E,EAAA,QAAA,CAAS,WAAA,GAAc,qBAAA;AAEvB,EAAA,MAAM,QAAA,GAA2B;AAAA,IAC/B,EAAA,EAAI,cAAA;AAAA,IACJ,IAAA,EAAM,gBAAA;AAAA,IACN,IAAA,EAAM,OAAA;AAAA,IACN,OAAA,EAAS,OAAA;AAAA,IACT,KAAA,EAAO,QAAQ,KAAA,IAAS,WAAA;AAAA,IACxB,YAAY,OAAA,CAAQ,UAAA;AAAA,IACpB,SAAA,EAAW,CAAC,SAAA,EAAW,cAAc,CAAA;AAAA,IACrC,cAAA,EAAgB,IAAA;AAAA,IAChB,cAAc,EAAC;AAAA;AAAA;AAAA,IAGf,YAAY,EAAC;AAAA,IACb,QAAQ,EAAC;AAAA,IACT,SAAS;AAAC,GACZ;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,EAAO;AACtC","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Public lead capture — types\n//\n// The contract between a marketing site's own form UI and the CRM. Sites keep\n// their bespoke layout and copy; all they hand over is a bag of values. Where\n// that lands (which tenant, which table, what status) is decided by the SDK and\n// the RPC behind it, never by the site.\n// ---------------------------------------------------------------------------\n\n/** What a form field may carry. Scalars and scalar lists — anything a checkbox\n * group, a select or a text input produces. Files are out of scope: a lead\n * form links to an upload, it does not embed one. */\nexport type LeadFieldValue = string | number | boolean | null | string[] | number[]\n\n/** The values a site collects, keyed by field id. Free-form on purpose: a new\n * landing page adds keys without touching the schema. */\nexport type LeadFields = Record<string, LeadFieldValue>\n\n/**\n * One form the site exposes. Registered up-front so submissions carry a stable\n * id (attribution) and a human name (what the operator reads in the CRM).\n */\nexport interface PublicFormDef {\n /** Stable id — the attribution key. Keep it stable across redesigns. */\n id: string\n /** Human name shown as the lead's source in the CRM. */\n name: string\n /**\n * Field ids that must be present and non-empty for the submission to be\n * attempted. Contact reachability (phone or email) is enforced server-side\n * regardless of what is declared here.\n */\n required?: string[]\n /**\n * Maps this form's field ids onto the lead's identity columns. Everything NOT\n * mapped stays in `fields` as a custom field.\n *\n * Defaults to { name: 'name', phone: 'phone', email: 'email' }.\n */\n identity?: {\n name?: string\n phone?: string\n email?: string\n /** Field whose value becomes the lead's free-text note. */\n notes?: string\n }\n /** Labels for custom fields, so the CRM shows \"Faixa etária\" not \"age_range\". */\n labels?: Record<string, string>\n}\n\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"]}
|
|
1
|
+
{"version":3,"sources":["../../src/public/types.ts","../../src/public/data.supabase.ts","../../src/public/inbox.ts","../../src/public/context.tsx","../../src/public/createPublicFormsPlugin.ts"],"names":[],"mappings":";;;;;;;AA2FO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EAEzC,WAAA,CAAY,MAA2B,OAAA,EAAiB;AACtD,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AACF;;;ACzEA,SAAS,SAAA,GAAuC;AAC9C,EAAA,OAAO,yBAAA,EAA0B;AACnC;AAGA,SAAS,cAAc,OAAA,EAAkC;AACvD,EAAA,MAAM,CAAA,GAAI,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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,cAAc,CAAA;AAAA,IACrC,cAAA,EAAgB,IAAA;AAAA,IAChB,cAAc,EAAC;AAAA;AAAA;AAAA,IAGf,YAAY,EAAC;AAAA,IACb,QAAQ,EAAC;AAAA,IACT,SAAS;AAAC,GACZ;AAEA,EAAA,OAAO,EAAE,QAAA,EAAU,QAAA,EAAU,MAAA,EAAO;AACtC","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Public lead capture — types\n//\n// The contract between a marketing site's own form UI and the CRM. Sites keep\n// their bespoke layout and copy; all they hand over is a bag of values. Where\n// that lands (which tenant, which table, what status) is decided by the SDK and\n// the RPC behind it, never by the site.\n// ---------------------------------------------------------------------------\n\n/** What a form field may carry. Scalars and scalar lists — anything a checkbox\n * group, a select or a text input produces. Files are out of scope: a lead\n * form links to an upload, it does not embed one. */\nexport type LeadFieldValue = string | number | boolean | null | string[] | number[]\n\n/** The values a site collects, keyed by field id. Free-form on purpose: a new\n * landing page adds keys without touching the schema. */\nexport type LeadFields = Record<string, LeadFieldValue>\n\n/**\n * One form the site exposes. Registered up-front so submissions carry a stable\n * id (attribution) and a human name (what the operator reads in the CRM).\n */\nexport interface PublicFormDef {\n /** Stable id — the attribution key. Keep it stable across redesigns. */\n id: string\n /** Human name shown as the lead's source in the CRM. */\n name: string\n /**\n * Field ids that must be present and non-empty for the submission to be\n * attempted. Contact reachability (phone or email) is enforced server-side\n * regardless of what is declared here.\n */\n required?: string[]\n /**\n * Maps this form's field ids onto the lead's identity columns. Everything NOT\n * mapped stays in `fields` as a custom field.\n *\n * Defaults to { name: 'name', phone: 'phone', email: 'email' }.\n */\n identity?: {\n name?: string\n phone?: string\n email?: string\n /** Field whose value becomes the lead's free-text note. */\n notes?: string\n }\n /** Labels for custom fields, so the CRM shows \"Faixa etária\" not \"age_range\". */\n labels?: Record<string, string>\n /**\n * Tags every lead from this form carries into the CRM, and from there onto\n * the card no funil (o trigger de lead→deal copia).\n *\n * Isto é o vocabulário CURADO: o que a landing page É (\"aluno-novo\",\n * \"parceria\"), não de qual campanha veio. Escreva em slug; o servidor\n * normaliza de qualquer jeito (minúscula, sem acento, hifenizado) e descarta\n * o que não der para normalizar em vez de derrubar o envio.\n *\n * Máximo de 10 tags por lead, somando estas e as automáticas.\n */\n tags?: string[]\n}\n\n/**\n * O que a PÁGINA decide na hora do envio, e o formulário não sabe de antemão.\n *\n * Existe porque uma landing page costuma ter mais de uma porta de entrada para\n * o mesmo formulário (a home e uma campanha específica levam ao mesmo\n * `/quero-ser-aluno`). Sem isto, distinguir as duas exigiria declarar um\n * formulário por porta, e cada um vira uma \"origem\" diferente no CRM para o que\n * é o mesmo formulário.\n */\nexport interface LeadSubmitOptions {\n /** Somadas às `tags` do formulário e às automáticas da campanha. */\n tags?: string[]\n}\n\n/** Result of a submission — enough for the site to show its own success state. */\nexport interface LeadSubmitResult {\n leadId: string\n createdAt: string\n /** False when the CRM write succeeded but the inbox notification did not. */\n notified: boolean\n}\n\n/** Thrown for problems the site should surface differently than a crash. */\nexport type LeadSubmitErrorKind =\n | 'validation' // missing required field / no contact channel\n | 'duplicate' // same contact, same form, seconds apart\n | 'rate_limited' // burst cap tripped\n | 'unavailable' // backend not configured or unreachable\n\nexport class LeadSubmitError extends Error {\n readonly kind: LeadSubmitErrorKind\n constructor(kind: LeadSubmitErrorKind, message: string) {\n super(message)\n this.name = 'LeadSubmitError'\n this.kind = kind\n }\n}\n\n/** UTM/attribution captured from the browser, merged into every submission. */\nexport interface LeadAttribution {\n utm_source?: string\n utm_medium?: string\n utm_campaign?: string\n utm_term?: string\n utm_content?: string\n /** Path the form was submitted from. */\n landing_page?: string\n referrer?: string\n}\n\n/** The transport a submission goes through. Swappable for tests. */\nexport interface PublicLeadDataProvider {\n createLead(input: {\n formId: string\n formName: string\n name: string\n phone?: string\n email?: string\n notes?: string\n fields: LeadFields\n attribution: LeadAttribution\n /** Slugs já resolvidos (curados do formulário + automáticos da campanha). */\n tags?: string[]\n }): Promise<{ leadId: string; createdAt: string }>\n}\n\n/** Notifies the site's admin that a lead arrived. */\nexport interface LeadNotifier {\n notify(input: {\n formId: string\n formName: string\n leadName: string\n phone?: string\n email?: string\n fields: LeadFields\n labels?: Record<string, string>\n attribution: LeadAttribution\n }): Promise<void>\n}\n","// ---------------------------------------------------------------------------\n// Supabase implementation of PublicLeadDataProvider — anon-safe.\n//\n// Public marketing pages run with the publishable (anon) key and NO user\n// session, so canonical tenant RLS yields nothing. This provider touches only\n// the one object designed for anon access:\n// - public.create_public_lead (SECURITY DEFINER RPC: validates, caps spam,\n// writes people[kind=lead] with the custom fields in metadata)\n// Shipped by plugins/plugin-crm/src/migrations/005_public_lead.sql.\n//\n// The RPC never reads back — a form writes, it does not query the CRM.\n// ---------------------------------------------------------------------------\n\nimport { getSupabaseClientOptional } from '@fayz-ai/core'\nimport { LeadSubmitError, type PublicLeadDataProvider } from './types'\n\nexport interface SupabasePublicLeadOptions {\n /** The tenant leads land in (RPC arg — required). */\n tenantId: string\n}\n\ninterface SupabaseLikeClient {\n rpc(fn: string, args: Record<string, unknown>): PromiseLike<{ data: unknown; error: { message: string } | null }>\n}\n\nfunction getClient(): SupabaseLikeClient | null {\n return getSupabaseClientOptional() as SupabaseLikeClient | null\n}\n\n/** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */\nfunction toSubmitError(message: string): LeadSubmitError {\n const m = message.toLowerCase()\n if (m.includes('duplicate submission')) {\n return new LeadSubmitError('duplicate', 'Recebemos seu contato há instantes.')\n }\n if (m.includes('too many submissions')) {\n return new LeadSubmitError('rate_limited', 'Muitos envios agora há pouco. Tente em instantes.')\n }\n if (\n m.includes('invalid') ||\n m.includes('required') ||\n m.includes('too many fields') ||\n m.includes('fields too large')\n ) {\n return new LeadSubmitError('validation', message)\n }\n return new LeadSubmitError('unavailable', message)\n}\n\nexport function createSupabasePublicLeadProvider(\n options: SupabasePublicLeadOptions,\n): PublicLeadDataProvider {\n const { tenantId } = options\n\n return {\n async createLead(input) {\n const client = getClient()\n if (!client) {\n throw new LeadSubmitError(\n 'unavailable',\n '[plugin-crm/public] no Supabase client — register one with setGlobalSupabaseClient.',\n )\n }\n\n const { data, error } = await client.rpc('create_public_lead', {\n p_tenant_id: tenantId,\n p_name: input.name,\n p_phone: input.phone ?? null,\n p_email: input.email ?? null,\n p_form_id: input.formId,\n p_form_name: input.formName,\n p_fields: input.fields,\n p_notes: input.notes ?? null,\n p_utm: input.attribution,\n p_tags: input.tags ?? [],\n })\n\n if (error) throw toSubmitError(error.message)\n\n const row = Array.isArray(data) ? (data[0] as Record<string, unknown> | undefined) : undefined\n if (!row?.lead_id) {\n throw new LeadSubmitError('unavailable', 'Lead não foi criado.')\n }\n return { leadId: String(row.lead_id), createdAt: String(row.created_at) }\n },\n }\n}\n","// ---------------------------------------------------------------------------\n// Fayz inbox notifier — tells the site's owner a lead just arrived.\n//\n// The Fayz platform already ships a public ingest endpoint built for exactly\n// this (\"Deployed user-sites POST here\"): it stores an InboxRecord against the\n// project and emails the project owner. We only have to speak to it.\n//\n// POST <base>/public/projects/:projectId/inbox\n// { source, subject, payload, metadata }\n//\n// SAME-ORIGIN BY DEFAULT. In production the API's CORS allowlist is a single\n// origin (the editor), so a cross-origin POST from a published site would be\n// refused at preflight. Fayz's Caddy proxies `/api/*` to the API \"regardless of\n// host\", so a published site — custom domain included — reaches it same-origin\n// with no preflight at all. Hence the default base '/api' (relative). Only pass\n// an absolute base when the site is NOT served by Fayz, and expect to widen\n// CORS on the API before it works.\n//\n// Best-effort by contract: the lead is already safe in the CRM by the time this\n// runs. A failed notification is logged and swallowed — never a failed form.\n// ---------------------------------------------------------------------------\n\nimport type { LeadNotifier, LeadFields } from './types'\n\nexport interface FayzInboxNotifierOptions {\n /**\n * Fayz project id. Injected into published builds as VITE_FAYZ_PROJECT_ID;\n * omit to read that env var automatically.\n */\n projectId?: string\n /**\n * API base. Defaults to '/api' (same-origin via Caddy) — see the note above\n * before changing it.\n */\n apiBaseUrl?: string\n /** Milliseconds before giving up. The visitor is waiting; keep it short. */\n timeoutMs?: number\n}\n\nfunction readEnv(key: string): string | undefined {\n try {\n const env = (import.meta as unknown as { env?: Record<string, string | undefined> }).env\n return env?.[key]\n } catch {\n return undefined\n }\n}\n\n/** \"age_range\" → \"Age range\", unless the form gave us a real label. */\nfunction humanize(key: string, labels?: Record<string, string>): string {\n if (labels?.[key]) return labels[key]\n const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\\d])([A-Z])/g, '$1 $2')\n return spaced.charAt(0).toUpperCase() + spaced.slice(1)\n}\n\nfunction renderValue(value: unknown): string {\n if (value === null || value === undefined || value === '') return '—'\n if (Array.isArray(value)) return value.length ? value.join(', ') : '—'\n if (typeof value === 'boolean') return value ? 'Sim' : 'Não'\n return String(value)\n}\n\n/**\n * Builds the flat, already-humanized payload the inbox renders. The editor\n * shows this verbatim, so it must read like a message — not like a database row.\n */\nfunction buildPayload(\n input: Parameters<LeadNotifier['notify']>[0],\n): Record<string, string> {\n const payload: Record<string, string> = { Nome: input.leadName }\n if (input.phone) payload['Telefone'] = input.phone\n if (input.email) payload['E-mail'] = input.email\n\n for (const [key, value] of Object.entries(input.fields as LeadFields)) {\n payload[humanize(key, input.labels)] = renderValue(value)\n }\n\n const { utm_source, utm_medium, utm_campaign, landing_page } = input.attribution\n if (utm_source) payload['Origem'] = utm_source\n if (utm_medium) payload['Mídia'] = utm_medium\n if (utm_campaign) payload['Campanha'] = utm_campaign\n if (landing_page) payload['Página'] = landing_page\n\n return payload\n}\n\n/**\n * A notifier that posts to the Fayz project inbox. Returns a no-op notifier\n * (with one loud warning) when no project id is resolvable, so a site running\n * outside Fayz still submits leads normally.\n */\nexport function createFayzInboxNotifier(options: FayzInboxNotifierOptions = {}): LeadNotifier {\n const projectId = options.projectId ?? readEnv('VITE_FAYZ_PROJECT_ID')\n const apiBaseUrl = (options.apiBaseUrl ?? readEnv('VITE_FAYZ_API_BASE_URL') ?? '/api').replace(/\\/$/, '')\n const timeoutMs = options.timeoutMs ?? 4000\n\n if (!projectId) {\n let warned = false\n return {\n async notify() {\n if (!warned && typeof console !== 'undefined') {\n warned = true\n console.warn(\n '[plugin-crm/public] no VITE_FAYZ_PROJECT_ID — leads are saved to the CRM but the ' +\n 'site owner is NOT notified in the Fayz inbox.',\n )\n }\n },\n }\n }\n\n return {\n async notify(input) {\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null\n const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null\n try {\n const res = await fetch(`${apiBaseUrl}/public/projects/${projectId}/inbox`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n signal: controller?.signal,\n body: JSON.stringify({\n source: 'form',\n subject: `Novo lead: ${input.leadName} — ${input.formName}`,\n payload: buildPayload(input),\n metadata: { formId: input.formId, formName: input.formName, ...input.attribution },\n }),\n })\n if (!res.ok) {\n throw new Error(`inbox responded ${res.status}`)\n }\n } finally {\n if (timer) clearTimeout(timer)\n }\n },\n }\n}\n","import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'\nimport { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types'\n\ninterface PublicFormsContextValue {\n forms: Map<string, PublicFormDef>\n submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>\n}\n\nconst PublicFormsContext = createContext<PublicFormsContextValue | null>(null)\n\nexport interface PublicFormsProviderProps extends PublicFormsContextValue {\n children: ReactNode\n}\n\nexport function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {\n const value = useMemo(() => ({ forms, submit }), [forms, submit])\n return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>\n}\n\n/** The hook a site's own form component calls. Owns only the submission\n * lifecycle — the markup, the fields and the validation copy stay the site's. */\nexport function useLeadForm(formId: string) {\n const ctx = useContext(PublicFormsContext)\n if (!ctx) {\n throw new Error('[plugin-crm] useLeadForm must be used within <PublicFormsProvider>.')\n }\n\n const [submitting, setSubmitting] = useState(false)\n const [error, setError] = useState<LeadSubmitError | null>(null)\n const [result, setResult] = useState<LeadSubmitResult | null>(null)\n\n const submit = useCallback(\n async (values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult | null> => {\n if (submitting) return null\n setSubmitting(true)\n setError(null)\n try {\n const res = await ctx.submit(formId, values, options)\n setResult(res)\n return res\n } catch (err) {\n const e =\n err instanceof LeadSubmitError\n ? err\n : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar.')\n setError(e)\n return null\n } finally {\n setSubmitting(false)\n }\n },\n [ctx, formId, submitting],\n )\n\n const reset = useCallback(() => {\n setError(null)\n setResult(null)\n }, [])\n\n return {\n submit,\n reset,\n submitting,\n error,\n result,\n success: result !== null,\n form: ctx.forms.get(formId) ?? null,\n }\n}\n","// ---------------------------------------------------------------------------\n// Public forms plugin — \"the site collects, the SDK decides where it goes\".\n//\n// Headless on purpose. Marketing sites have bespoke, brand-heavy forms; taking\n// over their markup would be a downgrade. So this ships no UI: a site keeps its\n// own inputs and calls submit() with a plain object of values.\n//\n// Every submission fans out to two places, in this order:\n// 1. the tenant's CRM (create_public_lead) — the record of truth\n// 2. the Fayz project inbox — so the site owner is told, and gets the email\n// Step 2 is best-effort: a notification outage must never cost a lead.\n// ---------------------------------------------------------------------------\n\nimport { createElement, type FC, type ReactNode } from 'react'\nimport type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'\nimport { createSupabasePublicLeadProvider } from './data.supabase'\nimport { createFayzInboxNotifier } from './inbox'\nimport { PublicFormsProvider } from './context'\nimport {\n LeadSubmitError,\n type LeadAttribution,\n type LeadFields,\n type LeadNotifier,\n type LeadSubmitOptions,\n type LeadSubmitResult,\n type PublicFormDef,\n type PublicLeadDataProvider,\n} from './types'\n\nexport interface PublicFormsOptions {\n /**\n * Tenant the leads land in. REQUIRED — this is the whole point of the\n * abstraction: the site never names a table, only a tenant.\n */\n tenantId: string\n /** The forms this site exposes, keyed by id. */\n forms: PublicFormDef[]\n /**\n * Notify the site owner in the Fayz project inbox. Default true; resolves the\n * project from VITE_FAYZ_PROJECT_ID. Pass false for sites outside Fayz.\n */\n inbox?: boolean | { projectId?: string; apiBaseUrl?: string }\n /** Inject a custom transport (tests, or a non-Supabase backend). */\n dataProvider?: PublicLeadDataProvider\n /** Inject a custom notifier (tests). */\n notifier?: LeadNotifier\n /**\n * Marca o lead com a campanha que o trouxe, lendo a UTM da URL.\n *\n * Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag\n * automática e tag curada convivem no mesmo array, e sem prefixo a primeira\n * engole a segunda — em seis meses ninguém sabe mais quais tags alguém\n * escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,\n * relatar e limpar cada grupo separadamente.\n *\n * `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica\n * desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.\n */\n campaignTags?: boolean | { campaign?: boolean; source?: boolean }\n scope?: PluginScope\n verticalId?: VerticalId\n}\n\n/** Teto por lead — o mesmo que o RPC aplica; aparar aqui evita mandar lixo. */\nconst MAX_TAGS = 10\n\n/**\n * Slug normalizado. O servidor normaliza de novo (é ele quem manda), mas fazer\n * aqui também mantém `camp:` legível e evita gastar as 10 vagas com duplicata.\n */\nfunction slugify(input: string): string {\n return input\n .normalize('NFD')\n // Marcas combinantes: o NFD separa o acento da letra, e este range remove\n // só o acento. Escapado em vez de literal — o caractere cru é invisível no\n // editor e some em qualquer copy-paste.\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .replace(/[^a-z0-9:]+/g, '-')\n .replace(/-{2,}/g, '-')\n .replace(/^-+|-+$/g, '')\n}\n\n/** Tags curadas do formulário + as automáticas da campanha, deduplicadas. */\nfunction resolveTags(\n formTags: string[] | undefined,\n callTags: string[] | undefined,\n attribution: LeadAttribution,\n campaignTags: PublicFormsOptions['campaignTags'],\n): string[] {\n const cfg =\n campaignTags === false\n ? { campaign: false, source: false }\n : campaignTags === true || campaignTags === undefined\n ? { campaign: true, source: false }\n : { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false }\n\n const out: string[] = []\n for (const raw of [...(formTags ?? []), ...(callTags ?? [])]) {\n const slug = slugify(raw)\n if (slug) out.push(slug)\n }\n if (cfg.campaign && attribution.utm_campaign) {\n const slug = slugify(attribution.utm_campaign)\n if (slug) out.push(`camp:${slug}`)\n }\n if (cfg.source && attribution.utm_source) {\n const slug = slugify(attribution.utm_source)\n if (slug) out.push(`src:${slug}`)\n }\n return [...new Set(out)].slice(0, MAX_TAGS)\n}\n\nexport interface PublicFormsPlugin {\n manifest: PluginManifest\n Provider: FC<{ children: ReactNode }>\n /** Imperative submit, for code paths outside React. */\n submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>\n}\n\n/** Reads UTM + page context off the browser. Safe to call during SSR. */\nexport function readAttribution(): LeadAttribution {\n if (typeof window === 'undefined') return {}\n const params = new URLSearchParams(window.location.search)\n const pick = (k: string) => params.get(k) || undefined\n return {\n utm_source: pick('utm_source'),\n utm_medium: pick('utm_medium'),\n utm_campaign: pick('utm_campaign'),\n utm_term: pick('utm_term'),\n utm_content: pick('utm_content'),\n landing_page: window.location.pathname,\n referrer: document.referrer || undefined,\n }\n}\n\nfunction isEmpty(value: unknown): boolean {\n if (value === null || value === undefined) return true\n if (typeof value === 'string') return value.trim() === ''\n if (Array.isArray(value)) return value.length === 0\n return false\n}\n\nfunction stripUndefined<T extends Record<string, unknown>>(obj: T): T {\n return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined)) as T\n}\n\nexport function createPublicFormsPlugin(options: PublicFormsOptions): PublicFormsPlugin {\n const { tenantId } = options\n const formsById = new Map(options.forms.map((f) => [f.id, f]))\n\n const provider: PublicLeadDataProvider =\n options.dataProvider ?? createSupabasePublicLeadProvider({ tenantId })\n\n const notifier: LeadNotifier | null =\n options.notifier ??\n (options.inbox === false\n ? null\n : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))\n\n async function submit(\n formId: string,\n values: LeadFields,\n submitOptions?: LeadSubmitOptions,\n ): Promise<LeadSubmitResult> {\n const form = formsById.get(formId)\n if (!form) {\n throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form \"${formId}\".`)\n }\n\n // Identity fields are pulled OUT of the bag; whatever remains is custom.\n const idMap = { name: 'name', phone: 'phone', email: 'email', ...form.identity }\n const name = String(values[idMap.name] ?? '').trim()\n const phone = idMap.phone ? String(values[idMap.phone] ?? '').trim() : ''\n const email = idMap.email ? String(values[idMap.email] ?? '').trim() : ''\n const notes = idMap.notes ? String(values[idMap.notes] ?? '').trim() : ''\n\n for (const key of form.required ?? []) {\n if (isEmpty(values[key])) {\n throw new LeadSubmitError('validation', `Campo obrigatório: ${form.labels?.[key] ?? key}`)\n }\n }\n if (!name) throw new LeadSubmitError('validation', 'Nome é obrigatório.')\n if (!phone && !email) {\n throw new LeadSubmitError('validation', 'Informe telefone ou e-mail.')\n }\n\n const identityKeys = new Set(Object.values(idMap).filter(Boolean) as string[])\n const fields: LeadFields = Object.fromEntries(\n Object.entries(values).filter(([k, v]) => !identityKeys.has(k) && !isEmpty(v)),\n )\n\n const attribution = readAttribution()\n const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags)\n\n // 1. CRM — if this throws, the submission failed and the site says so.\n const { leadId, createdAt } = await provider.createLead(\n stripUndefined({\n formId: form.id,\n formName: form.name,\n name,\n phone: phone || undefined,\n email: email || undefined,\n notes: notes || undefined,\n fields,\n attribution,\n tags: tags.length ? tags : undefined,\n }),\n )\n\n // 2. Inbox — the lead is already safe; never fail the form over a notice.\n let notified = false\n if (notifier) {\n try {\n await notifier.notify({\n formId: form.id,\n formName: form.name,\n leadName: name,\n phone: phone || undefined,\n email: email || undefined,\n fields,\n labels: form.labels,\n attribution,\n })\n notified = true\n } catch (err) {\n if (typeof console !== 'undefined') {\n console.error('[plugin-crm/public] lead saved but inbox notification failed:', err)\n }\n }\n }\n\n return { leadId, createdAt, notified }\n }\n\n const Provider: FC<{ children: ReactNode }> = ({ children }) =>\n createElement(PublicFormsProvider, { forms: formsById, submit, children })\n Provider.displayName = 'PublicFormsProvider'\n\n const manifest: PluginManifest = {\n id: 'public-forms',\n name: 'Formulários',\n icon: 'Inbox',\n version: '0.1.0',\n scope: options.scope ?? 'universal',\n verticalId: options.verticalId,\n scaffolds: ['website', 'landing_page'],\n defaultEnabled: true,\n dependencies: [],\n // Headless: the site owns the markup, so this plugin mounts no route and\n // contributes no navigation. It exists to be registered and provide context.\n navigation: [],\n routes: [],\n widgets: [],\n }\n\n return { manifest, Provider, submit }\n}\n"]}
|
package/dist/public/types.d.ts
CHANGED
|
@@ -35,6 +35,31 @@ export interface PublicFormDef {
|
|
|
35
35
|
};
|
|
36
36
|
/** Labels for custom fields, so the CRM shows "Faixa etária" not "age_range". */
|
|
37
37
|
labels?: Record<string, string>;
|
|
38
|
+
/**
|
|
39
|
+
* Tags every lead from this form carries into the CRM, and from there onto
|
|
40
|
+
* the card no funil (o trigger de lead→deal copia).
|
|
41
|
+
*
|
|
42
|
+
* Isto é o vocabulário CURADO: o que a landing page É ("aluno-novo",
|
|
43
|
+
* "parceria"), não de qual campanha veio. Escreva em slug; o servidor
|
|
44
|
+
* normaliza de qualquer jeito (minúscula, sem acento, hifenizado) e descarta
|
|
45
|
+
* o que não der para normalizar em vez de derrubar o envio.
|
|
46
|
+
*
|
|
47
|
+
* Máximo de 10 tags por lead, somando estas e as automáticas.
|
|
48
|
+
*/
|
|
49
|
+
tags?: string[];
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* O que a PÁGINA decide na hora do envio, e o formulário não sabe de antemão.
|
|
53
|
+
*
|
|
54
|
+
* Existe porque uma landing page costuma ter mais de uma porta de entrada para
|
|
55
|
+
* o mesmo formulário (a home e uma campanha específica levam ao mesmo
|
|
56
|
+
* `/quero-ser-aluno`). Sem isto, distinguir as duas exigiria declarar um
|
|
57
|
+
* formulário por porta, e cada um vira uma "origem" diferente no CRM para o que
|
|
58
|
+
* é o mesmo formulário.
|
|
59
|
+
*/
|
|
60
|
+
export interface LeadSubmitOptions {
|
|
61
|
+
/** Somadas às `tags` do formulário e às automáticas da campanha. */
|
|
62
|
+
tags?: string[];
|
|
38
63
|
}
|
|
39
64
|
/** Result of a submission — enough for the site to show its own success state. */
|
|
40
65
|
export interface LeadSubmitResult {
|
|
@@ -71,6 +96,8 @@ export interface PublicLeadDataProvider {
|
|
|
71
96
|
notes?: string;
|
|
72
97
|
fields: LeadFields;
|
|
73
98
|
attribution: LeadAttribution;
|
|
99
|
+
/** Slugs já resolvidos (curados do formulário + automáticos da campanha). */
|
|
100
|
+
tags?: string[];
|
|
74
101
|
}): Promise<{
|
|
75
102
|
leadId: string;
|
|
76
103
|
createdAt: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/public/types.ts"],"names":[],"mappings":"AASA;;sDAEsD;AACtD,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,MAAM,EAAE,GAAG,MAAM,EAAE,CAAA;AAEnF;0DAC0D;AAC1D,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAA;AAEvD;;;GAGG;AACH,MAAM,WAAW,aAAa;IAC5B,wEAAwE;IACxE,EAAE,EAAE,MAAM,CAAA;IACV,wDAAwD;IACxD,IAAI,EAAE,MAAM,CAAA;IACZ;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAA;IACnB;;;;;OAKG;IACH,QAAQ,CAAC,EAAE;QACT,IAAI,CAAC,EAAE,MAAM,CAAA;QACb,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,2DAA2D;QAC3D,KAAK,CAAC,EAAE,MAAM,CAAA;KACf,CAAA;IACD,iFAAiF;IACjF,MAAM,CAAC,EAAE,MAAM,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CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAC/B,WAAW,EAAE,eAAe,CAAA;KAC7B,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAClB"}
|
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;AA2EtD,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,EA4D5C,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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type StoreApi } from 'zustand/vanilla';
|
|
2
2
|
import type { CrmDataProvider } from './data/types';
|
|
3
|
-
import type { Pipeline, PipelineStage, Lead, Deal, Activity, Quote, CrmSummary, FunnelStage, LeadQuery, DealQuery, ActivityQuery, QuoteQuery, CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput } from './types';
|
|
3
|
+
import type { Pipeline, PipelineStage, Lead, Deal, Activity, Quote, TagDef, BoardFilter, CrmSummary, FunnelStage, LeadQuery, DealQuery, ActivityQuery, QuoteQuery, CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput } from './types';
|
|
4
4
|
export interface CrmUIState {
|
|
5
5
|
pipelines: Pipeline[];
|
|
6
6
|
stages: PipelineStage[];
|
|
@@ -20,12 +20,17 @@ export interface CrmUIState {
|
|
|
20
20
|
summary: CrmSummary | null;
|
|
21
21
|
summaryLoading: boolean;
|
|
22
22
|
funnel: FunnelStage[];
|
|
23
|
+
/** Cadastro de tags, por slug — rótulo e cor dos chips. */
|
|
24
|
+
tagDefs: Map<string, TagDef>;
|
|
23
25
|
fetchPipelines(): Promise<void>;
|
|
26
|
+
fetchTagDefs(): Promise<void>;
|
|
24
27
|
fetchSummary(): Promise<void>;
|
|
25
28
|
fetchFunnel(pipelineId: string): Promise<void>;
|
|
26
29
|
fetchLeads(query: LeadQuery): Promise<void>;
|
|
27
30
|
fetchDeals(query: DealQuery): Promise<void>;
|
|
28
|
-
fetchDealsByStage(pipelineId: string): Promise<void>;
|
|
31
|
+
fetchDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<void>;
|
|
32
|
+
/** Recarrega o quadro no MESMO recorte do último fetchDealsByStage. */
|
|
33
|
+
refreshBoard(): Promise<void>;
|
|
29
34
|
fetchActivities(query: ActivityQuery): Promise<void>;
|
|
30
35
|
/** Re-fetch the timeline with the last query — writes append system events. */
|
|
31
36
|
refreshActivities(): Promise<void>;
|
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,
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":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M,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,CA0Z9E"}
|
package/dist/types.d.ts
CHANGED
|
@@ -14,6 +14,24 @@ export interface ActivityTypeDef {
|
|
|
14
14
|
icon?: string;
|
|
15
15
|
isActive: boolean;
|
|
16
16
|
}
|
|
17
|
+
/**
|
|
18
|
+
* Uma tag do cadastro (plg_crm_tags).
|
|
19
|
+
*
|
|
20
|
+
* `slug` é o contrato: é isso que vive em Lead.tags / Deal.tags. `name` e
|
|
21
|
+
* `color` são só apresentação, e por isso renomear uma tag no cadastro não
|
|
22
|
+
* toca em nenhum registro.
|
|
23
|
+
*
|
|
24
|
+
* Um slug SEM linha de cadastro continua sendo uma tag válida — a UI mostra o
|
|
25
|
+
* slug humanizado num chip neutro. É o que deixa uma campanha marcar leads hoje
|
|
26
|
+
* sem esperar alguém cadastrar a tag antes.
|
|
27
|
+
*/
|
|
28
|
+
export interface TagDef {
|
|
29
|
+
id: string;
|
|
30
|
+
slug: string;
|
|
31
|
+
name: string;
|
|
32
|
+
color?: string;
|
|
33
|
+
isActive: boolean;
|
|
34
|
+
}
|
|
17
35
|
export interface Pipeline {
|
|
18
36
|
id: string;
|
|
19
37
|
name: string;
|
|
@@ -208,6 +226,25 @@ export interface DealQuery {
|
|
|
208
226
|
page?: number;
|
|
209
227
|
pageSize?: number;
|
|
210
228
|
}
|
|
229
|
+
/** Presets de período do funil. `custom` usa `createdFrom`/`createdTo`. */
|
|
230
|
+
export type BoardPeriod = 'all' | '24h' | '7d' | 'custom';
|
|
231
|
+
/**
|
|
232
|
+
* Filtro do quadro do funil.
|
|
233
|
+
*
|
|
234
|
+
* Vazio = quadro inteiro, que é o estado em que ele abre. Um funil filtrado por
|
|
235
|
+
* padrão esconde negócio sem avisar, e a pessoa conclui que o card sumiu.
|
|
236
|
+
*/
|
|
237
|
+
export interface BoardFilter {
|
|
238
|
+
/**
|
|
239
|
+
* Slugs. Semântica OU: marcar duas tags mostra quem tem QUALQUER uma delas.
|
|
240
|
+
* É o que um multi-select de chips dá a entender ("me mostra estes
|
|
241
|
+
* segmentos"); E seria uma interseção que quase sempre volta vazia.
|
|
242
|
+
*/
|
|
243
|
+
tags?: string[];
|
|
244
|
+
/** ISO. Filtram por `created_at` do negócio. */
|
|
245
|
+
createdFrom?: string;
|
|
246
|
+
createdTo?: string;
|
|
247
|
+
}
|
|
211
248
|
export interface ActivityQuery {
|
|
212
249
|
dealId?: string;
|
|
213
250
|
leadId?: string;
|