@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 { createContext, useCallback, useContext, useMemo, useState, type ReactNode } from 'react'
2
- import { LeadSubmitError, type LeadFields, type LeadSubmitResult, type PublicFormDef } from './types'
2
+ import { LeadSubmitError, type LeadFields, type LeadSubmitOptions, type LeadSubmitResult, type PublicFormDef } from './types'
3
3
 
4
4
  interface PublicFormsContextValue {
5
5
  forms: Map<string, PublicFormDef>
6
- submit: (formId: string, values: LeadFields) => Promise<LeadSubmitResult>
6
+ submit: (formId: string, values: LeadFields, options?: LeadSubmitOptions) => Promise<LeadSubmitResult>
7
7
  }
8
8
 
9
9
  const PublicFormsContext = createContext<PublicFormsContextValue | null>(null)
@@ -30,12 +30,12 @@ export function useLeadForm(formId: string) {
30
30
  const [result, setResult] = useState<LeadSubmitResult | null>(null)
31
31
 
32
32
  const submit = useCallback(
33
- async (values: LeadFields): Promise<LeadSubmitResult | null> => {
33
+ async (values: LeadFields, options?: LeadSubmitOptions): Promise<LeadSubmitResult | null> => {
34
34
  if (submitting) return null
35
35
  setSubmitting(true)
36
36
  setError(null)
37
37
  try {
38
- const res = await ctx.submit(formId, values)
38
+ const res = await ctx.submit(formId, values, options)
39
39
  setResult(res)
40
40
  return res
41
41
  } catch (err) {
@@ -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
 
@@ -11,7 +11,7 @@
11
11
  // The RPC never reads back — a form writes, it does not query the CRM.
12
12
  // ---------------------------------------------------------------------------
13
13
 
14
- import { getFayzCloudClient, getSupabaseClientOptional } from '@fayz-ai/core'
14
+ import { getSupabaseClientOptional } from '@fayz-ai/core'
15
15
  import { LeadSubmitError, type PublicLeadDataProvider } from './types'
16
16
 
17
17
  export interface SupabasePublicLeadOptions {
@@ -24,7 +24,7 @@ interface SupabaseLikeClient {
24
24
  }
25
25
 
26
26
  function getClient(): SupabaseLikeClient | null {
27
- return (getSupabaseClientOptional() ?? getFayzCloudClient()) as SupabaseLikeClient | null
27
+ return getSupabaseClientOptional() as SupabaseLikeClient | null
28
28
  }
29
29
 
30
30
  /** Map the RPC's RAISE EXCEPTION messages onto kinds the site can branch on. */
@@ -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
  ],
@@ -62,11 +67,21 @@ const activityTypeEntity: EntityDef = {
62
67
  defaultSort: 'name',
63
68
  fields: [
64
69
  { key: 'name', label: 'Name', type: 'text', required: true, showInTable: true },
65
- { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true },
70
+ { key: 'icon', label: 'Icon', type: 'text', showInTable: true },
71
+ { key: 'isActive', label: 'Active', type: 'boolean', showInTable: true, defaultValue: true, inlineToggle: true },
66
72
  ],
67
73
  data: { table: T.activityTypes, tenantScoped: true },
68
74
  }
69
75
 
76
+ export const DEFAULT_ACTIVITY_TYPES: Array<{ value: string; label: string; icon?: string }> = [
77
+ { value: 'call', label: 'Call', icon: 'Phone' },
78
+ { value: 'email', label: 'Email', icon: 'Mail' },
79
+ { value: 'meeting', label: 'Meeting', icon: 'Users' },
80
+ { value: 'note', label: 'Note', icon: 'FileText' },
81
+ { value: 'task', label: 'Task', icon: 'CheckSquare' },
82
+ { value: 'whatsapp', label: 'WhatsApp', icon: 'MessageCircle' },
83
+ ]
84
+
70
85
  export const crmRegistries: PluginRegistryDef[] = [
71
86
  {
72
87
  id: 'stages',
@@ -104,10 +119,14 @@ export const crmRegistries: PluginRegistryDef[] = [
104
119
  icon: 'Tag',
105
120
  description: 'Tags for organizing leads and deals',
106
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.
107
126
  seedData: [
108
- { id: 'tag-vip', name: 'VIP', color: '#f59e0b', isActive: true },
109
- { id: 'tag-hot', name: 'Hot Lead', color: '#ef4444', isActive: true },
110
- { 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 },
111
130
  ],
112
131
  },
113
132
  {
@@ -116,14 +135,28 @@ export const crmRegistries: PluginRegistryDef[] = [
116
135
  icon: 'MessageCircle',
117
136
  description: 'Types of activities and interactions',
118
137
  display: 'table',
119
- readOnly: true,
138
+ // Tenant-editable (the provider lazily seeds the app's set per tenant);
139
+ // system timeline events (lead_created, stage_changed…) are product-defined
140
+ // and never appear here.
120
141
  seedData: [
121
- { id: 'at-call', name: 'Call', isActive: true },
122
- { id: 'at-email', name: 'Email', isActive: true },
123
- { id: 'at-meeting', name: 'Meeting', isActive: true },
124
- { id: 'at-note', name: 'Note', isActive: true },
125
- { id: 'at-task', name: 'Task', isActive: true },
126
- { id: 'at-whatsapp', name: 'WhatsApp', isActive: true },
142
+ ...DEFAULT_ACTIVITY_TYPES.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
127
143
  ],
128
144
  },
129
145
  ]
146
+
147
+ /** Registries with the app's activity-type set replacing the default seed. */
148
+ export function buildCrmRegistries(
149
+ activityTypes?: Array<{ value: string; label: string; icon?: string }>,
150
+ ): PluginRegistryDef[] {
151
+ if (!activityTypes?.length) return crmRegistries
152
+ return crmRegistries.map((registry) =>
153
+ registry.id === 'activity-types'
154
+ ? {
155
+ ...registry,
156
+ seedData: [
157
+ ...activityTypes.map((t) => ({ id: `at-${t.value}`, name: t.label, icon: t.icon, isActive: true })),
158
+ ],
159
+ }
160
+ : registry,
161
+ )
162
+ }
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,14 +28,21 @@ 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>
44
+ /** Re-fetch the timeline with the last query — writes append system events. */
45
+ refreshActivities(): Promise<void>
39
46
  fetchQuotes(query: QuoteQuery): Promise<void>
40
47
  createLead(input: CreateLeadInput): Promise<Lead>
41
48
  createDeal(input: CreateDealInput): Promise<Deal>
@@ -47,9 +54,15 @@ export interface CrmUIState {
47
54
  rejectQuote(id: string, reason: string): Promise<Quote>
48
55
  expireQuote(id: string): Promise<Quote>
49
56
  moveDealToStage(dealId: string, stageId: string): Promise<void>
57
+ archiveDeal(dealId: string): Promise<void>
58
+ archiveLead(leadId: string): Promise<void>
59
+ archiveQuote(quoteId: string): Promise<void>
50
60
  }
51
61
 
52
62
  export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState> {
63
+ let lastActivitiesQuery: ActivityQuery = {}
64
+ /** Pipeline + recorte do último carregamento do quadro (ver refreshBoard). */
65
+ let lastBoard: { pipelineId: string; filter?: BoardFilter } | null = null
53
66
  return createStore<CrmUIState>((set, get) => ({
54
67
  pipelines: [], stages: [],
55
68
  leads: [], leadsTotal: 0, leadsLoading: false,
@@ -59,6 +72,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
59
72
  quotes: [], quotesTotal: 0, quotesLoading: false,
60
73
  summary: null, summaryLoading: false,
61
74
  funnel: [],
75
+ tagDefs: new Map(),
62
76
 
63
77
  async fetchPipelines() {
64
78
  return dedup('crm:pipelines', async () => {
@@ -68,6 +82,21 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
68
82
  })
69
83
  },
70
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
+
71
100
  async fetchSummary() {
72
101
  return dedup('crm:summary', async () => {
73
102
  set({ summaryLoading: true })
@@ -99,15 +128,32 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
99
128
  })
100
129
  },
101
130
 
102
- async fetchDealsByStage(pipelineId) {
103
- 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 () => {
104
140
  set({ dealsLoading: true })
105
- const dealsByStage = await provider.getDealsByStage(pipelineId)
141
+ const dealsByStage = await provider.getDealsByStage(pipelineId, filter)
106
142
  set({ dealsByStage, dealsLoading: false })
107
143
  })
108
144
  },
109
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
+
110
155
  async fetchActivities(query) {
156
+ lastActivitiesQuery = query
111
157
  return dedup('crm:activities:' + JSON.stringify(query), async () => {
112
158
  set({ activitiesLoading: true })
113
159
  const result = await provider.getActivities(query)
@@ -115,6 +161,13 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
115
161
  })
116
162
  },
117
163
 
164
+ async refreshActivities() {
165
+ try {
166
+ const result = await provider.getActivities(lastActivitiesQuery)
167
+ set({ activities: result.data, activitiesTotal: result.total })
168
+ } catch { /* timeline refresh is best-effort */ }
169
+ },
170
+
118
171
  async fetchQuotes(query) {
119
172
  return dedup('crm:quotes:' + JSON.stringify(query), async () => {
120
173
  set({ quotesLoading: true })
@@ -155,6 +208,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
155
208
 
156
209
  const summary = await provider.getSummary()
157
210
  set({ summary })
211
+ void get().refreshActivities()
158
212
  toast.success('Lead captured')
159
213
  return lead
160
214
  } catch (err: any) {
@@ -168,6 +222,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
168
222
  const deal = await provider.createDeal(input)
169
223
  const [summary] = await Promise.all([provider.getSummary()])
170
224
  set({ summary })
225
+ void get().refreshActivities()
171
226
  toast.success('Deal created')
172
227
  return deal
173
228
  } catch (err: any) {
@@ -265,12 +320,10 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
265
320
 
266
321
  // Refresh local state — quotes + pipeline
267
322
  set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }))
268
- if (defaultPipeline) {
269
- try {
270
- const dealsByStage = await provider.getDealsByStage(defaultPipeline.id)
271
- set({ dealsByStage })
272
- } catch { /* non-blocking */ }
273
- }
323
+ try {
324
+ await get().refreshBoard()
325
+ } catch { /* non-blocking */ }
326
+ void get().refreshActivities()
274
327
  toast.success('Quote created')
275
328
  return quote
276
329
  } catch (err: any) {
@@ -295,6 +348,7 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
295
348
  try {
296
349
  const quote = await provider.sendQuote(id)
297
350
  set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }))
351
+ void get().refreshActivities()
298
352
  toast.success('Quote sent')
299
353
  return quote
300
354
  } catch (err: any) {
@@ -306,17 +360,16 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
306
360
  async approveQuote(id) {
307
361
  try {
308
362
  const quote = await provider.approveQuote(id)
309
- // Full refresh — cascades touch deals, leads, quotes, creates invoice
310
- const { pipelines } = get()
311
- if (pipelines.length > 0) {
312
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
313
- provider.getDealsByStage(pipelines[0].id),
314
- provider.getSummary(),
315
- provider.getLeads({}),
316
- provider.getQuotes({}),
317
- ])
318
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
319
- }
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 })
372
+ void get().refreshActivities()
320
373
  toast.success('Quote approved — invoice created')
321
374
  return quote
322
375
  } catch (err: any) {
@@ -328,16 +381,14 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
328
381
  async rejectQuote(id, reason) {
329
382
  try {
330
383
  const quote = await provider.rejectQuote(id, reason)
331
- const { pipelines } = get()
332
- if (pipelines.length > 0) {
333
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
334
- provider.getDealsByStage(pipelines[0].id),
335
- provider.getSummary(),
336
- provider.getLeads({}),
337
- provider.getQuotes({}),
338
- ])
339
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
340
- }
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 })
391
+ void get().refreshActivities()
341
392
  toast.success('Quote rejected')
342
393
  return quote
343
394
  } catch (err: any) {
@@ -360,15 +411,61 @@ export function createCrmStore(provider: CrmDataProvider): StoreApi<CrmUIState>
360
411
 
361
412
  async moveDealToStage(dealId, stageId) {
362
413
  await provider.moveDealToStage(dealId, stageId)
363
- const { pipelines } = get()
364
- if (pipelines.length > 0) {
365
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
366
- provider.getDealsByStage(pipelines[0].id),
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()
419
+ void get().refreshActivities()
420
+ },
421
+
422
+ async archiveDeal(dealId) {
423
+ try {
424
+ await provider.archiveDeal(dealId)
425
+ const [, summary] = await Promise.all([
426
+ get().refreshBoard(),
367
427
  provider.getSummary(),
428
+ ])
429
+ set({ summary })
430
+ void get().refreshActivities()
431
+ toast.success('Deal archived')
432
+ } catch (err: any) {
433
+ toast.error('Failed to archive deal', { description: err?.message })
434
+ throw err
435
+ }
436
+ },
437
+
438
+ async archiveLead(leadId) {
439
+ try {
440
+ await provider.archiveLead(leadId)
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([
368
444
  provider.getLeads({}),
369
- provider.getQuotes({}),
445
+ provider.getSummary(),
446
+ get().refreshBoard(),
370
447
  ])
371
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total })
448
+ set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary })
449
+ void get().refreshActivities()
450
+ toast.success('Lead archived')
451
+ } catch (err: any) {
452
+ toast.error('Failed to archive lead', { description: err?.message })
453
+ throw err
454
+ }
455
+ },
456
+
457
+ async archiveQuote(quoteId) {
458
+ try {
459
+ await provider.archiveQuote(quoteId)
460
+ set((state) => ({
461
+ quotes: state.quotes.filter((q) => q.id !== quoteId),
462
+ quotesTotal: Math.max(0, state.quotesTotal - 1),
463
+ }))
464
+ void get().refreshActivities()
465
+ toast.success('Quote archived')
466
+ } catch (err: any) {
467
+ toast.error('Failed to archive quote', { description: err?.message })
468
+ throw err
372
469
  }
373
470
  },
374
471
  }))
package/src/types.ts CHANGED
@@ -8,10 +8,46 @@
8
8
  // ============================================================
9
9
 
10
10
  export type LeadStatus = 'new' | 'contacted' | 'qualified' | 'unqualified' | 'converted' | 'lost'
11
- export type DealStatus = 'open' | 'won' | 'lost'
12
- export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired'
11
+ export type DealStatus = 'open' | 'won' | 'lost' | 'archived'
12
+ export type QuoteStatus = 'draft' | 'sent' | 'approved' | 'rejected' | 'expired' | 'archived'
13
13
  export type ActivityType = 'call' | 'email' | 'meeting' | 'note' | 'task' | 'whatsapp' | (string & {})
14
14
 
15
+ /** System timeline events auto-logged by the data provider at every CRM write.
16
+ * Product-defined (not tenant-editable); manual interaction TYPES live in the
17
+ * activity-types registry and are editable in settings. */
18
+ export const SYSTEM_ACTIVITY_TYPES = [
19
+ 'lead_created', 'lead_converted', 'lead_archived', 'deal_created', 'stage_changed',
20
+ 'deal_won', 'deal_lost', 'deal_archived', 'quote_created', 'quote_sent', 'quote_approved', 'quote_rejected', 'quote_archived',
21
+ ] as const
22
+ export type SystemActivityType = (typeof SYSTEM_ACTIVITY_TYPES)[number]
23
+
24
+ /** A tenant-editable manual interaction type (activity-types registry row). */
25
+ export interface ActivityTypeDef {
26
+ id: string
27
+ name: string
28
+ icon?: string
29
+ isActive: boolean
30
+ }
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
+
15
51
  // ============================================================
16
52
  // CORE ENTITIES
17
53
  // ============================================================
@@ -231,6 +267,27 @@ export interface DealQuery {
231
267
  pageSize?: number
232
268
  }
233
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
+
234
291
  export interface ActivityQuery {
235
292
  dealId?: string
236
293
  leadId?: string