@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,489 @@
1
+ import React, { useState, useEffect } from 'react'
2
+ import { Plus, Trash2, X, Check, ChevronDown } from 'lucide-react'
3
+ import { useCrmConfig, useCrmStore, useCrmProvider, formatCurrency } from '../CrmContext'
4
+ import { useTranslation } from '@fayz-ai/core'
5
+ import type { EntityLookupMap } from '@fayz-ai/saas'
6
+ import { SubpageHeader, useSaveBar, toast } from '@fayz-ai/ui'
7
+ import { SearchSelect, type SearchSelectOption } from '@fayz-ai/ui'
8
+ import { CurrencyInput } from '@fayz-ai/ui'
9
+ import { DatePicker } from '@fayz-ai/ui'
10
+
11
+ // ---------------------------------------------------------------------------
12
+ // Status indicator pills
13
+ // ---------------------------------------------------------------------------
14
+
15
+ const STATUSES = [
16
+ { value: 'draft', labelKey: 'crm.quoteForm.statusDraft', color: 'bg-primary text-primary-foreground' },
17
+ { value: 'sent', labelKey: 'crm.quoteForm.statusSent', color: 'bg-info-soft text-info-soft-foreground border border-info/30 dark:border-info/30' },
18
+ { value: 'approved', labelKey: 'crm.quoteForm.statusApproved', color: 'bg-success-soft text-success-soft-foreground border border-success/30 dark:border-success/30' },
19
+ { value: 'rejected', labelKey: 'crm.quoteForm.statusRejected', color: 'bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30' },
20
+ { value: 'expired', labelKey: 'crm.quoteForm.statusExpired', color: 'bg-muted text-muted-foreground border' },
21
+ ]
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Quote item
25
+ // ---------------------------------------------------------------------------
26
+
27
+ interface FormQuoteItem {
28
+ _id: string
29
+ itemKind: string
30
+ description: string
31
+ quantity: number
32
+ unitPrice: number
33
+ discount: number
34
+ }
35
+
36
+ let fid = 1
37
+ function nextId() { return `qi${fid++}` }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // Item row — compact collapsed, expandable for edit
41
+ // ---------------------------------------------------------------------------
42
+
43
+ function QuoteItemRow({ item, index, itemTypes, currency, expanded, onToggle, onUpdate, onRemove, showDiscount, onShowDiscount, onHideDiscount, entityLookups }: {
44
+ item: FormQuoteItem
45
+ index: number
46
+ itemTypes: Array<{ value: string; label: string }>
47
+ currency: { code: string; locale: string; symbol: string }
48
+ expanded: boolean
49
+ onToggle: () => void
50
+ onUpdate: (data: Partial<FormQuoteItem>) => void
51
+ onRemove: () => void
52
+ showDiscount: boolean
53
+ onShowDiscount: () => void
54
+ onHideDiscount: () => void
55
+ entityLookups: EntityLookupMap
56
+ }) {
57
+ const t = useTranslation()
58
+ const total = item.quantity * item.unitPrice - item.discount
59
+ const kindLabel = itemTypes.find((ty) => ty.value === item.itemKind)?.label ?? item.itemKind
60
+
61
+ return (
62
+ <div className="border-b last:border-0">
63
+ {/* Collapsed row */}
64
+ <div className="flex items-center gap-2 px-4 py-3 cursor-pointer hover:bg-muted/30 transition-colors group" onClick={onToggle}>
65
+ <ChevronDown className={`h-3 w-3 text-muted-foreground shrink-0 transition-transform ${expanded ? 'rotate-0' : '-rotate-90'}`} />
66
+ <span className="text-[10px] font-medium text-muted-foreground w-5 shrink-0">{index + 1}.</span>
67
+ <span className="inline-flex items-center rounded px-1.5 py-0.5 text-[9px] font-medium bg-muted text-muted-foreground shrink-0">{kindLabel}</span>
68
+ <span className="text-sm truncate flex-1 min-w-0">{item.description || <span className="text-muted-foreground italic">{t('crm.quoteForm.noDescription')}</span>}</span>
69
+ <span className="text-xs text-muted-foreground shrink-0">{item.quantity} x {formatCurrency(item.unitPrice, currency)}</span>
70
+ <span className="text-sm font-semibold shrink-0 min-w-[80px] text-right">{formatCurrency(total, currency)}</span>
71
+ <button onClick={(e) => { e.stopPropagation(); onRemove() }} className="p-1 text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-destructive transition-all shrink-0">
72
+ <Trash2 className="h-3 w-3" />
73
+ </button>
74
+ </div>
75
+
76
+ {/* Expanded edit */}
77
+ {expanded && (
78
+ <div className="px-4 pb-4 pt-1 ml-8 space-y-3 bg-muted/10">
79
+ {/* Type selector */}
80
+ <div className="flex gap-1.5">
81
+ {itemTypes.map((t) => (
82
+ <button key={t.value} onClick={() => onUpdate({ itemKind: t.value })}
83
+ className={`rounded-full px-2.5 py-1 text-[10px] font-medium transition-colors ${item.itemKind === t.value ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground hover:bg-muted/80'}`}>
84
+ {t.label}
85
+ </button>
86
+ ))}
87
+ </div>
88
+
89
+ {/* Fields */}
90
+ <div className="grid gap-3 grid-cols-12">
91
+ <div className="col-span-6 sm:col-span-7">
92
+ {entityLookups[item.itemKind] ? (
93
+ <SearchSelect
94
+ label="Item"
95
+ value={item._id}
96
+ displayValue={item.description}
97
+ loadOnOpen
98
+ onChange={(id, opt) => {
99
+ onUpdate({
100
+ description: opt?.label ?? '',
101
+ unitPrice: (opt?.data as any)?.price ?? item.unitPrice,
102
+ })
103
+ }}
104
+ onSearch={async (q) => {
105
+ const results = await entityLookups[item.itemKind].search(q)
106
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }))
107
+ }}
108
+ placeholder={`Search ${itemTypes.find((t) => t.value === item.itemKind)?.label?.toLowerCase() ?? 'item'}...`}
109
+ renderOption={(opt) => (
110
+ <div className="min-w-0 flex-1">
111
+ <p className="text-sm truncate">{opt.label}</p>
112
+ {opt.subtitle && <p className="text-[10px] text-muted-foreground">{opt.subtitle}</p>}
113
+ </div>
114
+ )}
115
+ />
116
+ ) : (
117
+ <>
118
+ <label className="text-[10px] font-medium text-muted-foreground">{t('crm.quoteForm.description')}</label>
119
+ <input type="text" value={item.description} onChange={(e) => onUpdate({ description: e.target.value })} placeholder={t('crm.quoteForm.itemDescriptionPlaceholder')} autoFocus className="w-full mt-0.5 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring" />
120
+ </>
121
+ )}
122
+ </div>
123
+ <div className="col-span-2 sm:col-span-1">
124
+ <label className="text-[10px] font-medium text-muted-foreground">{t('crm.quoteForm.qty')}</label>
125
+ <input type="number" min={1} value={item.quantity} onChange={(e) => onUpdate({ quantity: Number(e.target.value) || 1 })} className="w-full mt-0.5 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-2 py-1.5 text-sm text-center focus:outline-none focus:ring-2 focus:ring-ring" />
126
+ </div>
127
+ <div className="col-span-4">
128
+ <CurrencyInput label={t('crm.quoteForm.unitPrice')} value={item.unitPrice} onChange={(v) => onUpdate({ unitPrice: v })} symbol={currency.symbol} locale={currency.locale} currencyCode={currency.code} />
129
+ </div>
130
+ </div>
131
+
132
+ {/* Discount (optional) */}
133
+ {!showDiscount ? (
134
+ <button onClick={onShowDiscount} className="inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors">
135
+ <Plus className="h-3 w-3" /> {t('crm.quoteForm.discount')}
136
+ </button>
137
+ ) : (
138
+ <div className="grid gap-3 grid-cols-12 items-end">
139
+ <div className="col-span-4">
140
+ <CurrencyInput label={t('crm.quoteForm.discount')} value={item.discount} onChange={(v) => onUpdate({ discount: v })} symbol={currency.symbol} locale={currency.locale} currencyCode={currency.code} />
141
+ </div>
142
+ <div className="col-span-1">
143
+ <button onClick={() => { onUpdate({ discount: 0 }); onHideDiscount() }} className="mb-2 p-1 text-muted-foreground hover:text-destructive transition-colors">
144
+ <X className="h-3.5 w-3.5" />
145
+ </button>
146
+ </div>
147
+ </div>
148
+ )}
149
+
150
+ {/* Done */}
151
+ <div className="flex justify-end pt-1">
152
+ <button onClick={onToggle} className="inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-[11px] text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors">
153
+ <Check className="h-3 w-3" /> {t('crm.quoteForm.done')}
154
+ </button>
155
+ </div>
156
+ </div>
157
+ )}
158
+ </div>
159
+ )
160
+ }
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Add item step
164
+ // ---------------------------------------------------------------------------
165
+
166
+ function AddItemStep({ itemTypes, onSelect, onCancel }: {
167
+ itemTypes: Array<{ value: string; label: string }>
168
+ onSelect: (kind: string) => void
169
+ onCancel: () => void
170
+ }) {
171
+ const t = useTranslation()
172
+ return (
173
+ <div className="border-b px-4 py-3 bg-primary/5 animate-in fade-in-0 slide-in-from-top-1">
174
+ <p className="text-xs font-medium text-muted-foreground mb-2">{t('crm.quoteForm.selectItemType')}</p>
175
+ <div className="flex gap-2 flex-wrap">
176
+ {itemTypes.map((t) => (
177
+ <button key={t.value} onClick={() => onSelect(t.value)} className="inline-flex items-center gap-1.5 rounded-lg border-2 border-transparent bg-card px-4 py-2 text-sm font-medium shadow-sm hover:border-primary hover:shadow-md transition-all">
178
+ {t.label}
179
+ </button>
180
+ ))}
181
+ <button onClick={onCancel} className="inline-flex items-center rounded-lg px-3 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors">{t('crm.quoteForm.cancel')}</button>
182
+ </div>
183
+ </div>
184
+ )
185
+ }
186
+
187
+ // ---------------------------------------------------------------------------
188
+ // Quote form (create + edit)
189
+ // ---------------------------------------------------------------------------
190
+
191
+ export function QuoteFormView({ quoteId, leadId, onSaved }: { quoteId?: string; leadId?: string; onSaved?: (savedId?: string) => void }) {
192
+ const t = useTranslation()
193
+ const config = useCrmConfig()
194
+ const provider = useCrmProvider()
195
+ const { currency, itemTypes } = config
196
+ const createQuote = useCrmStore((s) => s.createQuote)
197
+ const updateQuote = useCrmStore((s) => s.updateQuote)
198
+
199
+ const isEdit = !!quoteId
200
+ const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId)
201
+
202
+ const [linkedLeadId, setLinkedLeadId] = useState(leadId ?? '')
203
+ const [linkedDealId, setLinkedDealId] = useState('')
204
+ const [contactName, setContactName] = useState('')
205
+ const [contactId, setContactId] = useState('')
206
+ const [quoteDate, setQuoteDate] = useState(new Date().toISOString().slice(0, 10))
207
+ const [validUntil, setValidUntil] = useState(() => {
208
+ const d = new Date(); d.setDate(d.getDate() + 30)
209
+ return d.toISOString().slice(0, 10)
210
+ })
211
+ const [currentStatus, setCurrentStatus] = useState('draft')
212
+ const [paymentConditions, setPaymentConditions] = useState('')
213
+ const [observations, setObservations] = useState('')
214
+ const [items, setItems] = useState<FormQuoteItem[]>([])
215
+ const [expandedItemId, setExpandedItemId] = useState<string | null>(null)
216
+ const [discountVisible, setDiscountVisible] = useState<Set<string>>(new Set())
217
+ const [addingItem, setAddingItem] = useState(false)
218
+ const [saving, setSaving] = useState(false)
219
+
220
+ // Load existing quote for edit mode
221
+ useEffect(() => {
222
+ if (!quoteId) return
223
+ provider.getQuoteById(quoteId).then((q) => {
224
+ if (q) {
225
+ setContactName(q.contactName ?? '')
226
+ setContactId(q.contactId ?? '')
227
+ setLinkedLeadId(q.leadId ?? '')
228
+ setLinkedDealId(q.dealId ?? '')
229
+ setQuoteDate(q.quoteDate)
230
+ setValidUntil(q.validUntil)
231
+ setCurrentStatus(q.status)
232
+ setPaymentConditions(q.paymentConditions ?? '')
233
+ setObservations(q.observations ?? '')
234
+ setItems(q.items.map((it) => ({
235
+ _id: nextId(),
236
+ itemKind: it.itemKind,
237
+ description: it.description,
238
+ quantity: it.quantity,
239
+ unitPrice: it.unitPrice,
240
+ discount: it.discount,
241
+ })))
242
+ setDiscountVisible(new Set(q.items.filter((it) => it.discount > 0).map((_, i) => `qi${fid - q.items.length + i}`)))
243
+ }
244
+ setLoadingExisting(false)
245
+ })
246
+ }, [quoteId])
247
+
248
+ // Pre-fill from lead
249
+ useEffect(() => {
250
+ if (!leadId || quoteId) return
251
+ provider.getLeadById(leadId).then(async (lead) => {
252
+ if (lead) {
253
+ setContactName(lead.name)
254
+ setContactId(lead.id)
255
+ setLinkedLeadId(lead.id)
256
+ // Find existing deal for this lead
257
+ const deal = await provider.getDealByLeadId(lead.id)
258
+ if (deal) setLinkedDealId(deal.id)
259
+ }
260
+ setLoadingExisting(false)
261
+ })
262
+ }, [leadId])
263
+
264
+ const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0)
265
+
266
+ function addItemOfKind(kind: string) {
267
+ const newItem: FormQuoteItem = { _id: nextId(), itemKind: kind, description: '', quantity: 1, unitPrice: 0, discount: 0 }
268
+ setItems([...items, newItem])
269
+ setExpandedItemId(newItem._id)
270
+ setAddingItem(false)
271
+ }
272
+
273
+ function updateItem(id: string, data: Partial<FormQuoteItem>) {
274
+ setItems(items.map((it) => it._id === id ? { ...it, ...data } : it))
275
+ }
276
+
277
+ function removeItem(id: string) {
278
+ setItems(items.filter((it) => it._id !== id))
279
+ if (expandedItemId === id) setExpandedItemId(null)
280
+ }
281
+
282
+ async function handleSave() {
283
+ if (items.length === 0) { toast.error(t('crm.quoteForm.errNoItems')); return }
284
+ setSaving(true)
285
+ try {
286
+ const input = {
287
+ contactId: contactId || undefined,
288
+ contactName: contactName || undefined,
289
+ leadId: linkedLeadId || undefined,
290
+ dealId: linkedDealId || undefined,
291
+ quoteDate,
292
+ validUntil,
293
+ paymentConditions: paymentConditions || undefined,
294
+ observations: observations || undefined,
295
+ items: items.map((it) => ({
296
+ itemKind: it.itemKind,
297
+ description: it.description,
298
+ quantity: it.quantity,
299
+ unitPrice: it.unitPrice,
300
+ discount: it.discount,
301
+ totalAmount: it.quantity * it.unitPrice - it.discount,
302
+ })),
303
+ }
304
+ if (isEdit) {
305
+ await updateQuote(quoteId!, input)
306
+ onSaved?.(quoteId)
307
+ } else {
308
+ const created = await createQuote(input)
309
+ onSaved?.(created?.id)
310
+ }
311
+ } finally { setSaving(false) }
312
+ }
313
+
314
+ // Dirty detection — snapshot editable fields once async load settles
315
+ const currentFields = {
316
+ contactId,
317
+ contactName,
318
+ linkedLeadId,
319
+ linkedDealId,
320
+ quoteDate,
321
+ validUntil,
322
+ currentStatus,
323
+ paymentConditions,
324
+ observations,
325
+ items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount })),
326
+ }
327
+ const snapshot = React.useRef<string | null>(null)
328
+ useEffect(() => {
329
+ if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields)
330
+ }, [loadingExisting])
331
+ const dirty = snapshot.current !== null && JSON.stringify(currentFields) !== snapshot.current
332
+
333
+ useSaveBar({
334
+ dirty,
335
+ saving,
336
+ onSave: () => { void handleSave() },
337
+ onDiscard: () => onSaved?.(),
338
+ saveLabel: isEdit ? t('crm.quoteForm.saveChanges') : t('crm.quoteForm.saveQuote'),
339
+ })
340
+
341
+ if (loadingExisting) {
342
+ return (
343
+ <div className="space-y-5">
344
+ <SubpageHeader title="" onBack={onSaved} parentLabel={t('crm.quotes.title')} />
345
+ <div className="grid gap-4 lg:grid-cols-3">
346
+ <div className="rounded-lg border bg-card shadow-sm p-5 space-y-4">
347
+ {[1, 2, 3, 4].map((i) => (
348
+ <div key={i} className="space-y-1.5">
349
+ <div className="h-3 w-16 rounded bg-muted/30 animate-pulse" />
350
+ <div className="h-9 w-full rounded-lg bg-muted/20 animate-pulse" />
351
+ </div>
352
+ ))}
353
+ </div>
354
+ <div className="lg:col-span-2 rounded-lg border bg-card shadow-sm p-5 space-y-3">
355
+ <div className="h-4 w-24 rounded bg-muted/30 animate-pulse" />
356
+ {[1, 2].map((i) => (
357
+ <div key={i} className="flex items-center gap-3 py-2">
358
+ <div className="h-4 w-4 rounded bg-muted/30 animate-pulse" />
359
+ <div className="h-4 flex-1 rounded bg-muted/20 animate-pulse" />
360
+ <div className="h-4 w-20 rounded bg-muted/30 animate-pulse" />
361
+ </div>
362
+ ))}
363
+ </div>
364
+ </div>
365
+ </div>
366
+ )
367
+ }
368
+
369
+ return (
370
+ <div className="space-y-5">
371
+ <SubpageHeader
372
+ title={isEdit ? t('crm.quoteForm.editTitle') : t('crm.quoteForm.newTitle')}
373
+ subtitle={isEdit ? t('crm.quoteForm.editSubtitle') : t('crm.quoteForm.newSubtitle')}
374
+ onBack={() => onSaved?.()}
375
+ parentLabel={t('crm.quotes.title')}
376
+ />
377
+
378
+ {/* Status indicator */}
379
+ <div className="flex gap-2">
380
+ {STATUSES.map((s) => (
381
+ <span key={s.value} className={`inline-flex items-center rounded-full px-3 py-1 text-xs font-medium ${s.value === currentStatus ? s.color : 'bg-muted/30 text-muted-foreground/50'}`}>
382
+ {t(s.labelKey)}
383
+ </span>
384
+ ))}
385
+ </div>
386
+
387
+ {/* Quote details + Items — side by side */}
388
+ <div className="grid gap-4 lg:grid-cols-3">
389
+ {/* Left: Quote details */}
390
+ <div className="rounded-lg border bg-card shadow-sm p-5 space-y-4">
391
+ <h3 className="text-sm font-semibold">{t('crm.quoteForm.quoteDetails')}</h3>
392
+
393
+ <SearchSelect
394
+ value={contactId}
395
+ displayValue={contactName}
396
+ onChange={(id, opt) => { setContactId(id); setContactName(opt?.label ?? '') }}
397
+ onSearch={async (q) => {
398
+ if (!config.contactLookup) return []
399
+ const results = await config.contactLookup.search(q)
400
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }))
401
+ }}
402
+ label={t('crm.quoteForm.client')}
403
+ required
404
+ placeholder={t('crm.quoteForm.searchClient')}
405
+ allowCreate
406
+ createLabel={t('crm.quoteForm.addAsLead')}
407
+ onCreate={async (name) => {
408
+ const lead = await provider.createLead({ name })
409
+ setContactId(lead.id)
410
+ setContactName(lead.name)
411
+ }}
412
+ />
413
+
414
+ <div>
415
+ <label className="text-xs font-medium text-muted-foreground">{t('crm.quoteForm.quoteDate')}</label>
416
+ <DatePicker value={quoteDate} onChange={setQuoteDate} className="mt-1" />
417
+ </div>
418
+
419
+ <div>
420
+ <label className="text-xs font-medium text-muted-foreground">{t('crm.quoteForm.validUntil')}</label>
421
+ <DatePicker value={validUntil} onChange={setValidUntil} className="mt-1" />
422
+ </div>
423
+
424
+ <div>
425
+ <label className="text-xs font-medium text-muted-foreground">{t('crm.quoteForm.paymentConditions')}</label>
426
+ <textarea value={paymentConditions} onChange={(e) => setPaymentConditions(e.target.value)} rows={2} placeholder={t('crm.quoteForm.paymentConditionsPlaceholder')} 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" />
427
+ </div>
428
+
429
+ <div>
430
+ <label className="text-xs font-medium text-muted-foreground">{t('crm.quoteForm.notes')}</label>
431
+ <textarea value={observations} onChange={(e) => setObservations(e.target.value)} rows={2} placeholder={t('crm.quoteForm.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" />
432
+ </div>
433
+ </div>
434
+
435
+ {/* Right: Items */}
436
+ <div className="lg:col-span-2 rounded-lg border bg-card shadow-sm overflow-hidden flex flex-col">
437
+ <div className="flex items-center justify-between px-4 py-3 border-b">
438
+ <h3 className="text-sm font-semibold">{t('crm.quoteForm.quoteItems')}</h3>
439
+ <button onClick={() => setAddingItem(true)} 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">
440
+ <Plus className="h-3 w-3" /> {t('crm.quoteForm.addItem')}
441
+ </button>
442
+ </div>
443
+
444
+ <div className="flex-1">
445
+ {addingItem && (
446
+ <AddItemStep itemTypes={itemTypes} onSelect={addItemOfKind} onCancel={() => setAddingItem(false)} />
447
+ )}
448
+
449
+ {items.length === 0 && !addingItem ? (
450
+ <div className="py-12 text-center">
451
+ <p className="text-sm text-muted-foreground">{t('crm.quoteForm.noItems')}</p>
452
+ <button onClick={() => setAddingItem(true)} className="text-xs text-primary hover:underline mt-1">{t('crm.quoteForm.addFirstItem')}</button>
453
+ </div>
454
+ ) : (
455
+ items.map((item, i) => (
456
+ <QuoteItemRow
457
+ key={item._id}
458
+ item={item}
459
+ index={i}
460
+ itemTypes={itemTypes}
461
+ currency={currency}
462
+ expanded={expandedItemId === item._id}
463
+ onToggle={() => setExpandedItemId(expandedItemId === item._id ? null : item._id)}
464
+ onUpdate={(data) => updateItem(item._id, data)}
465
+ onRemove={() => removeItem(item._id)}
466
+ showDiscount={discountVisible.has(item._id) || item.discount > 0}
467
+ onShowDiscount={() => setDiscountVisible((prev) => new Set(prev).add(item._id))}
468
+ onHideDiscount={() => setDiscountVisible((prev) => { const next = new Set(prev); next.delete(item._id); return next })}
469
+ entityLookups={config.entityLookups}
470
+ />
471
+ ))
472
+ )}
473
+ </div>
474
+
475
+ {/* Total footer */}
476
+ {items.length > 0 && (
477
+ <div className="px-4 py-3 border-t bg-muted/20 flex justify-between items-center mt-auto">
478
+ <span className="text-xs text-muted-foreground">{t('crm.quoteForm.itemCount', { count: String(items.length) })}</span>
479
+ <div className="text-right">
480
+ <span className="text-xs text-muted-foreground">{t('crm.quoteForm.total')}: </span>
481
+ <span className="text-lg font-bold">{formatCurrency(totalAmount, currency)}</span>
482
+ </div>
483
+ </div>
484
+ )}
485
+ </div>
486
+ </div>
487
+ </div>
488
+ )
489
+ }
@@ -0,0 +1,101 @@
1
+ import React, { useEffect } from 'react'
2
+ import { FileText, Pencil } from 'lucide-react'
3
+ import type { ColumnDef } from '@tanstack/react-table'
4
+ import { DataTable } from '@fayz-ai/ui'
5
+ import { useCrmStore, useCrmConfig, formatCurrency } from '../CrmContext'
6
+ import { useTranslation } from '@fayz-ai/core'
7
+ import { SubpageHeader } from '@fayz-ai/ui'
8
+ import type { Quote } from '../types'
9
+
10
+ const STATUS_COLORS: Record<string, string> = {
11
+ draft: 'bg-muted text-muted-foreground',
12
+ sent: 'bg-info-soft text-info-soft-foreground',
13
+ approved: 'bg-success-soft text-success-soft-foreground',
14
+ rejected: 'bg-destructive-soft text-destructive-soft-foreground',
15
+ expired: 'bg-warning-soft text-warning-soft-foreground',
16
+ invoiced: 'bg-warning-soft text-warning-soft-foreground',
17
+ paid: 'bg-success-soft text-success-soft-foreground',
18
+ partial: 'bg-warning-soft text-warning-soft-foreground',
19
+ overdue: 'bg-destructive-soft text-destructive-soft-foreground',
20
+ cancelled: 'bg-muted text-muted-foreground',
21
+ }
22
+
23
+ function useQuoteColumns(currency: { code: string; locale: string; symbol: string }, onEditQuote?: (id: string) => void): ColumnDef<Quote, any>[] {
24
+ const t = useTranslation()
25
+ const cols: ColumnDef<Quote, any>[] = [
26
+ { accessorKey: 'quoteNumber', header: '#', cell: ({ getValue }) => <span className="text-xs text-muted-foreground">{getValue() as string}</span> },
27
+ { accessorKey: 'contactName', header: t('crm.quotes.contact'), cell: ({ getValue }) => <span className="font-medium">{(getValue() as string) || '—'}</span> },
28
+ { accessorKey: 'quoteDate', header: t('crm.quotes.date'), cell: ({ getValue }) => <span className="text-xs text-muted-foreground">{getValue() as string}</span> },
29
+ {
30
+ accessorKey: 'totalAmount', header: t('crm.quotes.amount'),
31
+ cell: ({ getValue }) => <span className="font-medium">{formatCurrency(getValue() as number, currency)}</span>,
32
+ },
33
+ {
34
+ accessorKey: 'status', header: t('crm.quotes.status'),
35
+ cell: ({ getValue }) => {
36
+ const status = getValue() as string
37
+ return <span className={`inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ${STATUS_COLORS[status] ?? 'bg-muted text-muted-foreground'}`}>{status}</span>
38
+ },
39
+ },
40
+ ]
41
+
42
+ if (onEditQuote) {
43
+ cols.push({
44
+ id: 'actions', header: '',
45
+ cell: ({ row }) => (
46
+ <div className="text-right">
47
+ <button
48
+ onClick={(e) => { e.stopPropagation(); onEditQuote(row.original.id) }}
49
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors"
50
+ title="Edit quote"
51
+ >
52
+ <Pencil className="h-3.5 w-3.5" />
53
+ </button>
54
+ </div>
55
+ ),
56
+ })
57
+ }
58
+
59
+ return cols
60
+ }
61
+
62
+ export function QuoteListView({ onNew, onEdit, onEditQuote }: { onNew?: () => void; onEdit?: (id: string) => void; onEditQuote?: (id: string) => void }) {
63
+ const t = useTranslation()
64
+ const { currency } = useCrmConfig()
65
+ const quotes = useCrmStore((s) => s.quotes)
66
+ const quotesLoading = useCrmStore((s) => s.quotesLoading)
67
+ const fetchQuotes = useCrmStore((s) => s.fetchQuotes)
68
+
69
+ useEffect(() => { fetchQuotes({}) }, [])
70
+
71
+ const columns = useQuoteColumns(currency, onEditQuote)
72
+
73
+ return (
74
+ <div className="space-y-4">
75
+ <SubpageHeader
76
+ title={t('crm.quotes.title')}
77
+ subtitle={t('crm.quotes.quotesCount', { count: String(quotes.length) })}
78
+ actions={onNew && (
79
+ <button onClick={onNew} className="inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors">
80
+ <span className="h-3.5 w-3.5 inline-flex items-center justify-center">+</span> {t('crm.quotes.newQuote')}
81
+ </button>
82
+ )}
83
+ />
84
+ {quotesLoading ? (
85
+ <DataTable columns={columns} data={[]} loading />
86
+ ) : quotes.length === 0 ? (
87
+ <div className="flex flex-col items-center justify-center py-12 text-center rounded-lg border-2 border-dashed border-muted">
88
+ <FileText className="h-8 w-8 text-muted-foreground/30 mb-2" />
89
+ <p className="text-sm text-muted-foreground">{t('crm.quotes.noQuotes')}</p>
90
+ {onNew && <button onClick={onNew} className="text-xs text-primary hover:underline mt-1">{t('crm.quotes.createFirst')}</button>}
91
+ </div>
92
+ ) : (
93
+ <DataTable
94
+ columns={columns}
95
+ data={quotes}
96
+ onRowClick={(row) => onEdit?.(row.id)}
97
+ />
98
+ )}
99
+ </div>
100
+ )
101
+ }