@fayz-ai/plugin-crm 0.8.4 → 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 (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
@@ -21,6 +21,7 @@ import {
21
21
  type LeadAttribution,
22
22
  type LeadFields,
23
23
  type LeadNotifier,
24
+ type LeadSubmitOptions,
24
25
  type LeadSubmitResult,
25
26
  type PublicFormDef,
26
27
  type PublicLeadDataProvider,
@@ -43,15 +44,78 @@ export interface PublicFormsOptions {
43
44
  dataProvider?: PublicLeadDataProvider
44
45
  /** Inject a custom notifier (tests). */
45
46
  notifier?: LeadNotifier
47
+ /**
48
+ * Marca o lead com a campanha que o trouxe, lendo a UTM da URL.
49
+ *
50
+ * Sai com NAMESPACE (`camp:promo-verao`, `src:instagram`) de propósito: tag
51
+ * automática e tag curada convivem no mesmo array, e sem prefixo a primeira
52
+ * engole a segunda — em seis meses ninguém sabe mais quais tags alguém
53
+ * escolheu e quais uma querystring inventou. Com prefixo dá para filtrar,
54
+ * relatar e limpar cada grupo separadamente.
55
+ *
56
+ * `campaign` liga por padrão: é o eixo que o marketing pergunta. `source` fica
57
+ * desligado porque utm_source costuma ser alto-cardinal e vira ruído no card.
58
+ */
59
+ campaignTags?: boolean | { campaign?: boolean; source?: boolean }
46
60
  scope?: PluginScope
47
61
  verticalId?: VerticalId
48
62
  }
49
63
 
64
+ /** Teto por lead — o mesmo que o RPC aplica; aparar aqui evita mandar lixo. */
65
+ const MAX_TAGS = 10
66
+
67
+ /**
68
+ * Slug normalizado. O servidor normaliza de novo (é ele quem manda), mas fazer
69
+ * aqui também mantém `camp:` legível e evita gastar as 10 vagas com duplicata.
70
+ */
71
+ function slugify(input: string): string {
72
+ return input
73
+ .normalize('NFD')
74
+ // Marcas combinantes: o NFD separa o acento da letra, e este range remove
75
+ // só o acento. Escapado em vez de literal — o caractere cru é invisível no
76
+ // editor e some em qualquer copy-paste.
77
+ .replace(/[\u0300-\u036f]/g, '')
78
+ .toLowerCase()
79
+ .replace(/[^a-z0-9:]+/g, '-')
80
+ .replace(/-{2,}/g, '-')
81
+ .replace(/^-+|-+$/g, '')
82
+ }
83
+
84
+ /** Tags curadas do formulário + as automáticas da campanha, deduplicadas. */
85
+ function resolveTags(
86
+ formTags: string[] | undefined,
87
+ callTags: string[] | undefined,
88
+ attribution: LeadAttribution,
89
+ campaignTags: PublicFormsOptions['campaignTags'],
90
+ ): string[] {
91
+ const cfg =
92
+ campaignTags === false
93
+ ? { campaign: false, source: false }
94
+ : campaignTags === true || campaignTags === undefined
95
+ ? { campaign: true, source: false }
96
+ : { campaign: campaignTags.campaign ?? true, source: campaignTags.source ?? false }
97
+
98
+ const out: string[] = []
99
+ for (const raw of [...(formTags ?? []), ...(callTags ?? [])]) {
100
+ const slug = slugify(raw)
101
+ if (slug) out.push(slug)
102
+ }
103
+ if (cfg.campaign && attribution.utm_campaign) {
104
+ const slug = slugify(attribution.utm_campaign)
105
+ if (slug) out.push(`camp:${slug}`)
106
+ }
107
+ if (cfg.source && attribution.utm_source) {
108
+ const slug = slugify(attribution.utm_source)
109
+ if (slug) out.push(`src:${slug}`)
110
+ }
111
+ return [...new Set(out)].slice(0, MAX_TAGS)
112
+ }
113
+
50
114
  export interface PublicFormsPlugin {
51
115
  manifest: PluginManifest
52
116
  Provider: FC<{ children: ReactNode }>
53
117
  /** Imperative submit, for code paths outside React. */
54
- submit(formId: string, values: LeadFields): Promise<LeadSubmitResult>
118
+ submit(formId: string, values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult>
55
119
  }
56
120
 
57
121
  /** Reads UTM + page context off the browser. Safe to call during SSR. */
@@ -94,7 +158,11 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
94
158
  ? null
95
159
  : createFayzInboxNotifier(typeof options.inbox === 'object' ? options.inbox : {}))
96
160
 
97
- async function submit(formId: string, values: LeadFields): Promise<LeadSubmitResult> {
161
+ async function submit(
162
+ formId: string,
163
+ values: LeadFields,
164
+ submitOptions?: LeadSubmitOptions,
165
+ ): Promise<LeadSubmitResult> {
98
166
  const form = formsById.get(formId)
99
167
  if (!form) {
100
168
  throw new LeadSubmitError('validation', `[plugin-crm/public] unknown form "${formId}".`)
@@ -123,6 +191,7 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
123
191
  )
124
192
 
125
193
  const attribution = readAttribution()
194
+ const tags = resolveTags(form.tags, submitOptions?.tags, attribution, options.campaignTags)
126
195
 
127
196
  // 1. CRM — if this throws, the submission failed and the site says so.
128
197
  const { leadId, createdAt } = await provider.createLead(
@@ -135,6 +204,7 @@ export function createPublicFormsPlugin(options: PublicFormsOptions): PublicForm
135
204
  notes: notes || undefined,
136
205
  fields,
137
206
  attribution,
207
+ tags: tags.length ? tags : undefined,
138
208
  }),
139
209
  )
140
210
 
@@ -72,6 +72,7 @@ export function createSupabasePublicLeadProvider(
72
72
  p_fields: input.fields,
73
73
  p_notes: input.notes ?? null,
74
74
  p_utm: input.attribution,
75
+ p_tags: input.tags ?? [],
75
76
  })
76
77
 
77
78
  if (error) throw toSubmitError(error.message)
@@ -46,6 +46,32 @@ export interface PublicFormDef {
46
46
  }
47
47
  /** Labels for custom fields, so the CRM shows "Faixa etária" not "age_range". */
48
48
  labels?: Record<string, string>
49
+ /**
50
+ * Tags every lead from this form carries into the CRM, and from there onto
51
+ * the card no funil (o trigger de lead→deal copia).
52
+ *
53
+ * Isto é o vocabulário CURADO: o que a landing page É ("aluno-novo",
54
+ * "parceria"), não de qual campanha veio. Escreva em slug; o servidor
55
+ * normaliza de qualquer jeito (minúscula, sem acento, hifenizado) e descarta
56
+ * o que não der para normalizar em vez de derrubar o envio.
57
+ *
58
+ * Máximo de 10 tags por lead, somando estas e as automáticas.
59
+ */
60
+ tags?: string[]
61
+ }
62
+
63
+ /**
64
+ * O que a PÁGINA decide na hora do envio, e o formulário não sabe de antemão.
65
+ *
66
+ * Existe porque uma landing page costuma ter mais de uma porta de entrada para
67
+ * o mesmo formulário (a home e uma campanha específica levam ao mesmo
68
+ * `/quero-ser-aluno`). Sem isto, distinguir as duas exigiria declarar um
69
+ * formulário por porta, e cada um vira uma "origem" diferente no CRM para o que
70
+ * é o mesmo formulário.
71
+ */
72
+ export interface LeadSubmitOptions {
73
+ /** Somadas às `tags` do formulário e às automáticas da campanha. */
74
+ tags?: string[]
49
75
  }
50
76
 
51
77
  /** Result of a submission — enough for the site to show its own success state. */
@@ -95,6 +121,8 @@ export interface PublicLeadDataProvider {
95
121
  notes?: string
96
122
  fields: LeadFields
97
123
  attribution: LeadAttribution
124
+ /** Slugs já resolvidos (curados do formulário + automáticos da campanha). */
125
+ tags?: string[]
98
126
  }): Promise<{ leadId: string; createdAt: string }>
99
127
  }
100
128
 
package/src/registries.ts CHANGED
@@ -23,6 +23,11 @@ const tagEntity: EntityDef = {
23
23
  defaultSort: 'name',
24
24
  fields: [
25
25
  { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
26
+ // O slug é o que vive em people.tags/orders.tags — renomear a tag NÃO o
27
+ // muda (o trigger só o deriva quando está vazio), e é por isso que renomear
28
+ // não órfã registro. Exposto porque, quando um chip não aparece onde
29
+ // deveria, a resposta está sempre aqui.
30
+ { key: 'slug', label: 'Slug', type: 'text', showInTable: true },
26
31
  { key: 'color', label: 'Color', type: 'color', showInTable: true, defaultValue: '#6366f1' },
27
32
  { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true },
28
33
  ],
@@ -114,10 +119,14 @@ export const crmRegistries: PluginRegistryDef[] = [
114
119
  icon: 'Tag',
115
120
  description: 'Tags for organizing leads and deals',
116
121
  display: 'table',
122
+ // Só alimenta o provider MOCK (apps sem Supabase). Contra o banco, o
123
+ // cadastro se alimenta do uso: `crm_register_tags` insere a linha quando
124
+ // uma tag é gravada num lead. Semear vocabulário aqui encheria a tela de
125
+ // tags que nenhum registro carrega.
117
126
  seedData: [
118
- { id: 'tag-vip', name: 'VIP', color: '#f59e0b', isActive: true },
119
- { id: 'tag-hot', name: 'Hot Lead', color: '#ef4444', isActive: true },
120
- { id: 'tag-followup', name: 'Follow-up', color: '#3b82f6', isActive: true },
127
+ { id: 'tag-vip', name: 'VIP', slug: 'vip', color: '#f59e0b', isActive: true },
128
+ { id: 'tag-hot', name: 'Hot Lead', slug: 'hot-lead', color: '#ef4444', isActive: true },
129
+ { id: 'tag-followup', name: 'Follow-up', slug: 'follow-up', color: '#3b82f6', isActive: true },
121
130
  ],
122
131
  },
123
132
  {
package/src/store.ts CHANGED
@@ -3,7 +3,7 @@ import { dedup } from '@fayz-ai/saas'
3
3
  import { toast } from '@fayz-ai/ui'
4
4
  import type { CrmDataProvider } from './data/types'
5
5
  import type {
6
- Pipeline, PipelineStage, Lead, Deal, Activity, Quote,
6
+ Pipeline, PipelineStage, Lead, Deal, Activity, Quote, TagDef, BoardFilter,
7
7
  CrmSummary, FunnelStage,
8
8
  LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
9
9
  CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
@@ -28,13 +28,18 @@ export interface CrmUIState {
28
28
  summary: CrmSummary | null
29
29
  summaryLoading: boolean
30
30
  funnel: FunnelStage[]
31
+ /** Cadastro de tags, por slug — rótulo e cor dos chips. */
32
+ tagDefs: Map<string, TagDef>
31
33
 
32
34
  fetchPipelines(): Promise<void>
35
+ fetchTagDefs(): Promise<void>
33
36
  fetchSummary(): Promise<void>
34
37
  fetchFunnel(pipelineId: string): Promise<void>
35
38
  fetchLeads(query: LeadQuery): Promise<void>
36
39
  fetchDeals(query: DealQuery): Promise<void>
37
- fetchDealsByStage(pipelineId: string): Promise<void>
40
+ fetchDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<void>
41
+ /** Recarrega o quadro no MESMO recorte do último fetchDealsByStage. */
42
+ refreshBoard(): Promise<void>
38
43
  fetchActivities(query: ActivityQuery): Promise<void>
39
44
  /** Re-fetch the timeline with the last query — writes append system events. */
40
45
  refreshActivities(): Promise<void>
@@ -56,6 +61,8 @@ export interface CrmUIState {
56
61
 
57
62
  export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState> {
58
63
  let lastActivitiesQuery: ActivityQuery = {}
64
+ /** Pipeline + recorte do último carregamento do quadro (ver refreshBoard). */
65
+ let lastBoard: { pipelineId: string; filter?: BoardFilter } | null = null
59
66
  return createStore<CrmUIState>((set, get) => ({
60
67
  pipelines: [], stages: [],
61
68
  leads: [], leadsTotal: 0, leadsLoading: false,
@@ -65,6 +72,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
65
72
  quotes: [], quotesTotal: 0, quotesLoading: false,
66
73
  summary: null, summaryLoading: false,
67
74
  funnel: [],
75
+ tagDefs: new Map(),
68
76
 
69
77
  async fetchPipelines() {
70
78
  return dedup('crm:pipelines', async () => {
@@ -74,6 +82,21 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
74
82
  })
75
83
  },
76
84
 
85
+ async fetchTagDefs() {
86
+ return dedup('crm:tag-defs', async () => {
87
+ // Só apresentação: uma tag sem linha de cadastro ainda renderiza (chip
88
+ // neutro com o slug humanizado), então falhar aqui não pode esconder o
89
+ // card. Por isso o catch silencioso — ao contrário dos outros fetches,
90
+ // não há nada para o operador fazer com este erro.
91
+ try {
92
+ const defs = await provider.getTagDefs()
93
+ set({ tagDefs: new Map(defs.map((d) => [d.slug, d])) })
94
+ } catch {
95
+ /* chips caem no rótulo derivado do slug */
96
+ }
97
+ })
98
+ },
99
+
77
100
  async fetchSummary() {
78
101
  return dedup('crm:summary', async () => {
79
102
  set({ summaryLoading: true })
@@ -105,14 +128,30 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
105
128
  })
106
129
  },
107
130
 
108
- async fetchDealsByStage(pipelineId) {
109
- return dedup('crm:dealsByStage:' + pipelineId, async () => {
131
+ async fetchDealsByStage(pipelineId, filter) {
132
+ // Guardado para o refreshBoard: quem recarrega depois de uma escrita não
133
+ // sabe (nem deveria saber) qual recorte está na tela.
134
+ lastBoard = { pipelineId, filter }
135
+ // A chave do dedup inclui o filtro: sem isso, trocar o período enquanto a
136
+ // busca anterior está no ar seria descartado como duplicata e o quadro
137
+ // ficaria mostrando o recorte antigo.
138
+ const key = 'crm:dealsByStage:' + pipelineId + ':' + JSON.stringify(filter ?? {})
139
+ return dedup(key, async () => {
110
140
  set({ dealsLoading: true })
111
- const dealsByStage = await provider.getDealsByStage(pipelineId)
141
+ const dealsByStage = await provider.getDealsByStage(pipelineId, filter)
112
142
  set({ dealsByStage, dealsLoading: false })
113
143
  })
114
144
  },
115
145
 
146
+ async refreshBoard() {
147
+ // O ÚNICO caminho de recarga do quadro depois de uma escrita. Cada ação
148
+ // chamava `getDealsByStage(pipelines[0].id)` na mão, sem filtro: mover um
149
+ // card devolvia o quadro inteiro por cima do recorte que a pessoa tinha
150
+ // escolhido, e o filtro parecia ter se perdido sozinho.
151
+ if (!lastBoard) return
152
+ return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter)
153
+ },
154
+
116
155
  async fetchActivities(query) {
117
156
  lastActivitiesQuery = query
118
157
  return dedup('crm:activities:' + JSON.stringify(query), async () => {
@@ -281,12 +320,9 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
281
320
 
282
321
  // Refresh local state — quotes + pipeline
283
322
  set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }))
284
- if (defaultPipeline) {
285
- try {
286
- const dealsByStage = await provider.getDealsByStage(defaultPipeline.id)
287
- set({ dealsByStage })
288
- } catch { /* non-blocking */ }
289
- }
323
+ try {
324
+ await get().refreshBoard()
325
+ } catch { /* non-blocking */ }
290
326
  void get().refreshActivities()
291
327
  toast.success('Quote created')
292
328
  return quote
@@ -324,17 +360,15 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
324
360
  async approveQuote(id) {
325
361
  try {
326
362
  const quote = await provider.approveQuote(id)
327
- // Full refresh — cascades touch deals, leads, quotes, creates invoice
328
- const { pipelines } = get()
329
- if (pipelines.length > 0) {
330
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
331
- provider.getDealsByStage(pipelines[0].id),
332
- provider.getSummary(),
333
- provider.getLeads({}),
334
- provider.getQuotes({}),
335
- ])
336
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
337
- }
363
+ // Full refresh — cascades touch deals, leads, quotes, creates invoice.
364
+ // O quadro entra pelo refreshBoard para não perder o recorte da tela.
365
+ const [summary, leadsResult, quotesResult] = await Promise.all([
366
+ provider.getSummary(),
367
+ provider.getLeads({}),
368
+ provider.getQuotes({}),
369
+ get().refreshBoard(),
370
+ ])
371
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
338
372
  void get().refreshActivities()
339
373
  toast.success('Quote approved — invoice created')
340
374
  return quote
@@ -347,16 +381,13 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
347
381
  async rejectQuote(id, reason) {
348
382
  try {
349
383
  const quote = await provider.rejectQuote(id, reason)
350
- const { pipelines } = get()
351
- if (pipelines.length > 0) {
352
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
353
- provider.getDealsByStage(pipelines[0].id),
354
- provider.getSummary(),
355
- provider.getLeads({}),
356
- provider.getQuotes({}),
357
- ])
358
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
359
- }
384
+ const [summary, leadsResult, quotesResult] = await Promise.all([
385
+ provider.getSummary(),
386
+ provider.getLeads({}),
387
+ provider.getQuotes({}),
388
+ get().refreshBoard(),
389
+ ])
390
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
360
391
  void get().refreshActivities()
361
392
  toast.success('Quote rejected')
362
393
  return quote
@@ -380,30 +411,22 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
380
411
 
381
412
  async moveDealToStage(dealId, stageId) {
382
413
  await provider.moveDealToStage(dealId, stageId)
383
- const { pipelines } = get()
384
- if (pipelines.length > 0) {
385
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
386
- provider.getDealsByStage(pipelines[0].id),
387
- provider.getSummary(),
388
- provider.getLeads({}),
389
- provider.getQuotes({}),
390
- ])
391
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
392
- }
414
+ // Só o quadro. Arrastar um card entre etapas não muda a lista de leads nem
415
+ // a de orçamentos, e o resumo não está na tela — buscar os quatro fazia de
416
+ // cada arrastar quatro viagens, três delas para dados que ninguém olhava.
417
+ // Quem renderiza aquelas listas as recarrega ao montar.
418
+ await get().refreshBoard()
393
419
  void get().refreshActivities()
394
420
  },
395
421
 
396
422
  async archiveDeal(dealId) {
397
423
  try {
398
424
  await provider.archiveDeal(dealId)
399
- const { pipelines } = get()
400
- if (pipelines.length > 0) {
401
- const [dealsByStage, summary] = await Promise.all([
402
- provider.getDealsByStage(pipelines[0].id),
403
- provider.getSummary(),
404
- ])
405
- set({ dealsByStage, summary })
406
- }
425
+ const [, summary] = await Promise.all([
426
+ get().refreshBoard(),
427
+ provider.getSummary(),
428
+ ])
429
+ set({ summary })
407
430
  void get().refreshActivities()
408
431
  toast.success('Deal archived')
409
432
  } catch (err: any) {
@@ -415,16 +438,14 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
415
438
  async archiveLead(leadId) {
416
439
  try {
417
440
  await provider.archiveLead(leadId)
418
- const { pipelines } = get()
419
- const [leadsResult, summary, dealsByStage] = await Promise.all([
441
+ // Arquivar um lead tira o card do quadro também — mas no recorte que
442
+ // está na tela, não no quadro inteiro.
443
+ const [leadsResult, summary] = await Promise.all([
420
444
  provider.getLeads({}),
421
445
  provider.getSummary(),
422
- pipelines.length > 0 ? provider.getDealsByStage(pipelines[0].id) : Promise.resolve(null),
446
+ get().refreshBoard(),
423
447
  ])
424
- set({
425
- leads: leadsResult.data, leadsTotal: leadsResult.total, summary,
426
- ...(dealsByStage ? { dealsByStage } : {}),
427
- })
448
+ set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary })
428
449
  void get().refreshActivities()
429
450
  toast.success('Lead archived')
430
451
  } catch (err: any) {
package/src/types.ts CHANGED
@@ -29,6 +29,25 @@ export interface ActivityTypeDef {
29
29
  isActive: boolean
30
30
  }
31
31
 
32
+ /**
33
+ * Uma tag do cadastro (plg_crm_tags).
34
+ *
35
+ * `slug` é o contrato: é isso que vive em Lead.tags / Deal.tags. `name` e
36
+ * `color` são só apresentação, e por isso renomear uma tag no cadastro não
37
+ * toca em nenhum registro.
38
+ *
39
+ * Um slug SEM linha de cadastro continua sendo uma tag válida — a UI mostra o
40
+ * slug humanizado num chip neutro. É o que deixa uma campanha marcar leads hoje
41
+ * sem esperar alguém cadastrar a tag antes.
42
+ */
43
+ export interface TagDef {
44
+ id: string
45
+ slug: string
46
+ name: string
47
+ color?: string
48
+ isActive: boolean
49
+ }
50
+
32
51
  // ============================================================
33
52
  // CORE ENTITIES
34
53
  // ============================================================
@@ -248,6 +267,27 @@ export interface DealQuery {
248
267
  pageSize?: number
249
268
  }
250
269
 
270
+ /** Presets de período do funil. `custom` usa `createdFrom`/`createdTo`. */
271
+ export type BoardPeriod = 'all' | '24h' | '7d' | 'custom'
272
+
273
+ /**
274
+ * Filtro do quadro do funil.
275
+ *
276
+ * Vazio = quadro inteiro, que é o estado em que ele abre. Um funil filtrado por
277
+ * padrão esconde negócio sem avisar, e a pessoa conclui que o card sumiu.
278
+ */
279
+ export interface BoardFilter {
280
+ /**
281
+ * Slugs. Semântica OU: marcar duas tags mostra quem tem QUALQUER uma delas.
282
+ * É o que um multi-select de chips dá a entender ("me mostra estes
283
+ * segmentos"); E seria uma interseção que quase sempre volta vazia.
284
+ */
285
+ tags?: string[]
286
+ /** ISO. Filtram por `created_at` do negócio. */
287
+ createdFrom?: string
288
+ createdTo?: string
289
+ }
290
+
251
291
  export interface ActivityQuery {
252
292
  dealId?: string
253
293
  leadId?: string
@@ -3,8 +3,9 @@ import { Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Calend
3
3
  import { useTranslation } from '@fayz-ai/core'
4
4
  import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription, SegmentedControl } from '@fayz-ai/ui'
5
5
  import { PersonLink } from '@fayz-ai/saas'
6
- import { useCrmProvider, useCrmConfig, formatCurrency } from '../CrmContext'
6
+ import { useCrmProvider, useCrmConfig, useCrmStore, formatCurrency } from '../CrmContext'
7
7
  import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
8
+ import { TagChips } from '../components/TagChips'
8
9
  import { answerEntries, humanizeKey, renderFieldValue } from '../lib/form-answers'
9
10
  import type { Deal, Lead, Quote, Activity } from '../types'
10
11
 
@@ -93,6 +94,11 @@ function FormAnswers({ lead }: { lead: Lead | null }) {
93
94
  function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null; currency: { code: string; locale: string; symbol: string } }) {
94
95
  const t = useTranslation()
95
96
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase()
97
+ // O painel também abre a partir do detalhe do lead, onde o board nunca
98
+ // montou — por isso busca por conta própria em vez de herdar do funil.
99
+ const tagDefs = useCrmStore((s) => s.tagDefs)
100
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs)
101
+ useEffect(() => { fetchTagDefs() }, [])
96
102
 
97
103
  return (
98
104
  <div className="space-y-5">
@@ -180,11 +186,8 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
180
186
  {deal.tags && deal.tags.length > 0 && (
181
187
  <div className="space-y-2">
182
188
  <h4 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{t('crm.dealSidebar.tags')}</h4>
183
- <div className="flex gap-1.5 flex-wrap">
184
- {deal.tags.map((tag) => (
185
- <span key={tag} className="inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground">{tag}</span>
186
- ))}
187
- </div>
189
+ {/* Sem `max`: no detalhe cabe tudo. É o card do funil que resume. */}
190
+ <TagChips tags={deal.tags} defs={tagDefs} size="sm" className="gap-1.5" />
188
191
  </div>
189
192
  )}
190
193