@fayz-ai/plugin-crm 0.8.5 → 0.9.0-next.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/dist/components/LeadAttachments.d.ts +8 -0
  2. package/dist/components/LeadAttachments.d.ts.map +1 -0
  3. package/dist/data/supabase.d.ts.map +1 -1
  4. package/dist/index.js +244 -30
  5. package/dist/index.js.map +1 -1
  6. package/dist/lib/form-answers.d.ts +21 -0
  7. package/dist/lib/form-answers.d.ts.map +1 -1
  8. package/dist/lib/relative-time.d.ts +10 -0
  9. package/dist/lib/relative-time.d.ts.map +1 -0
  10. package/dist/locales/en.d.ts.map +1 -1
  11. package/dist/locales/pt-BR.d.ts.map +1 -1
  12. package/dist/migrations/index.d.ts +2 -0
  13. package/dist/migrations/index.d.ts.map +1 -1
  14. package/dist/public/context.d.ts +25 -2
  15. package/dist/public/context.d.ts.map +1 -1
  16. package/dist/public/createPublicFormsPlugin.d.ts +9 -0
  17. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  18. package/dist/public/data.supabase.d.ts.map +1 -1
  19. package/dist/public/inbox.d.ts.map +1 -1
  20. package/dist/public/index.d.ts +4 -2
  21. package/dist/public/index.d.ts.map +1 -1
  22. package/dist/public/index.js +150 -8
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/public/types.d.ts +32 -1
  25. package/dist/public/types.d.ts.map +1 -1
  26. package/dist/public/uploads.d.ts +61 -0
  27. package/dist/public/uploads.d.ts.map +1 -0
  28. package/dist/views/ActivityListView.d.ts.map +1 -1
  29. package/dist/views/DealSidebar.d.ts.map +1 -1
  30. package/dist/views/LeadDetailView.d.ts.map +1 -1
  31. package/dist/views/PipelineView.d.ts.map +1 -1
  32. package/package.json +6 -6
  33. package/src/components/LeadAttachments.tsx +140 -0
  34. package/src/data/supabase.ts +3 -0
  35. package/src/lib/form-answers.tsx +41 -0
  36. package/src/lib/relative-time.ts +84 -0
  37. package/src/locales/en.ts +1 -0
  38. package/src/locales/pt-BR.ts +1 -0
  39. package/src/migrations/015_lead_attachments.sql +357 -0
  40. package/src/migrations/016_public_lead_activity.sql +123 -0
  41. package/src/migrations/index.ts +487 -1
  42. package/src/public/context.tsx +85 -4
  43. package/src/public/createPublicFormsPlugin.ts +25 -1
  44. package/src/public/data.supabase.ts +5 -0
  45. package/src/public/inbox.ts +7 -0
  46. package/src/public/index.ts +22 -1
  47. package/src/public/types.ts +33 -1
  48. package/src/public/uploads.ts +205 -0
  49. package/src/views/ActivityListView.tsx +16 -3
  50. package/src/views/DealSidebar.tsx +47 -19
  51. package/src/views/LeadDetailView.tsx +47 -5
  52. package/src/views/PipelineView.tsx +13 -0
@@ -1,4 +1,4 @@
1
- // AUTO-GENERATED from 000_plg_rename.sql, 001_crm_base.sql, 002_activities.sql, 003_crm_views_rls.sql, 004_seed_default_pipeline.sql, 005_public_lead.sql, 006_lead_enters_pipeline.sql, 007_activity_log.sql, 008_view_field_aliases.sql, 009_deal_archived_status.sql, 010_quote_archived_status.sql, 011_agent_rpc_update_lead.sql, 012_agent_rpc_create_lead.sql, 013_tag_slugs.sql, 014_public_lead_tags.sql — regenerate with scripts/embed-migrations.mjs
1
+ // AUTO-GENERATED from 000_plg_rename.sql, 001_crm_base.sql, 002_activities.sql, 003_crm_views_rls.sql, 004_seed_default_pipeline.sql, 005_public_lead.sql, 006_lead_enters_pipeline.sql, 007_activity_log.sql, 008_view_field_aliases.sql, 009_deal_archived_status.sql, 010_quote_archived_status.sql, 011_agent_rpc_update_lead.sql, 012_agent_rpc_create_lead.sql, 013_tag_slugs.sql, 014_public_lead_tags.sql, 015_lead_attachments.sql, 016_public_lead_activity.sql — regenerate with scripts/embed-migrations.mjs
2
2
  // SQL files are the source of truth; this inline copy lets the manifest declare
3
3
  // migrations as data. Do not edit by hand — run the embed script instead.
4
4
 
@@ -1518,6 +1518,490 @@ GRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text
1518
1518
  TO anon, authenticated;
1519
1519
  `
1520
1520
 
1521
+ export const MIGRATION_015_LEAD_ATTACHMENTS = `-- plugin-crm 015: um lead pode chegar com ANEXO.
1522
+ --
1523
+ -- O que faltava: create_public_lead aceita respostas (jsonb bounded, escalares),
1524
+ -- e é exatamente por isso que foto não cabia ali — uma landing page de
1525
+ -- diagnóstico capilar coleta 4 imagens, e base64 num campo custom seria parar
1526
+ -- documento dentro do CRM. O resultado prático era pior do que parece: o site
1527
+ -- pedia as fotos, o visitante mandava, e elas morriam no navegador.
1528
+ --
1529
+ -- O desenho aqui separa as duas coisas que sempre foram diferentes: o ARQUIVO
1530
+ -- vai para o Storage; o LEAD guarda só o CAMINHO. Assim o payload do RPC segue
1531
+ -- pequeno, o anexo herda os limites do bucket (tamanho, mime) e apagar a foto
1532
+ -- não exige reescrever o lead.
1533
+ --
1534
+ -- ---------------------------------------------------------------------------
1535
+ -- UM bucket, compartilhado; as PASTAS separam.
1536
+ -- ---------------------------------------------------------------------------
1537
+ -- Um bucket por tenant não escala num pool de indústria: são centenas de
1538
+ -- tenants no mesmo projeto, e cada bucket é configuração (mime, tamanho,
1539
+ -- política) para manter em sincronia. Um bucket só, com o tenant como PRIMEIRO
1540
+ -- segmento do caminho, é o mesmo padrão que shop-images já usa aqui — e o
1541
+ -- isolamento continua sendo decidido no banco, não no cliente.
1542
+ --
1543
+ -- Gramática do caminho (o SDK constrói, o banco confere):
1544
+ --
1545
+ -- {tenant_id}/{form_id}/{yyyy}/{mm}/{submission_id}/{slot}.{ext}
1546
+ -- 1 2 3 4 5 6
1547
+ --
1548
+ -- 1 tenant_id chave do isolamento — toda policy pendura aqui
1549
+ -- 2 form_id "capilar", "parceria" — dá listagem por formulário
1550
+ -- 3,4 yyyy/mm varredura de retenção por prefixo (LGPD) e pasta listável
1551
+ -- 5 submission_id uuid do cliente: agrupa os arquivos de UM envio e é
1552
+ -- imprevisível, então caminho não se adivinha nem colide
1553
+ -- 6 slot "frente", "nuca" — o nome que o operador entende
1554
+ --
1555
+ -- Confiança: quem escreve aqui é um browser ANÔNIMO. Ele não pode ler, não pode
1556
+ -- apagar, não pode sobrescrever (não há policy de UPDATE) e não pode escrever
1557
+ -- fora de um tenant que exista. Ler é privilégio de quem está logado no tenant
1558
+ -- daquela pasta.
1559
+
1560
+ -- ---------------------------------------------------------------------------
1561
+ -- 1. o bucket
1562
+ -- ---------------------------------------------------------------------------
1563
+ -- PRIVADO de propósito: anexo de lead é dado pessoal (numa clínica, dado de
1564
+ -- saúde). URL pública seria um endereço eterno e adivinhável para a foto do
1565
+ -- couro cabeludo de alguém. O backoffice lê por URL assinada, de curta duração.
1566
+ --
1567
+ -- DO UPDATE em vez de DO NOTHING: o re-apply converge a configuração do bucket
1568
+ -- (limite, mimes) em vez de deixar um pool antigo com o ajuste errado.
1569
+ INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
1570
+ VALUES (
1571
+ 'crm-lead-uploads',
1572
+ 'crm-lead-uploads',
1573
+ false,
1574
+ 10485760, -- 10 MB: foto de celular já comprimida cabe; documento não vira dump
1575
+ ARRAY['image/jpeg','image/png','image/webp','image/heic','image/heif','application/pdf']
1576
+ )
1577
+ ON CONFLICT (id) DO UPDATE SET
1578
+ public = EXCLUDED.public,
1579
+ file_size_limit = EXCLUDED.file_size_limit,
1580
+ allowed_mime_types = EXCLUDED.allowed_mime_types;
1581
+
1582
+ -- ---------------------------------------------------------------------------
1583
+ -- 2. o caminho é válido?
1584
+ -- ---------------------------------------------------------------------------
1585
+ -- SECURITY DEFINER porque a checagem precisa olhar \`tenants\`, que tem RLS: um
1586
+ -- EXISTS avaliado como anon voltaria falso para TODO mundo e o upload nunca
1587
+ -- passaria. STABLE + sem efeito colateral: só responde sim/não sobre um texto.
1588
+ CREATE OR REPLACE FUNCTION public.crm_lead_upload_path_ok(p_name text)
1589
+ RETURNS boolean
1590
+ LANGUAGE sql
1591
+ STABLE
1592
+ SECURITY DEFINER
1593
+ SET search_path TO 'public'
1594
+ AS $function$
1595
+ SELECT
1596
+ p_name IS NOT NULL
1597
+ AND length(p_name) <= 300
1598
+ -- 6 segmentos, na ordem da gramática acima. O regex barra ".." e "/" extra
1599
+ -- (o range de cada segmento não inclui barra nem ponto-ponto no início).
1600
+ AND p_name ~ ('^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
1601
+ || '/[a-z0-9][a-z0-9._-]{0,63}'
1602
+ || '/[0-9]{4}/[0-9]{2}'
1603
+ || '/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
1604
+ || '/[a-z0-9][a-z0-9._-]{0,63}\\.[a-z0-9]{1,8}$')
1605
+ -- comparação em texto (nunca \`::uuid\`): entrada malformada devolve falso em
1606
+ -- vez de derrubar a policy com erro de cast.
1607
+ AND EXISTS (
1608
+ SELECT 1 FROM public.tenants t WHERE t.id::text = split_part(p_name, '/', 1)
1609
+ );
1610
+ $function$;
1611
+
1612
+ COMMENT ON FUNCTION public.crm_lead_upload_path_ok(text) IS
1613
+ 'True when a storage object name follows the crm-lead-uploads grammar {tenant}/{form}/{yyyy}/{mm}/{submission}/{slot.ext} and segment 1 is a real tenant. Used by the anon INSERT policy on that bucket.';
1614
+
1615
+ GRANT EXECUTE ON FUNCTION public.crm_lead_upload_path_ok(text) TO anon, authenticated;
1616
+
1617
+ -- ---------------------------------------------------------------------------
1618
+ -- 3. políticas do bucket
1619
+ -- ---------------------------------------------------------------------------
1620
+ DROP POLICY IF EXISTS plg_crm_lead_uploads_insert ON storage.objects;
1621
+ DROP POLICY IF EXISTS plg_crm_lead_uploads_read ON storage.objects;
1622
+ DROP POLICY IF EXISTS plg_crm_lead_uploads_delete ON storage.objects;
1623
+
1624
+ -- Escrever: qualquer visitante, desde que dentro da gramática e de um tenant
1625
+ -- real. Não existe policy de UPDATE — sem ela o \`upsert\` falha, e um caminho
1626
+ -- já gravado não pode ser trocado por outro conteúdo.
1627
+ CREATE POLICY plg_crm_lead_uploads_insert ON storage.objects
1628
+ FOR INSERT TO anon, authenticated
1629
+ WITH CHECK (
1630
+ bucket_id = 'crm-lead-uploads'
1631
+ AND public.crm_lead_upload_path_ok(name)
1632
+ );
1633
+
1634
+ -- Ler: só quem está logado, e só na pasta de um tenant do qual é membro —
1635
+ -- a forma canônica de isolamento deste repo.
1636
+ CREATE POLICY plg_crm_lead_uploads_read ON storage.objects
1637
+ FOR SELECT TO authenticated
1638
+ USING (
1639
+ bucket_id = 'crm-lead-uploads'
1640
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text)
1641
+ );
1642
+
1643
+ -- Apagar: mesma regra da leitura. É o que torna "excluir os dados deste lead"
1644
+ -- executável por quem é dono deles.
1645
+ CREATE POLICY plg_crm_lead_uploads_delete ON storage.objects
1646
+ FOR DELETE TO authenticated
1647
+ USING (
1648
+ bucket_id = 'crm-lead-uploads'
1649
+ AND (storage.foldername(name))[1] IN (SELECT public.user_tenant_ids()::text)
1650
+ );
1651
+
1652
+ -- ---------------------------------------------------------------------------
1653
+ -- 4. o RPC público ganha p_attachments
1654
+ -- ---------------------------------------------------------------------------
1655
+ -- A assinatura de 014 precisa SAIR, pela mesma razão de lá: duas candidatas com
1656
+ -- os mesmos nomes de parâmetro fazem o PostgREST devolver PGRST203 em vez de
1657
+ -- escolher uma.
1658
+ DROP FUNCTION IF EXISTS public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[]);
1659
+
1660
+ CREATE OR REPLACE FUNCTION public.create_public_lead(
1661
+ p_tenant_id uuid,
1662
+ p_name text,
1663
+ p_phone text DEFAULT NULL,
1664
+ p_email text DEFAULT NULL,
1665
+ p_form_id text DEFAULT NULL,
1666
+ p_form_name text DEFAULT NULL,
1667
+ p_fields jsonb DEFAULT '{}'::jsonb,
1668
+ p_notes text DEFAULT NULL,
1669
+ p_utm jsonb DEFAULT '{}'::jsonb,
1670
+ p_tags text[] DEFAULT '{}'::text[],
1671
+ p_attachments jsonb DEFAULT '[]'::jsonb
1672
+ )
1673
+ RETURNS TABLE(lead_id uuid, created_at timestamptz)
1674
+ LANGUAGE plpgsql
1675
+ SECURITY DEFINER
1676
+ SET search_path TO 'public'
1677
+ AS $function$
1678
+ DECLARE
1679
+ v_person_id uuid;
1680
+ v_phone text;
1681
+ v_email text;
1682
+ v_fields jsonb;
1683
+ v_utm jsonb;
1684
+ v_tags text[];
1685
+ v_attachments jsonb;
1686
+ v_recent int;
1687
+ BEGIN
1688
+ -- ---------------------------------------------------------------------
1689
+ -- validation: anon-callable, so everything is checked here
1690
+ -- ---------------------------------------------------------------------
1691
+ IF p_name IS NULL OR length(trim(p_name)) NOT BETWEEN 2 AND 120 THEN
1692
+ RAISE EXCEPTION 'invalid name';
1693
+ END IF;
1694
+
1695
+ v_phone := NULLIF(regexp_replace(COALESCE(p_phone, ''), '\\D', '', 'g'), '');
1696
+ IF v_phone IS NOT NULL AND length(v_phone) NOT BETWEEN 8 AND 15 THEN
1697
+ RAISE EXCEPTION 'invalid phone';
1698
+ END IF;
1699
+
1700
+ v_email := NULLIF(trim(COALESCE(p_email, '')), '');
1701
+ IF v_email IS NOT NULL AND (length(v_email) > 254 OR v_email !~ '^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$') THEN
1702
+ RAISE EXCEPTION 'invalid email';
1703
+ END IF;
1704
+
1705
+ -- a lead with no way to reach them back is not a lead
1706
+ IF v_phone IS NULL AND v_email IS NULL THEN
1707
+ RAISE EXCEPTION 'phone or email required';
1708
+ END IF;
1709
+
1710
+ PERFORM 1 FROM tenants t WHERE t.id = p_tenant_id;
1711
+ IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;
1712
+
1713
+ -- ---------------------------------------------------------------------
1714
+ -- custom fields: object-only, bounded, and scalars only.
1715
+ -- ---------------------------------------------------------------------
1716
+ v_fields := COALESCE(p_fields, '{}'::jsonb);
1717
+ IF jsonb_typeof(v_fields) <> 'object' THEN
1718
+ RAISE EXCEPTION 'fields must be an object';
1719
+ END IF;
1720
+ IF length(v_fields::text) > 8000 THEN
1721
+ RAISE EXCEPTION 'fields too large';
1722
+ END IF;
1723
+ IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN
1724
+ RAISE EXCEPTION 'too many fields';
1725
+ END IF;
1726
+
1727
+ v_utm := COALESCE(p_utm, '{}'::jsonb);
1728
+ IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN
1729
+ RAISE EXCEPTION 'invalid utm';
1730
+ END IF;
1731
+
1732
+ -- ---------------------------------------------------------------------
1733
+ -- anexos: o lead guarda PONTEIRO, nunca conteúdo.
1734
+ --
1735
+ -- A regra que importa é a última: o caminho tem de começar pela pasta DESTE
1736
+ -- tenant. Sem ela, um caller poderia pendurar no próprio lead o caminho de um
1737
+ -- arquivo de outro tenant e ler, pelo backoffice, o que não é dele — o
1738
+ -- isolamento do bucket seria contornado pelo lado do CRM.
1739
+ --
1740
+ -- Anexo inválido é DESCARTADO, não derruba o envio: o formulário já foi
1741
+ -- preenchido, e perder o lead inteiro por causa de um caminho torto seria
1742
+ -- trocar o essencial pelo acessório (mesma escolha de 014 para as tags).
1743
+ -- ---------------------------------------------------------------------
1744
+ v_attachments := COALESCE(p_attachments, '[]'::jsonb);
1745
+ IF jsonb_typeof(v_attachments) <> 'array' THEN
1746
+ RAISE EXCEPTION 'attachments must be an array';
1747
+ END IF;
1748
+ IF jsonb_array_length(v_attachments) > 10 THEN
1749
+ RAISE EXCEPTION 'too many attachments';
1750
+ END IF;
1751
+
1752
+ SELECT jsonb_agg(a) INTO v_attachments FROM (
1753
+ SELECT jsonb_strip_nulls(jsonb_build_object(
1754
+ -- gravado por anexo, e não uma vez no plugin: se o bucket for renomeado,
1755
+ -- as linhas antigas continuam sabendo onde o arquivo delas está.
1756
+ 'bucket', 'crm-lead-uploads',
1757
+ 'path', e->>'path',
1758
+ 'slot', left(NULLIF(trim(COALESCE(e->>'slot', '')), ''), 48),
1759
+ 'mime', left(NULLIF(trim(COALESCE(e->>'mime', '')), ''), 128),
1760
+ 'size', CASE WHEN (e->>'size') ~ '^[0-9]{1,12}$' THEN (e->>'size')::bigint END
1761
+ )) AS a
1762
+ FROM jsonb_array_elements(v_attachments) e
1763
+ WHERE jsonb_typeof(e) = 'object'
1764
+ AND e->>'path' IS NOT NULL
1765
+ AND length(e->>'path') BETWEEN 16 AND 300
1766
+ AND e->>'path' LIKE p_tenant_id::text || '/%'
1767
+ ) valid;
1768
+ v_attachments := COALESCE(v_attachments, '[]'::jsonb);
1769
+
1770
+ -- ---------------------------------------------------------------------
1771
+ -- tags: normalizadas e limitadas aqui.
1772
+ -- ---------------------------------------------------------------------
1773
+ SELECT array_agg(s) INTO v_tags FROM (
1774
+ SELECT DISTINCT public.crm_tag_slug(t) AS s
1775
+ FROM unnest(COALESCE(p_tags, '{}'::text[])) AS t
1776
+ WHERE public.crm_tag_slug(t) IS NOT NULL
1777
+ AND length(public.crm_tag_slug(t)) <= 48
1778
+ LIMIT 10
1779
+ ) normalized;
1780
+ v_tags := COALESCE(v_tags, '{}'::text[]);
1781
+
1782
+ -- ---------------------------------------------------------------------
1783
+ -- anti-spam: same tenant + same contact + same form, twice in 5 minutes is
1784
+ -- a double-click or a bot, not two inquiries.
1785
+ -- ---------------------------------------------------------------------
1786
+ SELECT count(*) INTO v_recent
1787
+ FROM people p
1788
+ WHERE p.tenant_id = p_tenant_id
1789
+ AND p.kind = 'lead'
1790
+ AND p.created_at > now() - interval '5 minutes'
1791
+ AND COALESCE(p.metadata->>'formId', '') = COALESCE(p_form_id, '')
1792
+ AND (
1793
+ (v_phone IS NOT NULL AND p.phone = v_phone)
1794
+ OR (v_email IS NOT NULL AND p.email = v_email)
1795
+ );
1796
+ IF v_recent > 0 THEN
1797
+ RAISE EXCEPTION 'duplicate submission';
1798
+ END IF;
1799
+
1800
+ -- burst cap per tenant: a flood is never legitimate marketing traffic
1801
+ IF (
1802
+ SELECT count(*) FROM people p
1803
+ WHERE p.tenant_id = p_tenant_id
1804
+ AND p.kind = 'lead'
1805
+ AND p.created_at > now() - interval '1 minute'
1806
+ ) >= 20 THEN
1807
+ RAISE EXCEPTION 'too many submissions';
1808
+ END IF;
1809
+
1810
+ -- ---------------------------------------------------------------------
1811
+ -- the lead. status/kind are hardcoded — the caller cannot promote itself
1812
+ -- into a customer or land pre-qualified.
1813
+ -- ---------------------------------------------------------------------
1814
+ INSERT INTO people (tenant_id, kind, name, phone, email, notes, tags, is_active, metadata)
1815
+ VALUES (
1816
+ p_tenant_id,
1817
+ 'lead',
1818
+ trim(p_name),
1819
+ v_phone,
1820
+ v_email,
1821
+ left(p_notes, 2000),
1822
+ v_tags,
1823
+ true,
1824
+ jsonb_strip_nulls(
1825
+ jsonb_build_object(
1826
+ 'status', 'new',
1827
+ 'source', 'public_form',
1828
+ 'sourceName', COALESCE(NULLIF(trim(COALESCE(p_form_name, '')), ''), 'Site'),
1829
+ 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),
1830
+ 'fields', v_fields,
1831
+ 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END,
1832
+ 'attachments', CASE WHEN v_attachments = '[]'::jsonb THEN NULL ELSE v_attachments END
1833
+ )
1834
+ )
1835
+ )
1836
+ RETURNING id, people.created_at INTO v_person_id, created_at;
1837
+
1838
+ -- O cadastro de tags se alimenta do que foi usado, para a tela de settings
1839
+ -- refletir a realidade sem ninguém pré-preencher nada.
1840
+ IF array_length(v_tags, 1) > 0 THEN
1841
+ PERFORM public.crm_register_tags(p_tenant_id, v_tags);
1842
+ END IF;
1843
+
1844
+ lead_id := v_person_id;
1845
+ RETURN NEXT;
1846
+ END;
1847
+ $function$;
1848
+
1849
+ GRANT EXECUTE ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb)
1850
+ TO anon, authenticated;
1851
+
1852
+ -- ---------------------------------------------------------------------------
1853
+ -- 5. v_leads devolve os anexos
1854
+ -- ---------------------------------------------------------------------------
1855
+ -- Sem esta coluna o anexo é write-only: chega no metadata e nenhuma tela do CRM
1856
+ -- consegue ler de volta. Colunas são APENDADAS (CREATE OR REPLACE não reordena
1857
+ -- nem remove) sobre a forma de 008, e security_invoker=true mantém o RLS de
1858
+ -- people escopando as linhas por tenant.
1859
+ CREATE OR REPLACE VIEW public.v_leads
1860
+ WITH (security_invoker = true) AS
1861
+ SELECT
1862
+ p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
1863
+ p.metadata->>'company' AS company,
1864
+ p.metadata->>'sourceId' AS source_id,
1865
+ p.metadata->>'sourceName' AS source_name,
1866
+ COALESCE(p.metadata->>'status','new') AS lead_status,
1867
+ p.metadata->>'value' AS lead_value,
1868
+ p.metadata->>'assignedToId' AS assigned_to_id,
1869
+ p.created_at, p.updated_at,
1870
+ p.metadata->>'formId' AS form_id,
1871
+ COALESCE(p.metadata->'fields', '{}'::jsonb) AS custom_fields,
1872
+ COALESCE(p.metadata->'utm', '{}'::jsonb) AS utm,
1873
+ COALESCE(p.metadata->>'status','new') AS status,
1874
+ COALESCE(p.metadata->'attachments', '[]'::jsonb) AS attachments
1875
+ FROM public.people p
1876
+ WHERE p.kind = 'lead';
1877
+ GRANT SELECT ON public.v_leads TO authenticated;
1878
+ `
1879
+
1880
+ export const MIGRATION_016_PUBLIC_LEAD_ACTIVITY = `-- plugin-crm 016: lead vindo do site também entra no histórico.
1881
+ --
1882
+ -- O buraco: a linha do tempo (plg_crm_activities) é escrita pelo DATA PROVIDER
1883
+ -- — quando alguém cadastra um lead pelo admin, o TypeScript chama logEvent
1884
+ -- logo depois. O formulário público não passa por lá: ele fala direto com
1885
+ -- \`create_public_lead\`, um RPC, e não há cliente nenhum para registrar o
1886
+ -- evento.
1887
+ --
1888
+ -- O efeito é o que se vê na tela: o lead do site aparece no funil (o trigger de
1889
+ -- 006 cria o card) e some da aba Atividades. Quem trabalha pela linha do tempo
1890
+ -- simplesmente não fica sabendo que ele chegou — que é o oposto do motivo de
1891
+ -- existir de um formulário de captação.
1892
+ --
1893
+ -- Onde consertar: no TRIGGER, não no RPC. É lá que o id do card já é conhecido,
1894
+ -- e assim qualquer caminho que crie um lead público — este RPC hoje, outro
1895
+ -- amanhã — cai na mesma regra.
1896
+ --
1897
+ -- E só para lead PÚBLICO: o caminho do admin já registra pelo provider, e
1898
+ -- gravar aqui também produziria dois eventos idênticos para o mesmo cadastro.
1899
+
1900
+ CREATE OR REPLACE FUNCTION public.crm_log_public_lead_activity(p_lead_id uuid, p_deal_id uuid)
1901
+ RETURNS void
1902
+ LANGUAGE plpgsql
1903
+ SECURITY DEFINER
1904
+ SET search_path TO 'public'
1905
+ AS $function$
1906
+ DECLARE
1907
+ v_lead public.people%ROWTYPE;
1908
+ v_deal_id uuid := p_deal_id;
1909
+ BEGIN
1910
+ SELECT * INTO v_lead FROM public.people WHERE id = p_lead_id;
1911
+ IF NOT FOUND OR v_lead.kind <> 'lead' THEN RETURN; END IF;
1912
+
1913
+ -- Só o que veio de formulário público. Ver o cabeçalho.
1914
+ IF COALESCE(v_lead.metadata->>'source', '') <> 'public_form' THEN RETURN; END IF;
1915
+
1916
+ -- \`crm_place_lead_on_board\` devolve NULL quando o card JÁ existia (re-run,
1917
+ -- backfill). O evento continua devendo ser registrado, então o card é
1918
+ -- buscado em vez de assumido ausente.
1919
+ IF v_deal_id IS NULL THEN
1920
+ SELECT order_id INTO v_deal_id
1921
+ FROM public.plg_crm_deal_extensions WHERE lead_id = v_lead.id;
1922
+ END IF;
1923
+
1924
+ -- \`completed_at\` preenchido: é fato consumado, não tarefa pendente — a
1925
+ -- listagem separa as duas coisas por esta coluna.
1926
+ INSERT INTO public.plg_crm_activities
1927
+ (tenant_id, lead_id, contact_name, activity_type, title, description, completed_at, created_at)
1928
+ SELECT
1929
+ v_lead.tenant_id, v_lead.id, v_lead.name, 'lead_created', v_lead.name,
1930
+ -- Qual formulário trouxe. É a primeira pergunta de quem abre a lista.
1931
+ NULLIF(v_lead.metadata->>'sourceName', ''),
1932
+ v_lead.created_at, v_lead.created_at
1933
+ WHERE NOT EXISTS (
1934
+ SELECT 1 FROM public.plg_crm_activities a
1935
+ WHERE a.lead_id = v_lead.id AND a.activity_type = 'lead_created'
1936
+ );
1937
+
1938
+ IF v_deal_id IS NOT NULL THEN
1939
+ INSERT INTO public.plg_crm_activities
1940
+ (tenant_id, deal_id, lead_id, contact_name, activity_type, title, completed_at, created_at)
1941
+ SELECT
1942
+ v_lead.tenant_id, v_deal_id, v_lead.id, v_lead.name, 'deal_created', v_lead.name,
1943
+ v_lead.created_at, v_lead.created_at
1944
+ WHERE NOT EXISTS (
1945
+ SELECT 1 FROM public.plg_crm_activities a
1946
+ WHERE a.deal_id = v_deal_id AND a.activity_type = 'deal_created'
1947
+ );
1948
+ END IF;
1949
+ END;
1950
+ $function$;
1951
+
1952
+ COMMENT ON FUNCTION public.crm_log_public_lead_activity(uuid, uuid) IS
1953
+ 'Writes the lead_created/deal_created timeline entries for a lead captured by a public form (the admin path logs these from the data provider). Idempotent per lead/deal.';
1954
+
1955
+ -- ---------------------------------------------------------------------------
1956
+ -- O trigger de 006, agora também registrando.
1957
+ -- ---------------------------------------------------------------------------
1958
+ -- CREATE OR REPLACE da função do trigger: os próprios triggers (006) continuam
1959
+ -- apontando para ela, então nada precisa ser recriado.
1960
+ CREATE OR REPLACE FUNCTION public.crm_lead_to_board()
1961
+ RETURNS trigger
1962
+ LANGUAGE plpgsql
1963
+ SECURITY DEFINER
1964
+ SET search_path TO 'public'
1965
+ AS $function$
1966
+ DECLARE
1967
+ v_deal_id uuid;
1968
+ BEGIN
1969
+ IF NEW.kind <> 'lead' THEN RETURN NEW; END IF;
1970
+
1971
+ -- AFTER INSERT/UPDATE: uma falha aqui não pode derrubar a captação do lead.
1972
+ -- Registrar a chegada é importante; perder o lead por causa disso, não.
1973
+ BEGIN
1974
+ v_deal_id := public.crm_place_lead_on_board(NEW.id);
1975
+ PERFORM public.crm_log_public_lead_activity(NEW.id, v_deal_id);
1976
+ EXCEPTION WHEN OTHERS THEN
1977
+ RAISE WARNING 'crm_lead_to_board failed for lead %: %', NEW.id, SQLERRM;
1978
+ END;
1979
+
1980
+ -- AFTER trigger: o retorno é ignorado — NULL é a convenção, e é o que 006 usa.
1981
+ RETURN NULL;
1982
+ END;
1983
+ $function$;
1984
+
1985
+ -- ---------------------------------------------------------------------------
1986
+ -- Backfill: os leads públicos que já chegaram antes desta migration.
1987
+ -- ---------------------------------------------------------------------------
1988
+ -- Sem isto, a aba Atividades continua sem os leads que motivaram o conserto.
1989
+ -- Idempotente pelo mesmo NOT EXISTS por lead/card.
1990
+ DO $$
1991
+ DECLARE r record;
1992
+ BEGIN
1993
+ FOR r IN
1994
+ SELECT p.id AS lead_id, de.order_id AS deal_id
1995
+ FROM public.people p
1996
+ LEFT JOIN public.plg_crm_deal_extensions de ON de.lead_id = p.id
1997
+ WHERE p.kind = 'lead'
1998
+ AND COALESCE(p.metadata->>'source', '') = 'public_form'
1999
+ LOOP
2000
+ PERFORM public.crm_log_public_lead_activity(r.lead_id, r.deal_id);
2001
+ END LOOP;
2002
+ END $$;
2003
+ `
2004
+
1521
2005
  export const MIGRATIONS: Array<{ id: string; sql: string }> = [
1522
2006
  { id: "000_plg_rename", sql: MIGRATION_000_PLG_RENAME },
1523
2007
  { id: "001_crm_base", sql: MIGRATION_001_CRM_BASE },
@@ -1534,4 +2018,6 @@ export const MIGRATIONS: Array<{ id: string; sql: string }> = [
1534
2018
  { id: "012_agent_rpc_create_lead", sql: MIGRATION_012_AGENT_RPC_CREATE_LEAD },
1535
2019
  { id: "013_tag_slugs", sql: MIGRATION_013_TAG_SLUGS },
1536
2020
  { id: "014_public_lead_tags", sql: MIGRATION_014_PUBLIC_LEAD_TAGS },
2021
+ { id: "015_lead_attachments", sql: MIGRATION_015_LEAD_ATTACHMENTS },
2022
+ { id: "016_public_lead_activity", sql: MIGRATION_016_PUBLIC_LEAD_ACTIVITY },
1537
2023
  ]
@@ -1,9 +1,19 @@
1
- import { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
2
- import { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types'
1
+ import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from 'react'
2
+ import {
3
+ LeadSubmitError,
4
+ type LeadAttachment,
5
+ type LeadFields,
6
+ type LeadSubmitOptions,
7
+ type LeadSubmitResult,
8
+ type PublicFormDef,
9
+ } from './types'
10
+ import { newSubmissionId, type LeadUploader } from './uploads'
3
11
 
4
12
  interface PublicFormsContextValue {
5
13
  forms: Map<string, PublicFormDef>
6
14
  submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>
15
+ /** Null quando o app desligou anexos (`uploads: false`). */
16
+ uploader: LeadUploader | null
7
17
  }
8
18
 
9
19
  const PublicFormsContext = createContext<PublicFormsContextValue | null>(null)
@@ -12,8 +22,8 @@ export interface PublicFormsProviderProps extends PublicFormsContextValue {
12
22
  children: ReactNode
13
23
  }
14
24
 
15
- export function PublicFormsProvider({ forms, submit, children }: PublicFormsProviderProps) {
16
- const value = useMemo(() => ({ forms, submit }), [forms, submit])
25
+ export function PublicFormsProvider({ forms, submit, uploader, children }: PublicFormsProviderProps) {
26
+ const value = useMemo(() => ({ forms, submit, uploader }), [forms, submit, uploader])
17
27
  return <PublicFormsContext.Provider value={value}>{children}</PublicFormsContext.Provider>
18
28
  }
19
29
 
@@ -67,3 +77,74 @@ export function useLeadForm(formId: string) {
67
77
  form: ctx.forms.get(formId) ?? null,
68
78
  }
69
79
  }
80
+
81
+ /**
82
+ * Anexos de um formulário público.
83
+ *
84
+ * Separado de `useLeadForm` de propósito, porque os dois tempos são diferentes:
85
+ * o arquivo sobe ENQUANTO a pessoa preenche (é o passo lento, e ela precisa ver
86
+ * acontecer), e o lead é criado no fim. Amarrar os dois obrigaria a segurar
87
+ * megabytes em memória até o envio — que é exatamente o que este desenho
88
+ * substitui.
89
+ *
90
+ * Todos os anexos de um preenchimento compartilham um `submissionId`, então
91
+ * caem na mesma pasta do Storage.
92
+ */
93
+ export function useLeadUploads(formId: string) {
94
+ const ctx = useContext(PublicFormsContext)
95
+ if (!ctx) {
96
+ throw new Error('[plugin-crm] useLeadUploads must be used within <PublicFormsProvider>.')
97
+ }
98
+
99
+ // Um id por montagem do formulário: os arquivos deste preenchimento
100
+ // pertencem à mesma pasta, mesmo enviados minutos depois um do outro.
101
+ const submissionIdRef = useRef<string | null>(null)
102
+ if (submissionIdRef.current === null) submissionIdRef.current = newSubmissionId()
103
+
104
+ const [uploading, setUploading] = useState(false)
105
+ const [error, setError] = useState<LeadSubmitError | null>(null)
106
+
107
+ const upload = useCallback(
108
+ async (slot: string, file: File | Blob): Promise<LeadAttachment | null> => {
109
+ if (!ctx.uploader) {
110
+ setError(new LeadSubmitError('unavailable', 'Envio de arquivos não está habilitado neste site.'))
111
+ return null
112
+ }
113
+ setUploading(true)
114
+ setError(null)
115
+ try {
116
+ return await ctx.uploader.upload({
117
+ formId,
118
+ slot,
119
+ file,
120
+ submissionId: submissionIdRef.current!,
121
+ })
122
+ } catch (err) {
123
+ const e =
124
+ err instanceof LeadSubmitError
125
+ ? err
126
+ : new LeadSubmitError('unavailable', (err as Error)?.message ?? 'Falha ao enviar o arquivo.')
127
+ setError(e)
128
+ return null
129
+ } finally {
130
+ setUploading(false)
131
+ }
132
+ },
133
+ [ctx.uploader, formId],
134
+ )
135
+
136
+ /** Começa um novo preenchimento — chame depois de um envio bem-sucedido. */
137
+ const reset = useCallback(() => {
138
+ submissionIdRef.current = newSubmissionId()
139
+ setError(null)
140
+ }, [])
141
+
142
+ return {
143
+ upload,
144
+ reset,
145
+ uploading,
146
+ error,
147
+ enabled: ctx.uploader !== null,
148
+ submissionId: submissionIdRef.current!,
149
+ }
150
+ }
@@ -16,6 +16,7 @@ import type { PluginManifest, PluginScope, VerticalId } from '@fayz-ai/core'
16
16
  import { createSupabasePublicLeadProvider } from './data.supabase'
17
17
  import { createFayzInboxNotifier } from './inbox'
18
18
  import { PublicFormsProvider } from './context'
19
+ import { createSupabaseLeadUploader, MAX_LEAD_ATTACHMENTS, type LeadUploader } from './uploads'
19
20
  import {
20
21
  LeadSubmitError,
21
22
  type LeadAttribution,
@@ -44,6 +45,14 @@ export interface PublicFormsOptions {
44
45
  dataProvider?: PublicLeadDataProvider
45
46
  /** Inject a custom notifier (tests). */
46
47
  notifier?: LeadNotifier
48
+ /**
49
+ * Anexos nos formulários (fotos, documentos). Ligado por padrão; o arquivo vai
50
+ * para o bucket que o plugin resolve, na pasta do tenant. `false` desliga —
51
+ * `useLeadUploads().enabled` fica falso e o site não oferece o campo.
52
+ *
53
+ * Injete um `LeadUploader` para testar sem rede.
54
+ */
55
+ uploads?: boolean | LeadUploader
47
56
  /**
48
57
  * Marca o lead com a campanha que o trouxe, lendo a UTM da URL.
49
58
  *
@@ -158,6 +167,13 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
158
167
  ? null
159
168
  : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))
160
169
 
170
+ const uploader: LeadUploader | null =
171
+ options.uploads === false
172
+ ? null
173
+ : typeof options.uploads === 'object'
174
+ ? options.uploads
175
+ : createSupabaseLeadUploader({ tenantId })
176
+
161
177
  async function submit(
162
178
  formId: string,
163
179
  values: LeadFields,
@@ -193,6 +209,12 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
193
209
  const attribution = readAttribution()
194
210
  const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags)
195
211
 
212
+ // Ponteiros para arquivos que JÁ subiram (useLeadUploads). Aparados no teto
213
+ // do RPC: mandar mais só faria o servidor recusar o envio inteiro.
214
+ const attachments = (submitOptions?.attachments ?? [])
215
+ .filter((a) => a && typeof a.path === 'string' && a.path.length > 0)
216
+ .slice(0, MAX_LEAD_ATTACHMENTS)
217
+
196
218
  // 1. CRM — if this throws, the submission failed and the site says so.
197
219
  const { leadId, createdAt } = await provider.createLead(
198
220
  stripUndefined({
@@ -205,6 +227,7 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
205
227
  fields,
206
228
  attribution,
207
229
  tags: tags.length ? tags : undefined,
230
+ attachments: attachments.length ? attachments : undefined,
208
231
  }),
209
232
  )
210
233
 
@@ -221,6 +244,7 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
221
244
  fields,
222
245
  labels: form.labels,
223
246
  attribution,
247
+ attachmentCount: attachments.length || undefined,
224
248
  })
225
249
  notified = true
226
250
  } catch (err) {
@@ -234,7 +258,7 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
234
258
  }
235
259
 
236
260
  const Provider: FC<{ children: ReactNode }> = ({ children }) =>
237
- createElement(PublicFormsProvider, { forms: formsById, submit, children })
261
+ createElement(PublicFormsProvider, { forms: formsById, submit, uploader, children })
238
262
  Provider.displayName = 'PublicFormsProvider'
239
263
 
240
264
  const manifest: PluginManifest = {