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