@fayz-ai/plugin-crm 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) 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/mock.d.ts.map +1 -1
  7. package/dist/data/registries.d.ts.map +1 -0
  8. package/dist/data/types.d.ts +4 -1
  9. package/dist/data/types.d.ts.map +1 -1
  10. package/dist/index.d.ts +16 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +609 -493
  13. package/dist/index.js.map +1 -1
  14. package/dist/{cascade.d.ts → lib/cascade.d.ts} +1 -1
  15. package/dist/lib/cascade.d.ts.map +1 -0
  16. package/dist/lib/message-events.d.ts +13 -0
  17. package/dist/lib/message-events.d.ts.map +1 -0
  18. package/dist/lib/timeline-source.d.ts +10 -0
  19. package/dist/lib/timeline-source.d.ts.map +1 -0
  20. package/dist/locales/en.d.ts.map +1 -1
  21. package/dist/locales/pt-BR.d.ts.map +1 -1
  22. package/dist/public/context.d.ts +1 -1
  23. package/dist/public/context.d.ts.map +1 -1
  24. package/dist/public/createPublicFormsPlugin.d.ts +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  26. package/dist/public/{data.supabase.d.ts → data/supabase.d.ts} +2 -2
  27. package/dist/public/data/supabase.d.ts.map +1 -0
  28. package/dist/public/index.d.ts +6 -6
  29. package/dist/public/index.d.ts.map +1 -1
  30. package/dist/public/index.js +2 -2
  31. package/dist/public/index.js.map +1 -1
  32. package/dist/public/{inbox.d.ts → lib/inbox.d.ts} +1 -1
  33. package/dist/public/lib/inbox.d.ts.map +1 -0
  34. package/dist/public/{uploads.d.ts → lib/uploads.d.ts} +1 -1
  35. package/dist/public/lib/uploads.d.ts.map +1 -0
  36. package/dist/store.d.ts +9 -0
  37. package/dist/store.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts.map +1 -1
  39. package/dist/{CrmPage.d.ts → views/CrmPage.d.ts} +3 -3
  40. package/dist/views/CrmPage.d.ts.map +1 -0
  41. package/dist/views/DealSidebar.d.ts.map +1 -1
  42. package/dist/views/LeadListView.d.ts.map +1 -1
  43. package/dist/views/PipelineView.d.ts +3 -1
  44. package/dist/views/PipelineView.d.ts.map +1 -1
  45. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  46. package/dist/views/QuoteFormView.d.ts.map +1 -1
  47. package/dist/views/QuoteListView.d.ts.map +1 -1
  48. package/dist/views/dashboardWidgets.d.ts +1 -1
  49. package/dist/views/dashboardWidgets.d.ts.map +1 -1
  50. package/package.json +6 -10
  51. package/dist/CrmContext.d.ts.map +0 -1
  52. package/dist/CrmPage.d.ts.map +0 -1
  53. package/dist/cascade.d.ts.map +0 -1
  54. package/dist/public/data.supabase.d.ts.map +0 -1
  55. package/dist/public/inbox.d.ts.map +0 -1
  56. package/dist/public/uploads.d.ts.map +0 -1
  57. package/dist/registries.d.ts.map +0 -1
  58. package/src/CrmContext.tsx +0 -30
  59. package/src/CrmPage.tsx +0 -150
  60. package/src/README.md +0 -97
  61. package/src/cascade.ts +0 -26
  62. package/src/components/BoardFilters.tsx +0 -190
  63. package/src/components/CrmGeneralSettings.tsx +0 -56
  64. package/src/components/CrmOnboarding.tsx +0 -52
  65. package/src/components/LeadAttachments.tsx +0 -140
  66. package/src/components/PipelineSettings.tsx +0 -45
  67. package/src/components/QuoteStatusDropdown.tsx +0 -226
  68. package/src/components/TagChips.tsx +0 -80
  69. package/src/data/index.ts +0 -2
  70. package/src/data/mock.ts +0 -559
  71. package/src/data/supabase.ts +0 -928
  72. package/src/data/tables.ts +0 -11
  73. package/src/data/types.ts +0 -61
  74. package/src/index.ts +0 -429
  75. package/src/lib/access.ts +0 -11
  76. package/src/lib/form-answers.tsx +0 -80
  77. package/src/lib/relative-time.ts +0 -84
  78. package/src/lib/tenant.ts +0 -4
  79. package/src/locales/en.ts +0 -307
  80. package/src/locales/index.ts +0 -7
  81. package/src/locales/pt-BR.ts +0 -307
  82. package/src/migrations/000_plg_rename.sql +0 -28
  83. package/src/migrations/001_crm_base.sql +0 -73
  84. package/src/migrations/002_activities.sql +0 -33
  85. package/src/migrations/003_crm_views_rls.sql +0 -69
  86. package/src/migrations/004_seed_default_pipeline.sql +0 -31
  87. package/src/migrations/005_public_lead.sql +0 -189
  88. package/src/migrations/006_lead_enters_pipeline.sql +0 -265
  89. package/src/migrations/007_activity_log.sql +0 -55
  90. package/src/migrations/008_view_field_aliases.sql +0 -43
  91. package/src/migrations/009_deal_archived_status.sql +0 -30
  92. package/src/migrations/010_quote_archived_status.sql +0 -40
  93. package/src/migrations/011_agent_rpc_update_lead.sql +0 -153
  94. package/src/migrations/012_agent_rpc_create_lead.sql +0 -128
  95. package/src/migrations/013_tag_slugs.sql +0 -177
  96. package/src/migrations/014_public_lead_tags.sql +0 -172
  97. package/src/migrations/015_lead_attachments.sql +0 -357
  98. package/src/migrations/016_public_lead_activity.sql +0 -123
  99. package/src/migrations/index.ts +0 -2023
  100. package/src/public/context.tsx +0 -150
  101. package/src/public/createPublicFormsPlugin.ts +0 -282
  102. package/src/public/data.supabase.ts +0 -92
  103. package/src/public/inbox.ts +0 -143
  104. package/src/public/index.ts +0 -51
  105. package/src/public/types.ts +0 -173
  106. package/src/public/uploads.ts +0 -205
  107. package/src/registries.ts +0 -162
  108. package/src/schema/index.ts +0 -104
  109. package/src/store.ts +0 -472
  110. package/src/types.ts +0 -337
  111. package/src/views/ActivityListView.tsx +0 -264
  112. package/src/views/DashboardView.tsx +0 -12
  113. package/src/views/DealSidebar.tsx +0 -482
  114. package/src/views/LeadDetailView.tsx +0 -378
  115. package/src/views/LeadFormView.tsx +0 -66
  116. package/src/views/LeadListView.tsx +0 -100
  117. package/src/views/PipelineView.tsx +0 -446
  118. package/src/views/QuoteDetailView.tsx +0 -412
  119. package/src/views/QuoteFormView.tsx +0 -494
  120. package/src/views/QuoteListView.tsx +0 -115
  121. package/src/views/dashboardWidgets.tsx +0 -248
  122. /package/dist/{registries.d.ts → data/registries.d.ts} +0 -0
package/src/data/mock.ts DELETED
@@ -1,559 +0,0 @@
1
- import type { CrmDataProvider } from './types'
2
- import type {
3
- Pipeline, PipelineStage, Lead, Deal, Activity, ActivityTypeDef, TagDef, Quote, QuoteItem,
4
- CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
5
- LeadQuery, DealQuery, ActivityQuery, QuoteQuery, BoardFilter,
6
- PaginatedResult, CrmSummary, FunnelStage,
7
- LeadStatus, DealStatus, QuoteStatus, SystemActivityType,
8
- } from '../types'
9
- import { deriveLeadStatus, deriveQuoteStatus } from '../cascade'
10
-
11
- let nextId = 1
12
- function uid(): string { return String(nextId++) }
13
- function now(): string { return new Date().toISOString() }
14
- function today(): string { return new Date().toISOString().slice(0, 10) }
15
-
16
- /** Mesma paleta do `crm_tag_default_color` do banco, para o mock não parecer outro produto. */
17
- const MOCK_TAG_COLORS = ['#6366f1', '#0ea5e9', '#10b981', '#f59e0b', '#ef4444', '#ec4899', '#8b5cf6', '#14b8a6']
18
-
19
- function paginate<T>(items: T[], page?: number, pageSize?: number): PaginatedResult<T> {
20
- const p = page ?? 1
21
- const ps = pageSize ?? 50
22
- const start = (p - 1) * ps
23
- return { data: items.slice(start, start + ps), total: items.length }
24
- }
25
-
26
- interface MockStore {
27
- pipelines: Pipeline[]
28
- stages: PipelineStage[]
29
- leads: Lead[]
30
- deals: Deal[]
31
- activities: Activity[]
32
- quotes: Quote[]
33
- }
34
-
35
- function createStore(seedStages?: Array<{ name: string; color: string; probability: number }>): MockStore {
36
- const tenantId = 'mock-tenant'
37
- const pipelineId = uid()
38
-
39
- const defaultStages = seedStages ?? [
40
- { name: 'New', color: '#6366f1', probability: 10 },
41
- { name: 'Contacted', color: '#3b82f6', probability: 25 },
42
- { name: 'Qualified', color: '#f59e0b', probability: 50 },
43
- { name: 'Proposal', color: '#f97316', probability: 75 },
44
- { name: 'Negotiation', color: '#8b5cf6', probability: 90 },
45
- { name: 'Won', color: '#22c55e', probability: 100 },
46
- { name: 'Lost', color: '#ef4444', probability: 0 },
47
- ]
48
-
49
- const stages: PipelineStage[] = defaultStages.map((s, i) => ({
50
- id: uid(),
51
- pipelineId,
52
- name: s.name,
53
- order: i,
54
- color: s.color,
55
- probability: s.probability,
56
- isWon: s.name === 'Won',
57
- isLost: s.name === 'Lost',
58
- tenantId,
59
- createdAt: now(),
60
- }))
61
-
62
- return {
63
- pipelines: [{
64
- id: pipelineId,
65
- name: 'Sales Pipeline',
66
- isDefault: true,
67
- isActive: true,
68
- tenantId,
69
- createdAt: now(),
70
- updatedAt: now(),
71
- }],
72
- stages,
73
- leads: [],
74
- deals: [],
75
- activities: [],
76
- quotes: [],
77
- }
78
- }
79
-
80
- export function createMockCrmProvider(options?: {
81
- dealStages?: Array<{ name: string; color: string; probability: number }>
82
- activityTypes?: Array<{ value: string; label: string; icon?: string }>
83
- }): CrmDataProvider {
84
- const store = createStore(options?.dealStages)
85
- const tenantId = 'mock-tenant'
86
-
87
- // Parity with the Supabase provider's silent system timeline.
88
- function logEvent(input: {
89
- activityType: SystemActivityType
90
- title: string
91
- description?: string
92
- leadId?: string
93
- dealId?: string
94
- contactId?: string
95
- contactName?: string
96
- }): void {
97
- store.activities.push({
98
- id: uid(),
99
- dealId: input.dealId, leadId: input.leadId, contactId: input.contactId,
100
- contactName: input.contactName,
101
- activityType: input.activityType,
102
- title: input.title, description: input.description,
103
- completedAt: now(), tenantId, createdAt: now(),
104
- })
105
- }
106
-
107
- // --- Cascade helper: sync lead + quote statuses when a deal moves ---
108
- function cascadeFromStage(deal: Deal, stage: PipelineStage) {
109
- // Cascade to lead
110
- if (deal.leadId) {
111
- const lead = store.leads.find((l) => l.id === deal.leadId)
112
- if (lead) {
113
- lead.status = deriveLeadStatus(stage)
114
- lead.updatedAt = now()
115
- }
116
- }
117
- // Cascade to quotes
118
- for (const q of store.quotes) {
119
- if (q.dealId === deal.id) {
120
- q.status = deriveQuoteStatus(stage, q.status)
121
- q.updatedAt = now()
122
- }
123
- }
124
- }
125
-
126
- const provider: CrmDataProvider = {
127
- async getPipelines() { return store.pipelines },
128
- async getPipelineStages(pipelineId) { return store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order) },
129
-
130
- // Leads
131
- async getLeads(query: LeadQuery) {
132
- let results = store.leads.filter((l) => (l as Lead & { isActive?: boolean }).isActive !== false)
133
- if (query.status) {
134
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
135
- results = results.filter((l) => statuses.includes(l.status))
136
- }
137
- if (query.sourceId) results = results.filter((l) => l.sourceId === query.sourceId)
138
- if (query.search) {
139
- const s = query.search.toLowerCase()
140
- results = results.filter((l) => l.name.toLowerCase().includes(s) || l.email?.toLowerCase().includes(s) || l.company?.toLowerCase().includes(s))
141
- }
142
- results.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
143
- return paginate(results, query.page, query.pageSize)
144
- },
145
-
146
- async getLeadById(id) { return store.leads.find((l) => l.id === id) ?? null },
147
-
148
- async createLead(input: CreateLeadInput) {
149
- const lead: Lead = {
150
- id: uid(), name: input.name, email: input.email, phone: input.phone,
151
- company: input.company, sourceId: input.sourceId, status: 'new',
152
- assignedToId: input.assignedToId, value: input.value,
153
- tags: input.tags ?? [], notes: input.notes, tenantId,
154
- createdAt: now(), updatedAt: now(),
155
- }
156
- store.leads.push(lead)
157
- logEvent({ activityType: 'lead_created', title: lead.name, leadId: lead.id, contactName: lead.name })
158
- return lead
159
- },
160
-
161
- async updateLead(id, data) {
162
- const lead = store.leads.find((l) => l.id === id)
163
- if (!lead) throw new Error(`Lead ${id} not found`)
164
- Object.assign(lead, data, { updatedAt: now() })
165
- return lead
166
- },
167
-
168
- async convertLeadToDeal(leadId, dealInput) {
169
- const lead = store.leads.find((l) => l.id === leadId)
170
- if (!lead) throw new Error(`Lead ${leadId} not found`)
171
- lead.status = 'converted'
172
- lead.updatedAt = now()
173
- logEvent({ activityType: 'lead_converted', title: lead.name, leadId, contactName: lead.name })
174
- const deal = await provider.createDeal({ ...dealInput, leadId })
175
- return deal
176
- },
177
-
178
- // Deals
179
- async getDeals(query: DealQuery) {
180
- let results = [...store.deals]
181
- if (query.pipelineId) results = results.filter((d) => d.pipelineId === query.pipelineId)
182
- if (query.stageId) results = results.filter((d) => d.stageId === query.stageId)
183
- if (query.status) {
184
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
185
- results = results.filter((d) => statuses.includes(d.status))
186
- } else {
187
- results = results.filter((d) => d.status !== 'archived')
188
- }
189
- if (query.search) {
190
- const s = query.search.toLowerCase()
191
- results = results.filter((d) => d.title.toLowerCase().includes(s) || d.contactName?.toLowerCase().includes(s))
192
- }
193
- results.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
194
- return paginate(results, query.page, query.pageSize)
195
- },
196
-
197
- async getDealById(id) { return store.deals.find((d) => d.id === id) ?? null },
198
-
199
- async getDealsByStage(pipelineId, filter?: BoardFilter) {
200
- const stages = store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order)
201
- // Mesmas regras do provider real, para o mock não mentir sobre o filtro:
202
- // tags é OU, e o período corta por createdAt.
203
- const matches = (d: Deal) => {
204
- if (filter?.tags?.length && !filter.tags.some((t) => (d.tags ?? []).includes(t))) return false
205
- if (filter?.createdFrom && d.createdAt < filter.createdFrom) return false
206
- if (filter?.createdTo && d.createdAt > filter.createdTo) return false
207
- return true
208
- }
209
- const map = new Map<string, Deal[]>()
210
- for (const stage of stages) {
211
- map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === 'open' && matches(d)))
212
- }
213
- return map
214
- },
215
-
216
- async createDeal(input: CreateDealInput) {
217
- const stage = store.stages.find((s) => s.id === input.stageId)
218
- const deal: Deal = {
219
- id: uid(), leadId: input.leadId, title: input.title, value: input.value,
220
- pipelineId: input.pipelineId, stageId: input.stageId,
221
- stageName: stage?.name, stageColor: stage?.color,
222
- probability: stage?.probability ?? 0, expectedCloseDate: input.expectedCloseDate,
223
- assignedToId: input.assignedToId, contactId: input.contactId,
224
- contactName: input.contactName, status: 'open',
225
- tags: input.tags ?? [], notes: input.notes, tenantId,
226
- createdAt: now(), updatedAt: now(),
227
- }
228
- store.deals.push(deal)
229
- logEvent({
230
- activityType: 'deal_created', title: deal.title, dealId: deal.id,
231
- leadId: deal.leadId, contactId: deal.contactId, contactName: deal.contactName,
232
- })
233
- return deal
234
- },
235
-
236
- async updateDeal(id, data) {
237
- const deal = store.deals.find((d) => d.id === id)
238
- if (!deal) throw new Error(`Deal ${id} not found`)
239
- Object.assign(deal, data, { updatedAt: now() })
240
- return deal
241
- },
242
-
243
- async moveDealToStage(dealId, stageId) {
244
- const deal = store.deals.find((d) => d.id === dealId)
245
- if (!deal) throw new Error(`Deal ${dealId} not found`)
246
- const stage = store.stages.find((s) => s.id === stageId)
247
- if (!stage) throw new Error(`Stage ${stageId} not found`)
248
- deal.stageId = stageId
249
- deal.stageName = stage.name
250
- deal.stageColor = stage.color
251
- deal.probability = stage.probability ?? 0
252
- if (stage.isWon) deal.status = 'won'
253
- if (stage.isLost) deal.status = 'lost'
254
- deal.updatedAt = now()
255
-
256
- // Cascade to lead + quotes
257
- cascadeFromStage(deal, stage)
258
-
259
- logEvent({
260
- activityType: stage.isWon ? 'deal_won' : stage.isLost ? 'deal_lost' : 'stage_changed',
261
- title: deal.title || 'Deal',
262
- description: stage.name,
263
- dealId: deal.id,
264
- contactName: deal.contactName,
265
- })
266
- return deal
267
- },
268
-
269
- async archiveDeal(dealId) {
270
- const deal = store.deals.find((d) => d.id === dealId)
271
- if (!deal) throw new Error(`Deal ${dealId} not found`)
272
- deal.status = 'archived'
273
- deal.updatedAt = now()
274
- logEvent({ activityType: 'deal_archived', title: deal.title || 'Deal', dealId, contactName: deal.contactName })
275
- },
276
-
277
- async archiveLead(leadId) {
278
- const lead = store.leads.find((l) => l.id === leadId)
279
- if (!lead) throw new Error(`Lead ${leadId} not found`)
280
- ;(lead as Lead & { isActive?: boolean }).isActive = false
281
- lead.updatedAt = now()
282
- const deal = store.deals.find((d) => d.leadId === leadId && d.status === 'open')
283
- if (deal) await provider.archiveDeal(deal.id)
284
- logEvent({ activityType: 'lead_archived', title: lead.name, leadId, contactName: lead.name })
285
- },
286
-
287
- // Activities
288
- async getActivities(query: ActivityQuery) {
289
- let results = [...store.activities]
290
- if (query.dealId) results = results.filter((a) => a.dealId === query.dealId)
291
- if (query.leadId) results = results.filter((a) => a.leadId === query.leadId)
292
- if (query.activityType) results = results.filter((a) => a.activityType === query.activityType)
293
- if (query.completed !== undefined) {
294
- results = query.completed ? results.filter((a) => a.completedAt) : results.filter((a) => !a.completedAt)
295
- }
296
- results.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
297
- return paginate(results, query.page, query.pageSize)
298
- },
299
-
300
- async createActivity(input: CreateActivityInput) {
301
- const activity: Activity = {
302
- id: uid(), dealId: input.dealId, leadId: input.leadId,
303
- contactId: input.contactId, activityType: input.activityType,
304
- title: input.title, description: input.description,
305
- dueDate: input.dueDate, assignedToId: input.assignedToId,
306
- tenantId, createdAt: now(),
307
- }
308
- store.activities.push(activity)
309
- return activity
310
- },
311
-
312
- async completeActivity(id) {
313
- const activity = store.activities.find((a) => a.id === id)
314
- if (!activity) throw new Error(`Activity ${id} not found`)
315
- activity.completedAt = now()
316
- return activity
317
- },
318
-
319
- async getActivityTypes(): Promise<ActivityTypeDef[]> {
320
- const seed = options?.activityTypes ?? [
321
- { value: 'call', label: 'Call', icon: 'Phone' },
322
- { value: 'email', label: 'Email', icon: 'Mail' },
323
- { value: 'meeting', label: 'Meeting', icon: 'Users' },
324
- { value: 'note', label: 'Note', icon: 'FileText' },
325
- { value: 'task', label: 'Task', icon: 'CheckSquare' },
326
- { value: 'whatsapp', label: 'WhatsApp', icon: 'MessageCircle' },
327
- ]
328
- return seed.map((t, i) => ({ id: `at-${i}`, name: t.label, icon: t.icon, isActive: true }))
329
- },
330
-
331
- async getTagDefs(): Promise<TagDef[]> {
332
- // Derivado do que os registros mock realmente carregam, em vez de uma
333
- // lista fixa: assim o mock exercita o mesmo caminho do banco, onde o
334
- // cadastro se alimenta do uso.
335
- const used = new Set<string>()
336
- for (const l of store.leads) for (const t of l.tags ?? []) used.add(t)
337
- for (const d of store.deals) for (const t of d.tags ?? []) used.add(t)
338
- return [...used].sort().map((slug, i) => ({
339
- id: `tag-${i}`,
340
- slug,
341
- name: slug.replace(/^[a-z]+:/, '').replace(/-/g, ' ').replace(/\b\w/g, (c) => c.toUpperCase()),
342
- color: MOCK_TAG_COLORS[i % MOCK_TAG_COLORS.length],
343
- isActive: true,
344
- }))
345
- },
346
-
347
- // Quotes
348
- async getQuotes(query: QuoteQuery) {
349
- let results = store.quotes.filter((q) => q.status !== 'archived' || (query.status && (Array.isArray(query.status) ? query.status : [query.status]).includes('archived')))
350
- if (query.status) {
351
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
352
- results = results.filter((q) => statuses.includes(q.status))
353
- }
354
- if (query.contactId) results = results.filter((q) => q.contactId === query.contactId)
355
- if (query.search) {
356
- const s = query.search.toLowerCase()
357
- results = results.filter((q) => q.quoteNumber.includes(s) || q.contactName?.toLowerCase().includes(s))
358
- }
359
- results.sort((a, b) => b.createdAt.localeCompare(a.createdAt))
360
- return paginate(results, query.page, query.pageSize)
361
- },
362
-
363
- async getQuoteById(id) { return store.quotes.find((q) => q.id === id) ?? null },
364
-
365
- async createQuote(input: CreateQuoteInput) {
366
- const quoteId = uid()
367
- const items: QuoteItem[] = input.items.map((item) => ({
368
- id: uid(), quoteId, ...item, createdAt: now(),
369
- }))
370
- const totalAmount = items.reduce((sum, i) => sum + i.totalAmount, 0)
371
- const quote: Quote = {
372
- id: quoteId, dealId: input.dealId, leadId: input.leadId,
373
- contactId: input.contactId,
374
- contactName: input.contactName, quoteNumber: `Q-${String(store.quotes.length + 1).padStart(4, '0')}`,
375
- quoteDate: input.quoteDate, validUntil: input.validUntil,
376
- status: 'draft', totalAmount, observations: input.observations,
377
- paymentConditions: input.paymentConditions, items, tenantId,
378
- createdAt: now(), updatedAt: now(),
379
- }
380
- store.quotes.push(quote)
381
- if (quote.dealId && totalAmount > 0) {
382
- const deal = store.deals.find((d) => d.id === quote.dealId)
383
- if (deal) { deal.value = totalAmount; deal.updatedAt = now() }
384
- }
385
- logEvent({
386
- activityType: 'quote_created', title: quote.quoteNumber ?? 'Quote',
387
- description: quote.contactName, dealId: quote.dealId, leadId: quote.leadId,
388
- contactId: quote.contactId, contactName: quote.contactName,
389
- })
390
- return quote
391
- },
392
-
393
- async updateQuote(id, input: CreateQuoteInput) {
394
- const quote = store.quotes.find((q) => q.id === id)
395
- if (!quote) throw new Error(`Quote ${id} not found`)
396
- const items: QuoteItem[] = input.items.map((item) => ({
397
- id: uid(), quoteId: id, ...item, createdAt: now(),
398
- }))
399
- const totalAmount = items.reduce((sum, i) => sum + i.totalAmount, 0)
400
- quote.contactId = input.contactId
401
- quote.contactName = input.contactName
402
- quote.dealId = input.dealId
403
- quote.leadId = input.leadId
404
- quote.quoteDate = input.quoteDate
405
- quote.validUntil = input.validUntil
406
- quote.observations = input.observations
407
- quote.paymentConditions = input.paymentConditions
408
- quote.items = items
409
- quote.totalAmount = totalAmount
410
- quote.updatedAt = now()
411
- if (quote.dealId && totalAmount > 0) {
412
- const deal = store.deals.find((d) => d.id === quote.dealId)
413
- if (deal) { deal.value = totalAmount; deal.updatedAt = now() }
414
- }
415
- return quote
416
- },
417
-
418
- async sendQuote(id) {
419
- const quote = store.quotes.find((q) => q.id === id)
420
- if (!quote) throw new Error(`Quote ${id} not found`)
421
- quote.status = 'sent'
422
- quote.updatedAt = now()
423
- logEvent({
424
- activityType: 'quote_sent', title: quote.quoteNumber ?? 'Quote',
425
- description: quote.contactName, dealId: quote.dealId, leadId: quote.leadId,
426
- contactName: quote.contactName,
427
- })
428
- return quote
429
- },
430
-
431
- async approveQuote(id) {
432
- const quote = store.quotes.find((q) => q.id === id)
433
- if (!quote) throw new Error(`Quote ${id} not found`)
434
- quote.status = 'approved'
435
- quote.updatedAt = now()
436
-
437
- // Cascade: move deal to Won stage
438
- if (quote.dealId) {
439
- const deal = store.deals.find((d) => d.id === quote.dealId)
440
- if (deal) {
441
- const wonStage = store.stages.find((s) => s.pipelineId === deal.pipelineId && s.isWon)
442
- if (wonStage) {
443
- await provider.moveDealToStage(deal.id, wonStage.id)
444
- }
445
- }
446
- }
447
-
448
- // Generate mock invoice
449
- quote.convertedInvoiceId = uid()
450
-
451
- // Convert lead to client
452
- if (quote.leadId) {
453
- const lead = store.leads.find((l) => l.id === quote.leadId)
454
- if (lead) {
455
- lead.metadata = { ...lead.metadata, convertedFromLead: true }
456
- }
457
- }
458
-
459
- logEvent({
460
- activityType: 'quote_approved', title: quote.quoteNumber ?? 'Quote',
461
- description: quote.contactName, dealId: quote.dealId, leadId: quote.leadId,
462
- contactName: quote.contactName,
463
- })
464
- return quote
465
- },
466
-
467
- async rejectQuote(id, reason) {
468
- const quote = store.quotes.find((q) => q.id === id)
469
- if (!quote) throw new Error(`Quote ${id} not found`)
470
- quote.status = 'rejected'
471
- quote.rejectionReason = reason
472
- quote.updatedAt = now()
473
-
474
- // Cascade: move deal to Lost stage
475
- if (quote.dealId) {
476
- const deal = store.deals.find((d) => d.id === quote.dealId)
477
- if (deal) {
478
- const lostStage = store.stages.find((s) => s.pipelineId === deal.pipelineId && s.isLost)
479
- if (lostStage) {
480
- await provider.moveDealToStage(deal.id, lostStage.id)
481
- }
482
- }
483
- }
484
- logEvent({
485
- activityType: 'quote_rejected', title: quote.quoteNumber ?? 'Quote',
486
- description: reason, dealId: quote.dealId, leadId: quote.leadId,
487
- contactName: quote.contactName,
488
- })
489
- return quote
490
- },
491
-
492
- async expireQuote(id) {
493
- const quote = store.quotes.find((q) => q.id === id)
494
- if (!quote) throw new Error(`Quote ${id} not found`)
495
- quote.status = 'expired'
496
- quote.updatedAt = now()
497
- return quote
498
- },
499
-
500
- async archiveQuote(id) {
501
- const quote = store.quotes.find((q) => q.id === id)
502
- if (!quote) throw new Error(`Quote ${id} not found`)
503
- quote.status = 'archived'
504
- quote.updatedAt = now()
505
- logEvent({
506
- activityType: 'quote_archived', title: quote.quoteNumber ?? 'Quote',
507
- description: quote.contactName, dealId: quote.dealId, leadId: quote.leadId,
508
- contactName: quote.contactName,
509
- })
510
- },
511
-
512
- // Cross-entity lookups
513
- async getQuotesByDealId(dealId) {
514
- return store.quotes.filter((q) => q.dealId === dealId)
515
- },
516
-
517
- async getDealByLeadId(leadId) {
518
- return store.deals.find((d) => d.leadId === leadId) ?? null
519
- },
520
-
521
- // Summary
522
- async getSummary(): Promise<CrmSummary> {
523
- const monthStart = today().slice(0, 7) + '-01'
524
- const monthLeads = store.leads.filter((l) => l.createdAt >= monthStart)
525
- const wonDeals = store.deals.filter((d) => d.status === 'won')
526
- const wonThisMonth = wonDeals.filter((d) => d.updatedAt >= monthStart)
527
- const openDeals = store.deals.filter((d) => d.status === 'open')
528
- const totalConverted = store.leads.filter((l) => l.status === 'converted').length
529
- const pendingActivities = store.activities.filter((a) => !a.completedAt)
530
- const overdueActivities = pendingActivities.filter((a) => a.dueDate && a.dueDate < today())
531
-
532
- return {
533
- totalLeads: store.leads.length,
534
- newLeadsThisMonth: monthLeads.length,
535
- totalDeals: store.deals.length,
536
- openDealsValue: openDeals.reduce((s, d) => s + d.value, 0),
537
- wonDealsThisMonth: wonThisMonth.length,
538
- wonDealsValueThisMonth: wonThisMonth.reduce((s, d) => s + d.value, 0),
539
- conversionRate: store.leads.length > 0 ? (totalConverted / store.leads.length) * 100 : 0,
540
- averageDealValue: wonDeals.length > 0 ? wonDeals.reduce((s, d) => s + d.value, 0) / wonDeals.length : 0,
541
- pendingActivities: pendingActivities.length,
542
- overdueActivities: overdueActivities.length,
543
- }
544
- },
545
-
546
- async getFunnel(pipelineId) {
547
- const stages = store.stages.filter((s) => s.pipelineId === pipelineId && !s.isLost).sort((a, b) => a.order - b.order)
548
- return stages.map((stage) => {
549
- const deals = store.deals.filter((d) => d.stageId === stage.id)
550
- return {
551
- stageId: stage.id, stageName: stage.name, stageColor: stage.color,
552
- dealCount: deals.length, totalValue: deals.reduce((s, d) => s + d.value, 0),
553
- }
554
- })
555
- },
556
- }
557
-
558
- return provider
559
- }