@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,13 @@
1
1
  import React, { useEffect, useState } from 'react'
2
- import { Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Clock, Filter, Calendar } from 'lucide-react'
3
- import { useCrmStore } from '../CrmContext'
2
+ import {
3
+ Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Clock, Filter, Calendar,
4
+ UserPlus, ArrowRightLeft, Target, MoveRight, Trophy, XCircle, FilePlus2, Send, FileCheck2, FileX2, Sparkles, ArrowRight, Archive,
5
+ } from 'lucide-react'
6
+ import { useCrmStore, useCrmProvider } from '../CrmContext'
4
7
  import { useTranslation } from '@fayz-ai/core'
5
8
  import { SubpageHeader } from '@fayz-ai/ui'
6
- import type { ActivityType } from '../types'
9
+ import { DealSidebar } from './DealSidebar'
10
+ import { SYSTEM_ACTIVITY_TYPES, type ActivityType } from '../types'
7
11
 
8
12
  const TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; label: string }> = {
9
13
  call: { icon: Phone, color: 'bg-info/15 text-info dark:bg-info/20', label: 'Call' },
@@ -12,8 +16,25 @@ const TYPE_CONFIG: Record<string, { icon: React.ElementType; color: string; labe
12
16
  note: { icon: FileText, color: 'bg-warning/15 text-warning dark:bg-warning/20', label: 'Note' },
13
17
  task: { icon: CheckSquare, color: 'bg-pink-100 text-pink-600 dark:bg-pink-500/20 dark:text-pink-400', label: 'Task' },
14
18
  whatsapp: { icon: MessageCircle, color: 'bg-success/15 text-success dark:bg-success/20', label: 'WhatsApp' },
19
+ // System timeline events (auto-logged by the data provider on every CRM write)
20
+ lead_created: { icon: UserPlus, color: 'bg-info/15 text-info dark:bg-info/20', label: 'Lead created' },
21
+ lead_converted: { icon: ArrowRightLeft, color: 'bg-magic/15 text-magic dark:bg-magic/20', label: 'Lead converted' },
22
+ deal_created: { icon: Target, color: 'bg-info/15 text-info dark:bg-info/20', label: 'Deal created' },
23
+ stage_changed: { icon: MoveRight, color: 'bg-warning/15 text-warning dark:bg-warning/20', label: 'Stage changed' },
24
+ deal_won: { icon: Trophy, color: 'bg-success/15 text-success dark:bg-success/20', label: 'Deal won' },
25
+ deal_lost: { icon: XCircle, color: 'bg-destructive/15 text-destructive dark:bg-destructive/20', label: 'Deal lost' },
26
+ quote_created: { icon: FilePlus2, color: 'bg-info/15 text-info dark:bg-info/20', label: 'Quote created' },
27
+ quote_sent: { icon: Send, color: 'bg-magic/15 text-magic dark:bg-magic/20', label: 'Quote sent' },
28
+ quote_approved: { icon: FileCheck2, color: 'bg-success/15 text-success dark:bg-success/20', label: 'Quote approved' },
29
+ quote_rejected: { icon: FileX2, color: 'bg-destructive/15 text-destructive dark:bg-destructive/20', label: 'Quote rejected' },
30
+ lead_archived: { icon: Archive, color: 'bg-muted text-muted-foreground', label: 'Lead archived' },
31
+ deal_archived: { icon: Archive, color: 'bg-muted text-muted-foreground', label: 'Deal archived' },
32
+ quote_archived: { icon: Archive, color: 'bg-muted text-muted-foreground', label: 'Quote archived' },
15
33
  }
16
34
 
35
+ const SYSTEM_TYPES = new Set<string>(SYSTEM_ACTIVITY_TYPES)
36
+ const MANUAL_TYPES = Object.keys(TYPE_CONFIG).filter((t) => !SYSTEM_TYPES.has(t))
37
+
17
38
  function ActivitySkeleton() {
18
39
  return (
19
40
  <div className="space-y-2">
@@ -35,22 +56,34 @@ function ActivitySkeleton() {
35
56
  )
36
57
  }
37
58
 
38
- export function ActivityListView() {
59
+ export function ActivityListView({ onOpenLead, onOpenQuote }: {
60
+ /** Navigate to the lead detail (fallback for activities with no deal behind them). */
61
+ onOpenLead?: (leadId: string) => void
62
+ /** Navigate to a quote detail (links inside the deal sidebar). */
63
+ onOpenQuote?: (quoteId: string) => void
64
+ } = {}) {
39
65
  const t = useTranslation()
66
+ const provider = useCrmProvider()
67
+ // Clicking a row opens the SAME right-hand deal sheet the pipeline uses —
68
+ // the timeline stays underneath instead of navigating away.
69
+ const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
40
70
  const activities = useCrmStore((s) => s.activities)
41
71
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading)
42
72
  const fetchActivities = useCrmStore((s) => s.fetchActivities)
43
73
  const [typeFilter, setTypeFilter] = useState<string | null>(null)
44
74
  const [showCompleted, setShowCompleted] = useState<boolean | null>(null)
75
+ // 'events' = all system timeline types (filtered client-side; the provider
76
+ // query takes a single activityType).
77
+ const eventsFilter = typeFilter === 'events'
45
78
 
46
79
  useEffect(() => {
47
80
  fetchActivities({
48
- activityType: typeFilter as ActivityType | undefined,
49
- completed: showCompleted ?? undefined,
81
+ activityType: eventsFilter ? undefined : (typeFilter as ActivityType | undefined),
82
+ completed: eventsFilter ? undefined : (showCompleted ?? undefined),
50
83
  })
51
84
  }, [typeFilter, showCompleted])
52
85
 
53
- const filtered = activities
86
+ const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities
54
87
 
55
88
  // Stats
56
89
  const pendingCount = activities.filter((a) => !a.completedAt).length
@@ -73,7 +106,8 @@ export function ActivityListView() {
73
106
  >
74
107
  {t('crm.activities.all')}
75
108
  </button>
76
- {Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
109
+ {MANUAL_TYPES.map((type) => {
110
+ const cfg = TYPE_CONFIG[type]
77
111
  const Icon = cfg.icon
78
112
  return (
79
113
  <button
@@ -86,6 +120,13 @@ export function ActivityListView() {
86
120
  </button>
87
121
  )
88
122
  })}
123
+ <button
124
+ onClick={() => setTypeFilter(eventsFilter ? null : 'events')}
125
+ className={`inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${eventsFilter ? 'bg-primary/15 text-primary' : 'bg-muted/50 text-muted-foreground hover:bg-muted'}`}
126
+ >
127
+ <Sparkles className="h-3 w-3" />
128
+ {t('crm.activities.systemEvents')}
129
+ </button>
89
130
  </div>
90
131
 
91
132
  <div className="flex-1" />
@@ -123,12 +164,27 @@ export function ActivityListView() {
123
164
  {filtered.map((a) => {
124
165
  const cfg = TYPE_CONFIG[a.activityType] ?? { icon: FileText, color: 'bg-muted text-muted-foreground', label: a.activityType }
125
166
  const Icon = cfg.icon
167
+ const isSystem = SYSTEM_TYPES.has(a.activityType)
126
168
  const isOverdue = !a.completedAt && a.dueDate && a.dueDate < new Date().toISOString().slice(0, 10)
169
+ const openRecord = a.dealId
170
+ ? () => setSelectedDealId(a.dealId!)
171
+ : a.leadId
172
+ ? () => {
173
+ // Lead-only activity: its deal (auto-created with the lead)
174
+ // opens in the sheet; a dealless lead falls back to detail.
175
+ void provider.getDealByLeadId(a.leadId!).then((deal) => {
176
+ if (deal) setSelectedDealId(deal.id)
177
+ else onOpenLead?.(a.leadId!)
178
+ })
179
+ }
180
+ : undefined
127
181
 
128
182
  return (
129
183
  <div
130
184
  key={a.id}
131
- className={`flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? 'border-destructive/30 dark:border-destructive/20' : ''}`}
185
+ onClick={openRecord}
186
+ role={openRecord ? 'button' : undefined}
187
+ className={`group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? 'border-destructive/30 dark:border-destructive/20' : ''} ${openRecord ? 'cursor-pointer hover:bg-muted/30' : ''}`}
132
188
  >
133
189
  <div className={`flex h-9 w-9 items-center justify-center rounded-lg shrink-0 ${cfg.color}`}>
134
190
  <Icon className="h-4 w-4" />
@@ -136,7 +192,8 @@ export function ActivityListView() {
136
192
  <div className="flex-1 min-w-0 pt-0.5">
137
193
  <div className="flex items-center gap-2">
138
194
  <p className="text-sm font-medium truncate">{a.title}</p>
139
- {a.completedAt && (
195
+ {/* System events are facts, not tasks — no "done" badge noise. */}
196
+ {a.completedAt && !isSystem && (
140
197
  <span className="inline-flex items-center gap-0.5 rounded-full bg-success/15 px-1.5 py-0.5 text-[9px] font-medium text-success dark:bg-success/20">
141
198
  <Check className="h-2.5 w-2.5" /> {t('crm.activities.done')}
142
199
  </span>
@@ -170,14 +227,25 @@ export function ActivityListView() {
170
227
  )}
171
228
  </div>
172
229
  </div>
173
- <span className="text-[10px] text-muted-foreground shrink-0 pt-1">
230
+ <span className="flex items-center gap-1.5 text-[10px] text-muted-foreground shrink-0 pt-1">
174
231
  {new Date(a.createdAt).toLocaleDateString()}
232
+ {openRecord && (
233
+ <ArrowRight className="h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" />
234
+ )}
175
235
  </span>
176
236
  </div>
177
237
  )
178
238
  })}
179
239
  </div>
180
240
  )}
241
+
242
+ <DealSidebar
243
+ dealId={selectedDealId ?? ''}
244
+ open={!!selectedDealId}
245
+ onClose={() => setSelectedDealId(null)}
246
+ onViewLead={onOpenLead}
247
+ onViewQuote={onOpenQuote}
248
+ />
181
249
  </div>
182
250
  )
183
251
  }
@@ -1,10 +1,11 @@
1
1
  import React, { useEffect, useState } from 'react'
2
- import { Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Calendar, DollarSign, User, Target, Clock, ArrowRight } from 'lucide-react'
2
+ import { Phone, Mail, Users, FileText, CheckSquare, MessageCircle, Check, Calendar, DollarSign, User, Target, Clock, ArrowRight, UserPlus, ArrowRightLeft, MoveRight, Trophy, XCircle, FilePlus2, Send, FileCheck2, FileX2, Archive } from 'lucide-react'
3
3
  import { useTranslation } from '@fayz-ai/core'
4
- import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription } from '@fayz-ai/ui'
4
+ import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, SheetDescription, SegmentedControl } from '@fayz-ai/ui'
5
5
  import { PersonLink } from '@fayz-ai/saas'
6
- import { useCrmProvider, useCrmConfig, formatCurrency } from '../CrmContext'
6
+ import { useCrmProvider, useCrmConfig, useCrmStore, formatCurrency } from '../CrmContext'
7
7
  import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
8
+ import { TagChips } from '../components/TagChips'
8
9
  import { answerEntries, humanizeKey, renderFieldValue } from '../lib/form-answers'
9
10
  import type { Deal, Lead, Quote, Activity } from '../types'
10
11
 
@@ -14,6 +15,11 @@ import type { Deal, Lead, Quote, Activity } from '../types'
14
15
 
15
16
  const TYPE_ICONS: Record<string, React.ElementType> = {
16
17
  call: Phone, email: Mail, meeting: Users, note: FileText, task: CheckSquare, whatsapp: MessageCircle,
18
+ // System timeline events (auto-logged by the provider)
19
+ lead_created: UserPlus, lead_converted: ArrowRightLeft, deal_created: Target,
20
+ stage_changed: MoveRight, deal_won: Trophy, deal_lost: XCircle,
21
+ quote_created: FilePlus2, quote_sent: Send, quote_approved: FileCheck2, quote_rejected: FileX2,
22
+ lead_archived: Archive, deal_archived: Archive, quote_archived: Archive,
17
23
  }
18
24
 
19
25
 
@@ -25,34 +31,31 @@ type TabId = 'overview' | 'activity' | 'quotes'
25
31
 
26
32
  function TabBar({ active, counts, onChange }: { active: TabId; counts: { activity: number; quotes: number }; onChange: (id: TabId) => void }) {
27
33
  const t = useTranslation()
28
- const tabs: { id: TabId; label: string; count?: number }[] = [
29
- { id: 'overview', label: t('crm.dealSidebar.overview') },
30
- { id: 'activity', label: t('crm.dealSidebar.activity'), count: counts.activity },
31
- { id: 'quotes', label: t('crm.dealSidebar.quotes'), count: counts.quotes },
32
- ]
34
+
35
+ const label = (text: string, count: number | undefined, isActive: boolean) => (
36
+ <span className="inline-flex items-center gap-1.5">
37
+ {text}
38
+ {count != null && count > 0 && (
39
+ <span className={`inline-flex items-center justify-center min-w-[16px] h-4 rounded-full px-1 text-[10px] font-semibold ${
40
+ isActive ? 'bg-background/20 text-background' : 'bg-muted text-muted-foreground'
41
+ }`}>
42
+ {count}
43
+ </span>
44
+ )}
45
+ </span>
46
+ )
33
47
 
34
48
  return (
35
- <div className="flex items-center gap-0.5 px-5 py-2 border-b shrink-0 bg-muted/20">
36
- {tabs.map((tab) => (
37
- <button
38
- key={tab.id}
39
- onClick={() => onChange(tab.id)}
40
- className={`relative px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${
41
- active === tab.id
42
- ? 'bg-card text-foreground shadow-sm'
43
- : 'text-muted-foreground hover:text-foreground'
44
- }`}
45
- >
46
- {tab.label}
47
- {tab.count != null && tab.count > 0 && (
48
- <span className={`ml-1 inline-flex items-center justify-center min-w-[16px] h-4 rounded-full px-1 text-[10px] font-semibold ${
49
- active === tab.id ? 'bg-primary/10 text-primary' : 'bg-muted text-muted-foreground'
50
- }`}>
51
- {tab.count}
52
- </span>
53
- )}
54
- </button>
55
- ))}
49
+ <div className="px-5 py-2 border-b shrink-0">
50
+ <SegmentedControl<TabId>
51
+ value={active}
52
+ onChange={onChange}
53
+ options={[
54
+ { value: 'overview', label: label(t('crm.dealSidebar.overview'), undefined, active === 'overview') },
55
+ { value: 'activity', label: label(t('crm.dealSidebar.activity'), counts.activity, active === 'activity') },
56
+ { value: 'quotes', label: label(t('crm.dealSidebar.quotes'), counts.quotes, active === 'quotes') },
57
+ ]}
58
+ />
56
59
  </div>
57
60
  )
58
61
  }
@@ -91,6 +94,11 @@ function FormAnswers({ lead }: { lead: Lead | null }) {
91
94
  function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null; currency: { code: string; locale: string; symbol: string } }) {
92
95
  const t = useTranslation()
93
96
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase()
97
+ // O painel também abre a partir do detalhe do lead, onde o board nunca
98
+ // montou — por isso busca por conta própria em vez de herdar do funil.
99
+ const tagDefs = useCrmStore((s) => s.tagDefs)
100
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs)
101
+ useEffect(() => { fetchTagDefs() }, [])
94
102
 
95
103
  return (
96
104
  <div className="space-y-5">
@@ -178,11 +186,8 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
178
186
  {deal.tags && deal.tags.length > 0 && (
179
187
  <div className="space-y-2">
180
188
  <h4 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">{t('crm.dealSidebar.tags')}</h4>
181
- <div className="flex gap-1.5 flex-wrap">
182
- {deal.tags.map((tag) => (
183
- <span key={tag} className="inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground">{tag}</span>
184
- ))}
185
- </div>
189
+ {/* Sem `max`: no detalhe cabe tudo. É o card do funil que resume. */}
190
+ <TagChips tags={deal.tags} defs={tagDefs} size="sm" className="gap-1.5" />
186
191
  </div>
187
192
  )}
188
193
 
@@ -194,11 +199,6 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
194
199
  </div>
195
200
  )}
196
201
 
197
- {/* Dates */}
198
- <div className="flex items-center gap-4 pt-3 border-t text-[10px] text-muted-foreground">
199
- <span>{t('crm.dealSidebar.created')} {deal.createdAt?.slice(0, 10)}</span>
200
- {deal.updatedAt && <span>{t('crm.dealSidebar.updated')} {deal.updatedAt?.slice(0, 10)}</span>}
201
- </div>
202
202
  </div>
203
203
  )
204
204
  }
@@ -428,6 +428,15 @@ export function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }:
428
428
  )}
429
429
  </SheetBody>
430
430
 
431
+ {/* Timestamps pinned to the sheet foot — same pattern as the assistant
432
+ notes detail (border-t hairline, tiny muted line, `·` separator). */}
433
+ {deal && (
434
+ <p className="shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60">
435
+ {t('crm.dealSidebar.created')} {deal.createdAt?.slice(0, 10)}
436
+ {deal.updatedAt ? ` · ${t('crm.dealSidebar.updated')} ${deal.updatedAt.slice(0, 10)}` : ''}
437
+ </p>
438
+ )}
439
+
431
440
  {/* Footer */}
432
441
  {deal && lead && onViewLead && (
433
442
  <SheetFooter>
@@ -1,6 +1,7 @@
1
1
  import React, { useEffect, useState } from 'react'
2
- import { UserPlus, FileText } from 'lucide-react'
3
- import { useCrmProvider, useCrmConfig, formatCurrency } from '../CrmContext'
2
+ import { UserPlus, FileText, Archive } from 'lucide-react'
3
+ import { useCrmProvider, useCrmConfig, formatCurrency, useCrmStore } from '../CrmContext'
4
+ import { useCanArchive } from '../lib/access'
4
5
  import { useTranslation } from '@fayz-ai/core'
5
6
  import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
6
7
  import { Breadcrumb } from '@fayz-ai/ui'
@@ -49,6 +50,9 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
49
50
  const provider = useCrmProvider()
50
51
  const { currency } = useCrmConfig()
51
52
  const t = useTranslation()
53
+ const archiveLead = useCrmStore((s) => s.archiveLead)
54
+ const canArchive = useCanArchive()
55
+ const [archiving, setArchiving] = useState(false)
52
56
  const [lead, setLead] = useState<Lead | null>(null)
53
57
  const [deal, setDeal] = useState<Deal | null>(null)
54
58
  const [quotes, setQuotes] = useState<Quote[]>([])
@@ -140,14 +144,29 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
140
144
  </div>
141
145
  </div>
142
146
  {/* Actions */}
143
- {onCreateQuote && lead.status !== 'converted' && lead.status !== 'lost' && (
144
- <button
145
- onClick={() => onCreateQuote(leadId)}
146
- className="inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors shrink-0"
147
- >
148
- <FileText className="h-3 w-3" /> {t('crm.leadDetail.createQuote')}
149
- </button>
150
- )}
147
+ <div className="flex items-center gap-2 shrink-0">
148
+ {canArchive && (
149
+ <button
150
+ onClick={() => {
151
+ setArchiving(true)
152
+ archiveLead(leadId).then(onBack).catch(() => setArchiving(false))
153
+ }}
154
+ disabled={archiving}
155
+ title={t('crm.leadDetail.archive')}
156
+ className="inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground bg-card shadow-button active:shadow-button-inset transition-colors disabled:opacity-60"
157
+ >
158
+ <Archive className="h-3 w-3" /> {t('crm.leadDetail.archive')}
159
+ </button>
160
+ )}
161
+ {onCreateQuote && lead.status !== 'converted' && lead.status !== 'lost' && (
162
+ <button
163
+ onClick={() => onCreateQuote(leadId)}
164
+ className="inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors"
165
+ >
166
+ <FileText className="h-3 w-3" /> {t('crm.leadDetail.createQuote')}
167
+ </button>
168
+ )}
169
+ </div>
151
170
  </div>
152
171
 
153
172
  {/* Separator */}
@@ -1,11 +1,21 @@
1
- import React, { useEffect, useRef, useState } from 'react'
2
- import { Loader2, Plus } from 'lucide-react'
1
+ import React, { useEffect, useMemo, useRef, useState } from 'react'
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
- import { useTranslation, getSupabaseClientOptional } from '@fayz-ai/core'
5
+ import { useCanArchive } from '../lib/access'
6
+ import { useTranslation, getSupabaseClientOptional, useActiveTenantId } from '@fayz-ai/core'
6
7
  import { SubpageHeader } from '@fayz-ai/ui'
7
8
  import { DealSidebar } from './DealSidebar'
8
- 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
+ }
9
19
 
10
20
  // ---------------------------------------------------------------------------
11
21
  // Skeleton
@@ -43,27 +53,44 @@ function PipelineSkeleton() {
43
53
  // Deal card
44
54
  // ---------------------------------------------------------------------------
45
55
 
46
- function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }: {
56
+ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragStart, onDragEnd }: {
47
57
  deal: Deal
48
58
  saving?: boolean
49
59
  currency: { code: string; locale: string; symbol: string }
60
+ tagDefs?: Map<string, TagDef>
50
61
  onClick?: () => void
62
+ /** Present only when the archive permission resolved true (useCanArchive). */
63
+ onArchive?: () => void
51
64
  onDragStart: (e: React.DragEvent) => void
52
65
  onDragEnd: (e: React.DragEvent) => void
53
66
  }) {
67
+ const t = useTranslation()
54
68
  return (
55
69
  <div
56
70
  draggable={!saving}
57
71
  onDragStart={onDragStart}
58
72
  onDragEnd={onDragEnd}
59
73
  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'}`}
74
+ 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'}`}
61
75
  >
62
76
  <div className="flex items-center justify-between gap-2">
63
77
  <p className="text-sm font-medium truncate">{deal.title}</p>
64
78
  {saving && <Loader2 className="h-3 w-3 animate-spin text-muted-foreground shrink-0" />}
79
+ {!saving && onArchive && (
80
+ <button
81
+ onClick={(e) => { e.stopPropagation(); onArchive() }}
82
+ title={t('crm.pipeline.archive')}
83
+ 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"
84
+ >
85
+ <Archive className="h-3 w-3" />
86
+ </button>
87
+ )}
65
88
  </div>
66
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" />
67
94
  <div className="flex items-center justify-between mt-2">
68
95
  <span className="text-xs font-semibold">{formatCurrency(deal.value, currency)}</span>
69
96
  <span className="text-[10px] text-muted-foreground">{deal.probability}%</span>
@@ -76,15 +103,17 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }: {
76
103
  // Stage column
77
104
  // ---------------------------------------------------------------------------
78
105
 
79
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, 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 }: {
80
107
  stageId: string
81
108
  stageName: string
82
109
  stageColor: string
83
110
  deals: Deal[]
84
111
  savingDealIds: Set<string>
85
112
  currency: { code: string; locale: string; symbol: string }
113
+ tagDefs?: Map<string, TagDef>
86
114
  dragOverStageId: string | null
87
115
  onDealClick?: (id: string) => void
116
+ onArchiveDeal?: (id: string) => void
88
117
  onAddLead?: () => void
89
118
  onDragStart: (dealId: string, fromStageId: string) => void
90
119
  onDragEnd: () => void
@@ -134,7 +163,9 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
134
163
  deal={deal}
135
164
  saving={savingDealIds.has(deal.id)}
136
165
  currency={currency}
166
+ tagDefs={tagDefs}
137
167
  onClick={() => onDealClick?.(deal.id)}
168
+ onArchive={onArchiveDeal ? () => onArchiveDeal(deal.id) : undefined}
138
169
  onDragStart={(e) => {
139
170
  e.dataTransfer.effectAllowed = 'move'
140
171
  onDragStart(deal.id, stageId)
@@ -164,18 +195,58 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
164
195
  const dealsByStage = useCrmStore((s) => s.dealsByStage)
165
196
  const dealsLoading = useCrmStore((s) => s.dealsLoading)
166
197
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
198
+ const tagDefs = useCrmStore((s) => s.tagDefs)
199
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs)
167
200
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage)
201
+ const refreshBoard = useCrmStore((s) => s.refreshBoard)
168
202
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage)
203
+ const archiveDeal = useCrmStore((s) => s.archiveDeal)
204
+ const canArchive = useCanArchive()
169
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[]>([])
170
214
  const [dragOverStageId, setDragOverStageId] = useState<string | null>(null)
171
215
  const [savingDealIds, setSavingDealIds] = useState<Set<string>>(new Set())
172
216
  const [optimisticBoard, setOptimisticBoard] = useState<Map<string, Deal[]> | null>(null)
173
217
  const t = useTranslation()
174
218
  const [selectedDealId, setSelectedDealId] = useState<string | null>(null)
175
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)
176
232
 
177
- useEffect(() => { fetchPipelines() }, [])
178
- 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])
179
250
 
180
251
  // Live board. The card for an incoming lead is created by a DB trigger
181
252
  // (plugin-crm 006), so it appears with no client code involved at all — and
@@ -188,6 +259,10 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
188
259
  // moved, removed) touches it and nothing else does. A refetch rather than a
189
260
  // local patch — the payload alone lacks the joined stage/contact fields the
190
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.
191
266
  const pipelineId = pipelines[0]?.id
192
267
  useEffect(() => {
193
268
  if (!pipelineId) return
@@ -197,17 +272,29 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
197
272
  } | null
198
273
  if (!supabase) return
199
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
+
200
287
  // RLS scopes the stream to the caller's own tenants — no tenant filter here.
201
288
  const channel = supabase
202
289
  .channel(`crm:board:${pipelineId}`)
203
290
  .on(
204
291
  'postgres_changes',
205
292
  { event: '*', schema: 'public', table: 'plg_crm_deal_extensions' },
206
- () => { void fetchDealsByStage(pipelineId) },
293
+ onChange,
207
294
  )
208
295
  .subscribe()
209
296
 
210
- return () => { supabase.removeChannel(channel) }
297
+ return () => { clearTimeout(timer); supabase.removeChannel(channel) }
211
298
  }, [pipelineId])
212
299
 
213
300
  // Clear optimistic state when real data arrives and no moves are in-flight
@@ -291,6 +378,18 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
291
378
  <div className="space-y-4">
292
379
  <SubpageHeader title={t('crm.pipeline.title')} subtitle={t('crm.pipeline.subtitle')} />
293
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
+
294
393
  {dealsLoading && dealsByStage.size === 0 ? (
295
394
  <PipelineSkeleton />
296
395
  ) : (
@@ -306,8 +405,10 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
306
405
  deals={deals}
307
406
  savingDealIds={savingDealIds}
308
407
  currency={currency}
408
+ tagDefs={tagDefs}
309
409
  dragOverStageId={dragOverStageId}
310
410
  onDealClick={handleDealClick}
411
+ onArchiveDeal={canArchive ? (id) => { void archiveDeal(id) } : undefined}
311
412
  onAddLead={onAddLead}
312
413
  onDragStart={handleDragStart}
313
414
  onDragEnd={handleDragEnd}
@@ -340,15 +340,19 @@ export function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }: {
340
340
  )}
341
341
  </div>
342
342
 
343
- {/* Invoice link — when approved (quote IS the invoice, same row) */}
344
- {quote.status === 'approved' && (
343
+ {/* Invoice link — the promotion is IN PLACE (fn_invoice_from_order), so
344
+ after it the display status is the financial stage, never 'approved';
345
+ gating on approved alone hid this banner exactly when it mattered.
346
+ Financial has no per-invoice detail route — link to the receivables
347
+ list, where the REC-* reference lands. */}
348
+ {['approved', 'invoiced', 'paid', 'partial', 'overdue'].includes(quote.status) && (
345
349
  <div className="flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5">
346
350
  <div className="flex items-center gap-2 text-xs">
347
351
  <CircleCheckBig className="h-3.5 w-3.5 text-success" />
348
352
  <span className="text-muted-foreground">{t('crm.quoteDetail.invoiceCreated')}</span>
349
353
  </div>
350
354
  <a
351
- href={`#/financial/receivables/detail/${quote.id}`}
355
+ href="#/financial/receivables/list"
352
356
  className="inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline"
353
357
  >
354
358
  {t('crm.quoteDetail.viewInvoice')} <ArrowRight className="h-3 w-3" />