@fayz-ai/plugin-crm 0.1.1

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 (103) hide show
  1. package/dist/CrmContext.d.ts +32 -0
  2. package/dist/CrmContext.d.ts.map +1 -0
  3. package/dist/CrmPage.d.ts +13 -0
  4. package/dist/CrmPage.d.ts.map +1 -0
  5. package/dist/cascade.d.ts +13 -0
  6. package/dist/cascade.d.ts.map +1 -0
  7. package/dist/components/CrmGeneralSettings.d.ts +3 -0
  8. package/dist/components/CrmGeneralSettings.d.ts.map +1 -0
  9. package/dist/components/CrmOnboarding.d.ts +5 -0
  10. package/dist/components/CrmOnboarding.d.ts.map +1 -0
  11. package/dist/components/PipelineSettings.d.ts +3 -0
  12. package/dist/components/PipelineSettings.d.ts.map +1 -0
  13. package/dist/components/QuoteStatusDropdown.d.ts +8 -0
  14. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -0
  15. package/dist/data/index.d.ts +3 -0
  16. package/dist/data/index.d.ts.map +1 -0
  17. package/dist/data/mock.d.ts +9 -0
  18. package/dist/data/mock.d.ts.map +1 -0
  19. package/dist/data/supabase.d.ts +9 -0
  20. package/dist/data/supabase.d.ts.map +1 -0
  21. package/dist/data/types.d.ts +32 -0
  22. package/dist/data/types.d.ts.map +1 -0
  23. package/dist/index.cjs +4601 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.ts +72 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +4595 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/lib/tenant.d.ts +3 -0
  30. package/dist/lib/tenant.d.ts.map +1 -0
  31. package/dist/locales/en.d.ts +2 -0
  32. package/dist/locales/en.d.ts.map +1 -0
  33. package/dist/locales/index.d.ts +2 -0
  34. package/dist/locales/index.d.ts.map +1 -0
  35. package/dist/locales/pt-BR.d.ts +2 -0
  36. package/dist/locales/pt-BR.d.ts.map +1 -0
  37. package/dist/registries.d.ts +3 -0
  38. package/dist/registries.d.ts.map +1 -0
  39. package/dist/schema/index.d.ts +1036 -0
  40. package/dist/schema/index.d.ts.map +1 -0
  41. package/dist/store.d.ts +43 -0
  42. package/dist/store.d.ts.map +1 -0
  43. package/dist/types.d.ts +238 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/views/ActivityListView.d.ts +3 -0
  46. package/dist/views/ActivityListView.d.ts.map +1 -0
  47. package/dist/views/DashboardView.d.ts +9 -0
  48. package/dist/views/DashboardView.d.ts.map +1 -0
  49. package/dist/views/DealSidebar.d.ts +9 -0
  50. package/dist/views/DealSidebar.d.ts.map +1 -0
  51. package/dist/views/LeadDetailView.d.ts +8 -0
  52. package/dist/views/LeadDetailView.d.ts.map +1 -0
  53. package/dist/views/LeadFormView.d.ts +5 -0
  54. package/dist/views/LeadFormView.d.ts.map +1 -0
  55. package/dist/views/LeadListView.d.ts +6 -0
  56. package/dist/views/LeadListView.d.ts.map +1 -0
  57. package/dist/views/PipelineView.d.ts +8 -0
  58. package/dist/views/PipelineView.d.ts.map +1 -0
  59. package/dist/views/QuoteDetailView.d.ts +8 -0
  60. package/dist/views/QuoteDetailView.d.ts.map +1 -0
  61. package/dist/views/QuoteFormView.d.ts +7 -0
  62. package/dist/views/QuoteFormView.d.ts.map +1 -0
  63. package/dist/views/QuoteListView.d.ts +7 -0
  64. package/dist/views/QuoteListView.d.ts.map +1 -0
  65. package/dist/views/dashboardWidgets.d.ts +11 -0
  66. package/dist/views/dashboardWidgets.d.ts.map +1 -0
  67. package/package.json +55 -0
  68. package/src/CrmContext.tsx +30 -0
  69. package/src/CrmPage.tsx +152 -0
  70. package/src/README.md +97 -0
  71. package/src/cascade.ts +24 -0
  72. package/src/components/CrmGeneralSettings.tsx +36 -0
  73. package/src/components/CrmOnboarding.tsx +52 -0
  74. package/src/components/PipelineSettings.tsx +45 -0
  75. package/src/components/QuoteStatusDropdown.tsx +214 -0
  76. package/src/data/index.ts +2 -0
  77. package/src/data/mock.ts +426 -0
  78. package/src/data/supabase.ts +634 -0
  79. package/src/data/types.ts +50 -0
  80. package/src/index.ts +240 -0
  81. package/src/lib/tenant.ts +4 -0
  82. package/src/locales/en.ts +292 -0
  83. package/src/locales/index.ts +7 -0
  84. package/src/locales/pt-BR.ts +292 -0
  85. package/src/migrations/001_crm_base.sql +73 -0
  86. package/src/migrations/002_activities.sql +33 -0
  87. package/src/migrations/003_crm_views_rls.sql +61 -0
  88. package/src/migrations/004_seed_default_pipeline.sql +31 -0
  89. package/src/registries.ts +88 -0
  90. package/src/schema/index.ts +102 -0
  91. package/src/store.ts +375 -0
  92. package/src/types.ts +280 -0
  93. package/src/views/ActivityListView.tsx +183 -0
  94. package/src/views/DashboardView.tsx +12 -0
  95. package/src/views/DealSidebar.tsx +414 -0
  96. package/src/views/LeadDetailView.tsx +264 -0
  97. package/src/views/LeadFormView.tsx +56 -0
  98. package/src/views/LeadListView.tsx +81 -0
  99. package/src/views/PipelineView.tsx +299 -0
  100. package/src/views/QuoteDetailView.tsx +408 -0
  101. package/src/views/QuoteFormView.tsx +489 -0
  102. package/src/views/QuoteListView.tsx +101 -0
  103. package/src/views/dashboardWidgets.tsx +248 -0
@@ -0,0 +1,56 @@
1
+ import React, { useState, useEffect } from 'react'
2
+ import { useCrmStore } from '../CrmContext'
3
+ import { useTranslation } from '@fayz-ai/core'
4
+ import { SubpageHeader, useSaveBar, toast } from '@fayz-ai/ui'
5
+
6
+ export function LeadFormView({ onSaved }: { onSaved?: (id?: string) => void }) {
7
+ const t = useTranslation()
8
+ const createLead = useCrmStore((s) => s.createLead)
9
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
10
+ const pipelines = useCrmStore((s) => s.pipelines)
11
+
12
+ // Ensure pipelines are loaded so createLead can auto-create a deal
13
+ useEffect(() => { if (pipelines.length === 0) fetchPipelines() }, [])
14
+
15
+ const [name, setName] = useState('')
16
+ const [email, setEmail] = useState('')
17
+ const [phone, setPhone] = useState('')
18
+ const [company, setCompany] = useState('')
19
+ const [notes, setNotes] = useState('')
20
+ const [saving, setSaving] = useState(false)
21
+
22
+ async function handleSave() {
23
+ if (!name.trim()) { toast.error(t('common.formIncomplete')); return }
24
+ setSaving(true)
25
+ try {
26
+ const lead = await createLead({ name, email: email || undefined, phone: phone || undefined, company: company || undefined, notes: notes || undefined })
27
+ onSaved?.(lead.id)
28
+ } finally { setSaving(false) }
29
+ }
30
+
31
+ const dirty = !!(name || email || phone || company || notes)
32
+ useSaveBar({
33
+ dirty,
34
+ saving,
35
+ onSave: () => { void handleSave() },
36
+ onDiscard: () => onSaved?.(),
37
+ saveLabel: t('crm.leadForm.save'),
38
+ })
39
+
40
+ return (
41
+ <div className="space-y-5">
42
+ <SubpageHeader title={t('crm.leadForm.title')} subtitle={t('crm.leadForm.subtitle')} onBack={onSaved} parentLabel={t('crm.leads.title')} />
43
+ <div className="rounded-lg border bg-card shadow-sm p-5 space-y-4">
44
+ <div className="grid gap-4 sm:grid-cols-2">
45
+ <div><label className="text-xs font-medium text-muted-foreground">{t('crm.leadForm.name')}</label><input type="text" value={name} onChange={(e) => setName(e.target.value)} placeholder={t('crm.leadForm.namePlaceholder')} autoFocus className="w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" /></div>
46
+ <div><label className="text-xs font-medium text-muted-foreground">{t('crm.leadForm.company')}</label><input type="text" value={company} onChange={(e) => setCompany(e.target.value)} placeholder={t('crm.leadForm.companyPlaceholder')} className="w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" /></div>
47
+ </div>
48
+ <div className="grid gap-4 sm:grid-cols-2">
49
+ <div><label className="text-xs font-medium text-muted-foreground">{t('crm.leadForm.email')}</label><input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder={t('crm.leadForm.emailPlaceholder')} className="w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" /></div>
50
+ <div><label className="text-xs font-medium text-muted-foreground">{t('crm.leadForm.phone')}</label><input type="tel" value={phone} onChange={(e) => setPhone(e.target.value)} placeholder={t('crm.leadForm.phonePlaceholder')} className="w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" /></div>
51
+ </div>
52
+ <div><label className="text-xs font-medium text-muted-foreground">{t('crm.leadForm.notes')}</label><textarea value={notes} onChange={(e) => setNotes(e.target.value)} rows={2} placeholder={t('crm.leadForm.notesPlaceholder')} className="w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" /></div>
53
+ </div>
54
+ </div>
55
+ )
56
+ }
@@ -0,0 +1,81 @@
1
+ import React, { useEffect, useState, useMemo } from 'react'
2
+ import { UserPlus } from 'lucide-react'
3
+ import type { ColumnDef } from '@tanstack/react-table'
4
+ import { ListView } from '@fayz-ai/ui'
5
+ import { useCrmStore } from '../CrmContext'
6
+ import { useTranslation } from '@fayz-ai/core'
7
+ import { SubpageHeader } from '@fayz-ai/ui'
8
+ import type { Lead, LeadStatus } from '../types'
9
+
10
+ const STATUS_OPTIONS: { value: LeadStatus; label: string; color: string }[] = [
11
+ { value: 'new', label: 'New', color: 'bg-info-soft text-info-soft-foreground' },
12
+ { value: 'contacted', label: 'Contacted', color: 'bg-magic-soft text-magic-soft-foreground' },
13
+ { value: 'qualified', label: 'Qualified', color: 'bg-success-soft text-success-soft-foreground' },
14
+ { value: 'unqualified', label: 'Unqualified', color: 'bg-muted text-muted-foreground' },
15
+ { value: 'converted', label: 'Converted', color: 'bg-warning-soft text-warning-soft-foreground' },
16
+ ]
17
+
18
+ const columns: ColumnDef<Lead, any>[] = [
19
+ { accessorKey: 'name', header: 'Name', cell: ({ getValue }) => <span className="font-medium">{getValue() as string}</span> },
20
+ {
21
+ id: 'contact', header: 'Contact',
22
+ cell: ({ row }) => <span className="text-muted-foreground text-xs">{row.original.email || row.original.phone || '—'}</span>,
23
+ },
24
+ {
25
+ accessorKey: 'sourceName', header: 'Source',
26
+ cell: ({ getValue }) => <span className="text-muted-foreground text-xs">{(getValue() as string) || '—'}</span>,
27
+ },
28
+ {
29
+ accessorKey: 'status', header: 'Status',
30
+ cell: ({ getValue }) => {
31
+ const status = getValue() as string
32
+ const opt = STATUS_OPTIONS.find((o) => o.value === status)
33
+ return (
34
+ <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${opt?.color ?? 'bg-muted text-muted-foreground'}`}>
35
+ {opt?.label ?? status}
36
+ </span>
37
+ )
38
+ },
39
+ },
40
+ ]
41
+
42
+ export function LeadListView({ onNew, onEdit }: { onNew?: () => void; onEdit?: (id: string) => void }) {
43
+ const t = useTranslation()
44
+ const leads = useCrmStore((s) => s.leads)
45
+ const leadsLoading = useCrmStore((s) => s.leadsLoading)
46
+ const fetchLeads = useCrmStore((s) => s.fetchLeads)
47
+ const [search, setSearch] = useState('')
48
+ const [statusFilter, setStatusFilter] = useState<LeadStatus[]>([])
49
+
50
+ useEffect(() => {
51
+ fetchLeads({ status: statusFilter.length > 0 ? statusFilter : undefined, search: search || undefined })
52
+ }, [statusFilter, search])
53
+
54
+ // Multi-select tag filter: toggle individual statuses
55
+ const tags = useMemo(() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: o.label })), [])
56
+
57
+ return (
58
+ <div className="space-y-4">
59
+ <SubpageHeader title={t('crm.leads.title')} subtitle={`${leads.length} leads`} />
60
+ <ListView<Lead>
61
+ columns={columns}
62
+ data={leads}
63
+ loading={leadsLoading}
64
+ searchPlaceholder={t('crm.leads.searchPlaceholder')}
65
+ search={search}
66
+ onSearchChange={setSearch}
67
+ searchDebounce={0}
68
+ tags={tags}
69
+ activeTag={statusFilter.length === 1 ? statusFilter[0] : undefined}
70
+ onTagChange={(v) => setStatusFilter(v ? [v as LeadStatus] : [])}
71
+ newLabel={t('crm.leads.newLead')}
72
+ onNew={onNew}
73
+ onRowClick={(row) => onEdit?.(row.id)}
74
+ emptyIcon={UserPlus}
75
+ emptyMessage={t('crm.leads.noLeads')}
76
+ emptyActionLabel={onNew ? t('crm.leads.captureFirst') : undefined}
77
+ onEmptyAction={onNew}
78
+ />
79
+ </div>
80
+ )
81
+ }
@@ -0,0 +1,299 @@
1
+ import React, { useEffect, useRef, useState } from 'react'
2
+ import { Loader2, Plus } from 'lucide-react'
3
+ import { toast } from '@fayz-ai/ui'
4
+ import { useCrmStore, useCrmConfig, formatCurrency } from '../CrmContext'
5
+ import { useTranslation } from '@fayz-ai/core'
6
+ import { SubpageHeader } from '@fayz-ai/ui'
7
+ import { DealSidebar } from './DealSidebar'
8
+ import type { Deal } from '../types'
9
+
10
+ // ---------------------------------------------------------------------------
11
+ // Skeleton
12
+ // ---------------------------------------------------------------------------
13
+
14
+ function PipelineSkeleton() {
15
+ return (
16
+ <div className="flex gap-3 overflow-x-auto pb-2">
17
+ {[1, 2, 3, 4, 5].map((col) => (
18
+ <div key={col} className="min-w-[240px] max-w-[280px] flex-shrink-0">
19
+ <div className="flex items-center gap-2 mb-2 px-1">
20
+ <div className="h-2 w-2 rounded-full bg-muted/40 animate-pulse" />
21
+ <div className="h-3 w-16 rounded bg-muted/40 animate-pulse" />
22
+ <div className="h-3 w-5 rounded bg-muted/30 animate-pulse" />
23
+ </div>
24
+ <div className="space-y-2">
25
+ {Array.from({ length: col <= 2 ? 2 : 1 }).map((_, i) => (
26
+ <div key={i} className="rounded-lg border bg-card shadow-sm p-3 space-y-2">
27
+ <div className="h-4 w-3/4 rounded bg-muted/40 animate-pulse" />
28
+ <div className="h-3 w-1/2 rounded bg-muted/30 animate-pulse" />
29
+ <div className="flex items-center justify-between pt-1">
30
+ <div className="h-3 w-16 rounded bg-muted/40 animate-pulse" />
31
+ <div className="h-3 w-8 rounded bg-muted/30 animate-pulse" />
32
+ </div>
33
+ </div>
34
+ ))}
35
+ </div>
36
+ </div>
37
+ ))}
38
+ </div>
39
+ )
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Deal card
44
+ // ---------------------------------------------------------------------------
45
+
46
+ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }: {
47
+ deal: Deal
48
+ saving?: boolean
49
+ currency: { code: string; locale: string; symbol: string }
50
+ onClick?: () => void
51
+ onDragStart: (e: React.DragEvent) => void
52
+ onDragEnd: (e: React.DragEvent) => void
53
+ }) {
54
+ return (
55
+ <div
56
+ draggable={!saving}
57
+ onDragStart={onDragStart}
58
+ onDragEnd={onDragEnd}
59
+ onClick={onClick}
60
+ className={`rounded-lg border bg-card p-3 transition-shadow ${saving ? 'opacity-70' : 'hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70'}`}
61
+ >
62
+ <div className="flex items-center justify-between gap-2">
63
+ <p className="text-sm font-medium truncate">{deal.title}</p>
64
+ {saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground shrink-0" />}
65
+ </div>
66
+ {deal.contactName && <p className="text-[10px] text-muted-foreground mt-0.5">{deal.contactName}</p>}
67
+ <div className="flex items-center justify-between mt-2">
68
+ <span className="text-xs font-semibold">{formatCurrency(deal.value, currency)}</span>
69
+ <span className="text-[10px] text-muted-foreground">{deal.probability}%</span>
70
+ </div>
71
+ </div>
72
+ )
73
+ }
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // Stage column
77
+ // ---------------------------------------------------------------------------
78
+
79
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }: {
80
+ stageId: string
81
+ stageName: string
82
+ stageColor: string
83
+ deals: Deal[]
84
+ savingDealIds: Set<string>
85
+ currency: { code: string; locale: string; symbol: string }
86
+ dragOverStageId: string | null
87
+ onDealClick?: (id: string) => void
88
+ onAddLead?: () => void
89
+ onDragStart: (dealId: string, fromStageId: string) => void
90
+ onDragEnd: () => void
91
+ onDragOver: (e: React.DragEvent) => void
92
+ onDragLeave: () => void
93
+ onDrop: () => void
94
+ }) {
95
+ const t = useTranslation()
96
+ const isOver = dragOverStageId === stageId
97
+ const [hovered, setHovered] = useState(false)
98
+
99
+ return (
100
+ <div
101
+ className="min-w-[240px] max-w-[280px] flex-shrink-0 flex flex-col"
102
+ onMouseEnter={() => setHovered(true)}
103
+ onMouseLeave={() => setHovered(false)}
104
+ >
105
+ <div className="flex items-center gap-2 mb-2 px-1">
106
+ <div className="h-2 w-2 rounded-full shrink-0" style={{ backgroundColor: stageColor }} />
107
+ <span className="text-xs font-semibold">{stageName}</span>
108
+ <span className="text-[10px] text-muted-foreground">({deals.length})</span>
109
+ <div className="flex-1" />
110
+ {onAddLead && (
111
+ <button
112
+ onClick={onAddLead}
113
+ 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'}`}
114
+ title="Add lead"
115
+ >
116
+ <Plus className="h-3.5 w-3.5" />
117
+ </button>
118
+ )}
119
+ </div>
120
+ <div
121
+ onDragOver={onDragOver}
122
+ onDragLeave={onDragLeave}
123
+ onDrop={onDrop}
124
+ 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' : ''}`}
125
+ >
126
+ {deals.length === 0 ? (
127
+ <div className={`rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground ${isOver ? 'border-primary/30' : ''}`}>
128
+ {isOver ? t('crm.pipeline.dropHere') : t('crm.pipeline.noDeals')}
129
+ </div>
130
+ ) : (
131
+ deals.map((deal) => (
132
+ <DealCard
133
+ key={deal.id}
134
+ deal={deal}
135
+ saving={savingDealIds.has(deal.id)}
136
+ currency={currency}
137
+ onClick={() => onDealClick?.(deal.id)}
138
+ onDragStart={(e) => {
139
+ e.dataTransfer.effectAllowed = 'move'
140
+ onDragStart(deal.id, stageId)
141
+ }}
142
+ onDragEnd={onDragEnd}
143
+ />
144
+ ))
145
+ )}
146
+ </div>
147
+ </div>
148
+ )
149
+ }
150
+
151
+ // ---------------------------------------------------------------------------
152
+ // Pipeline view
153
+ // ---------------------------------------------------------------------------
154
+
155
+ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }: {
156
+ onDealClick?: (id: string) => void
157
+ onViewLead?: (id: string) => void
158
+ onViewQuote?: (id: string) => void
159
+ onAddLead?: () => void
160
+ }) {
161
+ const { currency } = useCrmConfig()
162
+ const pipelines = useCrmStore((s) => s.pipelines)
163
+ const stages = useCrmStore((s) => s.stages)
164
+ const dealsByStage = useCrmStore((s) => s.dealsByStage)
165
+ const dealsLoading = useCrmStore((s) => s.dealsLoading)
166
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
167
+ const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage)
168
+ const moveDealToStage = useCrmStore((s) => s.moveDealToStage)
169
+
170
+ const [dragOverStageId, setDragOverStageId] = useState<string | null>(null)
171
+ const [savingDealIds, setSavingDealIds] = useState<Set<string>>(new Set())
172
+ const [optimisticBoard, setOptimisticBoard] = useState<Map<string, Deal[]> | null>(null)
173
+ const t = useTranslation()
174
+ const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
175
+ const dragRef = useRef<{ dealId: string; fromStageId: string } | null>(null)
176
+
177
+ useEffect(() => { fetchPipelines() }, [])
178
+ useEffect(() => { if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id) }, [pipelines])
179
+
180
+ // Clear optimistic state when real data arrives and no moves are in-flight
181
+ useEffect(() => {
182
+ if (savingDealIds.size === 0) setOptimisticBoard(null)
183
+ }, [dealsByStage, savingDealIds])
184
+
185
+ const visibleStages = stages.filter((s) => !s.isLost)
186
+ const displayBoard = optimisticBoard ?? dealsByStage
187
+
188
+ function handleDragStart(dealId: string, fromStageId: string) {
189
+ dragRef.current = { dealId, fromStageId }
190
+ }
191
+
192
+ function handleDragEnd() {
193
+ dragRef.current = null
194
+ setDragOverStageId(null)
195
+ }
196
+
197
+ function handleDragOver(stageId: string, e: React.DragEvent) {
198
+ e.preventDefault()
199
+ e.dataTransfer.dropEffect = 'move'
200
+ if (dragOverStageId !== stageId) setDragOverStageId(stageId)
201
+ }
202
+
203
+ function handleDrop(toStageId: string) {
204
+ const drag = dragRef.current
205
+ if (!drag) return
206
+ dragRef.current = null
207
+ setDragOverStageId(null)
208
+
209
+ if (drag.fromStageId === toStageId) return
210
+
211
+ const { dealId, fromStageId } = drag
212
+ const targetStage = stages.find((s) => s.id === toStageId)
213
+
214
+ // Optimistic update — move the card instantly
215
+ const currentBoard = optimisticBoard ?? dealsByStage
216
+ const nextBoard = new Map(currentBoard)
217
+ const fromDeals = [...(nextBoard.get(fromStageId) ?? [])]
218
+ const movedDeal = fromDeals.find((d) => d.id === dealId)
219
+ if (!movedDeal) return
220
+
221
+ const updatedDeal: Deal = {
222
+ ...movedDeal,
223
+ stageId: toStageId,
224
+ stageName: targetStage?.name,
225
+ stageColor: targetStage?.color,
226
+ probability: targetStage?.probability ?? movedDeal.probability,
227
+ }
228
+
229
+ nextBoard.set(fromStageId, fromDeals.filter((d) => d.id !== dealId))
230
+ nextBoard.set(toStageId, [...(nextBoard.get(toStageId) ?? []), updatedDeal])
231
+ setOptimisticBoard(nextBoard)
232
+ setSavingDealIds((prev) => new Set(prev).add(dealId))
233
+
234
+ // Persist in background
235
+ moveDealToStage(dealId, toStageId)
236
+ .then(() => {
237
+ toast.success(t('crm.pipeline.movedTo', { stage: targetStage?.name ?? 'stage' }))
238
+ })
239
+ .catch(() => {
240
+ setOptimisticBoard(null)
241
+ toast.error(t('crm.pipeline.moveFailed'))
242
+ })
243
+ .finally(() => {
244
+ setSavingDealIds((prev) => {
245
+ const next = new Set(prev)
246
+ next.delete(dealId)
247
+ return next
248
+ })
249
+ })
250
+ }
251
+
252
+ function handleDealClick(dealId: string) {
253
+ setSelectedDealId(dealId)
254
+ onDealClick?.(dealId)
255
+ }
256
+
257
+ return (
258
+ <div className="space-y-4">
259
+ <SubpageHeader title={t('crm.pipeline.title')} subtitle={t('crm.pipeline.subtitle')} />
260
+
261
+ {dealsLoading && dealsByStage.size === 0 ? (
262
+ <PipelineSkeleton />
263
+ ) : (
264
+ <div className="flex gap-3 overflow-x-auto pb-2">
265
+ {visibleStages.map((stage) => {
266
+ const deals = displayBoard.get(stage.id) ?? []
267
+ return (
268
+ <StageColumn
269
+ key={stage.id}
270
+ stageId={stage.id}
271
+ stageName={stage.name}
272
+ stageColor={stage.color}
273
+ deals={deals}
274
+ savingDealIds={savingDealIds}
275
+ currency={currency}
276
+ dragOverStageId={dragOverStageId}
277
+ onDealClick={handleDealClick}
278
+ onAddLead={onAddLead}
279
+ onDragStart={handleDragStart}
280
+ onDragEnd={handleDragEnd}
281
+ onDragOver={(e) => handleDragOver(stage.id, e)}
282
+ onDragLeave={() => { if (dragOverStageId === stage.id) setDragOverStageId(null) }}
283
+ onDrop={() => handleDrop(stage.id)}
284
+ />
285
+ )
286
+ })}
287
+ </div>
288
+ )}
289
+
290
+ <DealSidebar
291
+ dealId={selectedDealId ?? ''}
292
+ open={!!selectedDealId}
293
+ onClose={() => setSelectedDealId(null)}
294
+ onViewLead={onViewLead}
295
+ onViewQuote={onViewQuote}
296
+ />
297
+ </div>
298
+ )
299
+ }