@fayz-ai/plugin-crm 0.11.3 → 0.12.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.
Files changed (53) hide show
  1. package/dist/components/AssigneeRota.d.ts +10 -0
  2. package/dist/components/AssigneeRota.d.ts.map +1 -0
  3. package/dist/components/LinkContactDialog.d.ts +16 -0
  4. package/dist/components/LinkContactDialog.d.ts.map +1 -0
  5. package/dist/components/PersonPhones.d.ts +20 -0
  6. package/dist/components/PersonPhones.d.ts.map +1 -0
  7. package/dist/context.d.ts +2 -0
  8. package/dist/context.d.ts.map +1 -1
  9. package/dist/data/mock.d.ts.map +1 -1
  10. package/dist/data/registries.d.ts.map +1 -1
  11. package/dist/data/supabase.d.ts.map +1 -1
  12. package/dist/data/tables.d.ts +15 -0
  13. package/dist/data/tables.d.ts.map +1 -1
  14. package/dist/data/types.d.ts +23 -1
  15. package/dist/data/types.d.ts.map +1 -1
  16. package/dist/index.d.ts +6 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +11148 -6448
  19. package/dist/index.js.map +1 -1
  20. package/dist/lib/identity.d.ts +32 -0
  21. package/dist/lib/identity.d.ts.map +1 -0
  22. package/dist/locales/en.d.ts.map +1 -1
  23. package/dist/locales/pt-BR.d.ts.map +1 -1
  24. package/dist/migrations/index.d.ts +8 -0
  25. package/dist/migrations/index.d.ts.map +1 -1
  26. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  27. package/dist/public/data/supabase.d.ts.map +1 -1
  28. package/dist/public/index.js +4 -1
  29. package/dist/public/index.js.map +1 -1
  30. package/dist/public/types.d.ts +14 -0
  31. package/dist/public/types.d.ts.map +1 -1
  32. package/dist/schema/index.d.ts +1610 -8
  33. package/dist/schema/index.d.ts.map +1 -1
  34. package/dist/schema.cjs +147 -3
  35. package/dist/schema.cjs.map +1 -1
  36. package/dist/schema.js +143 -5
  37. package/dist/schema.js.map +1 -1
  38. package/dist/store.d.ts +20 -1
  39. package/dist/store.d.ts.map +1 -1
  40. package/dist/types.d.ts +156 -0
  41. package/dist/types.d.ts.map +1 -1
  42. package/dist/views/CompanyDetailView.d.ts +8 -0
  43. package/dist/views/CompanyDetailView.d.ts.map +1 -0
  44. package/dist/views/CompanyFormView.d.ts +6 -0
  45. package/dist/views/CompanyFormView.d.ts.map +1 -0
  46. package/dist/views/CompanyListView.d.ts +6 -0
  47. package/dist/views/CompanyListView.d.ts.map +1 -0
  48. package/dist/views/CrmPage.d.ts.map +1 -1
  49. package/dist/views/LeadDetailView.d.ts +3 -1
  50. package/dist/views/LeadDetailView.d.ts.map +1 -1
  51. package/dist/views/PipelineView.d.ts.map +1 -1
  52. package/dist/views/dashboardWidgets.d.ts.map +1 -1
  53. package/package.json +4 -4
@@ -0,0 +1,32 @@
1
+ /** Sem máscara, maiúsculo. A única forma que compara igual dos dois lados. */
2
+ export declare function normalizeDocument(doc: string | null | undefined): string;
3
+ export type DocKind = 'cnpj' | 'cpf' | null;
4
+ /** Derivado do comprimento, nunca perguntado — quem classifica na mão erra
5
+ * justamente nas linhas de MEI, que é onde importa. */
6
+ export declare function documentKind(doc: string | null | undefined): DocKind;
7
+ /**
8
+ * Módulo 11 sobre `charCodeAt(0) - 48`, e não sobre dígitos.
9
+ *
10
+ * Para '0'..'9' o valor É o dígito, então a mesma conta serve o CNPJ numérico
11
+ * de hoje e o alfanumérico que passa a valer em julho de 2026 (IN RFB nº
12
+ * 2229/2024): as 12 primeiras posições aceitam letras maiúsculas, os dois
13
+ * verificadores continuam numéricos. Um validador escrito sobre `parseInt`
14
+ * começa a recusar empresa de verdade naquele dia.
15
+ */
16
+ export declare function isValidDocument(doc: string | null | undefined): boolean | null;
17
+ /** `12.345.678/0001-95` ou `123.456.789-09`. Só para mostrar — o que é gravado
18
+ * e comparado é sempre a forma sem máscara. */
19
+ export declare function formatDocument(doc: string | null | undefined): string;
20
+ /** A raiz do CNPJ: os 8 primeiros. É o que faz matriz e filial serem um grupo
21
+ * só. Não existe para CPF. */
22
+ export declare function documentRoot(doc: string | null | undefined): string | null;
23
+ /**
24
+ * Um número brasileiro, uma chave. Espelha `crm_phone_key`.
25
+ *
26
+ * Um número de 8 ou 9 dígitos não carrega DDD e portanto é chave FRACA — pode
27
+ * colidir entre cidades. Isso é aceitável porque a chave só SUGERE ("quem mais
28
+ * atende aqui?") e deduplica dentro de uma pessoa; ninguém funde dois cadastros
29
+ * por causa dela.
30
+ */
31
+ export declare function localPhoneKey(phone: string | null | undefined): string | null;
32
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../src/lib/identity.ts"],"names":[],"mappings":"AAeA,8EAA8E;AAC9E,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAExE;AAED,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG,KAAK,GAAG,IAAI,CAAA;AAE3C;wDACwD;AACxD,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,CAKpE;AAED;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,OAAO,GAAG,IAAI,CA2B9E;AAED;gDACgD;AAChD,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,CAKrE;AAED;+BAC+B;AAC/B,wBAAgB,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAE1E;AAED;;;;;;;GAOG;AACH,wBAAgB,aAAa,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,MAAM,GAAG,IAAI,CAgB7E"}
@@ -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,CAwfrC,CAAA"}
1
+ {"version":3,"file":"en.d.ts","sourceRoot":"","sources":["../../src/locales/en.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,EAAE,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAokBrC,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,CAwfvC,CAAA"}
1
+ {"version":3,"file":"pt-BR.d.ts","sourceRoot":"","sources":["../../src/locales/pt-BR.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAokBvC,CAAA"}
@@ -6,6 +6,14 @@ export declare const MIGRATION_004_UM_RECORTE_DE_GENTE_QUE_TEM_NOME = "-- 004_um
6
6
  export declare const MIGRATION_005_A_ETAPA_GANHA_UM_CODIGO_E_UM_COMECO = "-- 005_a_etapa_ganha_um_codigo_e_um_comeco.sql\n--\n-- O V1 tem uma tela chamada \"Configurar Pipelines\" onde se desenham as etapas\n-- do funil. O V2 tem uma que MOSTRA as etapas e n\u00E3o deixa mexer em nenhuma \u2014 o\n-- pr\u00F3prio rodap\u00E9 dela avisa que customizar n\u00E3o d\u00E1. Um funil cujas colunas\n-- ningu\u00E9m consegue desenhar n\u00E3o \u00E9 um funil configur\u00E1vel; \u00E9 um funil de f\u00E1brica\n-- com uma vitrine na frente.\n--\n-- Para a tela poder editar, faltam duas colunas \u2014 e as duas s\u00E3o as que o V1\n-- acerta:\n--\n-- 1. `code`. O V1 guarda um c\u00F3digo est\u00E1vel ao lado do nome (`new`, `qualified`,\n-- `won`). \u00C9 o que faz renomear \"Qualificado\" para \"Triado\" N\u00C3O quebrar a\n-- automa\u00E7\u00E3o que aponta para aquela etapa. Sem ele, a \u00FAnica identidade da\n-- etapa \u00E9 o uuid \u2014 que ningu\u00E9m escreve numa regra \u2014 ou o nome, que \u00E9\n-- exatamente o que muda. (O V1 erra em MOSTRAR o c\u00F3digo na tela, o que a\n-- ISSUES.md dele registra como V1-025; aqui ele \u00E9 identificador, n\u00E3o texto\n-- de interface.)\n--\n-- 2. `is_initial`. O V1 marca tr\u00EAs etapas como especiais: Inicial, Ganho e\n-- Perdido. O V2 tinha duas \u2014 ganho e perda \u2014 e INFERIA a inicial com\n-- `stages.filter(!won && !lost).sort(order)[0]`, no cliente. A infer\u00EAncia\n-- acerta quase sempre e erra em sil\u00EAncio quando algu\u00E9m reordena: o lead novo\n-- passa a entrar noutra etapa e ningu\u00E9m liga uma coisa \u00E0 outra. Onde entrar\n-- no funil \u00E9 uma decis\u00E3o, e decis\u00E3o se grava.\n--\n-- O QUE ESTA MIGRATION N\u00C3O FAZ: n\u00E3o impede duas etapas de ganho nem duas de\n-- perda. \"Perdido por pre\u00E7o\" e \"Perdido para concorrente\" s\u00E3o dois desfechos\n-- leg\u00EDtimos, e o `deriveLeadStatus` j\u00E1 l\u00EA os dois como perda. A ENTRADA \u00E9 que\n-- n\u00E3o pode ser amb\u00EDgua \u2014 da\u00ED o \u00EDndice \u00FAnico parcial s\u00F3 em `is_initial`.\n\n-- \u2500\u2500 um slug est\u00E1vel, para nascer com c\u00F3digo \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--\n-- IMMUTABLE porque um \u00EDndice pode precisar dela, e sem acento porque o c\u00F3digo\n-- vive em regra de automa\u00E7\u00E3o, em endere\u00E7o e em arquivo de configura\u00E7\u00E3o.\nCREATE OR REPLACE FUNCTION public.crm_slug(p_text text)\nRETURNS text\n LANGUAGE sql\n IMMUTABLE\n SET search_path TO ''\nAS $$\n SELECT nullif(\n btrim(\n regexp_replace(\n lower(translate(coalesce(p_text, ''),\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 '[^a-z0-9]+', '-', 'g'),\n '-'),\n '')\n$$;\n\nCOMMENT ON FUNCTION public.crm_slug(text) IS\n 'Nome \u2192 c\u00F3digo est\u00E1vel, sem acento. Usado para dar `code` a uma etapa que nasce sem (005).';\n\n-- \u2500\u2500 as duas colunas \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\nALTER TABLE public.plg_crm_pipeline_stages\n ADD COLUMN IF NOT EXISTS code text,\n ADD COLUMN IF NOT EXISTS is_initial boolean DEFAULT false NOT NULL;\n\nCOMMENT ON COLUMN public.plg_crm_pipeline_stages.code IS\n 'Identidade est\u00E1vel da etapa. Renomear a etapa N\u00C3O muda o c\u00F3digo, e \u00E9 isso que mant\u00E9m a automa\u00E7\u00E3o apontando para ela (005).';\nCOMMENT ON COLUMN public.plg_crm_pipeline_stages.is_initial IS\n 'Onde o lead entra no funil. Antes era inferido no cliente pela menor ordem entre as n\u00E3o-terminais \u2014 o que errava em sil\u00EAncio a cada reordena\u00E7\u00E3o (005).';\n\n-- \u2500\u2500 as etapas que j\u00E1 existem \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--\n-- C\u00F3digo a partir do nome, com desempate por ordem quando dois nomes colidem\n-- (\"Perdido\" e \"perdido \" dariam o mesmo slug). Sem o desempate, o \u00EDndice \u00FAnico\n-- abaixo recusaria a migration numa casa que j\u00E1 tem esse par.\nWITH slugged AS (\n SELECT s.id, s.pipeline_id,\n coalesce(public.crm_slug(s.name), 'etapa') AS base,\n row_number() OVER (\n PARTITION BY s.pipeline_id, coalesce(public.crm_slug(s.name), 'etapa')\n ORDER BY s.\"order\", s.created_at, s.id) AS dup\n FROM public.plg_crm_pipeline_stages s\n WHERE s.code IS NULL\n)\nUPDATE public.plg_crm_pipeline_stages t\n SET code = CASE WHEN g.dup = 1 THEN g.base ELSE g.base || '-' || g.dup END\n FROM slugged g\n WHERE t.id = g.id;\n\nALTER TABLE public.plg_crm_pipeline_stages\n ALTER COLUMN code SET NOT NULL;\n\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_pipeline_stages_code_key') THEN\n ALTER TABLE ONLY public.plg_crm_pipeline_stages\n ADD CONSTRAINT plg_crm_pipeline_stages_code_key UNIQUE (pipeline_id, code);\n END IF;\n -- Ganhar e perder ao mesmo tempo n\u00E3o \u00E9 um desfecho. `deriveLeadStatus` l\u00EA\n -- `isWon` primeiro, ent\u00E3o uma etapa com os dois marcados se comportaria como\n -- ganho e se leria na tela como perda.\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_pipeline_stages_not_both') THEN\n ALTER TABLE public.plg_crm_pipeline_stages\n ADD CONSTRAINT plg_crm_pipeline_stages_not_both CHECK (NOT (is_won AND is_lost));\n END IF;\nEND $$;\n\n-- A inicial de cada funil: a mesma que o cliente vinha inferindo, gravada uma\n-- vez. S\u00F3 onde ningu\u00E9m marcou ainda \u2014 rodar de novo n\u00E3o mexe em escolha feita.\nWITH first_open AS (\n SELECT DISTINCT ON (s.pipeline_id) s.id, s.pipeline_id\n FROM public.plg_crm_pipeline_stages s\n WHERE NOT s.is_won AND NOT s.is_lost\n ORDER BY s.pipeline_id, s.\"order\", s.created_at\n)\nUPDATE public.plg_crm_pipeline_stages t\n SET is_initial = true\n FROM first_open f\n WHERE t.id = f.id\n AND NOT EXISTS (\n SELECT 1 FROM public.plg_crm_pipeline_stages x\n WHERE x.pipeline_id = t.pipeline_id AND x.is_initial);\n\n-- UMA entrada por funil. \u00CDndice parcial e n\u00E3o CHECK: a regra \u00E9 entre linhas.\nCREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_stage_one_initial\n ON public.plg_crm_pipeline_stages (pipeline_id) WHERE is_initial;\n\n-- Etapa que nasce sem c\u00F3digo ganha um. A tela manda o c\u00F3digo, mas uma\n-- importa\u00E7\u00E3o, um seed ou um `insert` de agente n\u00E3o mandam \u2014 e uma etapa sem\n-- c\u00F3digo \u00E9 uma etapa que nenhuma automa\u00E7\u00E3o consegue nomear.\nCREATE OR REPLACE FUNCTION public.trg_crm_stage_code()\nRETURNS trigger\n LANGUAGE plpgsql\n SET search_path TO ''\nAS $$\nDECLARE v_base text; v_try text; v_n integer := 1;\nBEGIN\n IF NEW.code IS NOT NULL AND btrim(NEW.code) <> '' THEN\n NEW.code := public.crm_slug(NEW.code);\n IF NEW.code IS NULL THEN NEW.code := 'etapa'; END IF;\n RETURN NEW;\n END IF;\n v_base := coalesce(public.crm_slug(NEW.name), 'etapa');\n v_try := v_base;\n WHILE EXISTS (SELECT 1 FROM public.plg_crm_pipeline_stages s\n WHERE s.pipeline_id = NEW.pipeline_id AND s.code = v_try\n AND s.id IS DISTINCT FROM NEW.id) LOOP\n v_n := v_n + 1;\n v_try := v_base || '-' || v_n;\n END LOOP;\n NEW.code := v_try;\n RETURN NEW;\nEND $$;\n\nDROP TRIGGER IF EXISTS plg_crm_stage_code ON public.plg_crm_pipeline_stages;\nCREATE TRIGGER plg_crm_stage_code\n BEFORE INSERT OR UPDATE OF code, name ON public.plg_crm_pipeline_stages\n FOR EACH ROW\n EXECUTE FUNCTION public.trg_crm_stage_code();\n\nCOMMENT ON FUNCTION public.trg_crm_stage_code() IS\n 'Garante c\u00F3digo \u00E0 etapa que nasce sem. Renomear N\u00C3O regera o c\u00F3digo de quem j\u00E1 tem \u2014 \u00E9 o que faz o c\u00F3digo ser est\u00E1vel (005).';\n";
7
7
  export declare const MIGRATION_006_A_ESCADA_DO_RELACIONAMENTO = "-- 006_a_escada_do_relacionamento.sql\n--\n-- O V1 tem um eixo de est\u00E1gio no cadastro do cliente \u2014 Lead, Prospect,\n-- Oportunidade, Cliente, Inativo \u2014 e quatro itens de menu que o recortam. O\n-- eixo \u00E9 um CAMPO: algu\u00E9m digita, algu\u00E9m esquece. O resultado est\u00E1 na captura\n-- do pr\u00F3prio guia: **795 leads e 0 clientes ativos**, numa casa com receita no\n-- m\u00EAs. N\u00E3o \u00E9 que a casa n\u00E3o tenha cliente; \u00E9 que ningu\u00E9m foi promover 795\n-- fichas \u00E0 m\u00E3o.\n--\n-- Por isso aqui o est\u00E1gio \u00E9 DERIVADO. Ningu\u00E9m digita \"ativo\": a pessoa \u00E9 ativa\n-- porque comprou/atendeu-se dentro da janela que a casa considera ativa. N\u00E3o h\u00E1\n-- campo para esquecer, n\u00E3o h\u00E1 mutir\u00E3o de arruma\u00E7\u00E3o, e o n\u00FAmero da tela n\u00E3o pode\n-- discordar do hist\u00F3rico \u2014 ele \u00C9 o hist\u00F3rico.\n--\n-- A ESCADA \u00C9 A MESMA NOS DOIS IRM\u00C3OS; OS DEGRAUS, N\u00C3O. Noventa dias sem\n-- aparecer \u00E9 rotina num sal\u00E3o e \u00E9 quase um cliente perdido num delivery. Por\n-- isso os limites s\u00E3o por casa (`plg_crm_engagement_settings`) e a view os l\u00EA\n-- com COALESCE para o padr\u00E3o: quem nunca abriu a tela de configura\u00E7\u00E3o tem\n-- 30/90/180, e quem abriu manda.\n--\n-- DUAS ARMADILHAS DOS DADOS, ACHADAS OLHANDO O CLUSTER E N\u00C3O O C\u00D3DIGO:\n--\n-- 1. `completed_at` N\u00C3O quer dizer que aconteceu. H\u00E1 166 vendas com status\n-- 'cancelled' e `completed_at` preenchido. Contar por `completed_at IS NOT\n-- NULL` faria a venda cancelada manter o cliente \"ativo\" \u2014 o filtro \u00E9 pelo\n-- STATUS.\n-- 2. `direction` n\u00E3o separa venda de compra: 8.278 das 8.311 vendas est\u00E3o com\n-- ele nulo. Quem separa \u00E9 `kind`, e por isso a lista de esp\u00E9cies que contam\n-- \u00E9 expl\u00EDcita: esp\u00E9cie nova n\u00E3o entra na conta por acidente. `purchase` fica\n-- de fora de prop\u00F3sito \u2014 comprar do fornecedor n\u00E3o \u00E9 o cliente aparecendo.\n\n-- \u2500\u2500 os degraus, por casa \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\u2500\u2500\u2500\nCREATE TABLE IF NOT EXISTS public.plg_crm_engagement_settings (\n tenant_id uuid NOT NULL,\n -- Rec\u00E9m-chegado: o primeiro atendimento foi h\u00E1 menos que isto.\n new_days integer DEFAULT 30 NOT NULL,\n -- Ativo: apareceu dentro desta janela.\n active_days integer DEFAULT 90 NOT NULL,\n -- Em risco at\u00E9 aqui; passou disto, est\u00E1 parado.\n at_risk_days integer DEFAULT 180 NOT NULL,\n updated_by uuid,\n updated_at timestamp with time zone DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_engagement_settings_pkey PRIMARY KEY (tenant_id),\n -- A escada tem de subir. Sem isto, `active_days` maior que `at_risk_days`\n -- produz uma faixa \"em risco\" vazia e ningu\u00E9m entende por que o n\u00FAmero\n -- ficou zero.\n CONSTRAINT plg_crm_engagement_settings_ladder\n CHECK (new_days > 0 AND active_days > new_days AND at_risk_days > active_days)\n);\n\nALTER TABLE public.plg_crm_engagement_settings FORCE ROW LEVEL SECURITY;\n\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_engagement_settings_tenant_fkey') THEN\n ALTER TABLE ONLY public.plg_crm_engagement_settings\n ADD CONSTRAINT plg_crm_engagement_settings_tenant_fkey FOREIGN KEY (tenant_id)\n REFERENCES public.tenants(id) ON DELETE CASCADE;\n END IF;\nEND $$;\n\nCOMMENT ON TABLE public.plg_crm_engagement_settings IS\n 'Os degraus da escada de relacionamento, por casa. 90 dias sem aparecer \u00E9 rotina num sal\u00E3o e quase perda num delivery (006).';\n\nALTER TABLE public.plg_crm_engagement_settings ENABLE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS plg_crm_engagement_settings_authz_select ON public.plg_crm_engagement_settings;\nCREATE POLICY plg_crm_engagement_settings_authz_select ON public.plg_crm_engagement_settings\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_engagement_settings_authz_insert ON public.plg_crm_engagement_settings;\nCREATE POLICY plg_crm_engagement_settings_authz_insert ON public.plg_crm_engagement_settings\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_engagement_settings_authz_update ON public.plg_crm_engagement_settings;\nCREATE POLICY plg_crm_engagement_settings_authz_update ON public.plg_crm_engagement_settings\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nGRANT SELECT, INSERT, UPDATE ON public.plg_crm_engagement_settings TO authenticated;\nGRANT ALL ON public.plg_crm_engagement_settings TO service_role;\n\nINSERT INTO app.scaffold_registry\n (table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)\nVALUES\n ('public', 'plg_crm_engagement_settings', 'crm.engagement_settings', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)\nON CONFLICT DO NOTHING;\n\n-- \u2500\u2500 a leitura \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- `security_invoker` porque uma view sem ele roda com os direitos de QUEM A\n-- CRIOU e ignora a RLS de quem a l\u00EA \u2014 foi assim que views vazaram entre tenants\n-- neste repo antes.\n--\n-- Uma linha por pessoa, com o que a escada precisa e nada al\u00E9m: quem quer a\n-- ficha busca em `people`, que \u00E9 onde ela mora.\nCREATE OR REPLACE VIEW public.v_crm_person_engagement WITH (security_invoker='true') AS\nWITH cfg AS (\n SELECT t.id AS tenant_id,\n coalesce(e.new_days, 30) AS new_days,\n coalesce(e.active_days, 90) AS active_days,\n coalesce(e.at_risk_days, 180) AS at_risk_days\n FROM public.tenants t\n LEFT JOIN public.plg_crm_engagement_settings e ON e.tenant_id = t.id\n),\nvisits AS (\n SELECT o.tenant_id,\n o.party_id AS person_id,\n min(o.completed_at) AS first_at,\n max(o.completed_at) AS last_at,\n count(*) AS visits,\n sum(o.total) AS total_value\n FROM public.orders o\n WHERE o.party_id IS NOT NULL\n -- Pelo STATUS, n\u00E3o por `completed_at`: h\u00E1 venda cancelada com\n -- `completed_at` preenchido, e cont\u00E1-la manteria o cliente \"ativo\" por\n -- causa de uma compra que n\u00E3o houve.\n AND o.status = 'completed'\n -- Lista expl\u00EDcita: esp\u00E9cie nova n\u00E3o entra na conta por acidente.\n -- `purchase` fora \u2014 comprar do fornecedor n\u00E3o \u00E9 o cliente aparecendo.\n AND o.kind = ANY (ARRAY['sale', 'dine_in', 'takeout', 'delivery', 'appointment', 'service_order'])\n GROUP BY o.tenant_id, o.party_id\n)\nSELECT\n p.id AS person_id,\n p.tenant_id,\n p.unit_id,\n p.name,\n p.kind,\n v.first_at,\n v.last_at,\n coalesce(v.visits, 0)::bigint AS visits,\n coalesce(v.total_value, 0)::numeric AS total_value,\n CASE WHEN v.visits > 0 THEN round(v.total_value / v.visits, 2) END AS avg_value,\n CASE WHEN v.last_at IS NOT NULL\n THEN floor(EXTRACT(epoch FROM (now() - v.last_at)) / 86400)::integer END AS days_since_last,\n -- A ESCADA. A ordem dos ramos \u00E9 a regra: rec\u00E9m-chegado ganha de ativo nos\n -- primeiros dias porque \u00E9 a informa\u00E7\u00E3o mais \u00FAtil ali \u2014 depois ele vira ativo\n -- sozinho, sem ningu\u00E9m tocar em nada.\n CASE\n WHEN v.last_at IS NULL AND p.kind = 'lead' THEN 'lead'\n WHEN v.last_at IS NULL THEN 'prospect'\n WHEN v.first_at >= now() - make_interval(days => c.new_days) THEN 'new'\n WHEN v.last_at >= now() - make_interval(days => c.active_days) THEN 'active'\n WHEN v.last_at >= now() - make_interval(days => c.at_risk_days) THEN 'at_risk'\n ELSE 'dormant'\n END AS lifecycle\nFROM public.people p\nJOIN cfg c ON c.tenant_id = p.tenant_id\nLEFT JOIN visits v ON v.person_id = p.id AND v.tenant_id = p.tenant_id\nWHERE p.merged_into_id IS NULL;\n\nCOMMENT ON VIEW public.v_crm_person_engagement IS\n 'Rec\u00EAncia, frequ\u00EAncia, valor e o degrau da escada, por pessoa. O degrau \u00E9 DERIVADO: no V1 \u00E9 campo digitado, e a captura do guia dele mostra 795 leads com 0 clientes ativos numa casa faturando (006).';\n\nGRANT SELECT ON public.v_crm_person_engagement TO authenticated;\nGRANT SELECT ON public.v_crm_person_engagement TO service_role;\n\n-- \u2500\u2500 o resumo, para o painel \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--\n-- Quantos em cada degrau, mais as duas perguntas que o painel do V1 faz e n\u00E3o\n-- responde: quantos voltaram no m\u00EAs (reten\u00E7\u00E3o) e quantos voltaram DEPOIS de\n-- terem sumido (reativa\u00E7\u00E3o). A segunda \u00E9 a que paga campanha.\nCREATE OR REPLACE FUNCTION public.crm_engagement_summary()\nRETURNS jsonb\n LANGUAGE plpgsql\n SECURITY DEFINER\n STABLE\n SET search_path TO ''\nAS $$\nDECLARE\n v_tenant uuid := app.current_tenant_id();\n v_cfg record;\n v_out jsonb;\nBEGIN\n IF v_tenant IS NULL THEN\n RAISE EXCEPTION 'crm_engagement_summary: sem tenant na sess\u00E3o' USING ERRCODE = '42501';\n END IF;\n IF NOT app.has_permission('sales.read', NULL::uuid) THEN\n RAISE EXCEPTION 'crm_engagement_summary: exige sales.read' USING ERRCODE = '42501';\n END IF;\n\n SELECT coalesce(e.new_days, 30) AS new_days,\n coalesce(e.active_days, 90) AS active_days,\n coalesce(e.at_risk_days, 180) AS at_risk_days\n INTO v_cfg\n FROM public.tenants t\n LEFT JOIN public.plg_crm_engagement_settings e ON e.tenant_id = t.id\n WHERE t.id = v_tenant;\n\n SELECT jsonb_build_object(\n 'lead', count(*) FILTER (WHERE g.lifecycle = 'lead'),\n 'prospect', count(*) FILTER (WHERE g.lifecycle = 'prospect'),\n 'new', count(*) FILTER (WHERE g.lifecycle = 'new'),\n 'active', count(*) FILTER (WHERE g.lifecycle = 'active'),\n 'at_risk', count(*) FILTER (WHERE g.lifecycle = 'at_risk'),\n 'dormant', count(*) FILTER (WHERE g.lifecycle = 'dormant'),\n 'people', count(*),\n -- Reten\u00E7\u00E3o: dos que j\u00E1 tinham aparecido ANTES da janela, quantos\n -- apareceram DENTRO dela. Quem veio s\u00F3 uma vez n\u00E3o entra no denominador \u2014\n -- ele n\u00E3o tinha como \"voltar\".\n 'returned', count(*) FILTER (WHERE g.visits > 1 AND g.days_since_last <= v_cfg.active_days),\n 'returnable', count(*) FILTER (WHERE g.visits > 1),\n 'settings', jsonb_build_object(\n 'newDays', v_cfg.new_days, 'activeDays', v_cfg.active_days, 'atRiskDays', v_cfg.at_risk_days)\n ) INTO v_out\n FROM public.v_crm_person_engagement g\n WHERE g.tenant_id = v_tenant;\n\n RETURN v_out;\nEND $$;\n\nCOMMENT ON FUNCTION public.crm_engagement_summary() IS\n 'Quantos em cada degrau da escada, mais reten\u00E7\u00E3o. Uma chamada \u2014 o painel n\u00E3o pergunta seis vezes (006).';\n\nREVOKE ALL ON FUNCTION public.crm_engagement_summary() FROM PUBLIC, anon;\nGRANT EXECUTE ON FUNCTION public.crm_engagement_summary() TO authenticated;\nGRANT EXECUTE ON FUNCTION public.crm_engagement_summary() TO service_role;\n";
8
8
  export declare const MIGRATION_008_A_REGUA_DA_REDE_E_PUBLICA = "-- 008_a_regua_da_rede_e_publica.sql\n--\n-- O V1 tem duas telas de rede \u2014 Dashboard Operacional (ranking e indicadores\n-- por unidade) e Maturidade Operacional (nota 0\u2013100 por unidade). O documento\n-- do porte diz que o V2 \"ainda n\u00E3o tem o conceito de rede\"; **est\u00E1\n-- desatualizado**: as unidades existem, e o Espa\u00E7o Facial tem 65 delas no\n-- cluster hoje.\n--\n-- O QUE VALE A PENA COPIAR DO V1, e o pr\u00F3prio guia dele aponta: **a r\u00E9gua \u00E9\n-- p\u00FAblica**. Os pesos de cada dimens\u00E3o aparecem na mesma tela em que a nota \u00E9\n-- mostrada. Um score comparativo s\u00F3 \u00E9 aceito por quem \u00E9 comparado quando d\u00E1\n-- para ler como ele foi feito.\n--\n-- O QUE N\u00C3O VALE: os pesos serem FIXOS. No V1 n\u00E3o h\u00E1 campo para edit\u00E1-los \u2014 \u00E9 a\n-- r\u00E9gua do franqueador, igual para toda a rede, e a FAQ do pr\u00F3prio guia\n-- registra a pergunta \"posso mudar os pesos?\". Aqui eles s\u00E3o por casa: um\n-- delivery e um sal\u00E3o n\u00E3o pesam ocupa\u00E7\u00E3o do mesmo jeito.\n--\n-- A DECIS\u00C3O QUE MAIS MUDA O N\u00DAMERO: dimens\u00E3o SEM DADO n\u00E3o vale zero.\n--\n-- O V1 mede sete dimens\u00F5es. O V2 mede cinco com honestidade hoje \u2014 as outras\n-- duas (ocupa\u00E7\u00E3o e financeiro) dependem de fontes que este plugin n\u00E3o tem. A\n-- sa\u00EDda f\u00E1cil seria cont\u00E1-las como 0, e ela est\u00E1 errada: uma casa sem agenda\n-- instalada apareceria com nota baixa por FALTA DE DADO, indistingu\u00EDvel de uma\n-- casa com agenda vazia. Aqui a dimens\u00E3o sem fonte sai do c\u00E1lculo e os pesos\n-- restantes s\u00E3o RENORMALIZADOS \u2014 a nota diz \"de tudo o que d\u00E1 para medir, esta\n-- casa est\u00E1 em 72\", que \u00E9 uma frase verdadeira.\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_scorecard_weights (\n tenant_id uuid NOT NULL,\n dimension text NOT NULL,\n weight numeric(5,2) NOT NULL,\n updated_at timestamp with time zone DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_scorecard_weights_pkey PRIMARY KEY (tenant_id, dimension),\n CONSTRAINT plg_crm_scorecard_weights_dimension CHECK (\n dimension = ANY (ARRAY['conversion','retention','reactivation','productivity','satisfaction','speed','occupancy','financial'])),\n CONSTRAINT plg_crm_scorecard_weights_range CHECK (weight >= 0 AND weight <= 100)\n);\n\nALTER TABLE public.plg_crm_scorecard_weights FORCE ROW LEVEL SECURITY;\n\nDO $$ BEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_scorecard_weights_tenant_fkey') THEN\n ALTER TABLE ONLY public.plg_crm_scorecard_weights\n ADD CONSTRAINT plg_crm_scorecard_weights_tenant_fkey FOREIGN KEY (tenant_id)\n REFERENCES public.tenants(id) ON DELETE CASCADE;\n END IF;\nEND $$;\n\nCOMMENT ON TABLE public.plg_crm_scorecard_weights IS\n 'O peso de cada dimens\u00E3o da nota, POR CASA. No V1 os pesos s\u00E3o fixos e a FAQ dele registra a pergunta de quem queria mud\u00E1-los (008).';\n\nALTER TABLE public.plg_crm_scorecard_weights ENABLE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS plg_crm_scorecard_weights_authz_select ON public.plg_crm_scorecard_weights;\nCREATE POLICY plg_crm_scorecard_weights_authz_select ON public.plg_crm_scorecard_weights\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_scorecard_weights_authz_write ON public.plg_crm_scorecard_weights;\nCREATE POLICY plg_crm_scorecard_weights_authz_write ON public.plg_crm_scorecard_weights\n FOR ALL TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_scorecard_weights TO authenticated;\nGRANT ALL ON public.plg_crm_scorecard_weights TO service_role;\n\nINSERT INTO app.scaffold_registry\n (table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)\nVALUES\n ('public', 'plg_crm_scorecard_weights', 'crm.scorecard_weight', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)\nON CONFLICT DO NOTHING;\n\n-- \u2500\u2500 o placar da rede \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Uma linha por unidade, com as dimens\u00F5es medidas e a nota. Devolve NULO na\n-- dimens\u00E3o sem fonte \u2014 e \u00E9 o cliente que soma, com os pesos renormalizados\n-- sobre o que veio preenchido.\n--\n-- Cada dimens\u00E3o \u00E9 0\u2013100 de prop\u00F3sito, inclusive satisfa\u00E7\u00E3o. O V1 acerta nisso:\n-- misturar uma escala \u2212100..100 (NPS) com percentuais na mesma linha faz a\n-- m\u00E9dia ponderada mentir.\nCREATE OR REPLACE FUNCTION public.crm_unit_scorecard(\n p_from timestamp with time zone DEFAULT now() - interval '90 days',\n p_to timestamp with time zone DEFAULT now()\n) RETURNS TABLE(\n unit_id uuid,\n unit_name text,\n orders_count bigint,\n revenue numeric,\n people_count bigint,\n conversion numeric,\n retention numeric,\n reactivation numeric,\n productivity numeric,\n satisfaction numeric\n)\n LANGUAGE plpgsql\n SECURITY DEFINER\n STABLE\n SET search_path TO ''\nAS $$\nDECLARE v_tenant uuid := app.current_tenant_id();\nBEGIN\n IF v_tenant IS NULL THEN\n RAISE EXCEPTION 'crm_unit_scorecard: sem tenant na sess\u00E3o' USING ERRCODE = '42501';\n END IF;\n IF NOT app.has_permission('sales.read', NULL::uuid) THEN\n RAISE EXCEPTION 'crm_unit_scorecard: exige sales.read' USING ERRCODE = '42501';\n END IF;\n\n RETURN QUERY\n WITH un AS (\n SELECT u.id, u.name FROM app.units u WHERE u.tenant_id = v_tenant\n ),\n -- PESSOA N\u00C3O PERTENCE A UMA UNIDADE \u2014 ELA VISITA UNIDADES.\n --\n -- A primeira vers\u00E3o desta fun\u00E7\u00E3o agrupava por `people.unit_id`, e no cluster\n -- ela devolveu reten\u00E7\u00E3o, reativa\u00E7\u00E3o e convers\u00E3o NULAS at\u00E9 para a unidade com\n -- 5.111 pedidos: os pedidos t\u00EAm unidade, as fichas n\u00E3o. N\u00E3o era falta de\n -- dado \u2014 era o modelo errado. Numa rede, o cliente \u00E9 da REDE e frequenta uma\n -- loja; amarr\u00E1-lo a uma delas obrigaria a escolher uma resposta para quem\n -- passa em duas.\n --\n -- A unidade de uma pessoa \u00E9, ent\u00E3o, a da \u00DALTIMA vez que ela apareceu. \u00C9 a\n -- leitura que o franqueado reconhece: \"esse cliente \u00E9 meu porque foi aqui que\n -- ele veio da \u00FAltima vez\".\n person_unit AS (\n SELECT DISTINCT ON (o.party_id) o.party_id AS person_id, o.unit_id\n FROM public.orders o\n WHERE o.tenant_id = v_tenant AND o.status = 'completed' AND o.unit_id IS NOT NULL\n AND o.kind = ANY (ARRAY['sale','dine_in','takeout','delivery','appointment','service_order'])\n ORDER BY o.party_id, o.completed_at DESC\n ),\n sales AS (\n -- Mesma lista de esp\u00E9cies e o mesmo filtro por STATUS da 006: venda\n -- cancelada tem `completed_at` preenchido e n\u00E3o pode contar.\n SELECT o.unit_id, count(*) AS n, sum(o.total) AS revenue,\n count(DISTINCT o.assignee_id) FILTER (WHERE o.assignee_id IS NOT NULL) AS people\n FROM public.orders o\n WHERE o.tenant_id = v_tenant AND o.status = 'completed'\n AND o.completed_at >= p_from AND o.completed_at < p_to\n AND o.kind = ANY (ARRAY['sale','dine_in','takeout','delivery','appointment','service_order'])\n GROUP BY o.unit_id\n ),\n leads AS (\n -- A unidade da ficha quando ela tem; sen\u00E3o a da \u00FAltima visita. Um lead que\n -- nunca apareceu e n\u00E3o tem unidade fica fora da convers\u00E3o de todo mundo \u2014\n -- e \u00E9 o certo: ningu\u00E9m deixou de converter quem n\u00E3o era de ningu\u00E9m.\n SELECT coalesce(p.unit_id, pu.unit_id) AS unit_id, count(*) AS n\n FROM public.people p\n LEFT JOIN person_unit pu ON pu.person_id = p.id\n WHERE p.tenant_id = v_tenant AND p.kind = 'lead'\n AND p.created_at >= p_from AND p.created_at < p_to\n AND coalesce(p.unit_id, pu.unit_id) IS NOT NULL\n GROUP BY coalesce(p.unit_id, pu.unit_id)\n ),\n eng AS (\n SELECT pu.unit_id,\n count(*) FILTER (WHERE g.visits > 1) AS returnable,\n count(*) FILTER (WHERE g.visits > 1 AND g.lifecycle IN ('active','new')) AS returned,\n -- Reativa\u00E7\u00E3o \u00E9 indicador PR\u00D3PRIO, e o V1 acerta ao separ\u00E1-la:\n -- trazer de volta quem sumiu n\u00E3o \u00E9 a mesma coisa que manter quem j\u00E1\n -- vem, e a a\u00E7\u00E3o de cada uma \u00E9 diferente.\n count(*) FILTER (WHERE g.lifecycle IN ('at_risk','dormant')) AS lapsed\n FROM public.v_crm_person_engagement g\n JOIN person_unit pu ON pu.person_id = g.person_id\n WHERE g.tenant_id = v_tenant\n GROUP BY pu.unit_id\n ),\n sat AS (\n SELECT r.unit_id,\n -- Estrelas 1\u20135 normalizadas para 0\u2013100, a r\u00E9gua do painel do V1.\n round(avg((a.rating - 1) * 25.0), 1) AS score\n FROM public.plg_crm_survey_responses r\n JOIN public.plg_crm_survey_answers a ON a.response_id = r.id\n WHERE r.tenant_id = v_tenant AND a.rating IS NOT NULL\n AND r.submitted_at >= p_from AND r.submitted_at < p_to\n GROUP BY r.unit_id\n )\n SELECT\n un.id, un.name,\n coalesce(s.n, 0)::bigint,\n coalesce(s.revenue, 0)::numeric,\n coalesce(e.returnable, 0)::bigint,\n -- Convers\u00E3o: neg\u00F3cio fechado sobre lead que entrou. Sem lead no per\u00EDodo a\n -- resposta \u00E9 NULO e n\u00E3o 0 \u2014 dividir por zero e chamar de \"0% de convers\u00E3o\"\n -- acusa de n\u00E3o converter quem n\u00E3o teve o que converter.\n CASE WHEN coalesce(l.n, 0) > 0\n THEN round(least(100, coalesce(s.n, 0)::numeric * 100 / l.n), 1) END,\n CASE WHEN coalesce(e.returnable, 0) > 0\n THEN round(e.returned::numeric * 100 / e.returnable, 1) END,\n CASE WHEN coalesce(e.lapsed, 0) + coalesce(e.returned, 0) > 0\n THEN round(coalesce(e.returned, 0)::numeric * 100 / (e.lapsed + e.returned), 1) END,\n -- Produtividade: quanto cada pessoa que atendeu produziu, em rela\u00E7\u00E3o \u00E0\n -- melhor da rede. \u00C9 comparativo de prop\u00F3sito \u2014 \"R$ 4.200 por atendente\" n\u00E3o\n -- diz se \u00E9 bom sem algu\u00E9m do lado.\n CASE WHEN coalesce(s.people, 0) > 0 THEN round(s.revenue / s.people, 2) END,\n sat.score\n FROM un\n LEFT JOIN sales s ON s.unit_id = un.id\n LEFT JOIN leads l ON l.unit_id = un.id\n LEFT JOIN eng e ON e.unit_id = un.id\n LEFT JOIN sat ON sat.unit_id = un.id\n ORDER BY coalesce(s.revenue, 0) DESC, un.name;\nEND $$;\n\nCOMMENT ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) IS\n 'Uma linha por unidade com as dimens\u00F5es medidas. Dimens\u00E3o sem fonte volta NULO \u2014 contar como zero acusaria de mau desempenho quem s\u00F3 n\u00E3o tem o dado (008).';\n\nREVOKE ALL ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) FROM PUBLIC, anon;\nGRANT EXECUTE ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) TO authenticated;\nGRANT EXECUTE ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) TO service_role;\n\n-- \u2500\u2500 os pesos que a casa come\u00E7a tendo \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--\n-- Os mesmos do V1, que os publica na tela: convers\u00E3o 20, velocidade 15,\n-- reten\u00E7\u00E3o 15, produtividade 15, financeiro 15, follow-up 10, ocupa\u00E7\u00E3o 10.\n-- Aqui `follow-up` vira `reactivation` \u2014 no V1 ele mede se algu\u00E9m retomou o\n-- contato, que \u00E9 a mesma pergunta que reativa\u00E7\u00E3o responde com dado em vez de\n-- com tarefa marcada \u2014 e satisfa\u00E7\u00E3o entra porque o V2 tem a pesquisa portada.\nCREATE OR REPLACE FUNCTION public.crm_seed_tenant_scorecard_weights(p_tenant uuid)\nRETURNS jsonb\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $$\nDECLARE v_made integer := 0;\nBEGIN\n IF p_tenant IS NULL THEN RETURN jsonb_build_object('seeded', false); END IF;\n INSERT INTO public.plg_crm_scorecard_weights (tenant_id, dimension, weight)\n SELECT p_tenant, d.dimension, d.weight\n FROM (VALUES\n ('conversion', 20.0), ('retention', 15.0), ('reactivation', 10.0),\n ('productivity', 15.0), ('satisfaction', 15.0),\n -- Declaradas com peso e SEM FONTE ainda. Ficam aqui de prop\u00F3sito: o dia\n -- em que a fonte existir, o peso j\u00E1 est\u00E1 combinado \u2014 e at\u00E9 l\u00E1 a nota \u00E9\n -- calculada sem elas, n\u00E3o com zero no lugar delas.\n ('speed', 10.0), ('occupancy', 5.0), ('financial', 10.0)\n ) AS d(dimension, weight)\n WHERE NOT EXISTS (\n SELECT 1 FROM public.plg_crm_scorecard_weights x\n WHERE x.tenant_id = p_tenant AND x.dimension = d.dimension);\n GET DIAGNOSTICS v_made = ROW_COUNT;\n RETURN jsonb_build_object('seeded', true, 'weights', v_made);\nEND $$;\n\nREVOKE ALL ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) FROM PUBLIC, anon;\nGRANT EXECUTE ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) TO authenticated;\nGRANT EXECUTE ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) TO service_role;\n\n-- Entra no mesmo gatilho de tenant novo, ao lado das origens (001) e dos\n-- segmentos (004).\nCREATE OR REPLACE FUNCTION public.trg_crm_seed_new_tenant()\n RETURNS trigger\n LANGUAGE plpgsql\n SECURITY DEFINER\n SET search_path TO ''\nAS $$\nBEGIN\n BEGIN PERFORM public.crm_seed_tenant_lead_sources(NEW.id);\n EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_lead_sources % : %', NEW.id, SQLERRM; END;\n BEGIN PERFORM public.crm_seed_tenant_segments(NEW.id);\n EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_segments % : %', NEW.id, SQLERRM; END;\n BEGIN PERFORM public.crm_seed_tenant_scorecard_weights(NEW.id);\n EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_scorecard_weights % : %', NEW.id, SQLERRM; END;\n RETURN NEW;\nEND $$;\n\nDO $$\nDECLARE r record;\nBEGIN\n FOR r IN SELECT t.id FROM public.tenants t LOOP\n BEGIN PERFORM public.crm_seed_tenant_scorecard_weights(r.id);\n EXCEPTION WHEN OTHERS THEN RAISE WARNING 'backfill scorecard % : %', r.id, SQLERRM; END;\n END LOOP;\nEND $$;\n";
9
+ export declare const MIGRATION_009_THE_LEAD_OFFER_CASCADES = "-- 009_the_lead_offer_cascades.sql\n--\n-- THE LEAD IS OFFERED, NOT ASSIGNED. If nobody takes it, it falls to the next\n-- person, and then to the pool.\n--\n-- This is the *roleta de leads* every Brazilian vertical CRM ships and no\n-- open-source CRM has: a lead lands, one rep is given a short exclusive window,\n-- and when the window closes without a claim the lead cascades. Chatwoot \u2014 the\n-- cleanest routing schema surveyed \u2014 has the issue open and unimplemented.\n--\n-- THE ONE DECISION THAT CANNOT BE RETROFITTED: THE OFFER IS A ROW.\n--\n-- The obvious build is a field: set `owner_id`, start a timer, overwrite it on\n-- timeout. That loses the only thing the feature exists to produce \u2014 WHO WAS\n-- ASKED AND DID NOT ANSWER. After the third hop an overwritten field says the\n-- lead belongs to rep C and nothing else; the row says rep A had it for five\n-- minutes at 09:02 and let it go. That is the record a manager acts on, and it\n-- cannot be reconstructed later from a column that was overwritten.\n--\n-- So: `plg_crm_lead_offers`, one row per (lead, assignee), with an outcome. The\n-- deal's `owner_id` is still the answer to \"whose lead is this\" \u2014 it is what\n-- the RLS on `plg_crm_deals` already scopes by, and it has had a foreign key to\n-- `app.memberships` and owner-scoped SELECT/UPDATE/DELETE policies since the\n-- baseline with NOTHING EVER WRITING IT. This migration is the writer those\n-- policies were waiting for.\n--\n-- WHY A REP IS OFFERED A LEAD AT MOST ONCE. `UNIQUE (lead_id, assignee_id)`.\n-- Cycling the same three people through fifteen hops would turn the offer\n-- history into noise and the cascade into a loop with extra steps: somebody who\n-- ignored a lead at 09:02 is not a better bet at 09:17. The cascade therefore\n-- ends when the rota is exhausted, which is also the honest bound on `max_hops`.\n--\n-- WHY A CURSOR, PERSISTED. Without it the first offer always goes to whoever is\n-- first in the array, and that person absorbs every lead's first window all day.\n-- The cursor lives on the rule, moves on each offer, and survives a restart \u2014\n-- an in-memory rotation resets to zero and silently re-concentrates.\n--\n-- Its one arithmetic consequence, found by the test that asserted otherwise: a\n-- lead that cascades through EVERYBODY walks the cursor a full lap, so the next\n-- lead starts with the same person the exhausted one did. That is correct and\n-- not worth defending against \u2014 it only happens when the whole team ignored a\n-- lead, and at that point which name is offered first is not the problem.\n--\n-- WHY THE CLAIM RE-READS UNDER A LOCK. Two reps pressing \"take it\" in the same\n-- second is the normal case in a room, not an edge case. `FOR UPDATE` plus a\n-- recheck that the offer is still `pending` is what makes the second press lose\n-- cleanly instead of overwriting the first.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 table \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_assignment_rules (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n name text NOT NULL,\n -- NULL means \"every funnel\". A house running new business and renewals will\n -- want a different rota for each.\n pipeline_id uuid,\n -- The rota, in order. Membership user ids, because that is what\n -- `plg_crm_deals.owner_id` references and what the RLS compares to auth.uid().\n assignee_ids uuid[] DEFAULT '{}'::uuid[] NOT NULL,\n -- How long one rep has the lead to themselves. Five minutes is the default\n -- every documented Brazilian implementation lands on; it is short because\n -- speed-to-lead is the entire point.\n offer_minutes integer DEFAULT 5 NOT NULL,\n -- Where the rota is. Persisted so the first offer does not always land on the\n -- same person.\n rota_cursor integer DEFAULT 0 NOT NULL,\n is_active boolean DEFAULT false NOT NULL,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_assignment_rules_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_assignment_rules_window_check\n CHECK (offer_minutes > 0 AND offer_minutes <= 1440),\n -- Both are writable by any `sales.edit` user through the settings grid, and\n -- both crash the engine: a NULL element violates `assignee_id NOT NULL`, and\n -- a negative cursor makes `(-1) % n = -1` subscript the array at 0, which\n -- returns NULL and does the same. Refused at the edge instead.\n CONSTRAINT plg_crm_assignment_rules_cursor_check CHECK (rota_cursor >= 0),\n CONSTRAINT plg_crm_assignment_rules_rota_check\n CHECK (array_position(assignee_ids, NULL) IS NULL)\n);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_lead_offers (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n rule_id uuid,\n lead_id uuid NOT NULL,\n deal_id uuid,\n assignee_id uuid NOT NULL,\n -- 1 for the first person asked, 2 for the next. It is the hop count, and it\n -- is what \"the third person also ignored it\" is counted from.\n attempt_number integer DEFAULT 1 NOT NULL,\n offered_at timestamptz DEFAULT now() NOT NULL,\n expires_at timestamptz NOT NULL,\n outcome text DEFAULT 'pending' NOT NULL,\n decided_at timestamptz,\n CONSTRAINT plg_crm_lead_offers_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_lead_offers_outcome_check CHECK (\n outcome = ANY (ARRAY['pending'::text, 'accepted'::text, 'expired'::text,\n 'declined'::text, 'superseded'::text]))\n);\n\n-- \u2500\u2500 constraint \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE public.plg_crm_assignment_rules\n DROP CONSTRAINT IF EXISTS plg_crm_assignment_rules_tenant_fkey;\nALTER TABLE public.plg_crm_assignment_rules\n ADD CONSTRAINT plg_crm_assignment_rules_tenant_fkey\n FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;\n\nALTER TABLE public.plg_crm_lead_offers\n DROP CONSTRAINT IF EXISTS plg_crm_lead_offers_rule_fkey;\nALTER TABLE public.plg_crm_lead_offers\n ADD CONSTRAINT plg_crm_lead_offers_rule_fkey\n FOREIGN KEY (rule_id) REFERENCES public.plg_crm_assignment_rules(id) ON DELETE SET NULL;\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- A rep is asked about a given lead at most once. See the header.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_lead_offers_once_uq\n ON public.plg_crm_lead_offers (lead_id, assignee_id);\n-- One live offer per lead: the window is exclusive, or it is not a window.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_lead_offers_live_uq\n ON public.plg_crm_lead_offers (lead_id) WHERE outcome = 'pending';\n-- The sweep's index: due, pending, oldest first.\nCREATE INDEX IF NOT EXISTS plg_crm_lead_offers_due_idx\n ON public.plg_crm_lead_offers (expires_at) WHERE outcome = 'pending';\nCREATE INDEX IF NOT EXISTS plg_crm_lead_offers_inbox_idx\n ON public.plg_crm_lead_offers (tenant_id, assignee_id, outcome);\nCREATE INDEX IF NOT EXISTS plg_crm_assignment_rules_tenant_idx\n ON public.plg_crm_assignment_rules (tenant_id) WHERE is_active;\n\n-- \u2500\u2500 row security \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- ENABLE **and** FORCE. `packages/db/test/pgtap/900_verification/001_posture.sql`\n-- (N14b) fails the pool for an `enforce`-registered table that is not forced,\n-- and without FORCE the migration-owning role \u2014 which every SECURITY DEFINER\n-- function here runs as \u2014 bypasses these policies entirely.\nALTER TABLE public.plg_crm_assignment_rules ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_assignment_rules FORCE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_lead_offers ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_lead_offers FORCE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS plg_crm_assignment_rules_authz_select ON public.plg_crm_assignment_rules;\nCREATE POLICY plg_crm_assignment_rules_authz_select ON public.plg_crm_assignment_rules\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_assignment_rules_authz_insert ON public.plg_crm_assignment_rules;\nCREATE POLICY plg_crm_assignment_rules_authz_insert ON public.plg_crm_assignment_rules\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_assignment_rules_authz_update ON public.plg_crm_assignment_rules;\nCREATE POLICY plg_crm_assignment_rules_authz_update ON public.plg_crm_assignment_rules\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_assignment_rules_authz_delete ON public.plg_crm_assignment_rules;\nCREATE POLICY plg_crm_assignment_rules_authz_delete ON public.plg_crm_assignment_rules\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\n-- An offer is written by the engine and by `crm_offer_accept`, never by hand:\n-- a hand-edited outcome is a claim nobody can audit. Reading is deliberately\n-- wide \u2014 the whole point of the history is that a manager can see who let a\n-- lead go, so it is not scoped to the assignee.\nDROP POLICY IF EXISTS plg_crm_lead_offers_authz_select ON public.plg_crm_lead_offers;\nCREATE POLICY plg_crm_lead_offers_authz_select ON public.plg_crm_lead_offers\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_assignment_rules TO authenticated;\nGRANT ALL ON public.plg_crm_assignment_rules TO service_role;\nGRANT SELECT ON public.plg_crm_lead_offers TO authenticated;\nGRANT ALL ON public.plg_crm_lead_offers TO service_role;\n\nINSERT INTO app.scaffold_registry\n (table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)\nVALUES\n ('public', 'plg_crm_assignment_rules', 'crm.assignment_rule', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),\n ('public', 'plg_crm_lead_offers', 'crm.lead_offer', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)\nON CONFLICT DO NOTHING;\n\n-- \u2500\u2500 function \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- Offer a lead to the next person on the rota who has not already had it.\n-- Returns the offer, or NULL when there is no active rule or the rota is spent.\nCREATE OR REPLACE FUNCTION public.crm_offer_lead(\n p_tenant_id uuid, p_lead_id uuid, p_deal_id uuid DEFAULT NULL, p_attempt integer DEFAULT 1\n) RETURNS uuid\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE r record; v_n integer; v_i integer; v_candidate uuid; v_id uuid;\nBEGIN\n -- The rota for THIS funnel, falling back to the tenant-wide one. The column\n -- and the header promised per-funnel rotas and the lookup ignored both, so a\n -- house with a \"New business\" rota and a \"Renewals\" rota sent every lead to\n -- whichever was created first \u2014 and the second rota could only be made\n -- through the API, where it did nothing.\n --\n -- A NULL `pipeline_id` means \"every funnel\", so an exact match wins and the\n -- general rule catches the rest.\n SELECT r2.* INTO r FROM public.plg_crm_assignment_rules r2\n LEFT JOIN public.plg_crm_deals d ON d.id = p_deal_id\n WHERE r2.tenant_id = p_tenant_id AND r2.is_active\n AND (r2.pipeline_id IS NULL OR r2.pipeline_id = d.pipeline_id)\n ORDER BY (r2.pipeline_id IS NOT NULL) DESC, r2.created_at\n LIMIT 1\n FOR UPDATE OF r2;\n\n IF r.id IS NULL THEN RETURN NULL; END IF;\n\n v_n := coalesce(array_length(r.assignee_ids, 1), 0);\n IF v_n = 0 THEN RETURN NULL; END IF;\n\n -- Walk the rota from the cursor, skipping anybody who already had this lead.\n -- One full lap, then give up: the rota is the bound, not a hop counter that\n -- could outlive the list of people.\n FOR i IN 0 .. v_n - 1 LOOP\n v_i := ((r.rota_cursor + i) % v_n) + 1;\n v_candidate := r.assignee_ids[v_i];\n IF NOT EXISTS (SELECT 1 FROM public.plg_crm_lead_offers o\n WHERE o.lead_id = p_lead_id AND o.assignee_id = v_candidate) THEN\n INSERT INTO public.plg_crm_lead_offers\n (tenant_id, rule_id, lead_id, deal_id, assignee_id, attempt_number, expires_at)\n VALUES\n (p_tenant_id, r.id, p_lead_id, p_deal_id, v_candidate, p_attempt,\n now() + make_interval(mins => r.offer_minutes))\n ON CONFLICT DO NOTHING\n RETURNING id INTO v_id;\n\n IF v_id IS NOT NULL THEN\n -- The cursor moves PAST the person just offered, so the next lead\n -- starts with somebody else.\n UPDATE public.plg_crm_assignment_rules\n SET rota_cursor = (r.rota_cursor + i + 1) % v_n, updated_at = now()\n WHERE id = r.id;\n RETURN v_id;\n END IF;\n END IF;\n END LOOP;\n\n RETURN NULL;\nEND $$;\n\n-- Take the lead. Loses cleanly when somebody else got there first.\nCREATE OR REPLACE FUNCTION public.crm_offer_accept(p_offer_id uuid)\nRETURNS boolean\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE o record; v_uid uuid := auth.uid();\nBEGIN\n SELECT * INTO o FROM public.plg_crm_lead_offers\n WHERE id = p_offer_id\n FOR UPDATE;\n\n -- Re-read under the lock. Two people pressing \"take it\" in the same second is\n -- the normal case in a room; the second press must lose, not overwrite.\n IF o.id IS NULL OR o.outcome <> 'pending' THEN RETURN false; END IF;\n IF o.expires_at <= now() THEN RETURN false; END IF;\n -- Only the person asked can accept. The offer being readable by the whole\n -- team is what makes the history useful; it is not permission to take it.\n IF v_uid IS NOT NULL AND o.assignee_id <> v_uid THEN RETURN false; END IF;\n\n UPDATE public.plg_crm_lead_offers\n SET outcome = 'accepted', decided_at = now()\n WHERE id = o.id;\n\n -- `owner_id` is the answer to \"whose lead is this\", and the RLS on\n -- plg_crm_deals has scoped by it since the baseline with nothing writing it.\n IF o.deal_id IS NOT NULL THEN\n UPDATE public.plg_crm_deals\n SET owner_id = o.assignee_id, assigned_to_id = o.assignee_id, updated_at = now()\n WHERE id = o.deal_id;\n ELSE\n UPDATE public.plg_crm_deals\n SET owner_id = o.assignee_id, assigned_to_id = o.assignee_id, updated_at = now()\n WHERE lead_id = o.lead_id;\n END IF;\n\n RETURN true;\nEND $$;\n\n-- Hand it back without waiting for the window to close. A rep who knows they\n-- cannot take it now should not cost the lead five minutes.\nCREATE OR REPLACE FUNCTION public.crm_offer_decline(p_offer_id uuid)\nRETURNS boolean\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE o record; v_uid uuid := auth.uid();\nBEGIN\n SELECT * INTO o FROM public.plg_crm_lead_offers WHERE id = p_offer_id FOR UPDATE;\n IF o.id IS NULL OR o.outcome <> 'pending' THEN RETURN false; END IF;\n IF v_uid IS NOT NULL AND o.assignee_id <> v_uid THEN RETURN false; END IF;\n\n UPDATE public.plg_crm_lead_offers\n SET outcome = 'declined', decided_at = now()\n WHERE id = o.id;\n\n -- Cascade immediately rather than on the next sweep: the whole value of a\n -- decline over a timeout is the minutes it saves.\n PERFORM public.crm_offer_lead(o.tenant_id, o.lead_id, o.deal_id, o.attempt_number + 1);\n RETURN true;\nEND $$;\n\n-- The tick. Expires windows that closed and cascades to the next person.\nCREATE OR REPLACE FUNCTION public.crm_offers_sweep(p_limit integer DEFAULT 100)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n o record; v_expired integer := 0; v_cascaded integer := 0; v_pooled integer := 0;\n v_failed integer := 0; v_next uuid; v_rule record;\nBEGIN\n FOR o IN\n SELECT * FROM public.plg_crm_lead_offers\n WHERE outcome = 'pending' AND expires_at <= now()\n ORDER BY expires_at\n LIMIT greatest(p_limit, 0)\n FOR UPDATE SKIP LOCKED\n LOOP\n -- PER ROW, like `automations_flows_run_due`. Without this a single rota\n -- carrying a bad element raised out of `event_runner_tick`, aborting the\n -- whole transaction \u2014 so `consume_event_log`, `notifications_drain`,\n -- `marketing_run_due`, `reports_deliver_due` and the flows were all rolled\n -- back, every minute, for every tenant, until somebody found the row.\n BEGIN\n UPDATE public.plg_crm_lead_offers\n SET outcome = 'expired', decided_at = now()\n WHERE id = o.id;\n v_expired := v_expired + 1;\n\n v_next := public.crm_offer_lead(o.tenant_id, o.lead_id, o.deal_id, o.attempt_number + 1);\n IF v_next IS NOT NULL THEN\n v_cascaded := v_cascaded + 1;\n ELSE\n -- NULL from `crm_offer_lead` is overloaded: it also means \"no active\n -- rule\" and \"empty rota\". Pooling on all three meant that switching the\n -- rota OFF un-assigned every lead with a pending offer \u2014 including ones\n -- a manager had just assigned by hand. Only a spent rota pools.\n SELECT * INTO v_rule FROM public.plg_crm_assignment_rules\n WHERE tenant_id = o.tenant_id AND is_active\n ORDER BY created_at LIMIT 1;\n\n IF v_rule.id IS NOT NULL AND coalesce(array_length(v_rule.assignee_ids, 1), 0) > 0 THEN\n UPDATE public.plg_crm_deals\n SET owner_id = NULL, assigned_to_id = NULL, updated_at = now()\n WHERE lead_id = o.lead_id;\n v_pooled := v_pooled + 1;\n END IF;\n END IF;\n EXCEPTION WHEN OTHERS THEN\n v_failed := v_failed + 1;\n RAISE NOTICE 'crm_offers_sweep: offer % could not be swept (%)', o.id, SQLERRM;\n END;\n END LOOP;\n\n RETURN jsonb_build_object('expired', v_expired, 'cascaded', v_cascaded,\n 'pooled', v_pooled, 'failed', v_failed);\nEND $$;\n\n-- The event-log handler: a lead arrives, the rota starts.\nCREATE OR REPLACE FUNCTION public.plg_crm_on_lead_created_offer(p_event jsonb)\nRETURNS jsonb\nLANGUAGE plpgsql SECURITY DEFINER\nSET search_path TO ''\nAS $$\nDECLARE\n v_tenant uuid := nullif(p_event ->> 'tenant_id', '')::uuid;\n -- `consume_event_log` hands a handler `to_jsonb(v_event)` \u2014 the WHOLE\n -- event_log row. `tenant_id`, `subject_type` and `subject_id` are at the top\n -- level; everything the emitter chose to send is nested under `payload`.\n -- Reading `lead_id` at the top level, as the first cut did, found nothing on\n -- every real delivery: the rota never started, the delivery was marked\n -- DELIVERED, and nothing retried or reported it.\n v_lead uuid := nullif(coalesce(\n CASE WHEN p_event ->> 'subject_type' IN ('lead', 'person', 'contact')\n THEN p_event ->> 'subject_id' END,\n p_event -> 'payload' ->> 'lead_id',\n p_event -> 'payload' ->> 'person_id',\n p_event ->> 'lead_id'\n ), '')::uuid;\n v_deal uuid;\n v_id uuid;\nBEGIN\n IF v_tenant IS NULL OR v_lead IS NULL THEN\n RETURN jsonb_build_object('offered', false, 'reason', 'event carries no tenant or lead');\n END IF;\n\n -- The lead trigger has already created the card; the offer should carry it so\n -- accepting can set its owner without a second lookup.\n SELECT id INTO v_deal FROM public.plg_crm_deals WHERE lead_id = v_lead;\n\n v_id := public.crm_offer_lead(v_tenant, v_lead, v_deal, 1);\n RETURN jsonb_build_object('offered', v_id IS NOT NULL);\nEND $$;\n\nREVOKE ALL ON FUNCTION public.crm_offer_lead(uuid, uuid, uuid, integer) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_offer_lead(uuid, uuid, uuid, integer) TO service_role;\nREVOKE ALL ON FUNCTION public.crm_offer_accept(uuid) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_offer_accept(uuid) TO authenticated;\nGRANT EXECUTE ON FUNCTION public.crm_offer_accept(uuid) TO service_role;\nREVOKE ALL ON FUNCTION public.crm_offer_decline(uuid) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_offer_decline(uuid) TO authenticated;\nGRANT EXECUTE ON FUNCTION public.crm_offer_decline(uuid) TO service_role;\nREVOKE ALL ON FUNCTION public.crm_offers_sweep(integer) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_offers_sweep(integer) TO service_role;\nREVOKE ALL ON FUNCTION public.plg_crm_on_lead_created_offer(jsonb) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.plg_crm_on_lead_created_offer(jsonb) TO service_role;\n\n-- \u2500\u2500 subscription \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- A `subscribesTo` in the manifest is a declaration; THIS is what makes the\n-- event log call it. Without the row the reaction never happens and nothing\n-- says so, which is exactly what `check-event-contract` exists to catch.\nSELECT public.register_event_subscription(\n 'crm', 'crm.lead_created', 'plg_crm_on_lead_created_offer',\n 'Offer the new lead to the next person on the rota', 5);\n\n-- \u2500\u2500 view \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- What a rep is being asked to take, right now, with the lead's name on it.\n-- `security_invoker` is not decoration here. Without it the view runs as its\n-- OWNER, so it bypasses both the offers policy and `people`'s RLS and hands any\n-- authenticated caller every tenant's lead names and phone numbers. Every other\n-- view in this plugin sets it; 002 and 006 carry the comment explaining why.\nCREATE OR REPLACE VIEW public.v_crm_lead_offers WITH (security_invoker='true') AS\n SELECT o.id, o.tenant_id, o.lead_id, o.deal_id, o.assignee_id,\n o.attempt_number, o.offered_at, o.expires_at, o.outcome, o.decided_at,\n p.name AS lead_name, p.phone AS lead_phone,\n greatest(0, extract(epoch FROM (o.expires_at - now()))::integer) AS seconds_left\n FROM public.plg_crm_lead_offers o\n LEFT JOIN public.people p ON p.id = o.lead_id;\n\nGRANT SELECT ON public.v_crm_lead_offers TO authenticated;\nGRANT SELECT ON public.v_crm_lead_offers TO service_role;\n";
10
+ export declare const MIGRATION_010_THE_BOARD_HEARS_THE_DEAL = "-- 010_the_board_hears_the_deal.sql \u2014 the pipeline board repaints itself.\n--\n-- `PipelineView` opens a realtime channel so a card created by the lead trigger\n-- appears without a reload. That subscription pointed at\n-- `plg_crm_deal_extensions` until this wave moved it to `plg_crm_deals`, which\n-- is where the deal actually changes now.\n--\n-- NEITHER TABLE IS IN THE PUBLICATION ON THE CURRENT CHAIN. The only\n-- `ALTER PUBLICATION` plugin-crm ever shipped lives in\n-- `migrations.archive/006_lead_enters_pipeline.sql`, which the 1.0.0 squash\n-- retired unapplied. So the board has been subscribing to a table Postgres does\n-- not stream, and `.subscribe()` answers SUBSCRIBED and then says nothing \u2014\n-- forever, with no error and no warning.\n--\n-- That trap is written down twice in this repository already: in the archived\n-- 006 (\"the supabase_realtime publication was EMPTY \u2014 every .subscribe() in the\n-- SDK was silent\") and in `packages/kds/migrations/0002` (\"a wall that simply\n-- never updates until somebody reloads it\"). This is the same guard, copied\n-- rather than assumed to have run.\n--\n-- Replica identity stays DEFAULT. Every handler refetches the board, so the\n-- payload's contents are irrelevant, and FULL would put a customer's deal \u2014\n-- value, notes, contact \u2014 on a websocket for no gain.\n--\n-- Idempotent: adding a table already in the publication is a no-op, and a pool\n-- without the table is skipped rather than failed.\n\nDO $$\nDECLARE t text;\nBEGIN\n IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = 'supabase_realtime') THEN\n CREATE PUBLICATION supabase_realtime;\n END IF;\n\n FOREACH t IN ARRAY ARRAY['plg_crm_deals'] LOOP\n IF NOT EXISTS (SELECT 1 FROM pg_tables WHERE schemaname = 'public' AND tablename = t) THEN\n CONTINUE;\n END IF;\n IF NOT EXISTS (SELECT 1 FROM pg_publication_tables\n WHERE pubname = 'supabase_realtime' AND schemaname = 'public' AND tablename = t) THEN\n EXECUTE format('ALTER PUBLICATION supabase_realtime ADD TABLE public.%I', t);\n END IF;\n END LOOP;\nEND $$;\n";
11
+ export declare const MIGRATION_011_A_FUNNEL_IS_BORN_USABLE = "-- 011_a_funnel_is_born_usable.sql \u2014 the invariants move from one writer to the\n-- database.\n--\n-- Two rules made a funnel usable, and both lived exclusively inside\n-- `savePipeline` in the TypeScript provider:\n--\n-- 1. ONE DEFAULT PER HOUSE. Enforced by demoting the others before marking\n-- this one \u2014 and by nothing else. `plg_crm_pipelines.is_default` is a bare\n-- boolean with no constraint.\n-- 2. A FUNNEL IS BORN WITH STAGES. `savePipeline` inserts Novo / Ganho /\n-- Perdido after the row.\n--\n-- The moment a second writer appears \u2014 the settings grid this wave adds, a SQL\n-- seed, an import \u2014 both rules are gone, silently:\n--\n-- * Two defaults, and `getPipelines()` (ORDER BY is_default DESC, name) and\n-- `crm_place_lead_on_board` (ORDER BY is_default DESC, created_at ASC) pick\n-- DIFFERENT funnels. The board paints one while every new lead lands in the\n-- other, and nothing on either screen says so.\n-- * A funnel with no stages: `crm_place_lead_on_board` finds no entry stage,\n-- returns NULL at its guard, and the lead reaches no board at all.\n--\n-- So the rules come down here, where every writer passes.\n--\n-- The demotion is a BEFORE trigger rather than only a unique index, because an\n-- index REFUSES a second default and \"make this one the default\" has to move\n-- the flag, not fail. The index stays as the backstop that proves the trigger\n-- ran.\n--\n-- The stage seed is an AFTER trigger and `savePipeline` stops doing it \u2014 two\n-- seeders would give a new funnel six stages. Existing funnels are left alone:\n-- a house that deliberately deleted a stage is not asking for it back.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 normalise before constraining \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\n-- A tenant carrying two defaults today would refuse the index below. The\n-- OLDEST wins, which is the same tie-break `crm_place_lead_on_board` already\n-- applies, so this cannot move where leads are landing right now.\nWITH ranked AS (\n SELECT id, row_number() OVER (PARTITION BY tenant_id ORDER BY created_at, id) AS rn\n FROM public.plg_crm_pipelines\n WHERE is_default\n)\nUPDATE public.plg_crm_pipelines p\n SET is_default = false\n FROM ranked r\n WHERE p.id = r.id AND r.rn > 1;\n\n-- \u2500\u2500 function \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_pipelines_one_default() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n IF NEW.is_default THEN\n UPDATE public.plg_crm_pipelines\n SET is_default = false, updated_at = now()\n WHERE tenant_id = NEW.tenant_id\n AND id IS DISTINCT FROM NEW.id\n AND is_default;\n END IF;\n RETURN NEW;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_pipelines_seed_stages() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n -- The minimum that makes a board work: somewhere to enter, somewhere to win,\n -- somewhere to lose. `code` is derived by the 005 trigger.\n INSERT INTO public.plg_crm_pipeline_stages\n (tenant_id, pipeline_id, name, \"order\", color, probability, is_initial, is_won, is_lost)\n VALUES\n (NEW.tenant_id, NEW.id, 'Novo', 1, '#64748b', 10, true, false, false),\n (NEW.tenant_id, NEW.id, 'Ganho', 2, '#10b981', 100, false, true, false),\n (NEW.tenant_id, NEW.id, 'Perdido', 3, '#ef4444', 0, false, false, true);\n RETURN NULL;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.trg_plg_crm_pipelines_one_default() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_pipelines_one_default() TO authenticated, service_role;\nREVOKE ALL ON FUNCTION public.trg_plg_crm_pipelines_seed_stages() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_pipelines_seed_stages() TO authenticated, service_role;\n\n-- \u2500\u2500 trigger \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nDROP TRIGGER IF EXISTS plg_crm_pipelines_one_default ON public.plg_crm_pipelines;\nCREATE TRIGGER plg_crm_pipelines_one_default\n BEFORE INSERT OR UPDATE OF is_default ON public.plg_crm_pipelines\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_pipelines_one_default();\n\nDROP TRIGGER IF EXISTS plg_crm_pipelines_seed_stages ON public.plg_crm_pipelines;\nCREATE TRIGGER plg_crm_pipelines_seed_stages\n AFTER INSERT ON public.plg_crm_pipelines\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_pipelines_seed_stages();\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- The backstop. With the BEFORE trigger this can only fire if somebody\n-- disables the trigger \u2014 which is exactly when you want to hear about it.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_pipelines_one_default_uq\n ON public.plg_crm_pipelines (tenant_id) WHERE is_default;\n";
12
+ export declare const MIGRATION_012_THE_CRM_SAYS_WHAT_HAPPENED = "-- 012_the_crm_says_what_happened.sql \u2014 the facts the funnel emits, durably.\n--\n-- NOTHING IN THIS PLUGIN EVER WROTE TO `event_log`.\n--\n-- `lib/message-events.ts` declares six facts \u2014 `crm.lead_created`,\n-- `crm.stage_changed`, `crm.deal_won` and friends \u2014 and the automations screen\n-- lists them, so they look like a contract. They are not produced. Searching\n-- the plugin finds no `plg_emit_event` in its SQL, no `emitDomainEvent` in its\n-- TypeScript, and no `emitsFrom` in its manifest; `logEvent` writes a row to\n-- `plg_crm_activities`, which is the operator's timeline and not the event log.\n--\n-- So every `subscribesTo` pointed at a `crm.*` fact \u2014 the lead-offer rota in\n-- 009, and plugin-automations' cadence \u2014 was waiting on something that never\n-- arrives. The subscriptions are registered, the handlers exist, the delivery\n-- table stays empty, and nothing anywhere says why.\n--\n-- WHY A TRIGGER RATHER THAN A CALL IN THE PROVIDER. The lead does not only\n-- arrive through `createLead`: `crm_lead_to_board` fires on any `people` insert\n-- with `kind='lead'`, which is how a public capture form, an import and an\n-- agent RPC all create one. A fact emitted from one TypeScript path would miss\n-- the other three, and would miss them silently \u2014 which is the shape of bug\n-- this whole wave has been unpicking.\n--\n-- WHAT THE ENVELOPE CARRIES. `plg_emit_event` writes `subject_type`/`subject_id`\n-- alongside the payload, and `consume_event_log` hands the handler the whole\n-- row. Subject is the contract the shipped handlers already read\n-- (`plg_notifications_on_fulfillment_completed`), so the lead goes there; the\n-- payload carries what a message template would want to interpolate.\n--\n-- Only three facts, not all six. `crm.lead_created` is what starts a rota and a\n-- cadence; `crm.deal_won`/`crm.deal_lost` are what stop one. The quote facts\n-- have no consumer yet, and emitting a fact nobody reads is how `event_log`\n-- becomes noise.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 function \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE OR REPLACE FUNCTION public.trg_crm_emit_lead_created() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n IF NEW.kind IS DISTINCT FROM 'lead' THEN RETURN NULL; END IF;\n\n PERFORM public.plg_emit_event(\n 'crm.lead_created',\n jsonb_build_object(\n 'lead_id', NEW.id,\n 'person_id', NEW.id,\n 'name', NEW.name,\n 'phone', NEW.phone,\n 'email', NEW.email\n ),\n 'lead', NEW.id::text, NEW.tenant_id\n );\n RETURN NULL;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.trg_crm_emit_deal_outcome() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nDECLARE v_key text;\nBEGIN\n -- Only the TRANSITION. An update that leaves the status where it was is an\n -- edit, and a cadence that exits on every save of a won deal exits twice.\n IF NEW.status IS NOT DISTINCT FROM OLD.status THEN RETURN NULL; END IF;\n v_key := CASE NEW.status WHEN 'won' THEN 'crm.deal_won'\n WHEN 'lost' THEN 'crm.deal_lost' END;\n IF v_key IS NULL THEN RETURN NULL; END IF;\n\n -- The SUBJECT is the lead, not the deal. Everything downstream \u2014 a cadence\n -- enrolment, an offer \u2014 is keyed by the person, and a handler that had to\n -- resolve deal \u2192 lead itself would be a join each of them repeats.\n IF NEW.lead_id IS NULL THEN RETURN NULL; END IF;\n\n PERFORM public.plg_emit_event(\n v_key,\n jsonb_build_object(\n 'deal_id', NEW.id,\n 'lead_id', NEW.lead_id,\n 'person_id', NEW.lead_id,\n 'title', NEW.title,\n 'value', NEW.value\n ),\n 'lead', NEW.lead_id::text, NEW.tenant_id\n );\n RETURN NULL;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.trg_crm_emit_lead_created() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_crm_emit_lead_created() TO authenticated, service_role;\nREVOKE ALL ON FUNCTION public.trg_crm_emit_deal_outcome() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_crm_emit_deal_outcome() TO authenticated, service_role;\n\n-- \u2500\u2500 trigger \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- AFTER, so a failure to emit cannot refuse the lead. `plg_emit_event` only\n-- inserts a row; the consumer is what retries.\nDROP TRIGGER IF EXISTS crm_emit_lead_created ON public.people;\nCREATE TRIGGER crm_emit_lead_created\n AFTER INSERT ON public.people\n FOR EACH ROW EXECUTE FUNCTION public.trg_crm_emit_lead_created();\n\nDROP TRIGGER IF EXISTS crm_emit_deal_outcome ON public.plg_crm_deals;\nCREATE TRIGGER crm_emit_deal_outcome\n AFTER UPDATE OF status ON public.plg_crm_deals\n FOR EACH ROW EXECUTE FUNCTION public.trg_crm_emit_deal_outcome();\n";
13
+ export declare const MIGRATION_013_THE_COMPANY_HOLDS_ITS_PEOPLE = "-- 013_the_company_holds_its_people.sql \u2014 the CRM learns that a contact works\n-- somewhere.\n--\n-- UNTIL NOW THERE WAS NO COMPANY. `v_leads` publishes a column called\n-- `company`, and it is `metadata ->> 'company'` \u2014 free text, typed once per\n-- lead, never joined to anything. `company_legal_entities` is the tenant's own\n-- fiscal emitter (only `app.units` references it), not the customer's. So two\n-- people at the same restaurant are two unrelated rows that happen to have\n-- spelled the name the same way, and a deal knows a person but not a house.\n--\n-- WHY THIS SHAPE. Measured against the 297 real leads in the Abrasel file this\n-- was built for:\n--\n-- * 212 distinct CNPJs, 58 of them carrying more than one contact \u2014 134 of\n-- 297 leads (45%) sit at a company somebody else also sits at.\n-- * 139 leads (47%) are PROPRIET\u00C1RIO / S\u00D3CIO, the role that actually moves\n-- between houses.\n-- * 232 (78%) have RAZ\u00C3O SOCIAL different from NOME FANTASIA, and 31 raz\u00F5es\n-- sociais ARE a person's name (the empres\u00E1rio-individual format).\n-- * 229 (77%) use gmail/hotmail/\u2026 \u2014 an email domain identifies nothing.\n-- * 9 (3%) have no usable CNPJ at all.\n--\n-- Those numbers decide every choice below, and rule out three designs that are\n-- otherwise perfectly good:\n--\n-- Twenty keys a company by its web DOMAIN (a UNIQUE index on\n-- `company.domainName`) and a person by their email. That covers 23% of this\n-- file, and the counterexample is already in it: two different establishments\n-- whose owners' email domains are crossed would be merged into one company.\n--\n-- Krayin hangs the deal off the PERSON and reaches the company through\n-- `persons.organization_id`. With 45% of leads sharing a company and 47% of\n-- them being s\u00F3cios, moving one person rewrites the attribution of every\n-- historical deal, silently.\n--\n-- Odoo's party model \u2014 one `res_partner` table, `is_company` boolean,\n-- `parent_id` \u2014 copies the parent's `vat` down onto every child. OCA's\n-- `l10n-brazil` overrides `_commercial_sync_to_children` specifically to stop\n-- that, because here the company has a CNPJ and each s\u00F3cio has their own CPF.\n-- Starting by disabling your own base model's central behaviour is a bad\n-- start.\n--\n-- What is left is EspoCRM's shape \u2014 two tables and a join that carries the role\n-- \u2014 with the tax id as the identity key instead of a domain. That is what this\n-- file builds.\n--\n-- \u2500\u2500 the one decision that cannot be retrofitted \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--\n-- `plg_crm_deals.company_id` IS STAMPED AT INSERT AND NEVER RE-DERIVED.\n--\n-- Everything else here is a migration away from something else. A single FK can\n-- become a join table by backfill; `role` can be added with an ALTER; the\n-- identity key can be swapped as long as the CNPJ string was kept. This one\n-- cannot, because it is data that was never captured: once a s\u00F3cio moves, no\n-- query can reconstruct which house a past deal belonged to. Backfilling\n-- `company_id` from the person's CURRENT company looks like a repair and is a\n-- silent rewrite of history.\n--\n-- So the trigger below fires on INSERT only. An UPDATE may still set it \u2014 a\n-- human correcting a mistake is exactly the case that must stay possible \u2014 but\n-- nothing derives it after the fact.\n--\n-- \u2500\u2500 why the tax id is a normalised string \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--\n-- Not numeric: 9 of these CNPJs start with `0`, and the file's 74 CPFs have\n-- leading zeros that an integer column destroys. Not formatted either \u2014 OCA\n-- carries a regression test (`test_duplicate_cnpj.py`) that exists because the\n-- duplicate check compared MASKED values, so `06.990.590/0001-23` and\n-- `06.990.590/000123` slipped past each other. The trigger here strips before\n-- the unique index ever sees the value, so there is no unnormalised form to\n-- compare wrong.\n--\n-- The validator is mod-11 over `ascii(c) - 48` rather than over digits, because\n-- from July 2026 the CNPJ accepts uppercase letters in its first 12 positions\n-- (IN RFB n\u00BA 2229/2024 \u2014 worth confirming against the Receita text; the\n-- citation reaching us is erpbrasil/OCA, which already ships passing tests for\n-- it). For a purely numeric document `ascii(c) - 48` IS the digit, so the same\n-- code grades both eras.\n--\n-- Validity is RECORDED, never enforced. A real company with a typo'd CNPJ has\n-- to be able to enter the CRM; refusing it at the door just moves the record to\n-- a spreadsheet nobody joins. `document_valid` is a flag the UI can badge.\n--\n-- \u2500\u2500 why there is no shared telephone entity \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--\n-- EspoCRM is the only CRM surveyed that models a shared switchboard properly:\n-- a `phone_number` table with a polymorphic M:N to every entity. It has exactly\n-- 2 cases in these 297 leads (0.7%) \u2014 and its `opt_out` lives on the SHARED\n-- row, so opting out one switchboard opts out everyone reachable on it. That is\n-- the wrong failure mode for LGPD consent, which in this file is already\n-- recorded per person.\n--\n-- So phones are child rows OWNED BY THE PERSON (the Frappe/OroCRM shape) with a\n-- normalised `phone_key` and a plain index on it. That answers \"who else is at\n-- this number?\" without a scan \u2014 which matters, because the WhatsApp export\n-- this feeds means a shared number is two leads in one thread \u2014 and it keeps\n-- consent where it belongs.\n--\n-- \u2500\u2500 scope \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Tenant-scoped, no `unit_id`, like the rota tables in 009. A company belongs\n-- to the house, not to one of its branches; the deal already carries the unit.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 function: identity \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\u2500\u2500\n\n-- Strip the mask, uppercase, nothing else. The one form everything compares.\nCREATE OR REPLACE FUNCTION public.crm_document_normalize(p_doc text) RETURNS text\n LANGUAGE sql IMMUTABLE\n SET search_path TO ''\n AS $$\n SELECT nullif(upper(regexp_replace(coalesce(p_doc, ''), '[^0-9A-Za-z]', '', 'g')), '')\n$$;\n\n-- 11 normalised characters is a CPF, 14 a CNPJ, anything else is neither. The\n-- kind is derived rather than asked for: an importer that had to classify would\n-- get it wrong on exactly the MEI rows where it matters.\nCREATE OR REPLACE FUNCTION public.crm_document_kind(p_doc text) RETURNS text\n LANGUAGE sql IMMUTABLE\n SET search_path TO ''\n AS $$\n SELECT CASE length(public.crm_document_normalize(p_doc))\n WHEN 11 THEN 'cpf'\n WHEN 14 THEN 'cnpj'\n ELSE NULL\n END\n$$;\n\n-- Mod-11 over `ascii(c) - 48`, which is the digit itself for '0'..'9' and the\n-- alphanumeric CNPJ's value for 'A'..'Z'. Check digits stay numeric in both\n-- eras, so they are compared as characters.\nCREATE OR REPLACE FUNCTION public.crm_document_is_valid(p_doc text) RETURNS boolean\n LANGUAGE plpgsql IMMUTABLE\n SET search_path TO ''\n AS $$\nDECLARE\n d text := public.crm_document_normalize(p_doc);\n kind text;\n body_len int; -- characters before the two check digits: 9 for CPF, 12 for CNPJ\n round int; -- 1 for the first check digit, 2 for the second\n span int; -- how many characters this round sums over\n pos int;\n weight int;\n total int;\n rest int;\n expected int;\nBEGIN\n IF d IS NULL THEN RETURN NULL; END IF;\n kind := public.crm_document_kind(d);\n IF kind IS NULL THEN RETURN false; END IF;\n\n -- A single repeated character passes mod-11 and is never a real document.\n IF d ~ ('^(.)\\1{' || (length(d) - 1)::text || '}$') THEN RETURN false; END IF;\n -- The two check digits stay numeric in both the numeric and the alphanumeric\n -- CNPJ; a CPF is numeric throughout.\n IF right(d, 2) !~ '^[0-9]{2}$' THEN RETURN false; END IF;\n IF kind = 'cpf' AND d !~ '^[0-9]{11}$' THEN RETURN false; END IF;\n IF kind = 'cnpj' AND d !~ '^[0-9A-Z]{14}$' THEN RETURN false; END IF;\n\n body_len := length(d) - 2;\n\n FOR round IN 1..2 LOOP\n span := body_len + round - 1;\n total := 0;\n\n FOR pos IN 1..span LOOP\n -- Both series are the same series read from the right. The CPF counts\n -- down (10\u20262, then 11\u20262); the CNPJ runs 2\u20269 and wraps.\n weight := CASE WHEN kind = 'cpf'\n THEN span + 2 - pos\n ELSE ((span - pos) % 8) + 2\n END;\n total := total + (ascii(substr(d, pos, 1)) - 48) * weight;\n END LOOP;\n\n rest := total % 11;\n expected := CASE WHEN rest < 2 THEN 0 ELSE 11 - rest END;\n\n IF expected <> (ascii(substr(d, body_len + round, 1)) - 48) THEN\n RETURN false;\n END IF;\n END LOOP;\n\n RETURN true;\nEND $$;\n\n-- \u2500\u2500 function: telephone \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\u2500\n\n-- One Brazilian number, one key. Deliberately a COPY of the logic\n-- plugin-notifications carries rather than a call into it: plugin-crm declares\n-- no dependency on that plugin, and a cross-plugin function reference would\n-- make this file fail to apply wherever the CRM is installed alone.\n--\n-- A bare 8- or 9-digit number keeps no area code and is therefore a weak key \u2014\n-- it can collide across cities. That is tolerable here because the key is only\n-- ever used to SUGGEST (\"who else is at this number?\") and to deduplicate\n-- within one person; nothing merges two people on it.\nCREATE OR REPLACE FUNCTION public.crm_phone_key(p_phone text) RETURNS text\n LANGUAGE plpgsql IMMUTABLE\n SET search_path TO ''\n AS $$\nDECLARE\n d text;\n area text;\n sub text;\nBEGIN\n IF p_phone IS NULL THEN RETURN NULL; END IF;\n d := regexp_replace(p_phone, '[^0-9]', '', 'g');\n\n -- Country code, only when what remains is still a whole Brazilian number.\n IF length(d) IN (12, 13) AND left(d, 2) = '55' THEN\n d := substr(d, 3);\n END IF;\n -- Trunk prefix. No area code starts with 0, so this cannot eat a real digit.\n IF length(d) IN (11, 12) AND left(d, 1) = '0' THEN\n d := substr(d, 2);\n END IF;\n\n IF length(d) < 8 OR length(d) > 11 THEN RETURN NULL; END IF;\n\n -- A mobile written the way it was written before 2016.\n IF length(d) = 10 THEN\n area := left(d, 2);\n sub := substr(d, 3);\n IF left(sub, 1) IN ('6', '7', '8', '9') THEN\n d := area || '9' || sub;\n END IF;\n END IF;\n\n RETURN d;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.crm_document_normalize(text) FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.crm_document_kind(text) FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.crm_document_is_valid(text) FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.crm_phone_key(text) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_document_normalize(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.crm_document_kind(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.crm_document_is_valid(text) TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.crm_phone_key(text) TO authenticated, service_role;\n\n-- \u2500\u2500 table \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_companies (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n -- What you call them. NOME FANTASIA when there is one, raz\u00E3o social when\n -- there is not \u2014 the trigger below fills it either way, so every row has\n -- something to show and to search.\n name text NOT NULL,\n -- RAZ\u00C3O SOCIAL, kept beside it rather than instead of it: 78% of the leads\n -- this was built for have the two different, and 31 raz\u00F5es sociais are a\n -- person's own name.\n legal_name text,\n -- Normalised, unmasked, uppercase. Nullable \u2014 3% of real leads have no\n -- usable CNPJ, and a company you cannot key is still a company.\n document_number text,\n document_kind text,\n -- The first 8 characters of a CNPJ: what makes matriz and filial the same\n -- economic group. Meaningless for a CPF, so the trigger leaves it NULL there.\n document_root text,\n -- Recorded, never enforced. See the header.\n document_valid boolean,\n email text,\n phone text,\n website text,\n address text,\n city text,\n state text,\n country text DEFAULT 'BR'::text,\n postal_code text,\n tags text[] DEFAULT '{}'::text[] NOT NULL,\n notes text,\n metadata jsonb DEFAULT '{}'::jsonb NOT NULL,\n custom_fields jsonb DEFAULT '{}'::jsonb NOT NULL,\n owner_id uuid,\n is_active boolean DEFAULT true NOT NULL,\n created_by uuid,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_companies_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_companies_tenant_id_id_key UNIQUE (tenant_id, id),\n CONSTRAINT plg_crm_companies_kind_check\n CHECK (document_kind IS NULL OR document_kind = ANY (ARRAY['cpf'::text, 'cnpj'::text]))\n);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_company_people (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n company_id uuid NOT NULL,\n person_id uuid NOT NULL,\n -- The job title lives HERE and not on the person, which is the one thing\n -- EspoCRM gets right and OroCRM does not: OroCRM pays for a full M:N so a\n -- consultant can sit at three accounts, then stores their title \u2014 the single\n -- fact that varies per account \u2014 on the person row. Free text, because the\n -- vocabulary is the file's own (PROPRIET\u00C1RIO / S\u00D3CIO, GER\u00CANCIA, \u2026) and a\n -- closed list would silently drop the rest.\n role text,\n is_primary boolean DEFAULT false NOT NULL,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_company_people_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_company_people_pair_key UNIQUE (company_id, person_id)\n);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_person_phones (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n person_id uuid NOT NULL,\n -- As typed. Kept verbatim so what an operator sees is what they entered.\n phone text NOT NULL,\n -- Derived by trigger. NULL when the input cannot be a Brazilian number,\n -- which is not an error \u2014 it is a number nobody can dial from here.\n phone_key text,\n label text,\n is_primary boolean DEFAULT false NOT NULL,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_person_phones_pkey PRIMARY KEY (id)\n);\n\n-- \u2500\u2500 constraint \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE public.plg_crm_companies\n DROP CONSTRAINT IF EXISTS plg_crm_companies_tenant_fkey;\nALTER TABLE public.plg_crm_companies\n ADD CONSTRAINT plg_crm_companies_tenant_fkey\n FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;\n\n-- Composite, against (tenant_id, id), so a link cannot reach across tenants\n-- even if RLS is off \u2014 which it is for every SECURITY DEFINER function here.\nALTER TABLE public.plg_crm_company_people\n DROP CONSTRAINT IF EXISTS plg_crm_company_people_company_fkey;\nALTER TABLE public.plg_crm_company_people\n ADD CONSTRAINT plg_crm_company_people_company_fkey\n FOREIGN KEY (tenant_id, company_id)\n REFERENCES public.plg_crm_companies(tenant_id, id) ON DELETE CASCADE;\n\nALTER TABLE public.plg_crm_company_people\n DROP CONSTRAINT IF EXISTS plg_crm_company_people_person_fkey;\nALTER TABLE public.plg_crm_company_people\n ADD CONSTRAINT plg_crm_company_people_person_fkey\n FOREIGN KEY (tenant_id, person_id)\n REFERENCES public.people(tenant_id, id) ON DELETE CASCADE;\n\nALTER TABLE public.plg_crm_person_phones\n DROP CONSTRAINT IF EXISTS plg_crm_person_phones_person_fkey;\nALTER TABLE public.plg_crm_person_phones\n ADD CONSTRAINT plg_crm_person_phones_person_fkey\n FOREIGN KEY (tenant_id, person_id)\n REFERENCES public.people(tenant_id, id) ON DELETE CASCADE;\n\n-- \u2500\u2500 the deal remembers the house \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\nALTER TABLE public.plg_crm_deals ADD COLUMN IF NOT EXISTS company_id uuid;\n\nALTER TABLE public.plg_crm_deals\n DROP CONSTRAINT IF EXISTS plg_crm_deals_company_fkey;\nALTER TABLE public.plg_crm_deals\n ADD CONSTRAINT plg_crm_deals_company_fkey\n FOREIGN KEY (tenant_id, company_id)\n REFERENCES public.plg_crm_companies(tenant_id, id) ON DELETE SET NULL (company_id);\n-- THE COLUMN LIST IS NOT DECORATION. A bare `ON DELETE SET NULL` on a COMPOSITE\n-- key nulls EVERY referencing column \u2014 including `tenant_id`, which is NOT\n-- NULL. Deleting a company that any deal was stamped with then fails with\n-- `null value in column \"tenant_id\" \u2026 violates not-null constraint`, naming a\n-- column the operator never touched. Deleting a company is a granted,\n-- policy-backed operation here, so that is a reachable dead end, not a\n-- hypothetical. Postgres 15+ takes the column list; this chain is on 17.\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- The identity key. Per tenant, because two houses may legitimately both have\n-- the same supplier on their books.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_companies_document_uq\n ON public.plg_crm_companies (tenant_id, document_number)\n WHERE document_number IS NOT NULL;\n-- The matriz/filial rollup.\nCREATE INDEX IF NOT EXISTS plg_crm_companies_root_idx\n ON public.plg_crm_companies (tenant_id, document_root)\n WHERE document_root IS NOT NULL;\nCREATE INDEX IF NOT EXISTS plg_crm_companies_name_idx\n ON public.plg_crm_companies (tenant_id, lower(name));\n\nCREATE INDEX IF NOT EXISTS plg_crm_company_people_person_idx\n ON public.plg_crm_company_people (tenant_id, person_id);\nCREATE INDEX IF NOT EXISTS plg_crm_company_people_company_idx\n ON public.plg_crm_company_people (tenant_id, company_id);\n-- One primary employer per person. The trigger moves the flag; this refuses a\n-- second one, which is how you find out the trigger was bypassed.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_company_people_primary_uq\n ON public.plg_crm_company_people (person_id) WHERE is_primary;\n\n-- \"Who else is at this number?\" \u2014 one index instead of a full scan.\nCREATE INDEX IF NOT EXISTS plg_crm_person_phones_key_idx\n ON public.plg_crm_person_phones (tenant_id, phone_key)\n WHERE phone_key IS NOT NULL;\n-- The same number twice on one person is a duplicate, not a second line.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_person_phones_person_key_uq\n ON public.plg_crm_person_phones (person_id, phone_key)\n WHERE phone_key IS NOT NULL;\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_person_phones_primary_uq\n ON public.plg_crm_person_phones (person_id) WHERE is_primary;\n-- Both indexes above are PARTIAL, so neither serves \"this person's lines\" nor\n-- the ON DELETE CASCADE from `people`. The link table got this and the phone\n-- table did not.\nCREATE INDEX IF NOT EXISTS plg_crm_person_phones_person_idx\n ON public.plg_crm_person_phones (tenant_id, person_id);\n\nCREATE INDEX IF NOT EXISTS plg_crm_deals_company_idx\n ON public.plg_crm_deals (tenant_id, company_id)\n WHERE company_id IS NOT NULL;\n\n-- \u2500\u2500 function: the invariants \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\n-- Normalisation happens HERE and not in the provider, because the provider is\n-- not the only writer: an import, a seed and an agent RPC all reach this table,\n-- and a rule that lives in one writer is a rule three writers do not have.\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_companies_identity() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n NEW.document_number := public.crm_document_normalize(NEW.document_number);\n NEW.document_kind := public.crm_document_kind(NEW.document_number);\n NEW.document_valid := public.crm_document_is_valid(NEW.document_number);\n NEW.document_root := CASE WHEN NEW.document_kind = 'cnpj'\n THEN left(NEW.document_number, 8) END;\n\n -- A row has to be findable. An importer holding only a raz\u00E3o social should\n -- not have to duplicate it into `name` to satisfy NOT NULL.\n IF nullif(btrim(coalesce(NEW.name, '')), '') IS NULL THEN\n NEW.name := nullif(btrim(coalesce(NEW.legal_name, '')), '');\n END IF;\n IF NEW.name IS NULL THEN\n RAISE EXCEPTION 'plg_crm_companies: a company needs a name or a legal_name';\n END IF;\n\n NEW.updated_at := now();\n RETURN NEW;\nEND $$;\n\n-- One primary employer per person, and the FIRST link is it. Without the\n-- second half an importer creating links in bulk leaves every person with no\n-- primary, and `v_crm_leads` \u2014 which reads the primary \u2014 shows no company at\n-- all for a lead that plainly has one.\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_company_people_primary() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n IF TG_OP = 'INSERT' AND NOT NEW.is_primary THEN\n IF NOT EXISTS (SELECT 1 FROM public.plg_crm_company_people\n WHERE person_id = NEW.person_id AND is_primary) THEN\n NEW.is_primary := true;\n END IF;\n END IF;\n\n -- Only when the flag is actually MOVING. Re-saving a row that is already\n -- primary used to rewrite every sibling for nothing, and on a bulk edit that\n -- is the difference between one write and one write per link.\n -- KNOWN LIMIT, measured rather than assumed: PROMOTE ONE AT A TIME.\n --\n -- A single statement that promotes more than one of a person's links \u2014\n -- `UPDATE \u2026 SET is_primary = true WHERE person_id = X` \u2014 makes this trigger\n -- write a sibling row that the same command is also about to update, and\n -- Postgres aborts the transaction with \"tuple to be updated was already\n -- modified by an operation triggered by the current command\". It is\n -- order-dependent: the same two rows succeed or abort depending on which\n -- tuple version the scan reaches first.\n --\n -- It is NOT catchable here \u2014 the error is raised by the outer statement when\n -- it reaches the row this trigger rewrote, not by the UPDATE below. An\n -- EXCEPTION block around it does nothing; that was tried.\n --\n -- The statement it refuses is incoherent anyway: \"which of these two is the\n -- main one?\" has no answer. The provider always updates one link by `id`, so\n -- no shipped path reaches it. `test/pgtap/003` pins the behaviour so it is\n -- known rather than discovered.\n IF NEW.is_primary AND (TG_OP = 'INSERT' OR OLD.is_primary IS DISTINCT FROM NEW.is_primary) THEN\n -- Only when the flag is actually MOVING. Re-saving a row that is already\n -- primary used to rewrite every sibling for nothing.\n UPDATE public.plg_crm_company_people\n SET is_primary = false, updated_at = now()\n WHERE person_id = NEW.person_id\n AND id IS DISTINCT FROM NEW.id\n AND is_primary;\n END IF;\n\n NEW.updated_at := now();\n RETURN NEW;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_person_phones_key() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n NEW.phone_key := public.crm_phone_key(NEW.phone);\n\n IF TG_OP = 'INSERT' AND NOT NEW.is_primary THEN\n IF NOT EXISTS (SELECT 1 FROM public.plg_crm_person_phones\n WHERE person_id = NEW.person_id AND is_primary) THEN\n NEW.is_primary := true;\n END IF;\n END IF;\n\n -- Same rule, same known limit as `plg_crm_company_people`: only when the flag\n -- is actually moving, and a statement that promotes two of one person's lines\n -- at once is refused by Postgres rather than silently resolved. See the\n -- comment on the link trigger above.\n IF NEW.is_primary AND (TG_OP = 'INSERT' OR OLD.is_primary IS DISTINCT FROM NEW.is_primary) THEN\n UPDATE public.plg_crm_person_phones\n SET is_primary = false, updated_at = now()\n WHERE person_id = NEW.person_id\n AND id IS DISTINCT FROM NEW.id\n AND is_primary;\n END IF;\n\n NEW.updated_at := now();\n RETURN NEW;\nEND $$;\n\n-- INSERT ONLY. This is the whole argument of the header: the house a deal\n-- belongs to is a fact AT DEAL TIME, and a rule that also fired on UPDATE would\n-- quietly re-attribute every open deal the next time a s\u00F3cio changed employer.\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_deals_stamp_company() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n IF NEW.company_id IS NOT NULL THEN RETURN NEW; END IF;\n\n SELECT cp.company_id INTO NEW.company_id\n FROM public.plg_crm_company_people cp\n WHERE cp.person_id = coalesce(NEW.lead_id, NEW.contact_id)\n AND cp.tenant_id = NEW.tenant_id\n ORDER BY cp.is_primary DESC, cp.created_at\n LIMIT 1;\n\n RETURN NEW;\nEND $$;\n\n-- The other half of the stamp, and the one that makes the feature work at all.\n--\n-- `crm_lead_to_board` creates the deal from a trigger on `people` INSERT \u2014 it\n-- is how a capture form, an import and an agent RPC all put a lead on the board.\n-- So on the normal path the deal exists BEFORE anyone could have linked the\n-- person to a company, and `company_id` would be NULL forever.\n--\n-- Filling it when the link arrives is capture, not rewrite: there was no fact\n-- there to lose. Two bounds keep it honest \u2014\n--\n-- * ONLY WHERE company_id IS NULL. An existing stamp is never touched, which\n-- is the invariant the whole design rests on.\n-- * ONLY OPEN DEALS. A won or lost deal with no company is genuinely unknown,\n-- and attributing last year's sale to a company somebody linked today is a\n-- guess wearing the costume of a repair. It stays NULL.\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_company_people_backfill() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n -- IT MUST RESOLVE THE SAME WAY THE STAMP DOES, or the two disagree and the\n -- answer depends on which link was typed first. The first cut matched on\n -- `lead_id = person OR contact_id = person` and took whatever arrived \u2014 so a\n -- deal whose lead and contact are different people got the CONTACT's company\n -- when the stamp's own rule says the LEAD wins, and a non-primary link could\n -- win over a primary one simply by being inserted later.\n UPDATE public.plg_crm_deals d\n SET company_id = resolved.company_id\n FROM (\n SELECT dd.id,\n (SELECT cp.company_id\n FROM public.plg_crm_company_people cp\n WHERE cp.tenant_id = dd.tenant_id\n AND cp.person_id = coalesce(dd.lead_id, dd.contact_id)\n ORDER BY cp.is_primary DESC, cp.created_at\n LIMIT 1) AS company_id\n FROM public.plg_crm_deals dd\n WHERE dd.tenant_id = NEW.tenant_id\n AND dd.company_id IS NULL\n AND dd.status = 'open'\n AND coalesce(dd.lead_id, dd.contact_id) = NEW.person_id\n ) resolved\n WHERE d.id = resolved.id\n AND resolved.company_id IS NOT NULL\n -- THE PERMISSION CHECK IS NOT REDUNDANT. This function is SECURITY DEFINER\n -- so the stamp works whoever creates the lead, and the owning role has\n -- BYPASSRLS \u2014 which means without it `sales.edit` alone would let somebody\n -- write `company_id` onto deals they cannot read, in units they have no\n -- access to. `app.has_permission` reads the CALLER's claims, not the\n -- definer's, so it still answers for the person who inserted the link.\n --\n -- `auth.uid() IS NULL` is the backend, not a loophole: the insert policies\n -- on this table are `TO authenticated`, so a web caller always carries a\n -- JWT. No uid means a seed, an importer on service_role, or the migration\n -- itself \u2014 and gating those on a permission nobody holds is how the\n -- backfill silently stopped working the first time this check was added.\n AND (auth.uid() IS NULL\n OR ((SELECT app.has_permission('crm.pipeline.edit', d.unit_id))\n AND (d.unit_id IS NULL OR (SELECT app.has_unit(d.unit_id)))));\n RETURN NULL;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.trg_plg_crm_company_people_backfill() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_company_people_backfill() TO authenticated, service_role;\n\nREVOKE ALL ON FUNCTION public.trg_plg_crm_companies_identity() FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.trg_plg_crm_company_people_primary() FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.trg_plg_crm_person_phones_key() FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.trg_plg_crm_deals_stamp_company() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_companies_identity() TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_company_people_primary() TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_person_phones_key() TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_deals_stamp_company() TO authenticated, service_role;\n\n-- \u2500\u2500 trigger \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nDROP TRIGGER IF EXISTS plg_crm_companies_identity ON public.plg_crm_companies;\nCREATE TRIGGER plg_crm_companies_identity\n BEFORE INSERT OR UPDATE ON public.plg_crm_companies\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_companies_identity();\n\nDROP TRIGGER IF EXISTS plg_crm_company_people_primary ON public.plg_crm_company_people;\nCREATE TRIGGER plg_crm_company_people_primary\n BEFORE INSERT OR UPDATE ON public.plg_crm_company_people\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_company_people_primary();\n\nDROP TRIGGER IF EXISTS plg_crm_company_people_backfill ON public.plg_crm_company_people;\nCREATE TRIGGER plg_crm_company_people_backfill\n AFTER INSERT ON public.plg_crm_company_people\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_company_people_backfill();\n\nDROP TRIGGER IF EXISTS plg_crm_person_phones_key ON public.plg_crm_person_phones;\nCREATE TRIGGER plg_crm_person_phones_key\n BEFORE INSERT OR UPDATE ON public.plg_crm_person_phones\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_person_phones_key();\n\nDROP TRIGGER IF EXISTS plg_crm_deals_stamp_company ON public.plg_crm_deals;\nCREATE TRIGGER plg_crm_deals_stamp_company\n BEFORE INSERT ON public.plg_crm_deals\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_deals_stamp_company();\n\n-- \u2500\u2500 function: the seat does not stay empty \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\n-- Removing the primary used to leave a person with two employers and NO main\n-- one \u2014 the INSERT rule only ever promoted the first link, so nothing filled\n-- the seat again. `v_crm_leads` still resolved (its ORDER BY falls through to\n-- the oldest), but \"exactly one primary per person\" stopped being true, and the\n-- badge on the company file simply vanished.\n--\n-- ON DELETE ONLY, and that bound was learned the hard way. Firing on an\n-- `UPDATE OF is_primary` too meant this trigger ran INSIDE the promotion\n-- trigger's own demotion: at that instant the old primary had just been\n-- cleared and the new one was not yet written, so it saw an empty seat and\n-- re-promoted the row being demoted \u2014 breaking the single promote, which is the\n-- path the UI actually uses. Clearing the flag by hand without deleting the row\n-- therefore still leaves nobody primary; the provider has no such path (it\n-- unlinks by deleting) and inventing re-entrancy guards to cover it would cost\n-- more than the gap.\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_primary_vacated() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nDECLARE v_person uuid := coalesce(OLD.person_id, NEW.person_id);\nBEGIN\n IF EXISTS (SELECT 1 FROM public.plg_crm_company_people\n WHERE person_id = v_person AND is_primary) THEN\n RETURN NULL;\n END IF;\n -- The oldest surviving link, which is the same tie-break every other\n -- resolution in this file uses.\n UPDATE public.plg_crm_company_people\n SET is_primary = true, updated_at = now()\n WHERE id = (SELECT id FROM public.plg_crm_company_people\n WHERE person_id = v_person ORDER BY created_at, id LIMIT 1);\n RETURN NULL;\nEND $$;\n\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_phone_primary_vacated() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nDECLARE v_person uuid := coalesce(OLD.person_id, NEW.person_id);\nBEGIN\n IF EXISTS (SELECT 1 FROM public.plg_crm_person_phones\n WHERE person_id = v_person AND is_primary) THEN\n RETURN NULL;\n END IF;\n UPDATE public.plg_crm_person_phones\n SET is_primary = true, updated_at = now()\n WHERE id = (SELECT id FROM public.plg_crm_person_phones\n WHERE person_id = v_person ORDER BY created_at, id LIMIT 1);\n RETURN NULL;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.trg_plg_crm_primary_vacated() FROM PUBLIC;\nREVOKE ALL ON FUNCTION public.trg_plg_crm_phone_primary_vacated() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_primary_vacated() TO authenticated, service_role;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_phone_primary_vacated() TO authenticated, service_role;\n\nDROP TRIGGER IF EXISTS plg_crm_company_people_vacated ON public.plg_crm_company_people;\nCREATE TRIGGER plg_crm_company_people_vacated\n AFTER DELETE ON public.plg_crm_company_people\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_primary_vacated();\n\nDROP TRIGGER IF EXISTS plg_crm_person_phones_vacated ON public.plg_crm_person_phones;\nCREATE TRIGGER plg_crm_person_phones_vacated\n AFTER DELETE ON public.plg_crm_person_phones\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_phone_primary_vacated();\n\n-- \u2500\u2500 view \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- `security_invoker` on every one of them. A view without it runs as its owner\n-- and hands one tenant another tenant's rows \u2014 the exact leak this wave already\n-- had to close on `v_crm_lead_offers`.\n\n-- `v_deals` is where every deal read in this plugin goes \u2014 the board, the list,\n-- the company file. Adding the column to `plg_crm_deals` and stopping there\n-- left `Deal.companyId` undefined everywhere, so the company file's deal card\n-- filtered on a field that never arrives and rendered \"no deals\" beside its own\n-- `open_deals: 3`. The mock set it, so nothing caught it.\n--\n-- Replayed in full rather than ALTERed: `CREATE OR REPLACE VIEW` can only\n-- append columns, and this one is owned by this plugin's baseline.\nDROP VIEW IF EXISTS public.plg_crm_rep_deals;\nCREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS\n SELECT d.id,\n d.tenant_id,\n d.status,\n d.value,\n COALESCE(d.title, d.notes) AS title,\n d.contact_id,\n d.assigned_to_id,\n d.tags,\n (d.metadata ->> 'contactName'::text) AS contact_name,\n d.created_at,\n d.updated_at,\n d.pipeline_id,\n d.stage_id,\n d.probability,\n d.expected_close_date,\n d.lead_id,\n d.lost_reason,\n ps.name AS stage_name,\n ps.color AS stage_color,\n ps.\"order\" AS stage_order,\n ps.name AS stage,\n d.won_at,\n d.lost_at,\n d.company_id\n FROM (public.plg_crm_deals d\n LEFT JOIN public.plg_crm_pipeline_stages ps ON ((ps.id = d.stage_id)));\n\nCREATE OR REPLACE VIEW public.plg_crm_rep_deals WITH (security_invoker = true) AS\n SELECT id AS deal_id, tenant_id, created_at, title, contact_name, status,\n pipeline_id,\n COALESCE(NULLIF(stage_name, ''::text), 'Sem etapa'::text) AS stage_name,\n assigned_to_id, expected_close_date, lost_reason,\n COALESCE(value, (0)::numeric) AS value,\n 1 AS deals,\n CASE WHEN (status = 'won'::text) THEN COALESCE(value, (0)::numeric) ELSE (0)::numeric END AS won_value,\n CASE WHEN (status = 'open'::text) THEN COALESCE(value, (0)::numeric) ELSE (0)::numeric END AS open_value,\n CASE WHEN (status = 'won'::text) THEN 1 ELSE 0 END AS is_won,\n CASE WHEN (status = 'lost'::text) THEN 1 ELSE 0 END AS is_lost,\n CASE WHEN (status = 'open'::text) THEN 1 ELSE 0 END AS is_open\n FROM public.v_deals d\n WHERE (status <> 'archived'::text);\n\nGRANT SELECT ON public.v_deals TO authenticated, service_role;\nGRANT SELECT ON public.plg_crm_rep_deals TO authenticated, service_role;\n\nCREATE OR REPLACE VIEW public.v_crm_companies WITH (security_invoker = true) AS\n SELECT c.id,\n c.tenant_id,\n c.name,\n c.legal_name,\n c.document_number,\n c.document_kind,\n c.document_root,\n c.document_valid,\n c.email,\n c.phone,\n c.website,\n c.address,\n c.city,\n c.state,\n c.country,\n c.postal_code,\n c.tags,\n c.notes,\n c.metadata,\n c.custom_fields,\n c.owner_id,\n c.is_active,\n c.created_at,\n c.updated_at,\n coalesce(p.people_count, 0) AS people_count,\n coalesce(d.open_deals, 0) AS open_deals,\n coalesce(d.won_value, 0) AS won_value,\n -- How many OTHER companies share this CNPJ root. The matriz/filial\n -- signal the rollup index exists for, surfaced rather than computed\n -- again on every screen.\n CASE WHEN c.document_root IS NULL THEN 0\n ELSE coalesce(g.group_size, 1) - 1 END AS group_siblings\n FROM public.plg_crm_companies c\n LEFT JOIN LATERAL (\n -- Counted through `people` on purpose, the same inner join\n -- `v_crm_company_people` uses. `plg_crm_company_people` is gated on\n -- `sales.read` and `people` on `people.read`, so a role holding the first\n -- and not the second used to see \"1 contact\" as a badge beside an empty\n -- contact list, with nothing saying why. Fail closed, and agree.\n SELECT count(*)::int AS people_count\n FROM public.plg_crm_company_people cp\n JOIN public.people pe ON pe.id = cp.person_id\n WHERE cp.company_id = c.id\n ) p ON true\n LEFT JOIN LATERAL (\n SELECT count(*) FILTER (WHERE dl.status = 'open')::int AS open_deals,\n coalesce(sum(dl.value) FILTER (WHERE dl.status = 'won'), 0) AS won_value\n FROM public.plg_crm_deals dl\n WHERE dl.company_id = c.id\n ) d ON true\n LEFT JOIN LATERAL (\n SELECT count(*)::int AS group_size\n FROM public.plg_crm_companies s\n WHERE s.tenant_id = c.tenant_id\n AND s.document_root = c.document_root\n ) g ON true;\n\nCREATE OR REPLACE VIEW public.v_crm_company_people WITH (security_invoker = true) AS\n SELECT cp.id,\n cp.tenant_id,\n cp.company_id,\n cp.person_id,\n cp.role,\n cp.is_primary,\n cp.created_at,\n cp.updated_at,\n c.name AS company_name,\n c.document_number AS company_document,\n pe.name AS person_name,\n pe.email AS person_email,\n pe.phone AS person_phone,\n pe.kind AS person_kind\n FROM public.plg_crm_company_people cp\n JOIN public.plg_crm_companies c ON c.id = cp.company_id\n JOIN public.people pe ON pe.id = cp.person_id;\n\n-- The lead read model the CRM screens use from here on. It WRAPS the spine's\n-- `v_leads` rather than replacing it: `v_leads` is owned by @fayz-ai/db and is\n-- regenerated from its baseline, so a plugin that redefined it would have its\n-- columns silently dropped on the next emit. The legacy free-text\n-- `company` column is carried through untouched \u2014 it is the only thing 297\n-- imported leads have until they are linked, and dropping it would blank a\n-- screen.\n--\n-- `SELECT l.*` DELIBERATELY, and the failure mode was checked rather than\n-- assumed. Naming the spine's columns one by one would make a column added\n-- upstream silently absent here; the star makes it arrive. The cost is that if\n-- the spine ever publishes its own `company_id`, this CREATE OR REPLACE fails\n-- with `cannot change name of view column` \u2014 at migration time, on a red chain,\n-- with the name of the collision in the message. Loud beats absent.\nCREATE OR REPLACE VIEW public.v_crm_leads WITH (security_invoker = true) AS\n SELECT l.*,\n cp.company_id,\n cp.role AS company_role,\n c.name AS company_name,\n c.legal_name AS company_legal_name,\n c.document_number AS company_document\n FROM public.v_leads l\n LEFT JOIN LATERAL (\n SELECT x.company_id, x.role\n FROM public.plg_crm_company_people x\n WHERE x.person_id = l.id\n ORDER BY x.is_primary DESC, x.created_at\n LIMIT 1\n ) cp ON true\n LEFT JOIN public.plg_crm_companies c ON c.id = cp.company_id;\n\n-- \u2500\u2500 row security \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- ENABLE **and** FORCE. `packages/db/test/pgtap/900_verification/001_posture.sql`\n-- (N14b) fails the pool for an `enforce`-registered table that is not forced,\n-- and without FORCE the migration-owning role \u2014 which every SECURITY DEFINER\n-- function above runs as \u2014 bypasses these policies entirely.\nALTER TABLE public.plg_crm_companies ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_companies FORCE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_company_people ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_company_people FORCE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_person_phones ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_person_phones FORCE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS plg_crm_companies_authz_select ON public.plg_crm_companies;\nCREATE POLICY plg_crm_companies_authz_select ON public.plg_crm_companies\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_companies_authz_insert ON public.plg_crm_companies;\nCREATE POLICY plg_crm_companies_authz_insert ON public.plg_crm_companies\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_companies_authz_update ON public.plg_crm_companies;\nCREATE POLICY plg_crm_companies_authz_update ON public.plg_crm_companies\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_companies_authz_delete ON public.plg_crm_companies;\nCREATE POLICY plg_crm_companies_authz_delete ON public.plg_crm_companies\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_people_authz_select ON public.plg_crm_company_people;\nCREATE POLICY plg_crm_company_people_authz_select ON public.plg_crm_company_people\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_people_authz_insert ON public.plg_crm_company_people;\nCREATE POLICY plg_crm_company_people_authz_insert ON public.plg_crm_company_people\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_people_authz_update ON public.plg_crm_company_people;\nCREATE POLICY plg_crm_company_people_authz_update ON public.plg_crm_company_people\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_people_authz_delete ON public.plg_crm_company_people;\nCREATE POLICY plg_crm_company_people_authz_delete ON public.plg_crm_company_people\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_person_phones_authz_select ON public.plg_crm_person_phones;\nCREATE POLICY plg_crm_person_phones_authz_select ON public.plg_crm_person_phones\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_person_phones_authz_insert ON public.plg_crm_person_phones;\nCREATE POLICY plg_crm_person_phones_authz_insert ON public.plg_crm_person_phones\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_person_phones_authz_update ON public.plg_crm_person_phones;\nCREATE POLICY plg_crm_person_phones_authz_update ON public.plg_crm_person_phones\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_person_phones_authz_delete ON public.plg_crm_person_phones;\nCREATE POLICY plg_crm_person_phones_authz_delete ON public.plg_crm_person_phones\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\n-- \u2500\u2500 grant \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_companies TO authenticated;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_company_people TO authenticated;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_person_phones TO authenticated;\nGRANT ALL ON public.plg_crm_companies TO service_role;\nGRANT ALL ON public.plg_crm_company_people TO service_role;\nGRANT ALL ON public.plg_crm_person_phones TO service_role;\nGRANT SELECT ON public.v_crm_companies TO authenticated, service_role;\nGRANT SELECT ON public.v_crm_company_people TO authenticated, service_role;\nGRANT SELECT ON public.v_crm_leads TO authenticated, service_role;\n\nINSERT INTO app.scaffold_registry\n (table_schema, table_name, resource_type, plugin, owner_scoping, mode,\n previous_policies, audit_hook, scope, distributable)\nVALUES\n ('public', 'plg_crm_companies', 'crm.company', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),\n ('public', 'plg_crm_company_people', 'crm.company_person', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),\n ('public', 'plg_crm_person_phones', 'crm.person_phone', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)\nON CONFLICT DO NOTHING;\n\n-- \u2500\u2500 comment \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCOMMENT ON COLUMN public.plg_crm_deals.company_id IS\n 'The house this deal belongs to, stamped at INSERT and never re-derived. Deriving it through the contact re-attributes closed deals whenever a s\u00F3cio changes employer \u2014 see 013.';\nCOMMENT ON COLUMN public.plg_crm_companies.document_number IS\n 'CNPJ or CPF, normalised (no mask, uppercase) by trigger before the unique index sees it. Text, never numeric: leading zeros are real, and from 2026 the CNPJ carries letters.';\nCOMMENT ON COLUMN public.plg_crm_companies.document_valid IS\n 'Advisory. A real company with a typo''d CNPJ still belongs in the CRM; this is a badge, not a gate.';\n";
14
+ export declare const MIGRATION_014_THE_SECOND_FORM_IS_THE_SAME_PERSON = "-- 014_the_second_form_is_the_same_person.sql \u2014 o formul\u00E1rio p\u00FAblico para de\n-- criar uma pessoa nova a cada envio.\n--\n-- O QUE ACONTECIA. `create_public_lead` tinha uma \u00FAnica defesa: mesmo tenant,\n-- mesmo contato, mesmo formul\u00E1rio, DENTRO DE CINCO MINUTOS. Fora dessa janela\n-- ele inserta em `people` sem olhar se aquele e-mail j\u00E1 existe.\n--\n-- Um lead real preencheu o mesmo formul\u00E1rio em dois dias seguidos e virou dois\n-- cadastros com o mesmo e-mail. Como `people_lead_to_board` dispara em todo\n-- INSERT de lead, virou tamb\u00E9m DOIS NEG\u00D3CIOS no funil \u2014 e uma proposta ligada\n-- ao cadastro de ontem fica invis\u00EDvel no de hoje.\n--\n-- POR QUE A MAQUINARIA EXISTENTE N\u00C3O PEGOU. O n\u00FAcleo tem identidade de pessoa\n-- de verdade: `people_tenant_document_uidx`, `people_merge()`,\n-- `person_identity_quarantine`, `merged_into_id`. S\u00F3 que o \u00EDndice \u00FAnico \u00E9\n-- PARCIAL \u2014 `WHERE document_number IS NOT NULL` \u2014 e o formul\u00E1rio p\u00FAblico nunca\n-- coletou documento. A \u00FAnica chave de identidade do sistema nunca era\n-- preenchida no caminho por onde os leads de fato entram.\n--\n-- N\u00E3o havia \u00EDndice nem gatilho por e-mail ou telefone em `people`. O \u00FAnico\n-- \u00EDndice de telefone que existe \u00E9 `WHERE kind = 'customer'`, que n\u00E3o alcan\u00E7a\n-- lead nenhum.\n--\n-- \u2500\u2500 a pergunta de fundo \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\u2500\n--\n-- Um segundo formul\u00E1rio \u00E9 uma segunda PESSOA ou uma segunda INTEN\u00C7\u00C3O da mesma\n-- pessoa? Sempre a segunda. Pessoa \u00E9 uma linha; interesse \u00E9 um neg\u00F3cio.\n--\n-- Ent\u00E3o o envio repetido passa a ATUALIZAR quem j\u00E1 existe: preenche o que\n-- estava vazio, guarda as respostas novas sem sobrescrever as antigas, e\n-- registra uma atividade para o operador ver que a pessoa voltou. O funil n\u00E3o\n-- ganha card novo, porque `crm_lead_to_board` s\u00F3 dispara em INSERT.\n--\n-- \u2500\u2500 tr\u00EAs detalhes que decidem se funciona \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--\n-- 1. TELEFONE COMPARADO NORMALIZADO. `(11) 99999-0000` e `+5511999990000` s\u00E3o\n-- a mesma linha e eram duas pessoas. `crm_phone_key` (013) resolve, e \u00E9\n-- IMMUTABLE, ent\u00E3o serve de \u00EDndice.\n--\n-- 2. E-MAIL COMPARADO EM MIN\u00DASCULA. O RPC s\u00F3 fazia `trim`, ent\u00E3o\n-- `Ewertonpc_@hotmail.com` j\u00E1 seria um terceiro cadastro do mesmo homem.\n--\n-- 3. CPF IDENTIFICA PESSOA; CNPJ IDENTIFICA EMPRESA. Esta distin\u00E7\u00E3o n\u00E3o \u00E9\n-- preciosismo \u2014 a primeira vers\u00E3o deste arquivo usou os dois como\n-- identidade de pessoa, e no teste dois S\u00D3CIOS da mesma casa viraram um\n-- cadastro s\u00F3. Na lista real que motivou tudo isto, 45% dos leads dividem\n-- CNPJ com outra pessoa; deduplicar por CNPJ apagaria quase metade deles.\n--\n-- Ent\u00E3o: CPF entra na ordem de identidade (documento \u2192 e-mail \u2192 telefone).\n-- CNPJ n\u00E3o entra em identidade nenhuma \u2014 ele acha ou cria a EMPRESA\n-- (013) e pendura a pessoa nela.\n--\n-- \u2500\u2500 o que este arquivo N\u00C3O faz \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--\n-- N\u00E3o funde os duplicados que j\u00E1 existem. Isso \u00E9 `people_merge()`, que \u00E9 manual\n-- e tem trilha em `person_merges` \u2014 fundir pessoa \u00E9 decis\u00E3o de gente. O que\n-- entra aqui \u00E9 `v_crm_lead_duplicates`, que PROP\u00D5E os pares para algu\u00E9m\n-- aprovar.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- As duas buscas que o RPC passa a fazer em todo envio. Sem elas, cada\n-- submiss\u00E3o vira uma varredura de `people` inteira.\n--\n-- Parciais por `merged_into_id IS NULL`: uma l\u00E1pide de fus\u00E3o n\u00E3o deve ser\n-- encontrada como se fosse a pessoa viva \u2014 \u00E9 para isso que a coluna existe.\n--\n-- N\u00C3O s\u00E3o \u00FAnicos, de prop\u00F3sito. Dois leads leg\u00EDtimos podem dividir o e-mail da\n-- casa (`contato@restaurante.com.br`), e recusar o segundo no INSERT perderia\n-- o lead. A unicidade que vale \u00E9 a do documento, que o n\u00FAcleo j\u00E1 garante.\nCREATE INDEX IF NOT EXISTS people_tenant_lead_email_idx\n ON public.people (tenant_id, lower(email))\n WHERE email IS NOT NULL AND merged_into_id IS NULL;\n\n-- Sobre `crm_phone_key`, e n\u00E3o sobre `phone` cru: o \u00EDndice s\u00F3 serve se guardar\n-- a mesma forma que a busca procura. A fun\u00E7\u00E3o \u00E9 do plugin-crm e IMMUTABLE;\n-- apag\u00E1-la derruba este \u00EDndice junto, que \u00E9 o acoplamento aceito aqui.\nCREATE INDEX IF NOT EXISTS people_tenant_lead_phonekey_idx\n ON public.people (tenant_id, public.crm_phone_key(phone))\n WHERE phone IS NOT NULL AND merged_into_id IS NULL;\n\n-- \u2500\u2500 function: quem j\u00E1 \u00E9 esta pessoa \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\n-- Devolve o id de quem j\u00E1 est\u00E1 cadastrado com este documento, e-mail ou\n-- telefone \u2014 nesta ordem de for\u00E7a \u2014 ou NULL.\n--\n-- Procura em QUALQUER `kind`, n\u00E3o s\u00F3 em lead. Se o e-mail \u00E9 de algu\u00E9m que j\u00E1\n-- virou cliente, criar um lead novo duplicaria o mesmo ser humano; o certo \u00E9\n-- pendurar a inten\u00E7\u00E3o nova nele. Quem chama \u00E9 que decide n\u00E3o rebaixar o\n-- cliente de volta a lead.\nCREATE OR REPLACE FUNCTION public.crm_find_person_by_contact(\n p_tenant_id uuid,\n p_document text DEFAULT NULL,\n p_email text DEFAULT NULL,\n p_phone text DEFAULT NULL\n) RETURNS uuid\n LANGUAGE plpgsql STABLE SECURITY DEFINER\n SET search_path TO ''\n AS $$\nDECLARE\n v_doc text := public.people_normalize_document(p_document);\n v_email text := nullif(lower(btrim(coalesce(p_email, ''))), '');\n v_key text := public.crm_phone_key(p_phone);\n v_id uuid;\nBEGIN\n IF v_doc IS NOT NULL THEN\n SELECT id INTO v_id FROM public.people\n WHERE tenant_id = p_tenant_id AND document_number = v_doc\n AND merged_into_id IS NULL\n ORDER BY created_at LIMIT 1;\n IF v_id IS NOT NULL THEN RETURN v_id; END IF;\n END IF;\n\n IF v_email IS NOT NULL THEN\n SELECT id INTO v_id FROM public.people\n WHERE tenant_id = p_tenant_id AND lower(email) = v_email\n AND merged_into_id IS NULL\n ORDER BY created_at LIMIT 1;\n IF v_id IS NOT NULL THEN RETURN v_id; END IF;\n END IF;\n\n IF v_key IS NOT NULL THEN\n SELECT id INTO v_id FROM public.people\n WHERE tenant_id = p_tenant_id AND public.crm_phone_key(phone) = v_key\n AND merged_into_id IS NULL\n ORDER BY created_at LIMIT 1;\n IF v_id IS NOT NULL THEN RETURN v_id; END IF;\n END IF;\n\n -- O MAIS ANTIGO ganha em todos os tr\u00EAs. Quem chegou primeiro carrega o\n -- hist\u00F3rico; anexar ao mais novo espalharia a conversa por dois cadastros.\n RETURN NULL;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.crm_find_person_by_contact(uuid, text, text, text) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_find_person_by_contact(uuid, text, text, text)\n TO authenticated, service_role;\n\n-- \u2500\u2500 function: o formul\u00E1rio p\u00FAblico, agora com identidade \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- A ASSINATURA ANTIGA PRECISA MORRER, e explicitamente.\n--\n-- `CREATE OR REPLACE FUNCTION` com uma lista de par\u00E2metros diferente n\u00E3o\n-- substitui: cria uma SOBRECARGA. As duas passam a existir, e uma chamada que\n-- n\u00E3o casa exatamente com nenhuma falha com \"function is not unique\" \u2014 que foi\n-- o que aconteceu na primeira execu\u00E7\u00E3o deste arquivo.\n--\n-- Pior que o erro: enquanto as duas existem, um cliente antigo continua\n-- entrando pela vers\u00E3o sem deduplica\u00E7\u00E3o, e o duplicado volta em sil\u00EAncio.\nDROP FUNCTION IF EXISTS public.create_public_lead(\n uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb);\n-- E a PR\u00D3PRIA assinatura desta migration, que parece redundante e n\u00E3o \u00E9.\n--\n-- Uma migration posterior (016) muda o TIPO DE RETORNO desta fun\u00E7\u00E3o, e\n-- `CREATE OR REPLACE` n\u00E3o pode trocar retorno \u2014 ele falha com \"cannot change\n-- return type of existing function\". No replay, 014 roda de novo sobre o estado\n-- que 016 deixou e quebra a cadeia inteira.\n--\n-- Derrubar por lista de ARGUMENTOS ignora o retorno, ent\u00E3o este DROP funciona\n-- nas duas formas. O replay ent\u00E3o recria esta vers\u00E3o e 016 volta a corrigi-la\n-- logo depois, que \u00E9 a ordem da cadeia.\nDROP FUNCTION IF EXISTS public.create_public_lead(\n uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb, text);\n\nCREATE OR REPLACE FUNCTION public.create_public_lead(\n p_tenant_id uuid, p_name text,\n p_phone text DEFAULT NULL::text, p_email text DEFAULT NULL::text,\n p_form_id text DEFAULT NULL::text, p_form_name text DEFAULT NULL::text,\n p_fields jsonb DEFAULT '{}'::jsonb, p_notes text DEFAULT NULL::text,\n p_utm jsonb DEFAULT '{}'::jsonb, p_tags text[] DEFAULT '{}'::text[],\n p_attachments jsonb DEFAULT '[]'::jsonb,\n p_document text DEFAULT NULL::text\n) RETURNS TABLE(lead_id uuid, created_at timestamp with time zone, is_new boolean)\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO 'public'\n AS $_$\nDECLARE\n v_person_id uuid;\n v_existing uuid;\n v_phone text; v_email text; v_doc text; v_cpf text; v_cnpj text;\n v_company_id uuid;\n v_fields jsonb; v_utm jsonb; v_tags text[]; v_attachments jsonb;\n v_meta jsonb;\nBEGIN\n -- \u2500\u2500 valida\u00E7\u00E3o: \u00E9 cham\u00E1vel por anon, ent\u00E3o tudo \u00E9 conferido aqui \u2500\u2500\u2500\u2500\u2500\u2500\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(lower(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 -- Documento \u00E9 OPCIONAL e nunca recusado por d\u00EDgito verificador: uma empresa\n -- real com CNPJ digitado errado n\u00E3o pode perder o formul\u00E1rio inteiro. O\n -- selo de validade \u00E9 problema da tela (`document_valid` em 013).\n --\n -- E \u00E9 separado por TIPO, porque os dois significam coisas diferentes: 11\n -- caracteres \u00E9 CPF e diz quem a pessoa \u00E9; 14 \u00E9 CNPJ e diz onde ela trabalha.\n v_doc := public.people_normalize_document(p_document);\n v_cpf := CASE WHEN length(v_doc) = 11 THEN v_doc END;\n v_cnpj := CASE WHEN length(v_doc) = 14 THEN v_doc END;\n\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 v_fields := COALESCE(p_fields, '{}'::jsonb);\n IF jsonb_typeof(v_fields) <> 'object' THEN RAISE EXCEPTION 'fields must be an object'; END IF;\n IF length(v_fields::text) > 8000 THEN RAISE EXCEPTION 'fields too large'; END IF;\n IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN RAISE EXCEPTION 'too many fields'; END IF;\n\n v_utm := COALESCE(p_utm, '{}'::jsonb);\n IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN RAISE EXCEPTION 'invalid utm'; END IF;\n\n v_attachments := COALESCE(p_attachments, '[]'::jsonb);\n IF jsonb_typeof(v_attachments) <> 'array' THEN RAISE EXCEPTION 'attachments must be an array'; END IF;\n IF jsonb_array_length(v_attachments) > 10 THEN RAISE EXCEPTION 'too many attachments'; END IF;\n SELECT jsonb_agg(a) INTO v_attachments FROM (\n SELECT jsonb_strip_nulls(jsonb_build_object(\n 'bucket', 'crm-lead-uploads',\n 'path', e->>'path',\n 'slot', left(NULLIF(trim(COALESCE(e->>'slot', '')), ''), 48),\n 'mime', left(NULLIF(trim(COALESCE(e->>'mime', '')), ''), 128),\n 'size', CASE WHEN (e->>'size') ~ '^[0-9]{1,12}$' THEN (e->>'size')::bigint END\n )) AS a\n FROM jsonb_array_elements(v_attachments) e\n WHERE jsonb_typeof(e) = 'object'\n AND e->>'path' IS NOT NULL\n AND length(e->>'path') BETWEEN 16 AND 300\n AND e->>'path' LIKE p_tenant_id::text || '/%'\n ) valid;\n v_attachments := COALESCE(v_attachments, '[]'::jsonb);\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 AND length(public.crm_tag_slug(t)) <= 48\n LIMIT 10\n ) normalized;\n v_tags := COALESCE(v_tags, '{}'::text[]);\n\n -- Teto de rajada por tenant. Continua: uma enxurrada nunca \u00E9 tr\u00E1fego leg\u00EDtimo.\n -- A janela de 5 minutos que existia aqui SAIU \u2014 quem envia duas vezes agora\n -- recebe o mesmo lead de volta em vez de uma exce\u00E7\u00E3o, que \u00E9 melhor resposta\n -- para um duplo clique do que um erro na cara de quem preencheu.\n IF (\n SELECT count(*) FROM people p\n WHERE p.tenant_id = p_tenant_id 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 -- v_cpf, NUNCA v_cnpj. Ver o item 3 do cabe\u00E7alho.\n v_existing := public.crm_find_person_by_contact(p_tenant_id, v_cpf, v_email, v_phone);\n\n -- A empresa, quando veio CNPJ. Achar-ou-criar: o \u00EDndice \u00FAnico por\n -- (tenant_id, document_number) em `plg_crm_companies` garante que dois\n -- s\u00F3cios preenchendo o mesmo CNPJ cheguem na MESMA casa em vez de criarem\n -- duas. O nome do restaurante que o formul\u00E1rio coletou serve de nome quando\n -- a empresa ainda n\u00E3o existe.\n IF v_cnpj IS NOT NULL THEN\n SELECT id INTO v_company_id FROM plg_crm_companies\n WHERE tenant_id = p_tenant_id AND document_number = v_cnpj;\n IF v_company_id IS NULL THEN\n INSERT INTO plg_crm_companies (tenant_id, name, document_number)\n VALUES (p_tenant_id,\n COALESCE(NULLIF(btrim(COALESCE(v_fields->>'restaurant', '')), ''),\n NULLIF(btrim(COALESCE(v_fields->>'empresa', '')), ''),\n trim(p_name)),\n v_cnpj)\n RETURNING id INTO v_company_id;\n END IF;\n END IF;\n\n -- \u2500\u2500 j\u00E1 conhecemos esta pessoa \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_existing IS NOT NULL THEN\n SELECT metadata INTO v_meta FROM people WHERE id = v_existing;\n v_meta := COALESCE(v_meta, '{}'::jsonb);\n\n -- As respostas novas entram numa LISTA, n\u00E3o por cima das antigas. Quem\n -- preencheu duas vezes normalmente respondeu coisas diferentes, e a\n -- segunda n\u00E3o invalida a primeira \u2014 \u00E9 o hist\u00F3rico do interesse dele.\n v_meta := jsonb_set(v_meta, '{submissions}',\n COALESCE(v_meta->'submissions', '[]'::jsonb) || jsonb_build_array(\n jsonb_strip_nulls(jsonb_build_object(\n 'at', now(),\n 'formId', NULLIF(trim(COALESCE(p_form_id, '')), ''),\n 'formName', NULLIF(trim(COALESCE(p_form_name, '')), ''),\n 'fields', CASE WHEN v_fields = '{}'::jsonb THEN NULL ELSE v_fields END,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END\n ))), true);\n\n -- `fields` continua sendo o que a tela l\u00EA, ent\u00E3o recebe o mais recente por\n -- cima \u2014 mas s\u00F3 as chaves que vieram, preservando as que n\u00E3o vieram.\n v_meta := jsonb_set(v_meta, '{fields}', COALESCE(v_meta->'fields', '{}'::jsonb) || v_fields, true);\n IF v_attachments <> '[]'::jsonb THEN\n v_meta := jsonb_set(v_meta, '{attachments}',\n COALESCE(v_meta->'attachments', '[]'::jsonb) || v_attachments, true);\n END IF;\n\n -- O `status` N\u00C3O volta para 'new'. Se algu\u00E9m j\u00E1 qualificou esta pessoa,\n -- um formul\u00E1rio novo n\u00E3o desfaz esse trabalho.\n UPDATE people SET\n -- S\u00F3 preenche o que estava vazio. O operador pode ter corrigido o nome \u00E0\n -- m\u00E3o, e o formul\u00E1rio n\u00E3o \u00E9 mais confi\u00E1vel que ele.\n name = CASE WHEN nullif(btrim(name), '') IS NULL THEN trim(p_name) ELSE name END,\n phone = COALESCE(phone, v_phone),\n email = COALESCE(email, v_email),\n document_number = COALESCE(document_number, v_cpf),\n notes = CASE WHEN nullif(btrim(coalesce(notes, '')), '') IS NULL\n THEN left(p_notes, 2000) ELSE notes END,\n tags = (SELECT array_agg(DISTINCT t) FROM unnest(tags || v_tags) t),\n is_active = true,\n metadata = v_meta\n WHERE id = v_existing;\n\n -- Que o operador veja que a pessoa voltou. Sem isto a re-submiss\u00E3o \u00E9\n -- silenciosa e o card parece parado desde a primeira vez.\n BEGIN\n PERFORM public.crm_log_public_lead_activity(v_existing, NULL);\n EXCEPTION WHEN OTHERS THEN NULL;\n END;\n\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 IF v_company_id IS NOT NULL THEN\n -- ON CONFLICT: o mesmo par pessoa/empresa chegando de novo \u00E9 a mesma\n -- verdade, n\u00E3o um erro. O gatilho de 013 cuida do `is_primary`.\n INSERT INTO plg_crm_company_people (tenant_id, company_id, person_id)\n VALUES (p_tenant_id, v_company_id, v_existing)\n ON CONFLICT (company_id, person_id) DO NOTHING;\n END IF;\n\n SELECT p.created_at INTO created_at FROM people p WHERE p.id = v_existing;\n lead_id := v_existing;\n is_new := false;\n RETURN NEXT;\n RETURN;\n END IF;\n\n -- \u2500\u2500 pessoa nova \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\u2500\u2500\u2500\u2500\u2500\n INSERT INTO people (tenant_id, kind, name, phone, email, document_number,\n notes, tags, is_active, metadata)\n VALUES (\n p_tenant_id, 'lead', trim(p_name), v_phone, v_email, v_cpf,\n left(p_notes, 2000), v_tags, true,\n jsonb_strip_nulls(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 'attachments', CASE WHEN v_attachments = '[]'::jsonb THEN NULL ELSE v_attachments END\n ))\n )\n RETURNING id, people.created_at INTO v_person_id, created_at;\n\n IF v_company_id IS NOT NULL THEN\n INSERT INTO plg_crm_company_people (tenant_id, company_id, person_id)\n VALUES (p_tenant_id, v_company_id, v_person_id)\n ON CONFLICT (company_id, person_id) DO NOTHING;\n END IF;\n\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 is_new := true;\n RETURN NEXT;\nEND;\n$_$;\n\nGRANT ALL ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb, text)\n TO anon, authenticated, service_role;\n\n-- \u2500\u2500 view: os duplicados que j\u00E1 existem \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\n-- PROP\u00D5E pares, n\u00E3o funde nada. Fundir pessoa \u00E9 `people_merge()`, que \u00E9 manual\n-- e deixa trilha em `person_merges` \u2014 e \u00E9 decis\u00E3o de gente, porque duas linhas\n-- com o mesmo e-mail podem ser m\u00E3e e filho na mesma casa.\n--\n-- Ordenado por for\u00E7a da evid\u00EAncia: documento igual \u00E9 praticamente certeza,\n-- e-mail igual \u00E9 forte, telefone igual \u00E9 sugest\u00E3o.\nCREATE OR REPLACE VIEW public.v_crm_lead_duplicates WITH (security_invoker = true) AS\n WITH candidates AS (\n SELECT p.tenant_id, 'documento'::text AS evidence, 1 AS strength,\n p.document_number AS value, p.id, p.name, p.email, p.phone, p.created_at\n FROM public.people p\n WHERE p.document_number IS NOT NULL AND p.merged_into_id IS NULL\n UNION ALL\n SELECT p.tenant_id, 'email', 2, lower(p.email), p.id, p.name, p.email, p.phone, p.created_at\n FROM public.people p\n WHERE p.email IS NOT NULL AND p.merged_into_id IS NULL\n UNION ALL\n SELECT p.tenant_id, 'telefone', 3, public.crm_phone_key(p.phone),\n p.id, p.name, p.email, p.phone, p.created_at\n FROM public.people p\n WHERE public.crm_phone_key(p.phone) IS NOT NULL AND p.merged_into_id IS NULL\n ), grouped AS (\n SELECT tenant_id, evidence, strength, value,\n count(*) AS n,\n array_agg(id ORDER BY created_at) AS ids,\n array_agg(name ORDER BY created_at) AS names,\n min(created_at) AS first_seen,\n max(created_at) AS last_seen\n FROM candidates\n GROUP BY tenant_id, evidence, strength, value\n HAVING count(*) > 1\n )\n SELECT tenant_id, evidence, value, n AS people_count,\n ids[1] AS keep_id, names[1] AS keep_name,\n ids[2:] AS duplicate_ids, names[2:] AS duplicate_names,\n first_seen, last_seen\n FROM grouped\n ORDER BY strength, n DESC, last_seen DESC;\n\nGRANT SELECT ON public.v_crm_lead_duplicates TO authenticated, service_role;\n\nCOMMENT ON VIEW public.v_crm_lead_duplicates IS\n 'Pares de pessoas que parecem a mesma, por documento, e-mail ou telefone normalizado. PROPOSTA \u2014 funde-se com people_merge(), que \u00E9 manual de prop\u00F3sito.';\nCOMMENT ON FUNCTION public.crm_find_person_by_contact(uuid, text, text, text) IS\n 'Quem j\u00E1 \u00E9 esta pessoa neste tenant: documento, depois e-mail, depois telefone normalizado. O mais antigo ganha.';\n";
15
+ export declare const MIGRATION_015_THE_FAMILY_OWNS_MORE_THAN_ONE_HOUSE = "-- 015_the_family_owns_more_than_one_house.sql \u2014 tr\u00EAs empresas irm\u00E3s, nenhuma\n-- acima da outra.\n--\n-- O 013 deu ao CRM a empresa, e `document_root` agrupa matriz e filial de\n-- gra\u00E7a: mesma raiz de CNPJ, mesmo grupo, sem ningu\u00E9m precisar declarar nada.\n--\n-- Isso n\u00E3o alcan\u00E7a uma FAM\u00CDLIA. Na lista real que motivou tudo isto h\u00E1 tr\u00EAs\n-- restaurantes de uma fam\u00EDlia s\u00F3 \u2014 DIZZY, RESTAURANTE NOSU e RESTAURANTE O\n-- COMPADRE \u2014 com TR\u00CAS ra\u00EDzes de CNPJ diferentes, tr\u00EAs nomes fantasia\n-- diferentes e tr\u00EAs endere\u00E7os diferentes. O que os liga \u00E9 um telefone\n-- compartilhado entre dois deles e um dom\u00EDnio de e-mail que \u00E9 o sobrenome do\n-- terceiro. Nenhum campo do cadastro os junta.\n--\n-- Dos 64 grupos que a varredura acha nessa lista, 57 s\u00E3o uma empresa com v\u00E1rios\n-- funcion\u00E1rios (o 013 j\u00E1 cobre), 2 t\u00EAm mesma raiz de CNPJ (o `document_root` j\u00E1\n-- cobre) e 5 t\u00EAm ra\u00EDzes distintas. \u00C9 para esses 5 que este arquivo existe.\n--\n-- \u2500\u2500 por que n\u00E3o `parent_id`, que \u00E9 o padr\u00E3o da ind\u00FAstria \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- Cinco dos oito CRMs pesquisados t\u00EAm hierarquia de empresa, e TODOS a fazem\n-- com uma self-FK que EXIGE UM PAI: `accounts.parent_id` (SuiteCRM),\n-- `vtiger_account.parentid`, `res_partner.parent_id` (Odoo),\n-- `oro_customer.parent_id`. Funciona para eles porque o pai existe no mundo:\n-- uma holding, uma matriz, uma franqueadora.\n--\n-- Aqui ele n\u00E3o existe. Adotar a self-FK obrigaria a escolher entre duas\n-- mentiras: eleger a DIZZY como subordinada ao O COMPADRE, ou inventar uma\n-- quarta linha \"Grupo Temperani\" SEM CNPJ dentro de `plg_crm_companies` \u2014 que\n-- ficaria fora do \u00EDndice \u00FAnico, fora do `document_root`, com `document_valid`\n-- nulo, e obrigaria toda contagem de empresas a filtr\u00E1-la para sempre.\n--\n-- E o custo da self-FK est\u00E1 documentado no c\u00F3digo alheio:\n--\n-- * O Oro precisou shipar uma migration de conserto cujo corpo inteiro \u00E9\n-- `UPDATE oro_customer SET parent_id = NULL WHERE parent_id = id` \u2014\n-- clientes tinham virado pais de si mesmos em produ\u00E7\u00E3o.\n-- * O Odoo avisa na tela que trocar o pai de um contato \"s\u00F3 deveria ser feito\n-- se nunca tivesse sido definido corretamente\", e para empresas nem avisa:\n-- recusa com \"The company hierarchy cannot be changed.\"\n-- * Definir o pai SOBRESCREVE o endere\u00E7o do filho (\u00E9 o\n-- `_commercial_fields` do Odoo copiando para baixo). Tr\u00EAs restaurantes com\n-- tr\u00EAs endere\u00E7os \u00E9 a pior entrada poss\u00EDvel para isso.\n--\n-- \u2500\u2500 o que se escolheu, e o que ela n\u00E3o faz \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--\n-- Um GRUPO \u00E9 uma linha pr\u00F3pria, e a participa\u00E7\u00E3o \u00E9 um v\u00EDnculo. Tr\u00EAs irm\u00E3s = um\n-- grupo + tr\u00EAs v\u00EDnculos, ningu\u00E9m acima de ningu\u00E9m. O rollup \u00E9 um join com\n-- GROUP BY \u2014 sem recurs\u00E3o, sem caminho materializado, sem closure table \u2014\n-- porque o grafo tem um n\u00EDvel s\u00F3 por constru\u00E7\u00E3o.\n--\n-- V\u00EDnculo \u00E9 tabela de liga\u00E7\u00E3o e n\u00E3o uma FK \u00FAnica na empresa, ao contr\u00E1rio do\n-- `group_id` do Oro e do `customer_group` do ERPNext. Mesma raz\u00E3o que levou o\n-- 013 a fazer `plg_crm_company_people` assim: a DIZZY pode estar em \"Grupo\n-- Temperani\" e em \"Associados Abrasel-SP\" ao mesmo tempo. E a tabela de liga\u00E7\u00E3o\n-- \u00E9 onde cabe `source` \u2014 por que achamos que pertencem juntos \u2014 que uma FK\n-- jogaria fora.\n--\n-- O NEG\u00D3CIO N\u00C3O CARIMBA O GRUPO. A OCA carimba (`company_group_id` como campo\n-- related armazenado em `crm.lead` e `account.move`), e por isso mover uma\n-- empresa de grupo l\u00E1 reescreve o grupo de todo lead hist\u00F3rico. \u00C9 exatamente a\n-- falha que o 013 gasta sessenta linhas recusando para `plg_crm_deals.company_id`.\n-- O neg\u00F3cio chega ao grupo ATRAV\u00C9S da empresa; `company_id` \u00E9 fato do momento\n-- do neg\u00F3cio, participa\u00E7\u00E3o em grupo \u00E9 fato sobre a empresa AGORA, e soldar os\n-- dois destr\u00F3i a primeira.\n--\n-- NADA AQUI CRIA GRUPO SOZINHO. O sinal que temos \u2014 um telefone repetido, um\n-- dom\u00EDnio que \u00E9 sobrenome \u2014 \u00E9 bom para SUGERIR e ruim para decidir: naquela\n-- fam\u00EDlia ele ligaria dois dos tr\u00EAs e perderia o terceiro. `source` na\n-- participa\u00E7\u00E3o registra se veio de gente ou de varredura.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 table \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_company_groups (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n name text NOT NULL,\n -- O que este grupo \u00C9. Um grupo familiar, uma franquia e uma associa\u00E7\u00E3o de\n -- classe se parecem na tabela e n\u00E3o significam a mesma coisa para quem vende.\n kind text DEFAULT 'economic_group' NOT NULL,\n -- Preenchido s\u00F3 quando o grupo \u00C9 um grupo de raiz de CNPJ. Deixa o caso\n -- DERIVADO (matriz/filial, que ningu\u00E9m declara) e o caso DECLARADO (a\n -- fam\u00EDlia) compartilharem um modelo de leitura s\u00F3.\n document_root text,\n notes text,\n metadata jsonb DEFAULT '{}'::jsonb NOT NULL,\n custom_fields jsonb DEFAULT '{}'::jsonb NOT NULL,\n owner_id uuid,\n is_active boolean DEFAULT true NOT NULL,\n created_by uuid,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_company_groups_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_company_groups_tenant_id_id_key UNIQUE (tenant_id, id),\n CONSTRAINT plg_crm_company_groups_kind_check CHECK (kind = ANY (ARRAY[\n 'economic_group'::text, 'franchise'::text, 'holding'::text, 'association'::text]))\n);\n\nCREATE TABLE IF NOT EXISTS public.plg_crm_company_group_members (\n id uuid DEFAULT gen_random_uuid() NOT NULL,\n tenant_id uuid NOT NULL,\n group_id uuid NOT NULL,\n company_id uuid NOT NULL,\n -- O papel DESTA empresa NESTE grupo: 'matriz', 'franqueada', 'opera\u00E7\u00E3o'. Mesmo\n -- argumento do `role` em `plg_crm_company_people` \u2014 \u00E9 fato da rela\u00E7\u00E3o, e uma\n -- empresa em dois grupos tem dois pap\u00E9is.\n role text,\n -- De onde veio a cren\u00E7a de que pertencem juntos. Sem isto, seis meses depois\n -- ningu\u00E9m sabe se um agrupamento foi decidido por gente ou inferido por um\n -- telefone repetido \u2014 e a diferen\u00E7a decide se d\u00E1 para confiar nele.\n source text DEFAULT 'manual' NOT NULL,\n created_at timestamptz DEFAULT now() NOT NULL,\n updated_at timestamptz DEFAULT now() NOT NULL,\n CONSTRAINT plg_crm_company_group_members_pkey PRIMARY KEY (id),\n CONSTRAINT plg_crm_company_group_members_pair_key UNIQUE (group_id, company_id),\n CONSTRAINT plg_crm_company_group_members_source_check CHECK (source = ANY (ARRAY[\n 'manual'::text, 'document_root'::text, 'shared_phone'::text,\n 'email_domain'::text, 'import'::text]))\n);\n\n-- \u2500\u2500 constraint \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE public.plg_crm_company_groups\n DROP CONSTRAINT IF EXISTS plg_crm_company_groups_tenant_fkey;\nALTER TABLE public.plg_crm_company_groups\n ADD CONSTRAINT plg_crm_company_groups_tenant_fkey\n FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;\n\n-- Compostas contra `(tenant_id, id)`, como tudo no 013: um v\u00EDnculo n\u00E3o pode\n-- atravessar tenant nem com a RLS desligada, que \u00E9 o estado em que toda fun\u00E7\u00E3o\n-- SECURITY DEFINER daqui roda.\nALTER TABLE public.plg_crm_company_group_members\n DROP CONSTRAINT IF EXISTS plg_crm_company_group_members_group_fkey;\nALTER TABLE public.plg_crm_company_group_members\n ADD CONSTRAINT plg_crm_company_group_members_group_fkey\n FOREIGN KEY (tenant_id, group_id)\n REFERENCES public.plg_crm_company_groups(tenant_id, id) ON DELETE CASCADE;\n\nALTER TABLE public.plg_crm_company_group_members\n DROP CONSTRAINT IF EXISTS plg_crm_company_group_members_company_fkey;\nALTER TABLE public.plg_crm_company_group_members\n ADD CONSTRAINT plg_crm_company_group_members_company_fkey\n FOREIGN KEY (tenant_id, company_id)\n REFERENCES public.plg_crm_companies(tenant_id, id) ON DELETE CASCADE;\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE INDEX IF NOT EXISTS plg_crm_company_groups_tenant_idx\n ON public.plg_crm_company_groups (tenant_id) WHERE is_active;\nCREATE INDEX IF NOT EXISTS plg_crm_company_groups_name_idx\n ON public.plg_crm_company_groups (tenant_id, lower(name));\n-- Um grupo por raiz de CNPJ, quando declarado. Impede duas linhas dizendo a\n-- mesma coisa sobre o mesmo grupo econ\u00F4mico.\nCREATE UNIQUE INDEX IF NOT EXISTS plg_crm_company_groups_root_uq\n ON public.plg_crm_company_groups (tenant_id, document_root)\n WHERE document_root IS NOT NULL;\n\nCREATE INDEX IF NOT EXISTS plg_crm_company_group_members_group_idx\n ON public.plg_crm_company_group_members (tenant_id, group_id);\nCREATE INDEX IF NOT EXISTS plg_crm_company_group_members_company_idx\n ON public.plg_crm_company_group_members (tenant_id, company_id);\n\n-- \u2500\u2500 trigger \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nCREATE OR REPLACE FUNCTION public.trg_plg_crm_company_groups_touch() RETURNS trigger\n LANGUAGE plpgsql SECURITY DEFINER\n SET search_path TO ''\n AS $$\nBEGIN\n NEW.name := nullif(btrim(NEW.name), '');\n IF NEW.name IS NULL THEN\n RAISE EXCEPTION 'plg_crm_company_groups: a group needs a name';\n END IF;\n NEW.document_root := nullif(btrim(coalesce(NEW.document_root, '')), '');\n NEW.updated_at := now();\n RETURN NEW;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.trg_plg_crm_company_groups_touch() FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.trg_plg_crm_company_groups_touch() TO authenticated, service_role;\n\nDROP TRIGGER IF EXISTS plg_crm_company_groups_touch ON public.plg_crm_company_groups;\nCREATE TRIGGER plg_crm_company_groups_touch\n BEFORE INSERT OR UPDATE ON public.plg_crm_company_groups\n FOR EACH ROW EXECUTE FUNCTION public.trg_plg_crm_company_groups_touch();\n\n-- \u2500\u2500 view \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- O rollup. Um join e um GROUP BY, porque o grafo tem um n\u00EDvel s\u00F3 \u2014 nenhum dos\n-- oito CRMs pesquisados consegue isso sem \u00E1rvore, caminho materializado ou\n-- closure table.\nCREATE OR REPLACE VIEW public.v_crm_company_groups WITH (security_invoker = true) AS\n SELECT g.id, g.tenant_id, g.name, g.kind, g.document_root, g.notes,\n g.metadata, g.owner_id, g.is_active, g.created_at, g.updated_at,\n (SELECT count(*)::int FROM public.plg_crm_company_group_members gm\n WHERE gm.group_id = g.id) AS companies_count,\n -- DISTINCT na pessoa: um s\u00F3cio em duas empresas do grupo \u00E9 uma pessoa,\n -- n\u00E3o duas.\n (SELECT count(DISTINCT cp.person_id)::int\n FROM public.plg_crm_company_group_members gm\n JOIN public.plg_crm_company_people cp ON cp.company_id = gm.company_id\n WHERE gm.group_id = g.id) AS people_count,\n (SELECT count(*)::int\n FROM public.plg_crm_company_group_members gm\n JOIN public.plg_crm_deals d ON d.company_id = gm.company_id\n WHERE gm.group_id = g.id AND d.status = 'open') AS open_deals,\n -- Subconsultas separadas em vez de um join s\u00F3: juntar pessoas e\n -- neg\u00F3cios no mesmo FROM multiplica as linhas, e a\u00ED `sum` conta o\n -- mesmo neg\u00F3cio uma vez por s\u00F3cio.\n (SELECT coalesce(sum(d.value), 0)\n FROM public.plg_crm_company_group_members gm\n JOIN public.plg_crm_deals d ON d.company_id = gm.company_id\n WHERE gm.group_id = g.id AND d.status = 'won') AS won_value\n FROM public.plg_crm_company_groups g;\n\n-- Quem est\u00E1 em qual grupo, com o nome dos dois lados resolvido.\nCREATE OR REPLACE VIEW public.v_crm_company_group_members WITH (security_invoker = true) AS\n SELECT gm.id, gm.tenant_id, gm.group_id, gm.company_id, gm.role, gm.source,\n gm.created_at, gm.updated_at,\n g.name AS group_name, g.kind AS group_kind,\n c.name AS company_name, c.legal_name AS company_legal_name,\n c.document_number AS company_document, c.document_root AS company_document_root\n FROM public.plg_crm_company_group_members gm\n JOIN public.plg_crm_company_groups g ON g.id = gm.group_id\n JOIN public.plg_crm_companies c ON c.id = gm.company_id;\n\n-- Grupos que a RAIZ DO CNPJ j\u00E1 revela e ningu\u00E9m declarou \u2014 matriz e filial.\n-- Uma PROPOSTA, como `v_crm_lead_duplicates`: nada aqui cria v\u00EDnculo. O sinal \u00E9\n-- forte (mesma raiz \u00E9 o mesmo grupo econ\u00F4mico por defini\u00E7\u00E3o legal), mas quem\n-- decide se isso vira cadastro \u00E9 gente.\nCREATE OR REPLACE VIEW public.v_crm_company_group_candidates WITH (security_invoker = true) AS\n SELECT c.tenant_id,\n 'document_root'::text AS evidence,\n c.document_root AS value,\n count(*)::int AS companies_count,\n array_agg(c.id ORDER BY c.created_at) AS company_ids,\n array_agg(c.name ORDER BY c.created_at) AS company_names\n FROM public.plg_crm_companies c\n WHERE c.document_root IS NOT NULL\n AND NOT EXISTS (SELECT 1 FROM public.plg_crm_company_group_members gm\n WHERE gm.company_id = c.id)\n GROUP BY c.tenant_id, c.document_root\n HAVING count(*) > 1;\n\n-- \u2500\u2500 row security \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nALTER TABLE public.plg_crm_company_groups ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_company_groups FORCE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_company_group_members ENABLE ROW LEVEL SECURITY;\nALTER TABLE public.plg_crm_company_group_members FORCE ROW LEVEL SECURITY;\n\nDROP POLICY IF EXISTS plg_crm_company_groups_authz_select ON public.plg_crm_company_groups;\nCREATE POLICY plg_crm_company_groups_authz_select ON public.plg_crm_company_groups\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_groups_authz_insert ON public.plg_crm_company_groups;\nCREATE POLICY plg_crm_company_groups_authz_insert ON public.plg_crm_company_groups\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_groups_authz_update ON public.plg_crm_company_groups;\nCREATE POLICY plg_crm_company_groups_authz_update ON public.plg_crm_company_groups\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_groups_authz_delete ON public.plg_crm_company_groups;\nCREATE POLICY plg_crm_company_groups_authz_delete ON public.plg_crm_company_groups\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_group_members_authz_select ON public.plg_crm_company_group_members;\nCREATE POLICY plg_crm_company_group_members_authz_select ON public.plg_crm_company_group_members\n FOR SELECT TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.read', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_group_members_authz_insert ON public.plg_crm_company_group_members;\nCREATE POLICY plg_crm_company_group_members_authz_insert ON public.plg_crm_company_group_members\n FOR INSERT TO authenticated WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_group_members_authz_update ON public.plg_crm_company_group_members;\nCREATE POLICY plg_crm_company_group_members_authz_update ON public.plg_crm_company_group_members\n FOR UPDATE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)))\n WITH CHECK (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\nDROP POLICY IF EXISTS plg_crm_company_group_members_authz_delete ON public.plg_crm_company_group_members;\nCREATE POLICY plg_crm_company_group_members_authz_delete ON public.plg_crm_company_group_members\n FOR DELETE TO authenticated USING (\n tenant_id = (SELECT app.current_tenant_id())\n AND (SELECT app.has_permission('sales.edit', NULL::uuid)));\n\n-- \u2500\u2500 grant \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_company_groups TO authenticated;\nGRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_company_group_members TO authenticated;\nGRANT ALL ON public.plg_crm_company_groups TO service_role;\nGRANT ALL ON public.plg_crm_company_group_members TO service_role;\nGRANT SELECT ON public.v_crm_company_groups TO authenticated, service_role;\nGRANT SELECT ON public.v_crm_company_group_members TO authenticated, service_role;\nGRANT SELECT ON public.v_crm_company_group_candidates TO authenticated, service_role;\n\nINSERT INTO app.scaffold_registry\n (table_schema, table_name, resource_type, plugin, owner_scoping, mode,\n previous_policies, audit_hook, scope, distributable)\nVALUES\n ('public', 'plg_crm_company_groups', 'crm.company_group', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false),\n ('public', 'plg_crm_company_group_members', 'crm.company_group_member', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)\nON CONFLICT DO NOTHING;\n\nCOMMENT ON TABLE public.plg_crm_company_groups IS\n 'Grupo econ\u00F4mico: empresas que pertencem juntas sem que nenhuma esteja acima da outra. N\u00E3o \u00E9 hierarquia \u2014 ver o cabe\u00E7alho de 015 para por que parent_id foi recusado.';\nCOMMENT ON COLUMN public.plg_crm_company_group_members.source IS\n 'De onde veio a cren\u00E7a de que pertencem juntos. Um agrupamento inferido por telefone repetido n\u00E3o tem o mesmo peso de um confirmado por gente.';\n";
16
+ export declare const MIGRATION_016_THE_STRANGER_ONLY_EDITS_WHAT_IT_MADE = "-- 016_the_stranger_only_edits_what_it_made.sql \u2014 a deduplica\u00E7\u00E3o do formul\u00E1rio\n-- p\u00FAblico para de dar poder de escrita a quem \u00E9 an\u00F4nimo por defini\u00E7\u00E3o.\n--\n-- A 014 fez `create_public_lead` reconhecer quem j\u00E1 existe e ATUALIZAR a pessoa.\n-- Isso consertou o duplicado e abriu tr\u00EAs buracos, todos encontrados por uma\n-- varredura adversarial contra banco vivo, todos reproduzidos.\n--\n-- \u2500\u2500 1. O CAMINHO DE BUSCA DEIXAVA O LEAD SUMIR \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--\n-- A fun\u00E7\u00E3o tinha `SET search_path TO 'public'`. O Postgres procura `pg_temp`\n-- ANTES dos schemas listados, a menos que `pg_temp` seja nomeado. E `anon` tem\n-- TEMPORARY no banco. Ent\u00E3o:\n--\n-- CREATE TEMP TABLE people (LIKE public.people INCLUDING DEFAULTS);\n-- SELECT create_public_lead(...); -- devolve lead_id, is_new = true\n--\n-- \u2026grava em `pg_temp.people`, some no fim da sess\u00E3o, e o site mostra \"Pedido\n-- recebido\". O lead nunca existiu.\n--\n-- Isto n\u00E3o \u00E9 novo: a migration 018 foi escrita para fechar exatamente isto e\n-- cita esta fun\u00E7\u00E3o pelo nome (\"create_public_lead is reachable from a public\n-- form, so its caller is a stranger by design\"). Ela fixou `public, pg_catalog`,\n-- que TAMB\u00C9M n\u00E3o fecha, porque `pg_temp` continua vindo antes. A 014 reemitiu a\n-- fun\u00E7\u00E3o com `'public'` sozinho e reabriu a porta.\n--\n-- A \u00FAnica forma que fecha \u00E9 `search_path = ''` com tudo qualificado, que \u00E9 o que\n-- `crm_find_person_by_contact` j\u00E1 fazia certo.\n--\n-- \u2500\u2500 2. UM ESTRANHO PODIA EDITAR QUALQUER PESSOA DA CASA \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n--\n-- A busca de identidade procura em qualquer `kind` \u2014 o que \u00E9 certo para N\u00C3O\n-- duplicar um ser humano que j\u00E1 virou cliente. Mas o UPDATE seguinte n\u00E3o olhava\n-- `kind` nenhum. Reproduzido: como `anon`, sobre uma linha `staff`, foi poss\u00EDvel\n-- gravar um CPF escolhido pelo atacante, trocar as tags, injetar texto em\n-- `notes` e reativar (`is_active = true`) algu\u00E9m desativado.\n--\n-- A corre\u00E7\u00E3o n\u00E3o \u00E9 conferir `kind`. \u00C9 mais estreita: o formul\u00E1rio s\u00F3 pode\n-- ATUALIZAR uma linha QUE ELE MESMO CRIOU \u2014 `kind = 'lead'` e\n-- `metadata->>'source' = 'public_form'`. Sobre essas, um an\u00F4nimo j\u00E1 tinha poder\n-- de escrita (foi ele quem as criou), ent\u00E3o n\u00E3o h\u00E1 escalada.\n--\n-- Quando o casamento cai em qualquer outra coisa \u2014 um cliente, um funcion\u00E1rio,\n-- um lead cadastrado \u00E0 m\u00E3o pelo operador \u2014 nada \u00E9 tocado. Cria-se o lead novo e\n-- `v_crm_lead_duplicates` prop\u00F5e a fus\u00E3o para um humano. Duplicar e propor \u00E9\n-- recuper\u00E1vel; deixar um estranho escrever no cadastro do cliente n\u00E3o \u00E9.\n--\n-- \u2500\u2500 3. A RESPOSTA ERA UM OR\u00C1CULO \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--\n-- `is_new` dizia se o contato existe; `lead_id` devolvia o UUID REAL da pessoa;\n-- e `created_at` devolvia a data de cria\u00E7\u00E3o DELA, n\u00E3o do envio. Uma requisi\u00E7\u00E3o\n-- an\u00F4nima respondia: este e-mail \u00E9 de algu\u00E9m real, aqui est\u00E1 o id interno, e a\n-- conta \u00E9 desta data. O tenant vai no bundle da landing page, ent\u00E3o bastava uma\n-- lista de e-mails.\n--\n-- `is_new` sai (nenhum consumidor o lia \u2014 o plugin descartava o campo) e\n-- `created_at` passa a ser a hora do ENVIO. O or\u00E1culo n\u00E3o desaparece por\n-- completo enquanto `lead_id` for est\u00E1vel para um lead do pr\u00F3prio formul\u00E1rio,\n-- mas deixa de alcan\u00E7ar cliente e funcion\u00E1rio, que \u00E9 o que valia enumerar.\n--\n-- \u2500\u2500 e mais quatro, do mesmo relat\u00F3rio \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--\n-- * `array_agg` sobre conjunto vazio devolve NULL, ent\u00E3o um reenvio sem tags\n-- NULAVA `people.tags` \u2014 a coluna aceita NULL e falhava calada.\n-- * O INSERT da empresa n\u00E3o tinha `ON CONFLICT`: dois s\u00F3cios enviando ao mesmo\n-- tempo faziam o segundo abortar a transa\u00E7\u00E3o inteira e PERDER o lead. \u00C9\n-- exatamente o caso para o qual a feature foi constru\u00EDda.\n-- * `crm_phone_key` n\u00E3o \u00E9 injetivo \u2014 `crm_phone_key('1160001234')` e\n-- `crm_phone_key('11960001234')` d\u00E3o a mesma chave, porque o d\u00EDgito 9 \u00E9\n-- inserido em todo n\u00FAmero de 10 d\u00EDgitos cujo assinante come\u00E7a em 6-9. A 013\n-- diz explicitamente que nada funde pessoas por ela; a 014 passou a fundir.\n-- Agora s\u00F3 vale como identidade com DDD e 11 d\u00EDgitos.\n-- * Um CPF digitado na caixa \"CNPJ (opcional)\" fundia duas pessoas sem rela\u00E7\u00E3o.\n--\n-- E um quinto, achado ao conferir a corre\u00E7\u00E3o do quarto: o formul\u00E1rio gravava\n-- `people.document_number`, que \u00E9 a coluna de identidade do n\u00FAcleo, protegida\n-- por um \u00EDndice \u00DANICO por tenant. Um estranho podia ent\u00E3o SEQUESTRAR o CPF de\n-- algu\u00E9m \u2014 enviar um formul\u00E1rio com o CPF de terceiro e fazer o cadastro real\n-- daquela pessoa falhar depois com viola\u00E7\u00E3o de unicidade.\n--\n-- Por isso o formul\u00E1rio p\u00FAblico N\u00C3O escreve mais `document_number`. O documento\n-- vai para `metadata.fields`, onde \u00E9 dado e n\u00E3o identidade, e um operador o\n-- promove quando confere. O CNPJ segue criando a empresa, que \u00E9 para o que ele\n-- realmente serve aqui \u2014 a landing page coleta CNPJ, n\u00E3o CPF.\n\nSET check_function_bodies = false;\n\n-- \u2500\u2500 function \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- Estreita a busca ao que o formul\u00E1rio pode tocar. A vers\u00E3o ampla continua\n-- existindo para quem precisa saber se a pessoa existe em qualquer forma \u2014\n-- `v_crm_lead_duplicates` e a tela de fus\u00E3o.\nCREATE OR REPLACE FUNCTION public.crm_find_form_lead(\n p_tenant_id uuid,\n p_document text DEFAULT NULL,\n p_email text DEFAULT NULL,\n p_phone text DEFAULT NULL\n) RETURNS uuid\n LANGUAGE plpgsql STABLE SECURITY DEFINER\n SET search_path TO ''\n AS $$\nDECLARE\n v_doc text := public.people_normalize_document(p_document);\n v_email text := nullif(lower(btrim(coalesce(p_email, ''))), '');\n v_key text := public.crm_phone_key(p_phone);\n v_id uuid;\nBEGIN\n -- Documento s\u00F3 identifica se FECHA. Um CPF com d\u00EDgito errado \u2014 ou um CNPJ\n -- truncado caindo em onze caracteres, que foi o caso reproduzido \u2014 casaria\n -- duas pessoas sem rela\u00E7\u00E3o nenhuma. Continua valendo para quem chama com um\n -- documento j\u00E1 conferido; o formul\u00E1rio p\u00FAblico n\u00E3o passa mais nenhum.\n IF v_doc IS NOT NULL AND (length(v_doc) <> 11\n OR public.crm_document_is_valid(v_doc) IS NOT TRUE) THEN\n v_doc := NULL;\n END IF;\n\n -- Telefone s\u00F3 identifica com DDD. Sem ele a chave tem 8 ou 9 d\u00EDgitos e\n -- colide entre cidades; e a restaura\u00E7\u00E3o do nono d\u00EDgito faz todo n\u00FAmero de 10\n -- d\u00EDgitos colidir com um celular real.\n IF v_key IS NOT NULL AND length(v_key) <> 11 THEN\n v_key := NULL;\n END IF;\n\n SELECT p.id INTO v_id\n FROM public.people p\n WHERE p.tenant_id = p_tenant_id\n AND p.merged_into_id IS NULL\n -- O ESTREITAMENTO QUE FECHA A ESCALADA: s\u00F3 linha que este formul\u00E1rio criou.\n AND p.kind = 'lead'\n AND p.metadata ->> 'source' = 'public_form'\n AND ( (v_doc IS NOT NULL AND p.document_number = v_doc)\n OR (v_email IS NOT NULL AND lower(p.email) = v_email)\n OR (v_key IS NOT NULL AND public.crm_phone_key(p.phone) = v_key) )\n ORDER BY\n -- Mesma ordem de for\u00E7a de sempre: documento, e-mail, telefone; e entre\n -- iguais, o mais antigo, que \u00E9 quem carrega o hist\u00F3rico.\n (v_doc IS NOT NULL AND p.document_number = v_doc) DESC,\n (v_email IS NOT NULL AND lower(p.email) = v_email) DESC,\n p.created_at\n LIMIT 1;\n\n RETURN v_id;\nEND $$;\n\nREVOKE ALL ON FUNCTION public.crm_find_form_lead(uuid, text, text, text) FROM PUBLIC;\nGRANT EXECUTE ON FUNCTION public.crm_find_form_lead(uuid, text, text, text)\n TO authenticated, service_role;\n\n-- A assinatura da 014 morre junto, sen\u00E3o sobra um caminho sem as corre\u00E7\u00F5es.\nDROP FUNCTION IF EXISTS public.create_public_lead(\n uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb, text);\n\nCREATE OR REPLACE FUNCTION public.create_public_lead(\n p_tenant_id uuid, p_name text,\n p_phone text DEFAULT NULL::text, p_email text DEFAULT NULL::text,\n p_form_id text DEFAULT NULL::text, p_form_name text DEFAULT NULL::text,\n p_fields jsonb DEFAULT '{}'::jsonb, p_notes text DEFAULT NULL::text,\n p_utm jsonb DEFAULT '{}'::jsonb, p_tags text[] DEFAULT '{}'::text[],\n p_attachments jsonb DEFAULT '[]'::jsonb,\n p_document text DEFAULT NULL::text\n) RETURNS TABLE(lead_id uuid, created_at timestamp with time zone)\n LANGUAGE plpgsql SECURITY DEFINER\n -- VAZIO, e tudo qualificado. Ver o item 1 do cabe\u00E7alho: com qualquer schema\n -- listado, `pg_temp` vem antes e um estranho faz o lead sumir.\n SET search_path TO ''\n AS $_$\nDECLARE\n v_person_id uuid;\n v_existing uuid;\n v_phone text; v_email text; v_doc text; v_cpf text; v_cnpj text;\n v_company_id uuid;\n v_fields jsonb; v_utm jsonb; v_tags text[]; v_attachments jsonb;\n v_meta jsonb; v_subs jsonb;\nBEGIN\n IF p_name IS NULL OR length(btrim(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(lower(btrim(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 v_doc := public.people_normalize_document(p_document);\n v_cpf := CASE WHEN length(v_doc) = 11 THEN v_doc END;\n v_cnpj := CASE WHEN length(v_doc) = 14 THEN v_doc END;\n\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 public.tenants t WHERE t.id = p_tenant_id;\n IF NOT FOUND THEN RAISE EXCEPTION 'unknown tenant'; END IF;\n\n v_fields := coalesce(p_fields, '{}'::jsonb);\n IF jsonb_typeof(v_fields) <> 'object' THEN RAISE EXCEPTION 'fields must be an object'; END IF;\n IF length(v_fields::text) > 8000 THEN RAISE EXCEPTION 'fields too large'; END IF;\n IF (SELECT count(*) FROM jsonb_object_keys(v_fields)) > 40 THEN RAISE EXCEPTION 'too many fields'; END IF;\n\n v_utm := coalesce(p_utm, '{}'::jsonb);\n IF jsonb_typeof(v_utm) <> 'object' OR length(v_utm::text) > 2000 THEN RAISE EXCEPTION 'invalid utm'; END IF;\n\n v_attachments := coalesce(p_attachments, '[]'::jsonb);\n IF jsonb_typeof(v_attachments) <> 'array' THEN RAISE EXCEPTION 'attachments must be an array'; END IF;\n IF jsonb_array_length(v_attachments) > 10 THEN RAISE EXCEPTION 'too many attachments'; END IF;\n SELECT jsonb_agg(a) INTO v_attachments FROM (\n SELECT jsonb_strip_nulls(jsonb_build_object(\n 'bucket', 'crm-lead-uploads',\n 'path', e->>'path',\n 'slot', left(nullif(btrim(coalesce(e->>'slot', '')), ''), 48),\n 'mime', left(nullif(btrim(coalesce(e->>'mime', '')), ''), 128),\n 'size', CASE WHEN (e->>'size') ~ '^[0-9]{1,12}$' THEN (e->>'size')::bigint END\n )) AS a\n FROM jsonb_array_elements(v_attachments) e\n WHERE jsonb_typeof(e) = 'object'\n AND e->>'path' IS NOT NULL\n AND length(e->>'path') BETWEEN 16 AND 300\n AND e->>'path' LIKE p_tenant_id::text || '/%'\n ) valid;\n v_attachments := coalesce(v_attachments, '[]'::jsonb);\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 AND length(public.crm_tag_slug(t)) <= 48\n LIMIT 10\n ) normalized;\n v_tags := coalesce(v_tags, '{}'::text[]);\n\n IF (\n SELECT count(*) FROM public.people p\n WHERE p.tenant_id = p_tenant_id 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 -- S\u00F3 o que o formul\u00E1rio criou, e SEM documento como chave. Ver o item 2 e o\n -- quinto item do cabe\u00E7alho.\n v_existing := public.crm_find_form_lead(p_tenant_id, NULL, v_email, v_phone);\n\n -- O CPF vira DADO, n\u00E3o identidade: vai no bag de respostas junto do resto.\n IF v_cpf IS NOT NULL THEN\n v_fields := v_fields || jsonb_build_object('document', v_cpf);\n END IF;\n\n -- A empresa. `ON CONFLICT` e reconsulta: sem isso, dois s\u00F3cios enviando ao\n -- mesmo tempo faziam o segundo abortar a transa\u00E7\u00E3o inteira e perder o lead \u2014\n -- e esse \u00E9 o caso exato para o qual isto foi constru\u00EDdo.\n IF v_cnpj IS NOT NULL THEN\n INSERT INTO public.plg_crm_companies (tenant_id, name, document_number)\n VALUES (p_tenant_id,\n coalesce(nullif(btrim(coalesce(v_fields->>'restaurant', '')), ''),\n nullif(btrim(coalesce(v_fields->>'empresa', '')), ''),\n btrim(p_name)),\n v_cnpj)\n -- O predicado repetido n\u00E3o \u00E9 decora\u00E7\u00E3o: o \u00EDndice \u00FAnico da 013 \u00E9 PARCIAL\n -- (`WHERE document_number IS NOT NULL`), e sem repeti-lo o Postgres recusa\n -- com \"there is no unique or exclusion constraint matching the ON CONFLICT\n -- specification\" \u2014 o que derrubaria todo envio com CNPJ.\n ON CONFLICT (tenant_id, document_number) WHERE document_number IS NOT NULL\n DO NOTHING\n RETURNING id INTO v_company_id;\n\n IF v_company_id IS NULL THEN\n SELECT id INTO v_company_id FROM public.plg_crm_companies\n WHERE tenant_id = p_tenant_id AND document_number = v_cnpj;\n END IF;\n END IF;\n\n IF v_existing IS NOT NULL THEN\n SELECT p.metadata INTO v_meta FROM public.people p WHERE p.id = v_existing;\n v_meta := coalesce(v_meta, '{}'::jsonb);\n\n -- Teto na lista. Sem ele, o caminho de casamento n\u00E3o cria linha nenhuma,\n -- logo o teto de rajada (que conta INSERTs) n\u00E3o o enxerga, e 200 envios\n -- puseram 1,5 MB numa pessoa s\u00F3. Vinte \u00E9 mais hist\u00F3rico do que qualquer\n -- operador l\u00EA; o mais antigo sai primeiro.\n v_subs := coalesce(v_meta->'submissions', '[]'::jsonb) || jsonb_build_array(\n jsonb_strip_nulls(jsonb_build_object(\n 'at', now(),\n 'formId', nullif(btrim(coalesce(p_form_id, '')), ''),\n 'formName', nullif(btrim(coalesce(p_form_name, '')), ''),\n 'fields', CASE WHEN v_fields = '{}'::jsonb THEN NULL ELSE v_fields END,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END)));\n IF jsonb_array_length(v_subs) > 20 THEN\n v_subs := (SELECT jsonb_agg(e) FROM (\n SELECT e FROM jsonb_array_elements(v_subs) WITH ORDINALITY AS t(e, i)\n ORDER BY i OFFSET jsonb_array_length(v_subs) - 20) s);\n END IF;\n v_meta := jsonb_set(v_meta, '{submissions}', v_subs, true);\n v_meta := jsonb_set(v_meta, '{fields}', coalesce(v_meta->'fields', '{}'::jsonb) || v_fields, true);\n IF v_attachments <> '[]'::jsonb THEN\n v_meta := jsonb_set(v_meta, '{attachments}',\n coalesce(v_meta->'attachments', '[]'::jsonb) || v_attachments, true);\n END IF;\n\n UPDATE public.people SET\n name = CASE WHEN nullif(btrim(name), '') IS NULL THEN btrim(p_name) ELSE name END,\n phone = coalesce(phone, v_phone),\n email = coalesce(email, v_email),\n notes = CASE WHEN nullif(btrim(coalesce(notes, '')), '') IS NULL\n THEN left(p_notes, 2000) ELSE notes END,\n -- `coalesce` por fora: `array_agg` sobre conjunto vazio devolve NULL, e a\n -- coluna aceita NULL \u2014 um reenvio sem tags apagava as tags caladamente.\n tags = coalesce((SELECT array_agg(DISTINCT t)\n FROM unnest(coalesce(tags, '{}') || v_tags) t), '{}'),\n metadata = v_meta\n -- `is_active` N\u00C3O entra. Era incondicional, ent\u00E3o um estranho reativava\n -- qualquer pessoa desativada.\n WHERE id = v_existing;\n\n BEGIN\n PERFORM public.crm_log_public_lead_activity(v_existing, NULL);\n EXCEPTION WHEN OTHERS THEN NULL;\n END;\n\n IF v_company_id IS NOT NULL THEN\n INSERT INTO public.plg_crm_company_people (tenant_id, company_id, person_id)\n VALUES (p_tenant_id, v_company_id, v_existing)\n ON CONFLICT (company_id, person_id) DO NOTHING;\n END IF;\n\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_existing;\n -- A hora do ENVIO, n\u00E3o a da cria\u00E7\u00E3o da pessoa. Ver o item 3 do cabe\u00E7alho.\n created_at := now();\n RETURN NEXT;\n RETURN;\n END IF;\n\n INSERT INTO public.people (tenant_id, kind, name, phone, email, document_number,\n notes, tags, is_active, metadata)\n VALUES (\n p_tenant_id, 'lead', btrim(p_name), v_phone, v_email, NULL,\n left(p_notes, 2000), v_tags, true,\n jsonb_strip_nulls(jsonb_build_object(\n 'status', 'new',\n 'source', 'public_form',\n 'sourceName', coalesce(nullif(btrim(coalesce(p_form_name, '')), ''), 'Site'),\n 'formId', nullif(btrim(coalesce(p_form_id, '')), ''),\n 'fields', v_fields,\n 'utm', CASE WHEN v_utm = '{}'::jsonb THEN NULL ELSE v_utm END,\n 'attachments', CASE WHEN v_attachments = '[]'::jsonb THEN NULL ELSE v_attachments END))\n )\n RETURNING id, people.created_at INTO v_person_id, created_at;\n\n IF v_company_id IS NOT NULL THEN\n INSERT INTO public.plg_crm_company_people (tenant_id, company_id, person_id)\n VALUES (p_tenant_id, v_company_id, v_person_id)\n ON CONFLICT (company_id, person_id) DO NOTHING;\n END IF;\n\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$_$;\n\nGRANT ALL ON FUNCTION public.create_public_lead(uuid, text, text, text, text, text, jsonb, text, jsonb, text[], jsonb, text)\n TO anon, authenticated, service_role;\n\n-- \u2500\u2500 index \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\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n-- O \u00EDndice de telefone da 014 nunca foi usado: `crm_phone_key` n\u00E3o \u00E9 STRICT\n-- (trata NULL sozinha), ent\u00E3o o planejador n\u00E3o consegue provar o predicado\n-- parcial `phone IS NOT NULL` a partir de `crm_phone_key(phone) = $1`, e ca\u00EDa em\n-- Seq Scan. Medido: 34 ms contra 0,019 ms do \u00EDndice de e-mail, e `idx_scan = 0`\n-- depois de 276 buscas.\n--\n-- Sem o predicado parcial o planejador o usa. A linha com telefone nulo entra no\n-- \u00EDndice como NULL, o que custa pouco e \u00E9 o pre\u00E7o de ele servir para alguma\n-- coisa.\nDROP INDEX IF EXISTS public.people_tenant_lead_phonekey_idx;\nCREATE INDEX IF NOT EXISTS people_tenant_lead_phonekey_idx\n ON public.people (tenant_id, public.crm_phone_key(phone));\n\n-- O teto de rajada varria `people` inteira a cada envio.\nCREATE INDEX IF NOT EXISTS people_tenant_lead_recent_idx\n ON public.people (tenant_id, created_at DESC) WHERE kind = 'lead';\n\nCOMMENT ON FUNCTION public.crm_find_form_lead(uuid, text, text, text) IS\n 'Quem o FORMUL\u00C1RIO P\u00DABLICO j\u00E1 cadastrou neste tenant. Estreito de prop\u00F3sito: s\u00F3 kind=lead com source=public_form, porque quem chama \u00E9 an\u00F4nimo e n\u00E3o pode editar cliente nem funcion\u00E1rio. Para identidade ampla use crm_find_person_by_contact.';\n";
9
17
  export declare const MIGRATIONS: Array<{
10
18
  id: string;
11
19
  sql: string;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,0+/EAykDlC,CAAA;AAED,eAAO,MAAM,yCAAyC,8qYAkOrD,CAAA;AAED,eAAO,MAAM,+CAA+C,0onBAwT3D,CAAA;AAED,eAAO,MAAM,oDAAoD,8jpBAsYhE,CAAA;AAED,eAAO,MAAM,8CAA8C,gp4BAugB1D,CAAA;AAED,eAAO,MAAM,iDAAiD,47QA4J7D,CAAA;AAED,eAAO,MAAM,wCAAwC,gpYAiOpD,CAAA;AAED,eAAO,MAAM,uCAAuC,6sdA0RnD,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CASzD,CAAA"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/migrations/index.ts"],"names":[],"mappings":"AAIA,eAAO,MAAM,sBAAsB,0+/EAykDlC,CAAA;AAED,eAAO,MAAM,yCAAyC,8qYAkOrD,CAAA;AAED,eAAO,MAAM,+CAA+C,0onBAwT3D,CAAA;AAED,eAAO,MAAM,oDAAoD,8jpBAsYhE,CAAA;AAED,eAAO,MAAM,8CAA8C,gp4BAugB1D,CAAA;AAED,eAAO,MAAM,iDAAiD,47QA4J7D,CAAA;AAED,eAAO,MAAM,wCAAwC,gpYAiOpD,CAAA;AAED,eAAO,MAAM,uCAAuC,6sdA0RnD,CAAA;AAED,eAAO,MAAM,qCAAqC,m/vBAmcjD,CAAA;AAED,eAAO,MAAM,sCAAsC,gmEA4ClD,CAAA;AAED,eAAO,MAAM,qCAAqC,u6LA0GjD,CAAA;AAED,eAAO,MAAM,wCAAwC,o1KA6GpD,CAAA;AAED,eAAO,MAAM,0CAA0C,yhnDA6+BtD,CAAA;AAED,eAAO,MAAM,gDAAgD,+puBAub5D,CAAA;AAED,eAAO,MAAM,iDAAiD,iupBAwU7D,CAAA;AAED,eAAO,MAAM,kDAAkD,qqpBAyY9D,CAAA;AAED,eAAO,MAAM,UAAU,EAAE,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,CAiBzD,CAAA"}
@@ -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,EAAoD,KAAK,YAAY,EAAE,MAAM,eAAe,CAAA;AACnG,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,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;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,YAAY,CAAA;IAChC;;;;;;;;;;;OAWG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG;QAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;IACjE,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;AAoDD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,EAAE,CAAC;QAAE,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAA;IACrC,uDAAuD;IACvD,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACnG;AAED,yEAAyE;AACzE,wBAAgB,eAAe,IAAI,eAAe,CAajD;AAaD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,CA6HtF"}
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,EAAoD,KAAK,YAAY,EAAE,MAAM,eAAe,CAAA;AACnG,OAAO,EAEL,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,YAAY,EACjB,KAAK,iBAAiB,EACtB,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;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,OAAO,GAAG,YAAY,CAAA;IAChC;;;;;;;;;;;OAWG;IACH,YAAY,CAAC,EAAE,OAAO,GAAG;QAAE,QAAQ,CAAC,EAAE,OAAO,CAAC;QAAC,MAAM,CAAC,EAAE,OAAO,CAAA;KAAE,CAAA;IACjE,KAAK,CAAC,EAAE,WAAW,CAAA;IACnB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;AAoDD,MAAM,WAAW,iBAAiB;IAChC,QAAQ,EAAE,cAAc,CAAA;IACxB,QAAQ,EAAE,EAAE,CAAC;QAAE,QAAQ,EAAE,SAAS,CAAA;KAAE,CAAC,CAAA;IACrC,uDAAuD;IACvD,MAAM,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,UAAU,EAAE,OAAO,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAA;CACnG;AAED,yEAAyE;AACzE,wBAAgB,eAAe,IAAI,eAAe,CAajD;AAaD,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,iBAAiB,CA+HtF"}
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../../src/public/data/supabase.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,UAAU,CAAA;AAEvE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAoCxB"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../../src/public/data/supabase.ts"],"names":[],"mappings":"AAkBA,OAAO,EAAmB,KAAK,sBAAsB,EAAE,MAAM,UAAU,CAAA;AAEvE,MAAM,WAAW,yBAAyB;IACxC,qDAAqD;IACrD,QAAQ,EAAE,MAAM,CAAA;CACjB;AA8BD,wBAAgB,gCAAgC,CAC9C,OAAO,EAAE,yBAAyB,GACjC,sBAAsB,CAyCxB"}
@@ -52,7 +52,8 @@ function createSupabasePublicLeadProvider(options) {
52
52
  p_notes: input.notes ?? null,
53
53
  p_utm: input.attribution,
54
54
  p_tags: input.tags ?? [],
55
- p_attachments: input.attachments ?? []
55
+ p_attachments: input.attachments ?? [],
56
+ p_document: input.document ?? null
56
57
  });
57
58
  if (error) throw toSubmitError(error.message);
58
59
  const row = Array.isArray(data) ? data[0] : void 0;
@@ -385,6 +386,7 @@ function createPublicFormsPlugin(options) {
385
386
  const phone = idMap.phone ? String(values[idMap.phone] ?? "").trim() : "";
386
387
  const email = idMap.email ? String(values[idMap.email] ?? "").trim() : "";
387
388
  const notes = idMap.notes ? String(values[idMap.notes] ?? "").trim() : "";
389
+ const documentNumber = idMap.document ? String(values[idMap.document] ?? "").trim() : "";
388
390
  for (const key of form.required ?? []) {
389
391
  if (isEmpty(values[key])) {
390
392
  throw new LeadSubmitError("validation", `Campo obrigat\xF3rio: ${form.labels?.[key] ?? key}`);
@@ -408,6 +410,7 @@ function createPublicFormsPlugin(options) {
408
410
  name,
409
411
  phone: phone || void 0,
410
412
  email: email || void 0,
413
+ document: documentNumber || void 0,
411
414
  notes: notes || void 0,
412
415
  fields,
413
416
  attribution,