@fayz-ai/plugin-crm 0.9.0 → 0.9.2
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.
- package/README.md +3 -3
- package/dist/components/AutomationBolt.d.ts +22 -0
- package/dist/components/AutomationBolt.d.ts.map +1 -0
- package/dist/{CrmContext.d.ts → context.d.ts} +4 -2
- package/dist/context.d.ts.map +1 -0
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/registries.d.ts.map +1 -0
- package/dist/data/types.d.ts +4 -1
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.d.ts +16 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +609 -493
- package/dist/index.js.map +1 -1
- package/dist/{cascade.d.ts → lib/cascade.d.ts} +1 -1
- package/dist/lib/cascade.d.ts.map +1 -0
- package/dist/lib/message-events.d.ts +13 -0
- package/dist/lib/message-events.d.ts.map +1 -0
- package/dist/lib/timeline-source.d.ts +10 -0
- package/dist/lib/timeline-source.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/public/context.d.ts +1 -1
- package/dist/public/context.d.ts.map +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts +1 -1
- package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
- package/dist/public/{data.supabase.d.ts → data/supabase.d.ts} +2 -2
- package/dist/public/data/supabase.d.ts.map +1 -0
- package/dist/public/index.d.ts +6 -6
- package/dist/public/index.d.ts.map +1 -1
- package/dist/public/index.js +2 -2
- package/dist/public/index.js.map +1 -1
- package/dist/public/{inbox.d.ts → lib/inbox.d.ts} +1 -1
- package/dist/public/lib/inbox.d.ts.map +1 -0
- package/dist/public/{uploads.d.ts → lib/uploads.d.ts} +1 -1
- package/dist/public/lib/uploads.d.ts.map +1 -0
- package/dist/store.d.ts +9 -0
- package/dist/store.d.ts.map +1 -1
- package/dist/views/ActivityListView.d.ts.map +1 -1
- package/dist/{CrmPage.d.ts → views/CrmPage.d.ts} +3 -3
- package/dist/views/CrmPage.d.ts.map +1 -0
- package/dist/views/DealSidebar.d.ts.map +1 -1
- package/dist/views/LeadListView.d.ts.map +1 -1
- package/dist/views/PipelineView.d.ts +3 -1
- package/dist/views/PipelineView.d.ts.map +1 -1
- package/dist/views/QuoteDetailView.d.ts.map +1 -1
- package/dist/views/QuoteFormView.d.ts.map +1 -1
- package/dist/views/QuoteListView.d.ts.map +1 -1
- package/dist/views/dashboardWidgets.d.ts +1 -1
- package/dist/views/dashboardWidgets.d.ts.map +1 -1
- package/package.json +6 -10
- package/dist/CrmContext.d.ts.map +0 -1
- package/dist/CrmPage.d.ts.map +0 -1
- package/dist/cascade.d.ts.map +0 -1
- package/dist/public/data.supabase.d.ts.map +0 -1
- package/dist/public/inbox.d.ts.map +0 -1
- package/dist/public/uploads.d.ts.map +0 -1
- package/dist/registries.d.ts.map +0 -1
- package/src/CrmContext.tsx +0 -30
- package/src/CrmPage.tsx +0 -150
- package/src/README.md +0 -97
- package/src/cascade.ts +0 -26
- package/src/components/BoardFilters.tsx +0 -190
- package/src/components/CrmGeneralSettings.tsx +0 -56
- package/src/components/CrmOnboarding.tsx +0 -52
- package/src/components/LeadAttachments.tsx +0 -140
- package/src/components/PipelineSettings.tsx +0 -45
- package/src/components/QuoteStatusDropdown.tsx +0 -226
- package/src/components/TagChips.tsx +0 -80
- package/src/data/index.ts +0 -2
- package/src/data/mock.ts +0 -559
- package/src/data/supabase.ts +0 -928
- package/src/data/tables.ts +0 -11
- package/src/data/types.ts +0 -61
- package/src/index.ts +0 -429
- package/src/lib/access.ts +0 -11
- package/src/lib/form-answers.tsx +0 -80
- package/src/lib/relative-time.ts +0 -84
- package/src/lib/tenant.ts +0 -4
- package/src/locales/en.ts +0 -307
- package/src/locales/index.ts +0 -7
- package/src/locales/pt-BR.ts +0 -307
- package/src/migrations/000_plg_rename.sql +0 -28
- package/src/migrations/001_crm_base.sql +0 -73
- package/src/migrations/002_activities.sql +0 -33
- package/src/migrations/003_crm_views_rls.sql +0 -69
- package/src/migrations/004_seed_default_pipeline.sql +0 -31
- package/src/migrations/005_public_lead.sql +0 -189
- package/src/migrations/006_lead_enters_pipeline.sql +0 -265
- package/src/migrations/007_activity_log.sql +0 -55
- package/src/migrations/008_view_field_aliases.sql +0 -43
- package/src/migrations/009_deal_archived_status.sql +0 -30
- package/src/migrations/010_quote_archived_status.sql +0 -40
- package/src/migrations/011_agent_rpc_update_lead.sql +0 -153
- package/src/migrations/012_agent_rpc_create_lead.sql +0 -128
- package/src/migrations/013_tag_slugs.sql +0 -177
- package/src/migrations/014_public_lead_tags.sql +0 -172
- package/src/migrations/015_lead_attachments.sql +0 -357
- package/src/migrations/016_public_lead_activity.sql +0 -123
- package/src/migrations/index.ts +0 -2023
- package/src/public/context.tsx +0 -150
- package/src/public/createPublicFormsPlugin.ts +0 -282
- package/src/public/data.supabase.ts +0 -92
- package/src/public/inbox.ts +0 -143
- package/src/public/index.ts +0 -51
- package/src/public/types.ts +0 -173
- package/src/public/uploads.ts +0 -205
- package/src/registries.ts +0 -162
- package/src/schema/index.ts +0 -104
- package/src/store.ts +0 -472
- package/src/types.ts +0 -337
- package/src/views/ActivityListView.tsx +0 -264
- package/src/views/DashboardView.tsx +0 -12
- package/src/views/DealSidebar.tsx +0 -482
- package/src/views/LeadDetailView.tsx +0 -378
- package/src/views/LeadFormView.tsx +0 -66
- package/src/views/LeadListView.tsx +0 -100
- package/src/views/PipelineView.tsx +0 -446
- package/src/views/QuoteDetailView.tsx +0 -412
- package/src/views/QuoteFormView.tsx +0 -494
- package/src/views/QuoteListView.tsx +0 -115
- package/src/views/dashboardWidgets.tsx +0 -248
- /package/dist/{registries.d.ts → data/registries.d.ts} +0 -0
|
@@ -1,446 +0,0 @@
|
|
|
1
|
-
import React, { useEffect, useMemo, useRef, useState } from 'react'
|
|
2
|
-
import { Archive, Loader2, Plus } from 'lucide-react'
|
|
3
|
-
import { toast } from '@fayz-ai/ui'
|
|
4
|
-
import { useCrmStore, useCrmConfig, formatCurrency } from '../CrmContext'
|
|
5
|
-
import { useCanArchive } from '../lib/access'
|
|
6
|
-
import { useTranslation, getSupabaseClientOptional, useActiveTenantId } from '@fayz-ai/core'
|
|
7
|
-
import { SubpageHeader } from '@fayz-ai/ui'
|
|
8
|
-
import { DealSidebar } from './DealSidebar'
|
|
9
|
-
import { TagChips } from '../components/TagChips'
|
|
10
|
-
import { BoardFilters, periodToRange } from '../components/BoardFilters'
|
|
11
|
-
import { formatDateTime, formatRelativeTime } from '../lib/relative-time'
|
|
12
|
-
import type { BoardPeriod, Deal, TagDef } from '../types'
|
|
13
|
-
|
|
14
|
-
/** Uma data em YYYY-MM-DD, no fuso de quem está olhando (o DatePicker fala isso). */
|
|
15
|
-
function localDate(offsetDays = 0): string {
|
|
16
|
-
const d = new Date()
|
|
17
|
-
if (offsetDays) d.setDate(d.getDate() + offsetDays)
|
|
18
|
-
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
// ---------------------------------------------------------------------------
|
|
22
|
-
// Skeleton
|
|
23
|
-
// ---------------------------------------------------------------------------
|
|
24
|
-
|
|
25
|
-
function PipelineSkeleton() {
|
|
26
|
-
return (
|
|
27
|
-
<div className="flex gap-3 overflow-x-auto pb-2">
|
|
28
|
-
{[1, 2, 3, 4, 5].map((col) => (
|
|
29
|
-
<div key={col} className="min-w-[240px] max-w-[280px] flex-shrink-0">
|
|
30
|
-
<div className="flex items-center gap-2 mb-2 px-1">
|
|
31
|
-
<div className="h-2 w-2 rounded-full bg-muted/40 animate-pulse" />
|
|
32
|
-
<div className="h-3 w-16 rounded bg-muted/40 animate-pulse" />
|
|
33
|
-
<div className="h-3 w-5 rounded bg-muted/30 animate-pulse" />
|
|
34
|
-
</div>
|
|
35
|
-
<div className="space-y-2">
|
|
36
|
-
{Array.from({ length: col <= 2 ? 2 : 1 }).map((_, i) => (
|
|
37
|
-
<div key={i} className="rounded-lg border bg-card shadow-sm p-3 space-y-2">
|
|
38
|
-
<div className="h-4 w-3/4 rounded bg-muted/40 animate-pulse" />
|
|
39
|
-
<div className="h-3 w-1/2 rounded bg-muted/30 animate-pulse" />
|
|
40
|
-
<div className="flex items-center justify-between pt-1">
|
|
41
|
-
<div className="h-3 w-16 rounded bg-muted/40 animate-pulse" />
|
|
42
|
-
<div className="h-3 w-8 rounded bg-muted/30 animate-pulse" />
|
|
43
|
-
</div>
|
|
44
|
-
</div>
|
|
45
|
-
))}
|
|
46
|
-
</div>
|
|
47
|
-
</div>
|
|
48
|
-
))}
|
|
49
|
-
</div>
|
|
50
|
-
)
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
// ---------------------------------------------------------------------------
|
|
54
|
-
// Deal card
|
|
55
|
-
// ---------------------------------------------------------------------------
|
|
56
|
-
|
|
57
|
-
function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragStart, onDragEnd }: {
|
|
58
|
-
deal: Deal
|
|
59
|
-
saving?: boolean
|
|
60
|
-
currency: { code: string; locale: string; symbol: string }
|
|
61
|
-
tagDefs?: Map<string, TagDef>
|
|
62
|
-
onClick?: () => void
|
|
63
|
-
/** Present only when the archive permission resolved true (useCanArchive). */
|
|
64
|
-
onArchive?: () => void
|
|
65
|
-
onDragStart: (e: React.DragEvent) => void
|
|
66
|
-
onDragEnd: (e: React.DragEvent) => void
|
|
67
|
-
}) {
|
|
68
|
-
const t = useTranslation()
|
|
69
|
-
return (
|
|
70
|
-
<div
|
|
71
|
-
draggable={!saving}
|
|
72
|
-
onDragStart={onDragStart}
|
|
73
|
-
onDragEnd={onDragEnd}
|
|
74
|
-
onClick={onClick}
|
|
75
|
-
className={`group rounded-lg border bg-card p-3 transition-shadow ${saving ? 'opacity-70' : 'hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70'}`}
|
|
76
|
-
>
|
|
77
|
-
<div className="flex items-center justify-between gap-2">
|
|
78
|
-
<p className="text-sm font-medium truncate">{deal.title}</p>
|
|
79
|
-
{saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground shrink-0" />}
|
|
80
|
-
{!saving && onArchive && (
|
|
81
|
-
<button
|
|
82
|
-
onClick={(e) => { e.stopPropagation(); onArchive() }}
|
|
83
|
-
title={t('crm.pipeline.archive')}
|
|
84
|
-
className="flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100"
|
|
85
|
-
>
|
|
86
|
-
<Archive className="h-3 w-3" />
|
|
87
|
-
</button>
|
|
88
|
-
)}
|
|
89
|
-
</div>
|
|
90
|
-
{deal.contactName && <p className="text-[10px] text-muted-foreground mt-0.5">{deal.contactName}</p>}
|
|
91
|
-
{/* Teto de 3 no card: o funil se lê na diagonal, e uma pilha de chips
|
|
92
|
-
empurra valor e probabilidade para fora do primeiro olhar. O resto
|
|
93
|
-
vira "+N" e aparece inteiro no detalhe. */}
|
|
94
|
-
<TagChips tags={deal.tags} defs={tagDefs} max={3} className="mt-1.5" />
|
|
95
|
-
<div className="flex items-center justify-between mt-2">
|
|
96
|
-
<span className="text-xs font-semibold">{formatCurrency(deal.value, currency)}</span>
|
|
97
|
-
<span className="text-[10px] text-muted-foreground">{deal.probability}%</span>
|
|
98
|
-
</div>
|
|
99
|
-
{/* Idade do card. Sem ela, "parado há três semanas" e "chegou agora" são
|
|
100
|
-
visualmente idênticos — e é essa diferença que decide quem recebe o
|
|
101
|
-
próximo telefonema. A data exata fica no `title`, para quem precisar
|
|
102
|
-
dela sem abrir o card. */}
|
|
103
|
-
{deal.createdAt && (
|
|
104
|
-
<p
|
|
105
|
-
className="mt-1 text-[10px] text-muted-foreground"
|
|
106
|
-
title={formatDateTime(deal.createdAt, currency.locale)}
|
|
107
|
-
>
|
|
108
|
-
{formatRelativeTime(deal.createdAt, currency.locale)}
|
|
109
|
-
</p>
|
|
110
|
-
)}
|
|
111
|
-
</div>
|
|
112
|
-
)
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
// ---------------------------------------------------------------------------
|
|
116
|
-
// Stage column
|
|
117
|
-
// ---------------------------------------------------------------------------
|
|
118
|
-
|
|
119
|
-
function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, tagDefs, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }: {
|
|
120
|
-
stageId: string
|
|
121
|
-
stageName: string
|
|
122
|
-
stageColor: string
|
|
123
|
-
deals: Deal[]
|
|
124
|
-
savingDealIds: Set<string>
|
|
125
|
-
currency: { code: string; locale: string; symbol: string }
|
|
126
|
-
tagDefs?: Map<string, TagDef>
|
|
127
|
-
dragOverStageId: string | null
|
|
128
|
-
onDealClick?: (id: string) => void
|
|
129
|
-
onArchiveDeal?: (id: string) => void
|
|
130
|
-
onAddLead?: () => void
|
|
131
|
-
onDragStart: (dealId: string, fromStageId: string) => void
|
|
132
|
-
onDragEnd: () => void
|
|
133
|
-
onDragOver: (e: React.DragEvent) => void
|
|
134
|
-
onDragLeave: () => void
|
|
135
|
-
onDrop: () => void
|
|
136
|
-
}) {
|
|
137
|
-
const t = useTranslation()
|
|
138
|
-
const isOver = dragOverStageId === stageId
|
|
139
|
-
const [hovered, setHovered] = useState(false)
|
|
140
|
-
|
|
141
|
-
return (
|
|
142
|
-
<div
|
|
143
|
-
className="min-w-[240px] max-w-[280px] flex-shrink-0 flex flex-col"
|
|
144
|
-
onMouseEnter={() => setHovered(true)}
|
|
145
|
-
onMouseLeave={() => setHovered(false)}
|
|
146
|
-
>
|
|
147
|
-
<div className="flex items-center gap-2 mb-2 px-1">
|
|
148
|
-
<div className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: stageColor }} />
|
|
149
|
-
<span className="text-xs font-semibold">{stageName}</span>
|
|
150
|
-
<span className="text-[10px] text-muted-foreground">({deals.length})</span>
|
|
151
|
-
<div className="flex-1" />
|
|
152
|
-
{onAddLead && (
|
|
153
|
-
<button
|
|
154
|
-
onClick={onAddLead}
|
|
155
|
-
className={`flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-all ${hovered ? 'opacity-100' : 'opacity-0'}`}
|
|
156
|
-
title="Add lead"
|
|
157
|
-
>
|
|
158
|
-
<Plus className="h-3.5 w-3.5" />
|
|
159
|
-
</button>
|
|
160
|
-
)}
|
|
161
|
-
</div>
|
|
162
|
-
<div
|
|
163
|
-
onDragOver={onDragOver}
|
|
164
|
-
onDragLeave={onDragLeave}
|
|
165
|
-
onDrop={onDrop}
|
|
166
|
-
className={`flex-1 space-y-2 rounded-lg p-1 transition-colors min-h-[80px] ${isOver ? 'bg-primary/5 ring-2 ring-primary/20 ring-inset' : ''}`}
|
|
167
|
-
>
|
|
168
|
-
{deals.length === 0 ? (
|
|
169
|
-
<div className={`rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground ${isOver ? 'border-primary/30' : ''}`}>
|
|
170
|
-
{isOver ? t('crm.pipeline.dropHere') : t('crm.pipeline.noDeals')}
|
|
171
|
-
</div>
|
|
172
|
-
) : (
|
|
173
|
-
deals.map((deal) => (
|
|
174
|
-
<DealCard
|
|
175
|
-
key={deal.id}
|
|
176
|
-
deal={deal}
|
|
177
|
-
saving={savingDealIds.has(deal.id)}
|
|
178
|
-
currency={currency}
|
|
179
|
-
tagDefs={tagDefs}
|
|
180
|
-
onClick={() => onDealClick?.(deal.id)}
|
|
181
|
-
onArchive={onArchiveDeal ? () => onArchiveDeal(deal.id) : undefined}
|
|
182
|
-
onDragStart={(e) => {
|
|
183
|
-
e.dataTransfer.effectAllowed = 'move'
|
|
184
|
-
onDragStart(deal.id, stageId)
|
|
185
|
-
}}
|
|
186
|
-
onDragEnd={onDragEnd}
|
|
187
|
-
/>
|
|
188
|
-
))
|
|
189
|
-
)}
|
|
190
|
-
</div>
|
|
191
|
-
</div>
|
|
192
|
-
)
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
// ---------------------------------------------------------------------------
|
|
196
|
-
// Pipeline view
|
|
197
|
-
// ---------------------------------------------------------------------------
|
|
198
|
-
|
|
199
|
-
export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }: {
|
|
200
|
-
onDealClick?: (id: string) => void
|
|
201
|
-
onViewLead?: (id: string) => void
|
|
202
|
-
onViewQuote?: (id: string) => void
|
|
203
|
-
onAddLead?: () => void
|
|
204
|
-
}) {
|
|
205
|
-
const { currency } = useCrmConfig()
|
|
206
|
-
const pipelines = useCrmStore((s) => s.pipelines)
|
|
207
|
-
const stages = useCrmStore((s) => s.stages)
|
|
208
|
-
const dealsByStage = useCrmStore((s) => s.dealsByStage)
|
|
209
|
-
const dealsLoading = useCrmStore((s) => s.dealsLoading)
|
|
210
|
-
const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
|
|
211
|
-
const tagDefs = useCrmStore((s) => s.tagDefs)
|
|
212
|
-
const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs)
|
|
213
|
-
const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage)
|
|
214
|
-
const refreshBoard = useCrmStore((s) => s.refreshBoard)
|
|
215
|
-
const moveDealToStage = useCrmStore((s) => s.moveDealToStage)
|
|
216
|
-
const archiveDeal = useCrmStore((s) => s.archiveDeal)
|
|
217
|
-
const canArchive = useCanArchive()
|
|
218
|
-
|
|
219
|
-
const [period, setPeriod] = useState<BoardPeriod>('all')
|
|
220
|
-
// Hoje→hoje é o recorte mais estreito que existe: quem clica em
|
|
221
|
-
// "Personalizado" via o quadro esvaziar e tinha de mexer nos dois campos para
|
|
222
|
-
// ver qualquer coisa. Trinta dias é o passo natural depois de "7 dias" — a
|
|
223
|
-
// pessoa ajusta a partir de um recorte que já mostra algo.
|
|
224
|
-
const [customFrom, setCustomFrom] = useState(() => localDate(-30))
|
|
225
|
-
const [customTo, setCustomTo] = useState(() => localDate())
|
|
226
|
-
const [selectedTags, setSelectedTags] = useState<string[]>([])
|
|
227
|
-
const [dragOverStageId, setDragOverStageId] = useState<string | null>(null)
|
|
228
|
-
const [savingDealIds, setSavingDealIds] = useState<Set<string>>(new Set())
|
|
229
|
-
const [optimisticBoard, setOptimisticBoard] = useState<Map<string, Deal[]> | null>(null)
|
|
230
|
-
const t = useTranslation()
|
|
231
|
-
const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
|
|
232
|
-
const dragRef = useRef<{ dealId: string; fromStageId: string } | null>(null)
|
|
233
|
-
// O handler do realtime vive dentro de um effect keyed no pipeline: ler o
|
|
234
|
-
// estado por ref evita re-assinar o canal a cada card em voo.
|
|
235
|
-
const savingRef = useRef(savingDealIds)
|
|
236
|
-
savingRef.current = savingDealIds
|
|
237
|
-
|
|
238
|
-
// O filtro só existe como valor derivado: um estado separado guardando o
|
|
239
|
-
// mesmo recorte sairia de sincronia com os controles em alguma borda.
|
|
240
|
-
const boardFilter = useMemo(() => ({
|
|
241
|
-
...(selectedTags.length ? { tags: selectedTags } : {}),
|
|
242
|
-
...periodToRange(period, customFrom, customTo),
|
|
243
|
-
}), [selectedTags, period, customFrom, customTo])
|
|
244
|
-
const filterKey = JSON.stringify(boardFilter)
|
|
245
|
-
|
|
246
|
-
// O cadastro, não o que está no quadro AGORA: filtrar por uma tag encolhe o
|
|
247
|
-
// quadro, e derivar as opções dele faria as outras opções sumirem justamente
|
|
248
|
-
// quando a pessoa quer trocar de recorte.
|
|
249
|
-
const availableTags = useMemo(() => [...tagDefs.keys()], [tagDefs])
|
|
250
|
-
|
|
251
|
-
// Keyed no tenant, não em `[]`: a view monta antes do org store resolver, e
|
|
252
|
-
// uma leitura escopada por tenant que sai sem tenant volta VAZIA — igualzinho
|
|
253
|
-
// a "não há tags". Sem re-rodar quando o tenant chega, o filtro de tags só
|
|
254
|
-
// aparecia depois de sair da página e voltar.
|
|
255
|
-
// Sem `return` quando o tenant é undefined: providers que não dependem dele
|
|
256
|
-
// (mock) continuam carregando na montagem, e quem depende recarrega quando ele
|
|
257
|
-
// chega. O dedup absorve a chamada repetida.
|
|
258
|
-
const tenantId = useActiveTenantId()
|
|
259
|
-
useEffect(() => { fetchPipelines(); fetchTagDefs() }, [tenantId])
|
|
260
|
-
useEffect(() => {
|
|
261
|
-
if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id, boardFilter)
|
|
262
|
-
}, [pipelines, filterKey])
|
|
263
|
-
|
|
264
|
-
// Live board. The card for an incoming lead is created by a DB trigger
|
|
265
|
-
// (plugin-crm 006), so it appears with no client code involved at all — and
|
|
266
|
-
// without this subscription the only way to see it was a page reload. A
|
|
267
|
-
// pipeline left open on a screen all day is the normal case here, which is
|
|
268
|
-
// exactly when a stale board is worst.
|
|
269
|
-
//
|
|
270
|
-
// Subscribes to plg_crm_deal_extensions rather than orders: it is the row
|
|
271
|
-
// carrying pipeline_id/stage_id, so every board-visible change (card created,
|
|
272
|
-
// moved, removed) touches it and nothing else does. A refetch rather than a
|
|
273
|
-
// local patch — the payload alone lacks the joined stage/contact fields the
|
|
274
|
-
// board renders, and refetching keeps one source of truth for the board.
|
|
275
|
-
//
|
|
276
|
-
// `refreshBoard` e não `fetchDealsByStage(pipelineId)`: o evento não sabe qual
|
|
277
|
-
// recorte está na tela, e recarregar sem filtro trocava o quadro filtrado pelo
|
|
278
|
-
// quadro inteiro a cada mudança.
|
|
279
|
-
const pipelineId = pipelines[0]?.id
|
|
280
|
-
useEffect(() => {
|
|
281
|
-
if (!pipelineId) return
|
|
282
|
-
const supabase = getSupabaseClientOptional() as {
|
|
283
|
-
channel: (name: string) => { on: (...a: unknown[]) => { subscribe: () => unknown } }
|
|
284
|
-
removeChannel: (channel: unknown) => void
|
|
285
|
-
} | null
|
|
286
|
-
if (!supabase) return
|
|
287
|
-
|
|
288
|
-
let timer: ReturnType<typeof setTimeout> | undefined
|
|
289
|
-
const onChange = () => {
|
|
290
|
-
// A escrita da própria pessoa já está na tela (quadro otimista) e o
|
|
291
|
-
// moveDealToStage recarrega ao terminar: reagir ao eco do próprio arrastar
|
|
292
|
-
// era uma busca a mais por card movido, competindo com a que já vinha.
|
|
293
|
-
if (savingRef.current.size > 0) return
|
|
294
|
-
// Uma mudança vem em rajada (trigger de lead cria e logo atualiza a linha);
|
|
295
|
-
// uma busca por rajada, não por evento.
|
|
296
|
-
clearTimeout(timer)
|
|
297
|
-
timer = setTimeout(() => { void refreshBoard() }, 300)
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
// RLS scopes the stream to the caller's own tenants — no tenant filter here.
|
|
301
|
-
const channel = supabase
|
|
302
|
-
.channel(`crm:board:${pipelineId}`)
|
|
303
|
-
.on(
|
|
304
|
-
'postgres_changes',
|
|
305
|
-
{ event: '*', schema: 'public', table: 'plg_crm_deal_extensions' },
|
|
306
|
-
onChange,
|
|
307
|
-
)
|
|
308
|
-
.subscribe()
|
|
309
|
-
|
|
310
|
-
return () => { clearTimeout(timer); supabase.removeChannel(channel) }
|
|
311
|
-
}, [pipelineId])
|
|
312
|
-
|
|
313
|
-
// Clear optimistic state when real data arrives and no moves are in-flight
|
|
314
|
-
useEffect(() => {
|
|
315
|
-
if (savingDealIds.size === 0) setOptimisticBoard(null)
|
|
316
|
-
}, [dealsByStage, savingDealIds])
|
|
317
|
-
|
|
318
|
-
const visibleStages = stages.filter((s) => !s.isLost)
|
|
319
|
-
const displayBoard = optimisticBoard ?? dealsByStage
|
|
320
|
-
|
|
321
|
-
function handleDragStart(dealId: string, fromStageId: string) {
|
|
322
|
-
dragRef.current = { dealId, fromStageId }
|
|
323
|
-
}
|
|
324
|
-
|
|
325
|
-
function handleDragEnd() {
|
|
326
|
-
dragRef.current = null
|
|
327
|
-
setDragOverStageId(null)
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
function handleDragOver(stageId: string, e: React.DragEvent) {
|
|
331
|
-
e.preventDefault()
|
|
332
|
-
e.dataTransfer.dropEffect = 'move'
|
|
333
|
-
if (dragOverStageId !== stageId) setDragOverStageId(stageId)
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
function handleDrop(toStageId: string) {
|
|
337
|
-
const drag = dragRef.current
|
|
338
|
-
if (!drag) return
|
|
339
|
-
dragRef.current = null
|
|
340
|
-
setDragOverStageId(null)
|
|
341
|
-
|
|
342
|
-
if (drag.fromStageId === toStageId) return
|
|
343
|
-
|
|
344
|
-
const { dealId, fromStageId } = drag
|
|
345
|
-
const targetStage = stages.find((s) => s.id === toStageId)
|
|
346
|
-
|
|
347
|
-
// Optimistic update — move the card instantly
|
|
348
|
-
const currentBoard = optimisticBoard ?? dealsByStage
|
|
349
|
-
const nextBoard = new Map(currentBoard)
|
|
350
|
-
const fromDeals = [...(nextBoard.get(fromStageId) ?? [])]
|
|
351
|
-
const movedDeal = fromDeals.find((d) => d.id === dealId)
|
|
352
|
-
if (!movedDeal) return
|
|
353
|
-
|
|
354
|
-
const updatedDeal: Deal = {
|
|
355
|
-
...movedDeal,
|
|
356
|
-
stageId: toStageId,
|
|
357
|
-
stageName: targetStage?.name,
|
|
358
|
-
stageColor: targetStage?.color,
|
|
359
|
-
probability: targetStage?.probability ?? movedDeal.probability,
|
|
360
|
-
}
|
|
361
|
-
|
|
362
|
-
nextBoard.set(fromStageId, fromDeals.filter((d) => d.id !== dealId))
|
|
363
|
-
nextBoard.set(toStageId, [...(nextBoard.get(toStageId) ?? []), updatedDeal])
|
|
364
|
-
setOptimisticBoard(nextBoard)
|
|
365
|
-
setSavingDealIds((prev) => new Set(prev).add(dealId))
|
|
366
|
-
|
|
367
|
-
// Persist in background
|
|
368
|
-
moveDealToStage(dealId, toStageId)
|
|
369
|
-
.then(() => {
|
|
370
|
-
toast.success(t('crm.pipeline.movedTo', { stage: targetStage?.name ?? 'stage' }))
|
|
371
|
-
})
|
|
372
|
-
.catch(() => {
|
|
373
|
-
setOptimisticBoard(null)
|
|
374
|
-
toast.error(t('crm.pipeline.moveFailed'))
|
|
375
|
-
})
|
|
376
|
-
.finally(() => {
|
|
377
|
-
setSavingDealIds((prev) => {
|
|
378
|
-
const next = new Set(prev)
|
|
379
|
-
next.delete(dealId)
|
|
380
|
-
return next
|
|
381
|
-
})
|
|
382
|
-
})
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
function handleDealClick(dealId: string) {
|
|
386
|
-
setSelectedDealId(dealId)
|
|
387
|
-
onDealClick?.(dealId)
|
|
388
|
-
}
|
|
389
|
-
|
|
390
|
-
return (
|
|
391
|
-
<div className="space-y-4">
|
|
392
|
-
<SubpageHeader title={t('crm.pipeline.title')} subtitle={t('crm.pipeline.subtitle')} />
|
|
393
|
-
|
|
394
|
-
<BoardFilters
|
|
395
|
-
period={period}
|
|
396
|
-
onPeriodChange={setPeriod}
|
|
397
|
-
customFrom={customFrom}
|
|
398
|
-
customTo={customTo}
|
|
399
|
-
onCustomChange={(from, to) => { setCustomFrom(from); setCustomTo(to) }}
|
|
400
|
-
selectedTags={selectedTags}
|
|
401
|
-
onTagsChange={setSelectedTags}
|
|
402
|
-
tagDefs={tagDefs}
|
|
403
|
-
availableTags={availableTags}
|
|
404
|
-
/>
|
|
405
|
-
|
|
406
|
-
{dealsLoading && dealsByStage.size === 0 ? (
|
|
407
|
-
<PipelineSkeleton />
|
|
408
|
-
) : (
|
|
409
|
-
<div className="flex gap-3 overflow-x-auto pb-2">
|
|
410
|
-
{visibleStages.map((stage) => {
|
|
411
|
-
const deals = displayBoard.get(stage.id) ?? []
|
|
412
|
-
return (
|
|
413
|
-
<StageColumn
|
|
414
|
-
key={stage.id}
|
|
415
|
-
stageId={stage.id}
|
|
416
|
-
stageName={stage.name}
|
|
417
|
-
stageColor={stage.color}
|
|
418
|
-
deals={deals}
|
|
419
|
-
savingDealIds={savingDealIds}
|
|
420
|
-
currency={currency}
|
|
421
|
-
tagDefs={tagDefs}
|
|
422
|
-
dragOverStageId={dragOverStageId}
|
|
423
|
-
onDealClick={handleDealClick}
|
|
424
|
-
onArchiveDeal={canArchive ? (id) => { void archiveDeal(id) } : undefined}
|
|
425
|
-
onAddLead={onAddLead}
|
|
426
|
-
onDragStart={handleDragStart}
|
|
427
|
-
onDragEnd={handleDragEnd}
|
|
428
|
-
onDragOver={(e) => handleDragOver(stage.id, e)}
|
|
429
|
-
onDragLeave={() => { if (dragOverStageId === stage.id) setDragOverStageId(null) }}
|
|
430
|
-
onDrop={() => handleDrop(stage.id)}
|
|
431
|
-
/>
|
|
432
|
-
)
|
|
433
|
-
})}
|
|
434
|
-
</div>
|
|
435
|
-
)}
|
|
436
|
-
|
|
437
|
-
<DealSidebar
|
|
438
|
-
dealId={selectedDealId ?? ''}
|
|
439
|
-
open={!!selectedDealId}
|
|
440
|
-
onClose={() => setSelectedDealId(null)}
|
|
441
|
-
onViewLead={onViewLead}
|
|
442
|
-
onViewQuote={onViewQuote}
|
|
443
|
-
/>
|
|
444
|
-
</div>
|
|
445
|
-
)
|
|
446
|
-
}
|