@fayz-ai/plugin-crm 0.8.4 → 0.9.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/dist/components/BoardFilters.d.ts +23 -0
  2. package/dist/components/BoardFilters.d.ts.map +1 -0
  3. package/dist/components/TagChips.d.ts +16 -0
  4. package/dist/components/TagChips.d.ts.map +1 -0
  5. package/dist/data/mock.d.ts.map +1 -1
  6. package/dist/data/supabase.d.ts.map +1 -1
  7. package/dist/data/types.d.ts +4 -2
  8. package/dist/data/types.d.ts.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +461 -84
  12. package/dist/index.js.map +1 -1
  13. package/dist/locales/en.d.ts.map +1 -1
  14. package/dist/locales/pt-BR.d.ts.map +1 -1
  15. package/dist/migrations/index.d.ts +4 -0
  16. package/dist/migrations/index.d.ts.map +1 -1
  17. package/dist/public/context.d.ts +3 -3
  18. package/dist/public/context.d.ts.map +1 -1
  19. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  20. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  21. package/dist/public/data.supabase.d.ts.map +1 -1
  22. package/dist/public/index.js +29 -5
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/public/types.d.ts +27 -0
  25. package/dist/public/types.d.ts.map +1 -1
  26. package/dist/registries.d.ts.map +1 -1
  27. package/dist/store.d.ts +7 -2
  28. package/dist/store.d.ts.map +1 -1
  29. package/dist/types.d.ts +37 -0
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/views/DealSidebar.d.ts.map +1 -1
  32. package/dist/views/PipelineView.d.ts.map +1 -1
  33. package/package.json +15 -14
  34. package/src/components/BoardFilters.tsx +190 -0
  35. package/src/components/TagChips.tsx +80 -0
  36. package/src/data/mock.ts +31 -4
  37. package/src/data/supabase.ts +72 -5
  38. package/src/data/types.ts +6 -3
  39. package/src/index.ts +94 -0
  40. package/src/locales/en.ts +9 -0
  41. package/src/locales/pt-BR.ts +9 -0
  42. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  43. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  44. package/src/migrations/013_tag_slugs.sql +177 -0
  45. package/src/migrations/014_public_lead_tags.sql +172 -0
  46. package/src/migrations/index.ts +643 -1
  47. package/src/public/context.tsx +4 -4
  48. package/src/public/createPublicFormsPlugin.ts +72 -2
  49. package/src/public/data.supabase.ts +1 -0
  50. package/src/public/types.ts +28 -0
  51. package/src/registries.ts +12 -3
  52. package/src/store.ts +78 -57
  53. package/src/types.ts +40 -0
  54. package/src/views/DealSidebar.tsx +9 -6
  55. package/src/views/PipelineView.tsx +92 -9
  56. package/dist/index.cjs +0 -5354
  57. package/dist/index.cjs.map +0 -1
  58. package/dist/public/index.cjs +0 -306
  59. package/dist/public/index.cjs.map +0 -1
package/src/index.ts CHANGED
@@ -301,6 +301,95 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
301
301
  { label: "What's our conversion rate?" },
302
302
  ],
303
303
  },
304
+ {
305
+ id: 'crm.create-lead',
306
+ name: 'createLead',
307
+ description:
308
+ 'Opens a NEW lead. This is the ONLY way to create one — the leads entity is a read-only view, so createRecord cannot. ' +
309
+ 'Only `name` is required; send whatever else the user gave and omit the rest. Status defaults to "new" and belongs to a closed set: new, contacted, qualified, converted, lost. ' +
310
+ 'A lead whose e-mail or phone already exists is NOT duplicated — the existing one comes back with deduped:true, and changing it is updateLead. The user confirms before anything is written.',
311
+ icon: 'UserPlus',
312
+ mode: 'persist' as const,
313
+ limitKey: 'leads',
314
+ execution: { plane: 'server' as const, kind: 'rpc' as const, rpc: 'agent_crm_create_lead' },
315
+ category: 'Sales',
316
+ parameters: {
317
+ type: 'object' as const,
318
+ properties: {
319
+ name: { type: 'string' as const, description: "The person's name" },
320
+ email: { type: 'string' as const, description: 'E-mail' },
321
+ phone: { type: 'string' as const, description: 'Phone' },
322
+ company: { type: 'string' as const, description: 'Company' },
323
+ status: {
324
+ type: 'string' as const,
325
+ description: 'Funnel stage — defaults to "new"',
326
+ enum: ['new', 'contacted', 'qualified', 'converted', 'lost'],
327
+ },
328
+ value: { type: 'string' as const, description: 'Estimated value' },
329
+ source_name: { type: 'string' as const, description: 'Where the lead came from' },
330
+ assigned_to_id: { type: 'string' as const, description: 'Person the lead is assigned to (id)' },
331
+ notes: { type: 'string' as const, description: 'Notes' },
332
+ },
333
+ required: ['name'],
334
+ },
335
+ suggestions: [
336
+ { label: 'Cria um lead Noronha, interessado em tratamento facial' },
337
+ ],
338
+ permission: { feature: 'sales', action: 'create' as const },
339
+ },
340
+ {
341
+ id: 'crm.update-lead',
342
+ name: 'updateLead',
343
+ description:
344
+ 'Changes a lead that ALREADY EXISTS: move its status through the funnel, reassign it, or fix its data (name, email, phone, company, value, notes). ' +
345
+ 'This is the ONLY way to change a lead — the leads entity is a read-only view, so updateRecord cannot touch it. ' +
346
+ 'Status is a closed set: new (awaiting first contact), contacted, qualified, converted, lost. A proposal that went out is usually "qualified"; a closed sale is "converted". ' +
347
+ 'Takes the lead id from a previous search. The user confirms before anything changes.',
348
+ icon: 'UserCheck',
349
+ mode: 'persist' as const,
350
+ execution: { plane: 'server' as const, kind: 'rpc' as const, rpc: 'agent_crm_update_lead' },
351
+ category: 'Sales',
352
+ parameters: {
353
+ type: 'object' as const,
354
+ properties: {
355
+ lead_id: { type: 'string' as const, description: 'Id of the lead to change (from a search)' },
356
+ status: {
357
+ type: 'string' as const,
358
+ description: 'New funnel stage',
359
+ enum: ['new', 'contacted', 'qualified', 'converted', 'lost'],
360
+ },
361
+ name: { type: 'string' as const, description: 'Corrected name' },
362
+ email: { type: 'string' as const, description: 'Corrected e-mail' },
363
+ phone: { type: 'string' as const, description: 'Corrected phone' },
364
+ company: { type: 'string' as const, description: 'Company' },
365
+ value: { type: 'string' as const, description: 'Estimated value' },
366
+ assigned_to_id: { type: 'string' as const, description: 'Person the lead is assigned to (id)' },
367
+ notes: { type: 'string' as const, description: 'Notes' },
368
+ },
369
+ required: ['lead_id'],
370
+ },
371
+ suggestions: [
372
+ { label: 'Mandei a proposta pro Vini, atualiza o status' },
373
+ { label: 'Marca esse lead como perdido' },
374
+ ],
375
+ permission: { feature: 'sales', action: 'edit' as const },
376
+ },
377
+ ],
378
+ declaredRpcs: [
379
+ {
380
+ name: 'agent_crm_create_lead',
381
+ kind: 'write' as const,
382
+ description:
383
+ 'Guarded lead create: agent_guard (role→plan→leads cap), closed status set, e-mail/phone dedupe, audited.',
384
+ audits: true,
385
+ },
386
+ {
387
+ name: 'agent_crm_update_lead',
388
+ kind: 'write' as const,
389
+ description:
390
+ 'Guarded lead update: agent_guard (role→plan, no cap), closed status set, tenant+kind checked, audited.',
391
+ audits: true,
392
+ },
304
393
  ],
305
394
  registries: crmRegistries,
306
395
  settings: [
@@ -333,3 +422,8 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
333
422
 
334
423
  export type { CrmDataProvider } from './data/types'
335
424
  export type { ResolvedCrmConfig } from './CrmContext'
425
+ // Tags: o chip e o tipo do cadastro. Exportados para uma app renderizar a mesma
426
+ // leitura fora do funil (ex.: numa aba de pessoa) em vez de reinventar o chip.
427
+ export { TagChips, humanizeTag } from './components/TagChips'
428
+ export type { TagChipsProps } from './components/TagChips'
429
+ export type { TagDef } from './types'
package/src/locales/en.ts CHANGED
@@ -116,6 +116,15 @@ export const en: Record<string, string> = {
116
116
  "crm.page.newQuoteDesc": "Send a proposal",
117
117
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
118
118
  "crm.page.settingsTitle": "Sales & CRM Settings",
119
+ "crm.filters.period": "Period",
120
+ "crm.filters.periodAll": "All",
121
+ "crm.filters.period24h": "24 hours",
122
+ "crm.filters.period7d": "7 days",
123
+ "crm.filters.periodCustom": "Custom",
124
+ "crm.filters.tags": "Tags",
125
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
126
+ "crm.filters.clearTags": "Clear tags",
127
+ "crm.filters.noResults": "No deals match the current filter",
119
128
  "crm.pipeline.dropHere": "Drop here",
120
129
  "crm.pipeline.archive": "Archive",
121
130
  "crm.pipeline.moveFailed": "Failed to move deal",
@@ -116,6 +116,15 @@ export const ptBR: Record<string, string> = {
116
116
  "crm.page.newQuoteDesc": "Enviar um orçamento",
117
117
  "crm.page.settingsSubtitle": "Configure pipeline, gestão de leads e cadastros",
118
118
  "crm.page.settingsTitle": "Configurações de Vendas e CRM",
119
+ "crm.filters.period": "Período",
120
+ "crm.filters.periodAll": "Tudo",
121
+ "crm.filters.period24h": "24 horas",
122
+ "crm.filters.period7d": "7 dias",
123
+ "crm.filters.periodCustom": "Personalizado",
124
+ "crm.filters.tags": "Tags",
125
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
126
+ "crm.filters.clearTags": "Limpar tags",
127
+ "crm.filters.noResults": "Nenhum negócio no filtro atual",
119
128
  "crm.pipeline.dropHere": "Solte aqui",
120
129
  "crm.pipeline.archive": "Arquivar",
121
130
  "crm.pipeline.moveFailed": "Falha ao mover negócio",
@@ -0,0 +1,153 @@
1
+ -- ============================================================================
2
+ -- plugin-crm 011: agent_crm_update_lead — mover o status de um lead (e corrigir
3
+ -- seus dados) pelo agente.
4
+ --
5
+ -- Lacuna que isso fecha: o CRM não tinha NENHUMA escrita pelo agente. Pedido
6
+ -- real ("acabei de mandar a proposta pra ele, então atualiza o status") caía no
7
+ -- updateRecord genérico, que bate em v_leads — uma view sobre people —, e o
8
+ -- assistente só sabia dizer "essa entidade é somente leitura". Mudar status de
9
+ -- lead é a ação mais frequente de um CRM; sem ela o agente é só um relatório.
10
+ --
11
+ -- Sobre o feature id: `sales`, não `crm.leads`. Duas razões, ambas medidas em
12
+ -- pool real. (1) agent_guard concatena feature || '.' || action sem normalizar,
13
+ -- e nenhum pool guarda `crm.leads.edit` — beauty guarda `crm_leads.edit`,
14
+ -- great-djs não guarda nenhum dos dois. (2) `sales.edit` existe nos dois, e é o
15
+ -- que a própria tool declara em `permission`. Servidor e cliente checando
16
+ -- features diferentes é bug por construção.
17
+ -- ============================================================================
18
+
19
+ CREATE OR REPLACE FUNCTION public.agent_crm_update_lead(
20
+ p_tenant_id uuid,
21
+ p_actor_user_id uuid,
22
+ p_payload jsonb
23
+ ) RETURNS jsonb
24
+ LANGUAGE plpgsql SECURITY DEFINER
25
+ SET search_path = public
26
+ AS $$
27
+ DECLARE
28
+ v_denial jsonb;
29
+ v_id uuid;
30
+ v_row record;
31
+ v_status text;
32
+ v_patch jsonb := '{}'::jsonb;
33
+ v_meta jsonb := '{}'::jsonb;
34
+ v_touched boolean := false;
35
+ BEGIN
36
+ BEGIN
37
+ v_id := (p_payload->>'lead_id')::uuid;
38
+ EXCEPTION WHEN OTHERS THEN
39
+ RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
40
+ END;
41
+ IF v_id IS NULL THEN
42
+ RETURN jsonb_build_object('ok', false, 'error',
43
+ 'lead_id is required — search the leads first and reuse the id from the result');
44
+ END IF;
45
+
46
+ SELECT p.id, p.name, p.email, p.phone, p.notes, p.metadata, p.kind
47
+ INTO v_row
48
+ FROM people p
49
+ WHERE p.id = v_id AND p.tenant_id = p_tenant_id AND p.kind = 'lead';
50
+ IF NOT FOUND THEN
51
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown lead for this tenant');
52
+ END IF;
53
+
54
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'edit');
55
+ IF v_denial IS NOT NULL THEN
56
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
57
+ END IF;
58
+
59
+ -- Status is a CLOSED set. The model reached for 'proposta_enviada', which no
60
+ -- board column renders — an invalid status writes a lead nobody can find, so
61
+ -- the allowed values come back in the error for it to self-correct.
62
+ v_status := nullif(trim(lower(p_payload->>'status')), '');
63
+ IF v_status IS NOT NULL THEN
64
+ IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
65
+ RETURN jsonb_build_object(
66
+ 'ok', false,
67
+ 'error', format('unknown lead status %L', v_status),
68
+ 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'),
69
+ 'hint', 'A sent proposal is usually "qualified"; a closed sale is "converted".');
70
+ END IF;
71
+ v_meta := v_meta || jsonb_build_object('status', v_status);
72
+ v_touched := true;
73
+ END IF;
74
+
75
+ -- Top-level columns.
76
+ IF p_payload ? 'name' AND nullif(trim(p_payload->>'name'), '') IS NOT NULL THEN
77
+ v_patch := v_patch || jsonb_build_object('name', trim(p_payload->>'name'));
78
+ v_touched := true;
79
+ END IF;
80
+ IF p_payload ? 'email' THEN
81
+ v_patch := v_patch || jsonb_build_object('email', nullif(trim(p_payload->>'email'), ''));
82
+ v_touched := true;
83
+ END IF;
84
+ IF p_payload ? 'phone' THEN
85
+ v_patch := v_patch || jsonb_build_object('phone', nullif(trim(p_payload->>'phone'), ''));
86
+ v_touched := true;
87
+ END IF;
88
+ IF p_payload ? 'notes' THEN
89
+ v_patch := v_patch || jsonb_build_object('notes', left(p_payload->>'notes', 2000));
90
+ v_touched := true;
91
+ END IF;
92
+
93
+ -- Metadata-backed columns of v_leads.
94
+ IF p_payload ? 'company' THEN
95
+ v_meta := v_meta || jsonb_build_object('company', nullif(trim(p_payload->>'company'), ''));
96
+ v_touched := true;
97
+ END IF;
98
+ IF p_payload ? 'value' THEN
99
+ v_meta := v_meta || jsonb_build_object('value', p_payload->>'value');
100
+ v_touched := true;
101
+ END IF;
102
+ IF p_payload ? 'assigned_to_id' THEN
103
+ v_meta := v_meta || jsonb_build_object('assignedToId', nullif(trim(p_payload->>'assigned_to_id'), ''));
104
+ v_touched := true;
105
+ END IF;
106
+
107
+ IF NOT v_touched THEN
108
+ RETURN jsonb_build_object('ok', false, 'error',
109
+ 'nothing to change: send status, name, email, phone, company, value, assigned_to_id or notes');
110
+ END IF;
111
+
112
+ UPDATE people p SET
113
+ name = COALESCE(v_patch->>'name', p.name),
114
+ email = CASE WHEN v_patch ? 'email' THEN v_patch->>'email' ELSE p.email END,
115
+ phone = CASE WHEN v_patch ? 'phone' THEN v_patch->>'phone' ELSE p.phone END,
116
+ notes = CASE WHEN v_patch ? 'notes' THEN v_patch->>'notes' ELSE p.notes END,
117
+ metadata = COALESCE(p.metadata, '{}'::jsonb) || v_meta,
118
+ updated_at = now()
119
+ WHERE p.id = v_id AND p.tenant_id = p_tenant_id;
120
+
121
+ INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
122
+ VALUES (p_tenant_id, p_actor_user_id, 'agent.updateLead', 'lead', v_id::text,
123
+ jsonb_build_object('payload', p_payload,
124
+ 'previous', jsonb_build_object(
125
+ 'name', v_row.name,
126
+ 'email', v_row.email,
127
+ 'phone', v_row.phone,
128
+ 'status', COALESCE(v_row.metadata->>'status', 'new'))));
129
+
130
+ SELECT l.id, l.name, l.email, l.phone, l.company, l.status
131
+ INTO v_row
132
+ FROM v_leads l WHERE l.id = v_id;
133
+
134
+ RETURN jsonb_build_object(
135
+ 'ok', true,
136
+ 'id', v_id,
137
+ 'record', jsonb_build_object(
138
+ 'ref', jsonb_build_object('id', v_id, 'resource', 'people',
139
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
140
+ 'name', v_row.name,
141
+ 'email', v_row.email,
142
+ 'phone', v_row.phone,
143
+ 'company', v_row.company,
144
+ 'status', v_row.status
145
+ )
146
+ );
147
+ END;
148
+ $$;
149
+
150
+ REVOKE ALL ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM public;
151
+ REVOKE EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb) FROM anon;
152
+ GRANT EXECUTE ON FUNCTION public.agent_crm_update_lead(uuid, uuid, jsonb)
153
+ TO authenticated, service_role;
@@ -0,0 +1,128 @@
1
+ -- ============================================================================
2
+ -- plugin-crm 012: agent_crm_create_lead — abrir um lead pelo agente.
3
+ --
4
+ -- Par do 011. Sem ele, "cria um lead Noronha em stage qualified" caía no
5
+ -- createRecord genérico, batia no read_only de v_leads, e o modelo — vendo que
6
+ -- existia updateLead — chamava a tool de EDIÇÃO com `lead_id: "N/A"`. Faltando
7
+ -- o create, ele improvisa com o que tem.
8
+ --
9
+ -- Deduplicação é parte do contrato, não extra: e-mail ou telefone que já existem
10
+ -- no tenant devolvem o lead existente com `deduped: true` em vez de abrir um
11
+ -- segundo. Um CRM com o mesmo contato duas vezes é pior que um CRM vazio.
12
+ --
13
+ -- Feature `sales` pelo mesmo motivo do 011 — é a que existe em todo pool e a que
14
+ -- a tool declara.
15
+ -- ============================================================================
16
+
17
+ CREATE OR REPLACE FUNCTION public.agent_crm_create_lead(
18
+ p_tenant_id uuid,
19
+ p_actor_user_id uuid,
20
+ p_payload jsonb
21
+ ) RETURNS jsonb
22
+ LANGUAGE plpgsql SECURITY DEFINER
23
+ SET search_path = public
24
+ AS $$
25
+ DECLARE
26
+ v_denial jsonb;
27
+ v_used int;
28
+ v_name text;
29
+ v_email text;
30
+ v_phone text;
31
+ v_status text;
32
+ v_meta jsonb;
33
+ v_existing record;
34
+ v_id uuid;
35
+ v_row record;
36
+ BEGIN
37
+ v_name := nullif(trim(p_payload->>'name'), '');
38
+ v_email := lower(nullif(trim(p_payload->>'email'), ''));
39
+ v_phone := nullif(regexp_replace(coalesce(p_payload->>'phone', ''), '\D', '', 'g'), '');
40
+ IF v_name IS NULL THEN
41
+ RETURN jsonb_build_object('ok', false, 'error', 'name is required to open a lead');
42
+ END IF;
43
+
44
+ v_status := coalesce(nullif(trim(lower(p_payload->>'status')), ''), 'new');
45
+ IF v_status NOT IN ('new', 'contacted', 'qualified', 'converted', 'lost') THEN
46
+ RETURN jsonb_build_object(
47
+ 'ok', false,
48
+ 'error', format('unknown lead status %L', v_status),
49
+ 'allowed', jsonb_build_array('new', 'contacted', 'qualified', 'converted', 'lost'));
50
+ END IF;
51
+
52
+ -- ── authorization: role → plan → leads cap ───────────────────────────────
53
+ SELECT count(*) INTO v_used FROM people p
54
+ WHERE p.tenant_id = p_tenant_id AND p.kind = 'lead';
55
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create', 'leads', v_used, 1);
56
+ IF v_denial IS NOT NULL THEN
57
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
58
+ END IF;
59
+
60
+ -- ── dedupe before writing ────────────────────────────────────────────────
61
+ IF v_email IS NOT NULL OR v_phone IS NOT NULL THEN
62
+ SELECT p.id, p.name INTO v_existing
63
+ FROM people p
64
+ WHERE p.tenant_id = p_tenant_id
65
+ AND p.kind = 'lead'
66
+ AND (
67
+ (v_email IS NOT NULL AND lower(p.email) = v_email)
68
+ OR (v_phone IS NOT NULL AND regexp_replace(coalesce(p.phone, ''), '\D', '', 'g') = v_phone)
69
+ )
70
+ LIMIT 1;
71
+ IF FOUND THEN
72
+ RETURN jsonb_build_object(
73
+ 'ok', true,
74
+ 'deduped', true,
75
+ 'id', v_existing.id,
76
+ 'message', format('%L already exists as a lead with that e-mail/phone — returning it instead of creating a second one. Use updateLead to change it.', v_existing.name),
77
+ 'record', jsonb_build_object(
78
+ 'ref', jsonb_build_object('id', v_existing.id, 'resource', 'people',
79
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
80
+ 'name', v_existing.name));
81
+ END IF;
82
+ END IF;
83
+
84
+ v_meta := jsonb_strip_nulls(jsonb_build_object(
85
+ 'status', v_status,
86
+ 'source', 'agent',
87
+ 'company', nullif(trim(p_payload->>'company'), ''),
88
+ 'value', nullif(trim(p_payload->>'value'), ''),
89
+ 'sourceName', nullif(trim(p_payload->>'source_name'), ''),
90
+ 'assignedToId', nullif(trim(p_payload->>'assigned_to_id'), '')
91
+ ));
92
+
93
+ INSERT INTO people (tenant_id, kind, name, email, phone, notes, is_active, metadata)
94
+ VALUES (p_tenant_id, 'lead', v_name,
95
+ nullif(trim(p_payload->>'email'), ''),
96
+ nullif(trim(p_payload->>'phone'), ''),
97
+ left(p_payload->>'notes', 2000),
98
+ true, v_meta)
99
+ RETURNING id INTO v_id;
100
+
101
+ INSERT INTO audit_logs (tenant_id, user_id, action, entity_type, entity_id, metadata)
102
+ VALUES (p_tenant_id, p_actor_user_id, 'agent.createLead', 'lead', v_id::text,
103
+ jsonb_build_object('payload', p_payload));
104
+
105
+ SELECT l.id, l.name, l.email, l.phone, l.company, l.status
106
+ INTO v_row
107
+ FROM v_leads l WHERE l.id = v_id;
108
+
109
+ RETURN jsonb_build_object(
110
+ 'ok', true,
111
+ 'id', v_id,
112
+ 'record', jsonb_build_object(
113
+ 'ref', jsonb_build_object('id', v_id, 'resource', 'people',
114
+ 'archetype', 'person:lead', 'entityKey', 'crm:leads'),
115
+ 'name', v_row.name,
116
+ 'email', v_row.email,
117
+ 'phone', v_row.phone,
118
+ 'company', v_row.company,
119
+ 'status', v_row.status
120
+ )
121
+ );
122
+ END;
123
+ $$;
124
+
125
+ REVOKE ALL ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM public;
126
+ REVOKE EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb) FROM anon;
127
+ GRANT EXECUTE ON FUNCTION public.agent_crm_create_lead(uuid, uuid, jsonb)
128
+ TO authenticated, service_role;
@@ -0,0 +1,177 @@
1
+ -- plugin-crm 013: tags ganham um SLUG, que passa a ser o contrato.
2
+ --
3
+ -- people.tags e orders.tags sempre foram text[] livre, e plg_crm_tags sempre
4
+ -- foi um cadastro solto: nada ligava um ao outro. Na prática isso dá os dois
5
+ -- problemas clássicos de tag em CRM — "Live Agosto", "live agosto" e "Live
6
+ -- Agosto " viram três tags, e renomear a tag no cadastro órfã todo registro que
7
+ -- já carregava o nome antigo.
8
+ --
9
+ -- O slug resolve os dois: o ARRAY guarda slug (estável, normalizado), e o
10
+ -- cadastro guarda label + cor para exibição. Renomear passa a ser cosmético.
11
+ --
12
+ -- Slug DESCONHECIDO continua válido de propósito: uma campanha precisa poder
13
+ -- marcar leads hoje, sem esperar alguém cadastrar a tag. A UI mostra o slug
14
+ -- num chip neutro até o cadastro existir. Vocabulário controlado que degrada,
15
+ -- em vez de vocabulário que bloqueia.
16
+
17
+ -- ---------------------------------------------------------------------------
18
+ -- Normalizador. Sem depender da extensão unaccent (nem todo pool a tem):
19
+ -- translate() cobre o português, que é o que estas tags carregam.
20
+ -- IMMUTABLE porque é usado em índice/generated abaixo.
21
+ -- ---------------------------------------------------------------------------
22
+ CREATE OR REPLACE FUNCTION public.crm_tag_slug(p_input text)
23
+ RETURNS text
24
+ LANGUAGE sql
25
+ IMMUTABLE
26
+ SET search_path TO 'public'
27
+ AS $function$
28
+ SELECT NULLIF(
29
+ -- 4. colapsa hífens repetidos e apara as pontas
30
+ trim(BOTH '-' FROM regexp_replace(
31
+ -- 3. tudo que não for [a-z0-9:] vira hífen (':' sobrevive: é o separador
32
+ -- de namespace das tags automáticas, ex. 'camp:black-friday')
33
+ regexp_replace(
34
+ -- 2. minúscula
35
+ lower(
36
+ -- 1. tira acento
37
+ translate(
38
+ COALESCE(p_input, ''),
39
+ 'áàâãäéèêëíìîïóòôõöúùûüçñÁÀÂÃÄÉÈÊËÍÌÎÏÓÒÔÕÖÚÙÛÜÇÑ',
40
+ 'aaaaaeeeeiiiiooooouuuucnAAAAAEEEEIIIIOOOOOUUUUCN'
41
+ )
42
+ ),
43
+ '[^a-z0-9:]+', '-', 'g'
44
+ ),
45
+ '-{2,}', '-', 'g'
46
+ )),
47
+ ''
48
+ );
49
+ $function$;
50
+
51
+ COMMENT ON FUNCTION public.crm_tag_slug(text) IS
52
+ 'Normaliza um rótulo de tag para o slug que people.tags/orders.tags guardam. Preserva ":" como separador de namespace (camp:, src:).';
53
+
54
+ -- ---------------------------------------------------------------------------
55
+ -- Cadastro de tags: slug + backfill a partir do nome.
56
+ -- ---------------------------------------------------------------------------
57
+ ALTER TABLE public.plg_crm_tags
58
+ ADD COLUMN IF NOT EXISTS slug text;
59
+
60
+ UPDATE public.plg_crm_tags
61
+ SET slug = public.crm_tag_slug(name)
62
+ WHERE slug IS NULL;
63
+
64
+ -- Duas linhas com o mesmo nome no mesmo tenant colidiriam no índice único.
65
+ -- Desempata pela mais antiga (a que os registros provavelmente já referenciam)
66
+ -- e sufixa as demais, em vez de falhar a migration.
67
+ WITH dupes AS (
68
+ SELECT id, row_number() OVER (PARTITION BY tenant_id, slug ORDER BY created_at, id) AS rn
69
+ FROM public.plg_crm_tags
70
+ WHERE slug IS NOT NULL
71
+ )
72
+ UPDATE public.plg_crm_tags t
73
+ SET slug = t.slug || '-' || d.rn
74
+ FROM dupes d
75
+ WHERE d.id = t.id AND d.rn > 1;
76
+
77
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant_slug
78
+ ON public.plg_crm_tags (tenant_id, slug);
79
+
80
+ -- Um cadastro sem slug não serve para nada (nunca casa com um registro), então
81
+ -- o slug passa a ser derivado do nome quando o cliente não manda um.
82
+ CREATE OR REPLACE FUNCTION public.plg_crm_tags_fill_slug()
83
+ RETURNS trigger
84
+ LANGUAGE plpgsql
85
+ SET search_path TO 'public'
86
+ AS $function$
87
+ BEGIN
88
+ NEW.slug := COALESCE(public.crm_tag_slug(NEW.slug), public.crm_tag_slug(NEW.name));
89
+ RETURN NEW;
90
+ END;
91
+ $function$;
92
+
93
+ DROP TRIGGER IF EXISTS trg_plg_crm_tags_fill_slug ON public.plg_crm_tags;
94
+ CREATE TRIGGER trg_plg_crm_tags_fill_slug
95
+ BEFORE INSERT OR UPDATE OF name, slug ON public.plg_crm_tags
96
+ FOR EACH ROW EXECUTE FUNCTION public.plg_crm_tags_fill_slug();
97
+
98
+ -- ---------------------------------------------------------------------------
99
+ -- O cadastro passa a se alimentar do que é REALMENTE usado.
100
+ --
101
+ -- Até aqui plg_crm_tags só existia como tela: o `seedData` do registry alimenta
102
+ -- o provider mock, nunca o banco, então /settings/crm/_properties/tags lia uma
103
+ -- tabela vazia em todo tenant — e continuaria vazia mesmo com campanhas
104
+ -- marcando leads. Registrar na escrita inverte isso: a tag aparece no cadastro
105
+ -- porque foi usada, e o operador entra depois só para renomear ou trocar a cor.
106
+ --
107
+ -- Alternativa descartada: semear VIP/Hot Lead/Follow-up em todo tenant. Isso
108
+ -- enche o cadastro de vocabulário que ninguém escolheu e que não corresponde a
109
+ -- nenhum registro.
110
+ -- ---------------------------------------------------------------------------
111
+
112
+ -- Cor estável por slug: a mesma tag sai da mesma cor em qualquer tenant, e o
113
+ -- operador pode sobrescrever depois. Paleta com contraste suficiente em chip.
114
+ CREATE OR REPLACE FUNCTION public.crm_tag_default_color(p_slug text)
115
+ RETURNS text
116
+ LANGUAGE sql
117
+ IMMUTABLE
118
+ AS $function$
119
+ SELECT (ARRAY[
120
+ '#6366f1','#0ea5e9','#10b981','#f59e0b','#ef4444','#ec4899','#8b5cf6','#14b8a6'
121
+ ])[(abs(hashtext(COALESCE(p_slug, ''))) % 8) + 1];
122
+ $function$;
123
+
124
+ -- Rótulo legível a partir do slug: 'camp:black-friday' -> 'Black Friday'.
125
+ -- O namespace some do rótulo (a cor e o filtro já o distinguem) — quem lê o
126
+ -- card quer ver a campanha, não o prefixo.
127
+ CREATE OR REPLACE FUNCTION public.crm_tag_humanize(p_slug text)
128
+ RETURNS text
129
+ LANGUAGE sql
130
+ IMMUTABLE
131
+ AS $function$
132
+ SELECT initcap(replace(regexp_replace(COALESCE(p_slug, ''), '^[a-z]+:', ''), '-', ' '));
133
+ $function$;
134
+
135
+ CREATE OR REPLACE FUNCTION public.crm_register_tags(p_tenant_id uuid, p_slugs text[])
136
+ RETURNS void
137
+ LANGUAGE sql
138
+ SECURITY DEFINER
139
+ SET search_path TO 'public'
140
+ AS $function$
141
+ INSERT INTO public.plg_crm_tags (tenant_id, name, slug, color, is_active)
142
+ SELECT p_tenant_id,
143
+ public.crm_tag_humanize(s),
144
+ s,
145
+ public.crm_tag_default_color(s),
146
+ true
147
+ FROM unnest(COALESCE(p_slugs, '{}'::text[])) AS s
148
+ WHERE s IS NOT NULL AND s <> ''
149
+ ON CONFLICT (tenant_id, slug) DO NOTHING;
150
+ $function$;
151
+
152
+ -- INTERNA de propósito: é SECURITY DEFINER e recebe o tenant do caller, então
153
+ -- exposta ela deixaria qualquer um semear cadastro no tenant alheio. Só é
154
+ -- alcançável de dentro de outra função DEFINER que já validou o tenant — hoje,
155
+ -- create_public_lead. O caminho do ADMIN não passa por aqui: ele faz upsert
156
+ -- direto em plg_crm_tags, onde a RLS da tabela já faz a autorização certa.
157
+ REVOKE ALL ON FUNCTION public.crm_register_tags(uuid, text[]) FROM public, anon, authenticated;
158
+
159
+ -- Backfill: tudo que JÁ está em people.tags / orders.tags vira cadastro, para a
160
+ -- tela não nascer vazia num tenant que já vinha usando tags.
161
+ DO $$
162
+ DECLARE
163
+ r record;
164
+ BEGIN
165
+ FOR r IN
166
+ SELECT tenant_id, array_agg(DISTINCT public.crm_tag_slug(tag)) AS slugs
167
+ FROM (
168
+ SELECT tenant_id, unnest(tags) AS tag FROM public.people WHERE tags IS NOT NULL
169
+ UNION ALL
170
+ SELECT tenant_id, unnest(tags) AS tag FROM public.orders WHERE tags IS NOT NULL
171
+ ) used
172
+ WHERE public.crm_tag_slug(tag) IS NOT NULL
173
+ GROUP BY tenant_id
174
+ LOOP
175
+ PERFORM public.crm_register_tags(r.tenant_id, r.slugs);
176
+ END LOOP;
177
+ END $$;