@fayz-ai/plugin-crm 0.8.3 → 0.8.5

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 (84) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/BoardFilters.d.ts +23 -0
  3. package/dist/components/BoardFilters.d.ts.map +1 -0
  4. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  5. package/dist/components/TagChips.d.ts +16 -0
  6. package/dist/components/TagChips.d.ts.map +1 -0
  7. package/dist/data/mock.d.ts +5 -0
  8. package/dist/data/mock.d.ts.map +1 -1
  9. package/dist/data/supabase.d.ts +6 -0
  10. package/dist/data/supabase.d.ts.map +1 -1
  11. package/dist/data/types.d.ts +12 -2
  12. package/dist/data/types.d.ts.map +1 -1
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1136 -164
  16. package/dist/index.js.map +1 -1
  17. package/dist/lib/access.d.ts +8 -0
  18. package/dist/lib/access.d.ts.map +1 -0
  19. package/dist/locales/en.d.ts.map +1 -1
  20. package/dist/locales/pt-BR.d.ts.map +1 -1
  21. package/dist/migrations/index.d.ts +9 -1
  22. package/dist/migrations/index.d.ts.map +1 -1
  23. package/dist/public/context.d.ts +3 -3
  24. package/dist/public/context.d.ts.map +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  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 +31 -7
  29. package/dist/public/index.js.map +1 -1
  30. package/dist/public/types.d.ts +27 -0
  31. package/dist/public/types.d.ts.map +1 -1
  32. package/dist/registries.d.ts +11 -0
  33. package/dist/registries.d.ts.map +1 -1
  34. package/dist/store.d.ts +12 -2
  35. package/dist/store.d.ts.map +1 -1
  36. package/dist/types.d.ts +51 -2
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts +6 -1
  39. package/dist/views/ActivityListView.d.ts.map +1 -1
  40. package/dist/views/DealSidebar.d.ts.map +1 -1
  41. package/dist/views/LeadDetailView.d.ts.map +1 -1
  42. package/dist/views/PipelineView.d.ts.map +1 -1
  43. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  44. package/dist/views/QuoteListView.d.ts.map +1 -1
  45. package/package.json +15 -14
  46. package/src/CrmPage.tsx +1 -1
  47. package/src/cascade.ts +2 -0
  48. package/src/components/BoardFilters.tsx +190 -0
  49. package/src/components/QuoteStatusDropdown.tsx +15 -3
  50. package/src/components/TagChips.tsx +80 -0
  51. package/src/data/mock.ts +140 -7
  52. package/src/data/supabase.ts +256 -11
  53. package/src/data/types.ts +14 -3
  54. package/src/index.ts +179 -3
  55. package/src/lib/access.ts +11 -0
  56. package/src/locales/en.ts +13 -0
  57. package/src/locales/pt-BR.ts +18 -5
  58. package/src/migrations/003_crm_views_rls.sql +10 -2
  59. package/src/migrations/007_activity_log.sql +55 -0
  60. package/src/migrations/008_view_field_aliases.sql +43 -0
  61. package/src/migrations/009_deal_archived_status.sql +30 -0
  62. package/src/migrations/010_quote_archived_status.sql +40 -0
  63. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  64. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  65. package/src/migrations/013_tag_slugs.sql +177 -0
  66. package/src/migrations/014_public_lead_tags.sql +172 -0
  67. package/src/migrations/index.ts +833 -3
  68. package/src/public/context.tsx +4 -4
  69. package/src/public/createPublicFormsPlugin.ts +72 -2
  70. package/src/public/data.supabase.ts +3 -2
  71. package/src/public/types.ts +28 -0
  72. package/src/registries.ts +44 -11
  73. package/src/store.ts +135 -38
  74. package/src/types.ts +59 -2
  75. package/src/views/ActivityListView.tsx +79 -11
  76. package/src/views/DealSidebar.tsx +48 -39
  77. package/src/views/LeadDetailView.tsx +29 -10
  78. package/src/views/PipelineView.tsx +112 -11
  79. package/src/views/QuoteDetailView.tsx +7 -3
  80. package/src/views/QuoteListView.tsx +26 -12
  81. package/dist/index.cjs +0 -4759
  82. package/dist/index.cjs.map +0 -1
  83. package/dist/public/index.cjs +0 -306
  84. package/dist/public/index.cjs.map +0 -1
@@ -1,9 +1,9 @@
1
1
  import type { CrmDataProvider } from './types'
2
2
  import type {
3
- Pipeline, PipelineStage, Lead, Deal, Activity, Quote, QuoteItem,
3
+ Pipeline, PipelineStage, Lead, Deal, Activity, ActivityTypeDef, TagDef, Quote, QuoteItem,
4
4
  CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
5
- LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
6
- PaginatedResult, CrmSummary, FunnelStage,
5
+ LeadQuery, DealQuery, ActivityQuery, QuoteQuery, BoardFilter,
6
+ PaginatedResult, CrmSummary, FunnelStage, SystemActivityType,
7
7
  } from '../types'
8
8
  import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
9
9
  import { getCrmTenantId } from '../lib/tenant'
@@ -17,6 +17,15 @@ function getTenantId(): string | undefined {
17
17
  return getCrmTenantId() ?? getActiveTenantId()
18
18
  }
19
19
 
20
+ /** Mesmo rótulo que o `crm_tag_humanize` do banco produz, para os dois
21
+ * caminhos (site público e admin) nomearem a tag igual. */
22
+ function humanizeTagSlug(slug: string): string {
23
+ return slug
24
+ .replace(/^[a-z]+:/, '')
25
+ .replace(/-/g, ' ')
26
+ .replace(/\b\w/g, (c) => c.toUpperCase())
27
+ }
28
+
20
29
  function snakeToCamel(obj: Record<string, unknown>): Record<string, unknown> {
21
30
  const result: Record<string, unknown> = {}
22
31
  for (const [key, value] of Object.entries(obj)) {
@@ -56,7 +65,85 @@ async function mergePersonMetadata(personId: string, patch: Record<string, unkno
56
65
 
57
66
  export function createSupabaseCrmProvider(options?: {
58
67
  clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
68
+ /** Manual interaction types lazily seeded per tenant (settings-editable rows). */
69
+ activityTypes?: Array<{ value: string; label: string; icon?: string }>
59
70
  }): CrmDataProvider {
71
+ // System timeline event — written silently at every CRM write point.
72
+ // completed_at is stamped so events never pollute the "pending" task filter,
73
+ // and a log failure must never break the write it describes.
74
+ async function logEvent(input: {
75
+ activityType: SystemActivityType
76
+ title: string
77
+ description?: string
78
+ leadId?: string
79
+ dealId?: string
80
+ contactId?: string
81
+ contactName?: string
82
+ }): Promise<void> {
83
+ try {
84
+ const { pub } = getClients()
85
+ await pub.from(T.activities).insert({
86
+ tenant_id: getTenantId(),
87
+ deal_id: input.dealId ?? null,
88
+ lead_id: input.leadId ?? null,
89
+ contact_id: input.contactId ?? null,
90
+ contact_name: input.contactName ?? null,
91
+ activity_type: input.activityType,
92
+ title: input.title,
93
+ description: input.description ?? null,
94
+ completed_at: new Date().toISOString(),
95
+ })
96
+ } catch { /* timeline is best-effort */ }
97
+ }
98
+
99
+ // Lazy per-tenant seed of manual interaction types (the type set comes from
100
+ // app config — SQL can't know the vertical). Idempotent via (tenant, name).
101
+ const typesSeeded = new Set<string>()
102
+ async function ensureActivityTypes(tenantId: string): Promise<void> {
103
+ const seed = options?.activityTypes
104
+ if (!seed?.length || typesSeeded.has(tenantId)) return
105
+ typesSeeded.add(tenantId)
106
+ const { pub } = getClients()
107
+ await pub.from(T.activityTypes).upsert(
108
+ seed.map((t) => ({ tenant_id: tenantId, name: t.label, icon: t.icon ?? null, is_active: true })),
109
+ { onConflict: 'tenant_id,name', ignoreDuplicates: true },
110
+ )
111
+ }
112
+
113
+ /**
114
+ * Registra no cadastro qualquer tag que ainda não exista.
115
+ *
116
+ * O caminho público (create_public_lead) já faz isto dentro do RPC; aqui é o
117
+ * caminho do ADMIN — criar um lead/negócio com uma tag nova pela tela tem de
118
+ * alimentar o mesmo cadastro, senão o chip nasce sem cor e a tag não aparece
119
+ * como opção no filtro do funil.
120
+ *
121
+ * Upsert direto em vez do RPC `crm_register_tags`: aquele é SECURITY DEFINER e
122
+ * recebe o tenant do caller, então fica interno ao caminho anônimo. Aqui a RLS
123
+ * da própria tabela já autoriza — mesmo padrão de `ensureActivityTypes`.
124
+ *
125
+ * Best-effort: uma linha de cadastro não pode derrubar a criação do registro
126
+ * que o operador acabou de fazer.
127
+ */
128
+ async function registerTags(tags?: string[]): Promise<void> {
129
+ const tenantId = getTenantId()
130
+ if (!tenantId || !tags?.length) return
131
+ try {
132
+ const { pub } = getClients()
133
+ // name/color são só o ponto de partida: o trigger deriva o slug, e o
134
+ // operador renomeia/recolore depois sem afetar registro nenhum.
135
+ await pub.from(T.tags).upsert(
136
+ [...new Set(tags)].map((slug) => ({
137
+ tenant_id: tenantId,
138
+ slug,
139
+ name: humanizeTagSlug(slug),
140
+ is_active: true,
141
+ })),
142
+ { onConflict: 'tenant_id,slug', ignoreDuplicates: true },
143
+ )
144
+ } catch { /* o chip cai no rótulo derivado do slug */ }
145
+ }
146
+
60
147
  const provider: CrmDataProvider = {
61
148
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
62
149
  async getPipelines(): Promise<Pipeline[]> {
@@ -74,7 +161,7 @@ export function createSupabaseCrmProvider(options?: {
74
161
  // --- Leads (via view — single query) ---
75
162
  async getLeads(query: LeadQuery): Promise<PaginatedResult<Lead>> {
76
163
  const { pub } = getClients()
77
- let qb = pub.from('v_leads').select('*', { count: 'exact' })
164
+ let qb = pub.from('v_leads').select('*', { count: 'exact' }).eq('is_active', true)
78
165
  if (query.search) qb = qb.ilike('name', `%${query.search}%`)
79
166
  if (query.status) {
80
167
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
@@ -130,7 +217,11 @@ export function createSupabaseCrmProvider(options?: {
130
217
  }).select().single()
131
218
  if (error) throw new Error(error.message)
132
219
  const p = snakeToCamel(data) as any
133
- return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: 'new', tags: [], tenantId: tenantId!, createdAt: p.createdAt, updatedAt: p.updatedAt } as Lead
220
+ await registerTags(input.tags)
221
+ await logEvent({ activityType: 'lead_created', title: input.name, leadId: p.id, contactName: input.name })
222
+ // `tags` sai do que foi GRAVADO: devolver [] fixo fazia o card recém-criado
223
+ // nascer sem os chips que o formulário acabou de definir, até um refetch.
224
+ return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: 'new', tags: p.tags ?? input.tags ?? [], tenantId: tenantId!, createdAt: p.createdAt, updatedAt: p.updatedAt } as Lead
134
225
  },
135
226
 
136
227
  async updateLead(id: string, partial: Partial<Lead>): Promise<Lead> {
@@ -150,9 +241,14 @@ export function createSupabaseCrmProvider(options?: {
150
241
  },
151
242
 
152
243
  async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
153
- const { core } = getClients()
154
244
  // Update lead status to converted
155
245
  await mergePersonMetadata(leadId, { status: 'converted' })
246
+ await logEvent({
247
+ activityType: 'lead_converted',
248
+ title: dealInput.contactName ?? dealInput.title,
249
+ leadId,
250
+ contactName: dealInput.contactName,
251
+ })
156
252
  return provider.createDeal({ ...dealInput, leadId } as any)
157
253
  },
158
254
 
@@ -163,6 +259,8 @@ export function createSupabaseCrmProvider(options?: {
163
259
  if (query.status) {
164
260
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
165
261
  qb = qb.in('status', statuses)
262
+ } else {
263
+ qb = qb.neq('status', 'archived')
166
264
  }
167
265
  if (query.search) qb = qb.ilike('title', `%${query.search}%`)
168
266
  if (query.pipelineId) qb = qb.eq('pipeline_id', query.pipelineId)
@@ -216,11 +314,17 @@ export function createSupabaseCrmProvider(options?: {
216
314
  } as Deal
217
315
  },
218
316
 
219
- async getDealsByStage(pipelineId: string): Promise<Map<string, Deal[]>> {
317
+ async getDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<Map<string, Deal[]>> {
220
318
  const { pub } = getClients()
221
319
  const stages = await provider.getPipelineStages(pipelineId)
222
320
  // Single query via view — already has stage info joined
223
- const { data } = await pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).neq('status', 'lost')
321
+ let qb = pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).not('status', 'in', '(lost,archived)')
322
+ // `overlaps` = tem QUALQUER uma das tags. `contains` seria "tem todas",
323
+ // que num multi-select de segmentos quase sempre volta vazio.
324
+ if (filter?.tags?.length) qb = qb.overlaps('tags', filter.tags)
325
+ if (filter?.createdFrom) qb = qb.gte('created_at', filter.createdFrom)
326
+ if (filter?.createdTo) qb = qb.lte('created_at', filter.createdTo)
327
+ const { data } = await qb
224
328
  const deals = (data ?? []).map((r: any) => ({
225
329
  id: r.id, title: r.title ?? '', value: r.value ?? 0,
226
330
  pipelineId: r.pipeline_id, stageId: r.stage_id,
@@ -262,6 +366,17 @@ export function createSupabaseCrmProvider(options?: {
262
366
  lead_id: (input as any).leadId,
263
367
  })
264
368
 
369
+ await registerTags(input.tags)
370
+
371
+ await logEvent({
372
+ activityType: 'deal_created',
373
+ title: input.title,
374
+ dealId: order.id,
375
+ leadId: (input as any).leadId,
376
+ contactId: input.contactId,
377
+ contactName: input.contactName,
378
+ })
379
+
265
380
  return {
266
381
  id: order.id, title: input.title, value: input.value,
267
382
  pipelineId: input.pipelineId, stageId: input.stageId,
@@ -331,7 +446,49 @@ export function createSupabaseCrmProvider(options?: {
331
446
  }
332
447
  }
333
448
 
334
- return (await provider.getDealById(dealId))!
449
+ const moved = (await provider.getDealById(dealId))!
450
+ if (stageRow) {
451
+ await logEvent({
452
+ activityType: stageRow.is_won ? 'deal_won' : stageRow.is_lost ? 'deal_lost' : 'stage_changed',
453
+ title: moved.title || 'Deal',
454
+ description: stageRow.name,
455
+ dealId,
456
+ contactName: moved.contactName,
457
+ })
458
+ }
459
+ return moved
460
+ },
461
+
462
+ async archiveDeal(dealId: string): Promise<void> {
463
+ const { core } = getClients()
464
+ const deal = await provider.getDealById(dealId)
465
+ const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', dealId)
466
+ if (error) throw new Error(error.message)
467
+ await logEvent({
468
+ activityType: 'deal_archived',
469
+ title: deal?.title || 'Deal',
470
+ dealId,
471
+ contactName: deal?.contactName,
472
+ })
473
+ },
474
+
475
+ async archiveLead(leadId: string): Promise<void> {
476
+ const { core } = getClients()
477
+ const lead = await provider.getLeadById(leadId)
478
+ const { error } = await core.from('people').update({ is_active: false }).eq('id', leadId)
479
+ if (error) throw new Error(error.message)
480
+ // Its deal leaves the board too — an archived lead with a live card
481
+ // would resurrect on the next drag.
482
+ try {
483
+ const deal = await provider.getDealByLeadId(leadId)
484
+ if (deal && deal.status === 'open') await provider.archiveDeal(deal.id)
485
+ } catch { /* non-blocking */ }
486
+ await logEvent({
487
+ activityType: 'lead_archived',
488
+ title: lead?.name ?? 'Lead',
489
+ leadId,
490
+ contactName: lead?.name,
491
+ })
335
492
  },
336
493
 
337
494
  // --- Activities (public.plg_crm_activities) ---
@@ -370,6 +527,29 @@ export function createSupabaseCrmProvider(options?: {
370
527
  return snakeToCamel(data) as unknown as Activity
371
528
  },
372
529
 
530
+ async getActivityTypes(): Promise<ActivityTypeDef[]> {
531
+ const { pub } = getClients()
532
+ const tenantId = getTenantId()
533
+ if (!tenantId) return []
534
+ await ensureActivityTypes(tenantId)
535
+ const { data } = await pub.from(T.activityTypes)
536
+ .select('*').eq('tenant_id', tenantId).eq('is_active', true).order('name')
537
+ return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as ActivityTypeDef)
538
+ },
539
+
540
+ async getTagDefs(): Promise<TagDef[]> {
541
+ const { pub } = getClients()
542
+ const tenantId = getTenantId()
543
+ if (!tenantId) return []
544
+ const { data } = await pub.from(T.tags)
545
+ .select('*').eq('tenant_id', tenantId).eq('is_active', true).order('name')
546
+ return (data ?? [])
547
+ // Uma linha sem slug é de antes da 013 e não casa com registro nenhum;
548
+ // deixá-la passar só produziria um chip que nunca aparece.
549
+ .filter((r: any) => r.slug)
550
+ .map((r: any) => snakeToCamel(r) as unknown as TagDef)
551
+ },
552
+
373
553
  // --- Quotes (public.orders kind='quote' + order_items) ---
374
554
  async getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>> {
375
555
  const { core } = getClients()
@@ -377,6 +557,8 @@ export function createSupabaseCrmProvider(options?: {
377
557
  if (query.status) {
378
558
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
379
559
  qb = qb.in('status', statuses)
560
+ } else {
561
+ qb = qb.neq('status', 'archived')
380
562
  }
381
563
  if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`)
382
564
  const page = query.page ?? 1
@@ -455,6 +637,22 @@ export function createSupabaseCrmProvider(options?: {
455
637
  if (itemsError) throw new Error(itemsError.message)
456
638
  }
457
639
 
640
+ // The deal card renders the DEAL's value — a quote without this sync
641
+ // leaves R$ 0,00 on the board while the quote holds the real number.
642
+ if (input.dealId && totalAmount > 0) {
643
+ await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
644
+ }
645
+
646
+ await logEvent({
647
+ activityType: 'quote_created',
648
+ title: order.reference_number ?? 'Quote',
649
+ description: input.contactName,
650
+ dealId: input.dealId,
651
+ leadId: input.leadId,
652
+ contactId: input.contactId,
653
+ contactName: input.contactName,
654
+ })
655
+
458
656
  return {
459
657
  id: order.id, quoteNumber: order.reference_number,
460
658
  quoteDate: order.created_at?.slice(0, 10), validUntil: input.validUntil,
@@ -490,6 +688,10 @@ export function createSupabaseCrmProvider(options?: {
490
688
  if (itemsError) throw new Error(itemsError.message)
491
689
  }
492
690
 
691
+ if (input.dealId && totalAmount > 0) {
692
+ await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
693
+ }
694
+
493
695
  return (await provider.getQuoteById(id))!
494
696
  },
495
697
 
@@ -514,7 +716,16 @@ export function createSupabaseCrmProvider(options?: {
514
716
  }
515
717
  } catch { /* non-blocking */ }
516
718
 
517
- return (await provider.getQuoteById(id))!
719
+ const sent = (await provider.getQuoteById(id))!
720
+ await logEvent({
721
+ activityType: 'quote_sent',
722
+ title: sent.quoteNumber ?? 'Quote',
723
+ description: sent.contactName,
724
+ dealId: sent.dealId,
725
+ leadId: sent.leadId,
726
+ contactName: sent.contactName,
727
+ })
728
+ return sent
518
729
  },
519
730
 
520
731
  async approveQuote(id: string): Promise<Quote> {
@@ -574,7 +785,16 @@ export function createSupabaseCrmProvider(options?: {
574
785
  }
575
786
  }
576
787
 
577
- return (await provider.getQuoteById(id))!
788
+ const approved = (await provider.getQuoteById(id))!
789
+ await logEvent({
790
+ activityType: 'quote_approved',
791
+ title: approved.quoteNumber ?? 'Quote',
792
+ description: approved.contactName,
793
+ dealId: approved.dealId,
794
+ leadId: approved.leadId,
795
+ contactName: approved.contactName,
796
+ })
797
+ return approved
578
798
  },
579
799
 
580
800
  async rejectQuote(id: string, reason: string): Promise<Quote> {
@@ -597,6 +817,16 @@ export function createSupabaseCrmProvider(options?: {
597
817
  if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id)
598
818
  }
599
819
  }
820
+ if (quote) {
821
+ await logEvent({
822
+ activityType: 'quote_rejected',
823
+ title: quote.quoteNumber ?? 'Quote',
824
+ description: reason,
825
+ dealId: quote.dealId,
826
+ leadId: quote.leadId,
827
+ contactName: quote.contactName,
828
+ })
829
+ }
600
830
  return quote!
601
831
  },
602
832
 
@@ -606,6 +836,21 @@ export function createSupabaseCrmProvider(options?: {
606
836
  return (await provider.getQuoteById(id))!
607
837
  },
608
838
 
839
+ async archiveQuote(id: string): Promise<void> {
840
+ const { core } = getClients()
841
+ const quote = await provider.getQuoteById(id)
842
+ const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', id)
843
+ if (error) throw new Error(error.message)
844
+ await logEvent({
845
+ activityType: 'quote_archived',
846
+ title: quote?.quoteNumber ?? 'Quote',
847
+ description: quote?.contactName,
848
+ dealId: quote?.dealId,
849
+ leadId: quote?.leadId,
850
+ contactName: quote?.contactName,
851
+ })
852
+ },
853
+
609
854
  // Cross-entity lookups
610
855
  async getQuotesByDealId(dealId: string): Promise<Quote[]> {
611
856
  const { core } = getClients()
package/src/data/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type {
2
- Pipeline, PipelineStage, Lead, Deal, Activity, Quote,
2
+ Pipeline, PipelineStage, Lead, Deal, Activity, ActivityTypeDef, TagDef, Quote,
3
3
  CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
4
- LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
4
+ LeadQuery, DealQuery, ActivityQuery, QuoteQuery, BoardFilter,
5
5
  PaginatedResult, CrmSummary, FunnelStage,
6
6
  } from '../types'
7
7
 
@@ -20,15 +20,26 @@ export interface CrmDataProvider {
20
20
  // Deals
21
21
  getDeals(query: DealQuery): Promise<PaginatedResult<Deal>>
22
22
  getDealById(id: string): Promise<Deal | null>
23
- getDealsByStage(pipelineId: string): Promise<Map<string, Deal[]>>
23
+ getDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<Map<string, Deal[]>>
24
24
  createDeal(input: CreateDealInput): Promise<Deal>
25
25
  updateDeal(id: string, data: Partial<Deal>): Promise<Deal>
26
26
  moveDealToStage(dealId: string, stageId: string): Promise<Deal>
27
+ /** Soft-remove from the board (status='archived') — never a hard delete. */
28
+ archiveDeal(dealId: string): Promise<void>
29
+ /** Soft-remove a lead (is_active=false) and archive its deal. */
30
+ archiveLead(leadId: string): Promise<void>
31
+ /** Soft-remove a quote (status='archived') — never a hard delete. */
32
+ archiveQuote(quoteId: string): Promise<void>
27
33
 
28
34
  // Activities
29
35
  getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>>
30
36
  createActivity(input: CreateActivityInput): Promise<Activity>
31
37
  completeActivity(id: string): Promise<Activity>
38
+ /** Tenant's manual interaction types (activity-types registry rows). */
39
+ getActivityTypes(): Promise<ActivityTypeDef[]>
40
+
41
+ /** Cadastro de tags (tags registry rows) — rótulo e cor por slug. */
42
+ getTagDefs(): Promise<TagDef[]>
32
43
 
33
44
  // Quotes
34
45
  getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>>
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@ import { createMockCrmProvider } from './data/mock'
9
9
  import { createSafeDataProvider, registerTranslations } from '@fayz-ai/core'
10
10
  import { createSupabaseCrmProvider } from './data/supabase'
11
11
  import { createCrmStore } from './store'
12
- import { crmRegistries } from './registries'
12
+ import { buildCrmRegistries, DEFAULT_ACTIVITY_TYPES } from './registries'
13
13
  import { crmLocales } from './locales'
14
14
  import { CrmGeneralSettings } from './components/CrmGeneralSettings'
15
15
 
@@ -119,9 +119,11 @@ function resolveConfig(options?: CrmPluginOptions): ResolvedCrmConfig {
119
119
  export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
120
120
  const config = resolveConfig(options)
121
121
  registerTranslations(crmLocales)
122
+ const activityTypes = options?.activityTypes ?? DEFAULT_ACTIVITY_TYPES
123
+ const crmRegistries = buildCrmRegistries(activityTypes)
122
124
  const provider = options?.dataProvider ?? createSafeDataProvider(
123
- () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
124
- () => createMockCrmProvider(),
125
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion, activityTypes }),
126
+ () => createMockCrmProvider({ activityTypes }),
125
127
  )
126
128
  const store = createCrmStore(provider)
127
129
 
@@ -157,6 +159,86 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
157
159
  { key: 'deals', label: 'Deals', table: 'orders', kindFilter: 'deal' },
158
160
  { key: 'quotes', label: 'Quotes', table: 'orders', kindFilter: 'quote' },
159
161
  ],
162
+ // Read-models for the agent's data primitives (searchRecords/queryData).
163
+ // Without these the assistant cannot see leads/deals/activities at all and
164
+ // guesses wrong entities ("quem tá aguardando contato?" → invented filter
165
+ // on Cliente). Keys are stable ASCII; fields are camelCase output shape.
166
+ queryEntities: [
167
+ {
168
+ key: 'crm:leads',
169
+ writable: false,
170
+ entity: {
171
+ name: 'Lead',
172
+ namePlural: 'Leads',
173
+ icon: 'UserPlus',
174
+ permission: { feature: 'crm.leads', action: 'read' as const },
175
+ fields: [
176
+ { key: 'name', label: 'Name', type: 'text' as const, searchable: true },
177
+ { key: 'email', label: 'Email', type: 'text' as const, searchable: true },
178
+ { key: 'phone', label: 'Phone', type: 'text' as const, searchable: true },
179
+ { key: 'company', label: 'Company', type: 'text' as const },
180
+ { key: 'status', label: 'Status (new=awaiting first contact, contacted, qualified, converted, lost)', type: 'text' as const },
181
+ { key: 'sourceName', label: 'Source', type: 'text' as const },
182
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
183
+ ],
184
+ data: {
185
+ table: 'v_leads',
186
+ tenantScoped: true,
187
+ searchColumns: ['name', 'email', 'phone'],
188
+ },
189
+ },
190
+ },
191
+ {
192
+ key: 'crm:deals',
193
+ writable: false,
194
+ entity: {
195
+ name: 'Deal',
196
+ namePlural: 'Deals',
197
+ icon: 'Target',
198
+ permission: { feature: 'crm.pipeline', action: 'read' as const },
199
+ fields: [
200
+ { key: 'title', label: 'Title', type: 'text' as const, searchable: true },
201
+ { key: 'value', label: 'Value', type: 'number' as const },
202
+ { key: 'status', label: 'Status (open/won/lost)', type: 'text' as const },
203
+ { key: 'stage', label: 'Pipeline stage name', type: 'text' as const },
204
+ { key: 'contactName', label: 'Contact', type: 'text' as const, searchable: true },
205
+ { key: 'probability', label: 'Probability %', type: 'number' as const },
206
+ { key: 'expectedCloseDate', label: 'Expected close', type: 'text' as const },
207
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
208
+ ],
209
+ data: {
210
+ table: 'v_deals',
211
+ tenantScoped: true,
212
+ searchColumns: ['title', 'contact_name'],
213
+ },
214
+ },
215
+ },
216
+ {
217
+ key: 'crm:activities',
218
+ writable: false,
219
+ entity: {
220
+ name: 'CRM activity',
221
+ namePlural: 'CRM activities',
222
+ icon: 'MessageCircle',
223
+ permission: { feature: 'sales', action: 'read' as const },
224
+ fields: [
225
+ { key: 'activityType', label: 'Type (call/email/note… or system events: lead_created, deal_won, quote_approved…)', type: 'text' as const },
226
+ { key: 'title', label: 'Title', type: 'text' as const, searchable: true },
227
+ { key: 'description', label: 'Description', type: 'text' as const, searchable: true },
228
+ { key: 'contactName', label: 'Contact', type: 'text' as const, searchable: true },
229
+ { key: 'dueDate', label: 'Due date', type: 'text' as const },
230
+ { key: 'completedAt', label: 'Completed at', type: 'text' as const },
231
+ { key: 'assignedToName', label: 'Assigned to', type: 'text' as const },
232
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
233
+ ],
234
+ data: {
235
+ table: 'plg_crm_activities',
236
+ tenantScoped: true,
237
+ searchColumns: ['title', 'contact_name', 'description'],
238
+ },
239
+ },
240
+ },
241
+ ],
160
242
  navigation: [
161
243
  {
162
244
  section: options?.navSection ?? 'main',
@@ -219,6 +301,95 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
219
301
  { label: "What's our conversion rate?" },
220
302
  ],
221
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
+ },
222
393
  ],
223
394
  registries: crmRegistries,
224
395
  settings: [
@@ -251,3 +422,8 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
251
422
 
252
423
  export type { CrmDataProvider } from './data/types'
253
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'
@@ -0,0 +1,11 @@
1
+ import { useAccessOptional } from '@fayz-ai/saas'
2
+
3
+ /**
4
+ * Single resolver for "can this user archive CRM records?" (deals, leads).
5
+ * One feature/action pair resolved in ONE place — call sites render or hide
6
+ * the affordance off this boolean and never repeat the check. Degrades to
7
+ * allow under a bare host shell (useAccessOptional's contract).
8
+ */
9
+ export function useCanArchive(): boolean {
10
+ return useAccessOptional().can('sales', 'delete').allowed
11
+ }