@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
@@ -1,12 +1,21 @@
1
- import React, { useEffect, useRef, useState } from 'react'
1
+ import React, { useEffect, useMemo, useRef, useState } from 'react'
2
2
  import { Archive, Loader2, Plus } from 'lucide-react'
3
3
  import { toast } from '@fayz-ai/ui'
4
4
  import { useCrmStore, useCrmConfig, formatCurrency } from '../CrmContext'
5
5
  import { useCanArchive } from '../lib/access'
6
- import { useTranslation, getSupabaseClientOptional } from '@fayz-ai/core'
6
+ import { useTranslation, getSupabaseClientOptional, useActiveTenantId } from '@fayz-ai/core'
7
7
  import { SubpageHeader } from '@fayz-ai/ui'
8
8
  import { DealSidebar } from './DealSidebar'
9
- import type { Deal } from '../types'
9
+ import { TagChips } from '../components/TagChips'
10
+ import { BoardFilters, periodToRange } from '../components/BoardFilters'
11
+ import type { BoardPeriod, Deal, TagDef } from '../types'
12
+
13
+ /** Uma data em YYYY-MM-DD, no fuso de quem está olhando (o DatePicker fala isso). */
14
+ function localDate(offsetDays = 0): string {
15
+ const d = new Date()
16
+ if (offsetDays) d.setDate(d.getDate() + offsetDays)
17
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
18
+ }
10
19
 
11
20
  // ---------------------------------------------------------------------------
12
21
  // Skeleton
@@ -44,10 +53,11 @@ function PipelineSkeleton() {
44
53
  // Deal card
45
54
  // ---------------------------------------------------------------------------
46
55
 
47
- function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onDragEnd }: {
56
+ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragStart, onDragEnd }: {
48
57
  deal: Deal
49
58
  saving?: boolean
50
59
  currency: { code: string; locale: string; symbol: string }
60
+ tagDefs?: Map<string, TagDef>
51
61
  onClick?: () => void
52
62
  /** Present only when the archive permission resolved true (useCanArchive). */
53
63
  onArchive?: () => void
@@ -77,6 +87,10 @@ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onD
77
87
  )}
78
88
  </div>
79
89
  {deal.contactName && <p className="text-[10px] text-muted-foreground mt-0.5">{deal.contactName}</p>}
90
+ {/* Teto de 3 no card: o funil se lê na diagonal, e uma pilha de chips
91
+ empurra valor e probabilidade para fora do primeiro olhar. O resto
92
+ vira "+N" e aparece inteiro no detalhe. */}
93
+ <TagChips tags={deal.tags} defs={tagDefs} max={3} className="mt-1.5" />
80
94
  <div className="flex items-center justify-between mt-2">
81
95
  <span className="text-xs font-semibold">{formatCurrency(deal.value, currency)}</span>
82
96
  <span className="text-[10px] text-muted-foreground">{deal.probability}%</span>
@@ -89,13 +103,14 @@ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onD
89
103
  // Stage column
90
104
  // ---------------------------------------------------------------------------
91
105
 
92
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }: {
106
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, tagDefs, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }: {
93
107
  stageId: string
94
108
  stageName: string
95
109
  stageColor: string
96
110
  deals: Deal[]
97
111
  savingDealIds: Set<string>
98
112
  currency: { code: string; locale: string; symbol: string }
113
+ tagDefs?: Map<string, TagDef>
99
114
  dragOverStageId: string | null
100
115
  onDealClick?: (id: string) => void
101
116
  onArchiveDeal?: (id: string) => void
@@ -148,6 +163,7 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
148
163
  deal={deal}
149
164
  saving={savingDealIds.has(deal.id)}
150
165
  currency={currency}
166
+ tagDefs={tagDefs}
151
167
  onClick={() => onDealClick?.(deal.id)}
152
168
  onArchive={onArchiveDeal ? () => onArchiveDeal(deal.id) : undefined}
153
169
  onDragStart={(e) => {
@@ -179,20 +195,58 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
179
195
  const dealsByStage = useCrmStore((s) => s.dealsByStage)
180
196
  const dealsLoading = useCrmStore((s) => s.dealsLoading)
181
197
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
198
+ const tagDefs = useCrmStore((s) => s.tagDefs)
199
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs)
182
200
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage)
201
+ const refreshBoard = useCrmStore((s) => s.refreshBoard)
183
202
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage)
184
203
  const archiveDeal = useCrmStore((s) => s.archiveDeal)
185
204
  const canArchive = useCanArchive()
186
205
 
206
+ const [period, setPeriod] = useState<BoardPeriod>('all')
207
+ // Hoje→hoje é o recorte mais estreito que existe: quem clica em
208
+ // "Personalizado" via o quadro esvaziar e tinha de mexer nos dois campos para
209
+ // ver qualquer coisa. Trinta dias é o passo natural depois de "7 dias" — a
210
+ // pessoa ajusta a partir de um recorte que já mostra algo.
211
+ const [customFrom, setCustomFrom] = useState(() => localDate(-30))
212
+ const [customTo, setCustomTo] = useState(() => localDate())
213
+ const [selectedTags, setSelectedTags] = useState<string[]>([])
187
214
  const [dragOverStageId, setDragOverStageId] = useState<string | null>(null)
188
215
  const [savingDealIds, setSavingDealIds] = useState<Set<string>>(new Set())
189
216
  const [optimisticBoard, setOptimisticBoard] = useState<Map<string, Deal[]> | null>(null)
190
217
  const t = useTranslation()
191
218
  const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
192
219
  const dragRef = useRef<{ dealId: string; fromStageId: string } | null>(null)
220
+ // O handler do realtime vive dentro de um effect keyed no pipeline: ler o
221
+ // estado por ref evita re-assinar o canal a cada card em voo.
222
+ const savingRef = useRef(savingDealIds)
223
+ savingRef.current = savingDealIds
224
+
225
+ // O filtro só existe como valor derivado: um estado separado guardando o
226
+ // mesmo recorte sairia de sincronia com os controles em alguma borda.
227
+ const boardFilter = useMemo(() => ({
228
+ ...(selectedTags.length ? { tags: selectedTags } : {}),
229
+ ...periodToRange(period, customFrom, customTo),
230
+ }), [selectedTags, period, customFrom, customTo])
231
+ const filterKey = JSON.stringify(boardFilter)
193
232
 
194
- useEffect(() => { fetchPipelines() }, [])
195
- useEffect(() => { if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id) }, [pipelines])
233
+ // O cadastro, não o que está no quadro AGORA: filtrar por uma tag encolhe o
234
+ // quadro, e derivar as opções dele faria as outras opções sumirem justamente
235
+ // quando a pessoa quer trocar de recorte.
236
+ const availableTags = useMemo(() => [...tagDefs.keys()], [tagDefs])
237
+
238
+ // Keyed no tenant, não em `[]`: a view monta antes do org store resolver, e
239
+ // uma leitura escopada por tenant que sai sem tenant volta VAZIA — igualzinho
240
+ // a "não há tags". Sem re-rodar quando o tenant chega, o filtro de tags só
241
+ // aparecia depois de sair da página e voltar.
242
+ // Sem `return` quando o tenant é undefined: providers que não dependem dele
243
+ // (mock) continuam carregando na montagem, e quem depende recarrega quando ele
244
+ // chega. O dedup absorve a chamada repetida.
245
+ const tenantId = useActiveTenantId()
246
+ useEffect(() => { fetchPipelines(); fetchTagDefs() }, [tenantId])
247
+ useEffect(() => {
248
+ if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id, boardFilter)
249
+ }, [pipelines, filterKey])
196
250
 
197
251
  // Live board. The card for an incoming lead is created by a DB trigger
198
252
  // (plugin-crm 006), so it appears with no client code involved at all — and
@@ -205,6 +259,10 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
205
259
  // moved, removed) touches it and nothing else does. A refetch rather than a
206
260
  // local patch — the payload alone lacks the joined stage/contact fields the
207
261
  // board renders, and refetching keeps one source of truth for the board.
262
+ //
263
+ // `refreshBoard` e não `fetchDealsByStage(pipelineId)`: o evento não sabe qual
264
+ // recorte está na tela, e recarregar sem filtro trocava o quadro filtrado pelo
265
+ // quadro inteiro a cada mudança.
208
266
  const pipelineId = pipelines[0]?.id
209
267
  useEffect(() => {
210
268
  if (!pipelineId) return
@@ -214,17 +272,29 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
214
272
  } | null
215
273
  if (!supabase) return
216
274
 
275
+ let timer: ReturnType<typeof setTimeout> | undefined
276
+ const onChange = () => {
277
+ // A escrita da própria pessoa já está na tela (quadro otimista) e o
278
+ // moveDealToStage recarrega ao terminar: reagir ao eco do próprio arrastar
279
+ // era uma busca a mais por card movido, competindo com a que já vinha.
280
+ if (savingRef.current.size > 0) return
281
+ // Uma mudança vem em rajada (trigger de lead cria e logo atualiza a linha);
282
+ // uma busca por rajada, não por evento.
283
+ clearTimeout(timer)
284
+ timer = setTimeout(() => { void refreshBoard() }, 300)
285
+ }
286
+
217
287
  // RLS scopes the stream to the caller's own tenants — no tenant filter here.
218
288
  const channel = supabase
219
289
  .channel(`crm:board:${pipelineId}`)
220
290
  .on(
221
291
  'postgres_changes',
222
292
  { event: '*', schema: 'public', table: 'plg_crm_deal_extensions' },
223
- () => { void fetchDealsByStage(pipelineId) },
293
+ onChange,
224
294
  )
225
295
  .subscribe()
226
296
 
227
- return () => { supabase.removeChannel(channel) }
297
+ return () => { clearTimeout(timer); supabase.removeChannel(channel) }
228
298
  }, [pipelineId])
229
299
 
230
300
  // Clear optimistic state when real data arrives and no moves are in-flight
@@ -308,6 +378,18 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
308
378
  <div className="space-y-4">
309
379
  <SubpageHeader title={t('crm.pipeline.title')} subtitle={t('crm.pipeline.subtitle')} />
310
380
 
381
+ <BoardFilters
382
+ period={period}
383
+ onPeriodChange={setPeriod}
384
+ customFrom={customFrom}
385
+ customTo={customTo}
386
+ onCustomChange={(from, to) => { setCustomFrom(from); setCustomTo(to) }}
387
+ selectedTags={selectedTags}
388
+ onTagsChange={setSelectedTags}
389
+ tagDefs={tagDefs}
390
+ availableTags={availableTags}
391
+ />
392
+
311
393
  {dealsLoading && dealsByStage.size === 0 ? (
312
394
  <PipelineSkeleton />
313
395
  ) : (
@@ -323,6 +405,7 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
323
405
  deals={deals}
324
406
  savingDealIds={savingDealIds}
325
407
  currency={currency}
408
+ tagDefs={tagDefs}
326
409
  dragOverStageId={dragOverStageId}
327
410
  onDealClick={handleDealClick}
328
411
  onArchiveDeal={canArchive ? (id) => { void archiveDeal(id) } : undefined}