@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,634 @@
1
+ import type { CrmDataProvider } from './types'
2
+ import type {
3
+ Pipeline, PipelineStage, Lead, Deal, Activity, Quote, QuoteItem,
4
+ CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
5
+ LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
6
+ PaginatedResult, CrmSummary, FunnelStage,
7
+ } from '../types'
8
+ import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
9
+ import { getCrmTenantId } from '../lib/tenant'
10
+ import { deriveLeadStatus, deriveQuoteStatus } from '../cascade'
11
+
12
+ function getTenantId(): string | undefined {
13
+ // Plugin-local override wins; otherwise use the app's active tenant (set on
14
+ // org switch). Without this fallback, writes stamp tenant_id=undefined and
15
+ // fail the persons/orders RLS WITH CHECK (tenant_id IN user_tenant_ids()).
16
+ return getCrmTenantId() ?? getActiveTenantId()
17
+ }
18
+
19
+ function snakeToCamel(obj: Record<string, unknown>): Record<string, unknown> {
20
+ const result: Record<string, unknown> = {}
21
+ for (const [key, value] of Object.entries(obj)) {
22
+ result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = value
23
+ }
24
+ return result
25
+ }
26
+
27
+ function getClients() {
28
+ const supabase = getSupabaseClientOptional() as any
29
+ if (!supabase) throw new Error('Supabase not initialized')
30
+ return { core: supabase.schema('saas_core'), pub: supabase }
31
+ }
32
+
33
+ export function createSupabaseCrmProvider(options?: {
34
+ clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
35
+ }): CrmDataProvider {
36
+ const provider: CrmDataProvider = {
37
+ // --- Pipelines (public.pipelines + pipeline_stages) ---
38
+ async getPipelines(): Promise<Pipeline[]> {
39
+ const { pub } = getClients()
40
+ const { data } = await pub.from('pipelines').select('*').eq('is_active', true).order('name')
41
+ return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as Pipeline)
42
+ },
43
+
44
+ async getPipelineStages(pipelineId: string): Promise<PipelineStage[]> {
45
+ const { pub } = getClients()
46
+ const { data } = await pub.from('pipeline_stages').select('*').eq('pipeline_id', pipelineId).order('order')
47
+ return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as PipelineStage)
48
+ },
49
+
50
+ // --- Leads (via view — single query) ---
51
+ async getLeads(query: LeadQuery): Promise<PaginatedResult<Lead>> {
52
+ const { pub } = getClients()
53
+ let qb = pub.from('v_leads').select('*', { count: 'exact' })
54
+ if (query.search) qb = qb.ilike('name', `%${query.search}%`)
55
+ if (query.status) {
56
+ const statuses = Array.isArray(query.status) ? query.status : [query.status]
57
+ qb = qb.in('lead_status', statuses)
58
+ }
59
+ const page = query.page ?? 1
60
+ const pageSize = query.pageSize ?? 50
61
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
62
+ const { data, count } = await qb
63
+ return {
64
+ data: (data ?? []).map((r: any) => ({
65
+ id: r.id, name: r.name, email: r.email, phone: r.phone,
66
+ company: r.company, sourceId: r.source_id, sourceName: r.source_name,
67
+ status: r.lead_status ?? 'new',
68
+ assignedToId: r.assigned_to_id, value: r.lead_value ? Number(r.lead_value) : undefined,
69
+ tags: r.tags ?? [], notes: r.notes,
70
+ tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
71
+ } as Lead)),
72
+ total: count ?? 0,
73
+ }
74
+ },
75
+
76
+ async getLeadById(id: string): Promise<Lead | null> {
77
+ const { pub } = getClients()
78
+ // maybeSingle: callers pass a person id that may be a customer (not a lead);
79
+ // v_leads then returns 0 rows. single() would 406; maybeSingle() returns null.
80
+ const { data: r } = await pub.from('v_leads').select('*').eq('id', id).maybeSingle()
81
+ if (!r) return null
82
+ return {
83
+ id: r.id, name: r.name, email: r.email, phone: r.phone,
84
+ company: r.company, status: r.lead_status ?? 'new',
85
+ tags: r.tags ?? [], notes: r.notes,
86
+ tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
87
+ } as Lead
88
+ },
89
+
90
+ async createLead(input: CreateLeadInput): Promise<Lead> {
91
+ const { core } = getClients()
92
+ const tenantId = getTenantId()
93
+ const { data, error } = await core.from('persons').insert({
94
+ tenant_id: tenantId, kind: 'lead', name: input.name,
95
+ email: input.email, phone: input.phone,
96
+ notes: input.notes, tags: input.tags ?? [], is_active: true,
97
+ metadata: { company: input.company, sourceId: input.sourceId, status: 'new', value: input.value },
98
+ }).select().single()
99
+ if (error) throw new Error(error.message)
100
+ const p = snakeToCamel(data) as any
101
+ return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: 'new', tags: [], tenantId: tenantId!, createdAt: p.createdAt, updatedAt: p.updatedAt } as Lead
102
+ },
103
+
104
+ async updateLead(id: string, partial: Partial<Lead>): Promise<Lead> {
105
+ const { core } = getClients()
106
+ const row: any = {}
107
+ if (partial.name) row.name = partial.name
108
+ if (partial.email !== undefined) row.email = partial.email
109
+ if (partial.phone !== undefined) row.phone = partial.phone
110
+ if (partial.notes !== undefined) row.notes = partial.notes
111
+ if (partial.status) row.metadata = { status: partial.status }
112
+ const { data, error } = await core.from('persons').update(row).eq('id', id).select().single()
113
+ if (error) throw new Error(error.message)
114
+ return (await provider.getLeadById(id))!
115
+ },
116
+
117
+ async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
118
+ const { core } = getClients()
119
+ // Update lead status to converted
120
+ await core.from('persons').update({ metadata: { status: 'converted' } }).eq('id', leadId)
121
+ return provider.createDeal({ ...dealInput, leadId } as any)
122
+ },
123
+
124
+ // --- Deals (via view — single query with all joins) ---
125
+ async getDeals(query: DealQuery): Promise<PaginatedResult<Deal>> {
126
+ const { pub } = getClients()
127
+ let qb = pub.from('v_deals').select('*', { count: 'exact' })
128
+ if (query.status) {
129
+ const statuses = Array.isArray(query.status) ? query.status : [query.status]
130
+ qb = qb.in('status', statuses)
131
+ }
132
+ if (query.search) qb = qb.ilike('title', `%${query.search}%`)
133
+ if (query.pipelineId) qb = qb.eq('pipeline_id', query.pipelineId)
134
+ if (query.stageId) qb = qb.eq('stage_id', query.stageId)
135
+ const page = query.page ?? 1
136
+ const pageSize = query.pageSize ?? 50
137
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
138
+ const { data, count } = await qb
139
+
140
+ const deals: Deal[] = (data ?? []).map((r: any) => ({
141
+ id: r.id,
142
+ leadId: r.lead_id,
143
+ title: r.title ?? 'Untitled Deal',
144
+ value: r.value ?? 0,
145
+ pipelineId: r.pipeline_id ?? '',
146
+ stageId: r.stage_id ?? '',
147
+ stageName: r.stage_name,
148
+ stageColor: r.stage_color,
149
+ probability: r.probability ?? 0,
150
+ expectedCloseDate: r.expected_close_date,
151
+ assignedToId: r.assigned_to_id,
152
+ contactId: r.contact_id,
153
+ contactName: r.contact_name,
154
+ status: r.status ?? 'open',
155
+ lostReason: r.lost_reason,
156
+ tags: r.tags ?? [],
157
+ notes: r.title,
158
+ tenantId: r.tenant_id,
159
+ createdAt: r.created_at,
160
+ updatedAt: r.updated_at,
161
+ } as Deal))
162
+ return { data: deals, total: count ?? 0 }
163
+ },
164
+
165
+ async getDealById(id: string): Promise<Deal | null> {
166
+ const { pub } = getClients()
167
+ const { data: r } = await pub.from('v_deals').select('*').eq('id', id).maybeSingle()
168
+ if (!r) return null
169
+ return {
170
+ id: r.id, title: r.title ?? '', value: r.value ?? 0,
171
+ pipelineId: r.pipeline_id ?? '', stageId: r.stage_id ?? '',
172
+ stageName: r.stage_name, stageColor: r.stage_color,
173
+ probability: r.probability ?? 0, status: r.status ?? 'open',
174
+ contactName: r.contact_name, tags: r.tags ?? [],
175
+ tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
176
+ } as Deal
177
+ },
178
+
179
+ async getDealsByStage(pipelineId: string): Promise<Map<string, Deal[]>> {
180
+ const { pub } = getClients()
181
+ const stages = await provider.getPipelineStages(pipelineId)
182
+ // Single query via view — already has stage info joined
183
+ const { data } = await pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).neq('status', 'lost')
184
+ const deals = (data ?? []).map((r: any) => ({
185
+ id: r.id, title: r.title ?? '', value: r.value ?? 0,
186
+ pipelineId: r.pipeline_id, stageId: r.stage_id,
187
+ stageName: r.stage_name, stageColor: r.stage_color,
188
+ probability: r.probability ?? 0, status: r.status ?? 'open',
189
+ contactName: r.contact_name, tags: r.tags ?? [],
190
+ tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
191
+ } as Deal))
192
+
193
+ const map = new Map<string, Deal[]>()
194
+ for (const stage of stages) map.set(stage.id, [])
195
+ for (const deal of deals) {
196
+ const arr = map.get(deal.stageId)
197
+ if (arr) arr.push(deal)
198
+ }
199
+ return map
200
+ },
201
+
202
+ async createDeal(input: CreateDealInput): Promise<Deal> {
203
+ const { core, pub } = getClients()
204
+ const tenantId = getTenantId()
205
+
206
+ // Create order in saas_core
207
+ const { data: order, error } = await core.from('orders').insert({
208
+ tenant_id: tenantId, kind: 'deal', status: 'open',
209
+ total: input.value, party_id: input.contactId,
210
+ assignee_id: input.assignedToId, notes: input.title,
211
+ tags: input.tags ?? [], currency: 'BRL',
212
+ metadata: { contactName: input.contactName },
213
+ }).select().single()
214
+ if (error) throw new Error(error.message)
215
+
216
+ // Create deal extension with pipeline/stage info
217
+ await pub.from('deal_extensions').insert({
218
+ order_id: order.id, tenant_id: tenantId,
219
+ pipeline_id: input.pipelineId, stage_id: input.stageId,
220
+ probability: 0, expected_close_date: input.expectedCloseDate,
221
+ lead_id: (input as any).leadId,
222
+ })
223
+
224
+ return {
225
+ id: order.id, title: input.title, value: input.value,
226
+ pipelineId: input.pipelineId, stageId: input.stageId,
227
+ status: 'open', probability: 0, tags: input.tags ?? [],
228
+ contactName: input.contactName,
229
+ tenantId: tenantId!, createdAt: order.created_at, updatedAt: order.updated_at,
230
+ } as Deal
231
+ },
232
+
233
+ async updateDeal(id: string, partial: Partial<Deal>): Promise<Deal> {
234
+ const { core, pub } = getClients()
235
+ if (partial.title || partial.value || partial.status) {
236
+ const row: any = {}
237
+ if (partial.title) row.notes = partial.title
238
+ if (partial.value) row.total = partial.value
239
+ if (partial.status) row.status = partial.status
240
+ await core.from('orders').update(row).eq('id', id)
241
+ }
242
+ if (partial.stageId || partial.probability != null || partial.expectedCloseDate) {
243
+ const row: any = {}
244
+ if (partial.stageId) row.stage_id = partial.stageId
245
+ if (partial.probability != null) row.probability = partial.probability
246
+ if (partial.expectedCloseDate) row.expected_close_date = partial.expectedCloseDate
247
+ await pub.from('deal_extensions').update(row).eq('order_id', id)
248
+ }
249
+ return (await provider.getDealById(id))!
250
+ },
251
+
252
+ async moveDealToStage(dealId: string, stageId: string): Promise<Deal> {
253
+ const { core, pub } = getClients()
254
+ const { data: stageRow } = await pub.from('pipeline_stages').select('*').eq('id', stageId).single()
255
+ await pub.from('deal_extensions').update({
256
+ stage_id: stageId, probability: stageRow?.probability ?? 0,
257
+ }).eq('order_id', dealId)
258
+ if (stageRow?.is_won) await core.from('orders').update({ status: 'won' }).eq('id', dealId)
259
+ if (stageRow?.is_lost) await core.from('orders').update({ status: 'lost' }).eq('id', dealId)
260
+
261
+ // Cascade to lead + quotes
262
+ if (stageRow) {
263
+ const typedStage: import('../types').PipelineStage = {
264
+ id: stageRow.id, pipelineId: stageRow.pipeline_id, name: stageRow.name,
265
+ order: stageRow.order, color: stageRow.color, probability: stageRow.probability,
266
+ isWon: stageRow.is_won, isLost: stageRow.is_lost,
267
+ tenantId: stageRow.tenant_id, createdAt: stageRow.created_at,
268
+ }
269
+ // Update lead status
270
+ const { data: ext } = await pub.from('deal_extensions').select('lead_id').eq('order_id', dealId).single()
271
+ if (ext?.lead_id) {
272
+ const newLeadStatus = deriveLeadStatus(typedStage)
273
+ await core.from('persons').update({ metadata: { status: newLeadStatus } }).eq('id', ext.lead_id)
274
+ }
275
+ // Update quote statuses
276
+ const { data: quotes } = await core.from('orders').select('id, status').eq('kind', 'quote')
277
+ for (const q of quotes ?? []) {
278
+ const meta = (q as any).metadata
279
+ if (meta?.dealId === dealId) {
280
+ const newStatus = deriveQuoteStatus(typedStage, q.status)
281
+ if (newStatus !== q.status) {
282
+ await core.from('orders').update({ status: newStatus }).eq('id', q.id)
283
+ }
284
+ }
285
+ }
286
+ }
287
+
288
+ return (await provider.getDealById(dealId))!
289
+ },
290
+
291
+ // --- Activities (public.crm_activities) ---
292
+ async getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>> {
293
+ const { pub } = getClients()
294
+ let qb = pub.from('crm_activities').select('*', { count: 'exact' })
295
+ if (query.dealId) qb = qb.eq('deal_id', query.dealId)
296
+ if (query.leadId) qb = qb.eq('lead_id', query.leadId)
297
+ if (query.activityType) qb = qb.eq('activity_type', query.activityType)
298
+ if (query.completed === true) qb = qb.not('completed_at', 'is', null)
299
+ if (query.completed === false) qb = qb.is('completed_at', null)
300
+ const page = query.page ?? 1
301
+ const pageSize = query.pageSize ?? 50
302
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
303
+ const { data, count } = await qb
304
+ return { data: (data ?? []).map((r: any) => snakeToCamel(r) as unknown as Activity), total: count ?? 0 }
305
+ },
306
+
307
+ async createActivity(input: CreateActivityInput): Promise<Activity> {
308
+ const { pub } = getClients()
309
+ const tenantId = getTenantId()
310
+ const { data, error } = await pub.from('crm_activities').insert({
311
+ tenant_id: tenantId, deal_id: input.dealId, lead_id: input.leadId,
312
+ contact_id: input.contactId, activity_type: input.activityType,
313
+ title: input.title, description: input.description,
314
+ due_date: input.dueDate, assigned_to_id: input.assignedToId,
315
+ }).select().single()
316
+ if (error) throw new Error(error.message)
317
+ return snakeToCamel(data) as unknown as Activity
318
+ },
319
+
320
+ async completeActivity(id: string): Promise<Activity> {
321
+ const { pub } = getClients()
322
+ const { data, error } = await pub.from('crm_activities').update({ completed_at: new Date().toISOString() }).eq('id', id).select().single()
323
+ if (error) throw new Error(error.message)
324
+ return snakeToCamel(data) as unknown as Activity
325
+ },
326
+
327
+ // --- Quotes (saas_core.orders kind='quote' + order_items) ---
328
+ async getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>> {
329
+ const { core } = getClients()
330
+ let qb = core.from('orders').select('*', { count: 'exact' }).eq('kind', 'quote')
331
+ if (query.status) {
332
+ const statuses = Array.isArray(query.status) ? query.status : [query.status]
333
+ qb = qb.in('status', statuses)
334
+ }
335
+ if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`)
336
+ const page = query.page ?? 1
337
+ const pageSize = query.pageSize ?? 50
338
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
339
+ const { data, count } = await qb
340
+ const quotes: Quote[] = (data ?? []).map((r: any) => {
341
+ // Show financial stage as status when quote has been promoted
342
+ const stage = r.stage as string | undefined
343
+ const financialStages = ['invoiced', 'paid', 'partial', 'overdue']
344
+ const displayStatus = stage && financialStages.includes(stage) ? stage : (r.status ?? 'draft')
345
+ return {
346
+ id: r.id, quoteNumber: r.metadata?.quoteNumber ?? r.reference_number ?? '', quoteDate: r.created_at?.slice(0, 10) ?? '',
347
+ validUntil: r.due_at?.slice(0, 10) ?? '', status: displayStatus,
348
+ totalAmount: r.total ?? 0, contactId: r.party_id,
349
+ contactName: r.metadata?.contactName, observations: r.notes,
350
+ dealId: r.metadata?.dealId, leadId: r.metadata?.leadId, convertedInvoiceId: r.metadata?.convertedInvoiceId,
351
+ items: [], tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
352
+ } as Quote
353
+ })
354
+ return { data: quotes, total: count ?? 0 }
355
+ },
356
+
357
+ async getQuoteById(id: string): Promise<Quote | null> {
358
+ const { core } = getClients()
359
+ const { data: order } = await core.from('orders').select('*').eq('id', id).eq('kind', 'quote').maybeSingle()
360
+ if (!order) return null
361
+ const { data: items } = await core.from('order_items').select('*').eq('order_id', id).order('sort_order')
362
+ const stage = order.stage as string | undefined
363
+ const financialStages = ['invoiced', 'paid', 'partial', 'overdue']
364
+ const displayStatus = stage && financialStages.includes(stage) ? stage : (order.status ?? 'draft')
365
+ return {
366
+ id: order.id, quoteNumber: order.metadata?.quoteNumber ?? order.reference_number ?? '', quoteDate: order.created_at?.slice(0, 10) ?? '',
367
+ validUntil: order.due_at?.slice(0, 10) ?? '', status: displayStatus,
368
+ totalAmount: order.total ?? 0, contactId: order.party_id,
369
+ contactName: order.metadata?.contactName, observations: order.notes,
370
+ dealId: order.metadata?.dealId, leadId: order.metadata?.leadId, convertedInvoiceId: order.metadata?.convertedInvoiceId,
371
+ items: (items ?? []).map((i: any) => ({
372
+ id: i.id, quoteId: id, itemKind: i.metadata?.itemKind ?? 'other',
373
+ description: i.name ?? '', quantity: i.quantity ?? 1,
374
+ unitPrice: i.unit_price ?? 0, discount: i.discount ?? 0,
375
+ totalAmount: i.total ?? 0, createdAt: i.created_at,
376
+ } as QuoteItem)),
377
+ tenantId: order.tenant_id, createdAt: order.created_at, updatedAt: order.updated_at,
378
+ } as Quote
379
+ },
380
+
381
+ async createQuote(input: CreateQuoteInput): Promise<Quote> {
382
+ const { core } = getClients()
383
+ const tenantId = getTenantId()
384
+ const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0)
385
+
386
+ // Derive next quote number from existing quotes
387
+ const { count } = await core.from('orders').select('*', { count: 'exact', head: true }).eq('kind', 'quote')
388
+ const nextNum = (count ?? 0) + 1
389
+
390
+ const { data: order, error } = await core.from('orders').insert({
391
+ tenant_id: tenantId, kind: 'quote', status: 'draft',
392
+ reference_number: `Q-${String(nextNum).padStart(4, '0')}`,
393
+ total: totalAmount, party_id: input.contactId,
394
+ due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
395
+ notes: input.observations, currency: 'BRL',
396
+ metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId },
397
+ }).select().single()
398
+ if (error) throw new Error(error.message)
399
+
400
+ if (input.items.length > 0) {
401
+ const { error: itemsError } = await core.from('order_items').insert(
402
+ input.items.map((item, i) => ({
403
+ order_id: order.id, name: item.description,
404
+ quantity: item.quantity, unit_price: item.unitPrice,
405
+ discount: item.discount, total: item.totalAmount,
406
+ sort_order: i, metadata: { itemKind: item.itemKind },
407
+ }))
408
+ )
409
+ if (itemsError) throw new Error(itemsError.message)
410
+ }
411
+
412
+ return {
413
+ id: order.id, quoteNumber: order.reference_number,
414
+ quoteDate: order.created_at?.slice(0, 10), validUntil: input.validUntil,
415
+ status: 'draft', totalAmount, contactName: input.contactName,
416
+ dealId: input.dealId, leadId: input.leadId,
417
+ items: [], tenantId: tenantId!,
418
+ createdAt: order.created_at, updatedAt: order.updated_at,
419
+ } as unknown as Quote
420
+ },
421
+
422
+ async updateQuote(id: string, input: CreateQuoteInput): Promise<Quote> {
423
+ const { core } = getClients()
424
+ const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0)
425
+
426
+ const { error } = await core.from('orders').update({
427
+ total: totalAmount, party_id: input.contactId,
428
+ due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
429
+ notes: input.observations, metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId },
430
+ }).eq('id', id)
431
+ if (error) throw new Error(error.message)
432
+
433
+ // Replace items: delete existing, insert new
434
+ await core.from('order_items').delete().eq('order_id', id)
435
+ if (input.items.length > 0) {
436
+ const { error: itemsError } = await core.from('order_items').insert(
437
+ input.items.map((item, i) => ({
438
+ order_id: id, name: item.description,
439
+ quantity: item.quantity, unit_price: item.unitPrice,
440
+ discount: item.discount, total: item.totalAmount,
441
+ sort_order: i, metadata: { itemKind: item.itemKind },
442
+ }))
443
+ )
444
+ if (itemsError) throw new Error(itemsError.message)
445
+ }
446
+
447
+ return (await provider.getQuoteById(id))!
448
+ },
449
+
450
+ async sendQuote(id: string): Promise<Quote> {
451
+ const { core } = getClients()
452
+ await core.from('orders').update({ status: 'sent' }).eq('id', id)
453
+
454
+ // Move deal to Negotiation stage (only forward, never backward)
455
+ try {
456
+ const quote = await provider.getQuoteById(id)
457
+ if (quote?.dealId) {
458
+ const deal = await provider.getDealById(quote.dealId)
459
+ if (deal) {
460
+ const stages = await provider.getPipelineStages(deal.pipelineId)
461
+ const negotiationStage = stages.find((s) => s.name === 'Negotiation')
462
+ ?? stages.filter((s: any) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0]
463
+ const currentStage = stages.find((s) => s.id === deal.stageId)
464
+ if (negotiationStage && currentStage && negotiationStage.order > currentStage.order) {
465
+ await provider.moveDealToStage(deal.id, negotiationStage.id)
466
+ }
467
+ }
468
+ }
469
+ } catch { /* non-blocking */ }
470
+
471
+ return (await provider.getQuoteById(id))!
472
+ },
473
+
474
+ async approveQuote(id: string): Promise<Quote> {
475
+ const { core, pub } = getClients()
476
+ const tenantId = getTenantId()
477
+
478
+ const quote = await provider.getQuoteById(id)
479
+ if (!quote) throw new Error('Quote not found')
480
+
481
+ // 2-4. Atomic promotion (ref number + stage/direction + financial movement)
482
+ // in one transaction via the shared DB function. Replaces the
483
+ // multi-step write each plugin used to re-implement. Idempotent.
484
+ const { error: promoteErr } = await pub.rpc('fn_invoice_from_order', {
485
+ p_order_id: id,
486
+ p_due_date: quote.validUntil ?? null,
487
+ p_status: 'approved',
488
+ })
489
+ if (promoteErr) throw new Error(promoteErr.message)
490
+
491
+ // 5. Cascade: move deal to Won stage
492
+ if (quote.dealId) {
493
+ try {
494
+ const deal = await provider.getDealById(quote.dealId)
495
+ if (deal) {
496
+ const stages = await provider.getPipelineStages(deal.pipelineId)
497
+ const wonStage = stages.find((s) => s.isWon)
498
+ if (wonStage) await provider.moveDealToStage(deal.id, wonStage.id)
499
+ }
500
+ } catch { /* non-blocking */ }
501
+ }
502
+
503
+ // 6. Convert lead to client — use leadId or fall back to contactId (party_id)
504
+ const personToConvert = quote.leadId ?? quote.contactId
505
+ if (personToConvert) {
506
+ const clientKind = options?.clientConversion?.archetypeKind ?? 'client'
507
+ const { data: person } = await core.from('persons')
508
+ .select('kind, name, email, phone, tenant_id, metadata')
509
+ .eq('id', personToConvert).single()
510
+
511
+ // Only convert if they're actually a lead (not already a client/staff/etc.)
512
+ const personKind = (person as any)?.kind as string | undefined
513
+ if (person && (personKind === 'lead' || personKind === 'contact')) {
514
+ const personMeta = (person as any)?.metadata ?? {}
515
+ await core.from('persons').update({
516
+ kind: clientKind,
517
+ metadata: { ...personMeta, convertedFromLead: true },
518
+ }).eq('id', personToConvert)
519
+
520
+ // Create extension table record
521
+ if (options?.clientConversion) {
522
+ const { extensionTable, fkColumn } = options.clientConversion
523
+ await pub.from(extensionTable).upsert({
524
+ [fkColumn]: personToConvert,
525
+ tenant_id: (person as any).tenant_id,
526
+ }, { onConflict: fkColumn })
527
+ }
528
+ }
529
+ }
530
+
531
+ return (await provider.getQuoteById(id))!
532
+ },
533
+
534
+ async rejectQuote(id: string, reason: string): Promise<Quote> {
535
+ const { core } = getClients()
536
+ // Read existing metadata to merge
537
+ const { data: existing } = await core.from('orders').select('metadata').eq('id', id).single()
538
+ const existingMeta = (existing as any)?.metadata ?? {}
539
+ const { error } = await core.from('orders').update({
540
+ status: 'rejected',
541
+ metadata: { ...existingMeta, rejectionReason: reason },
542
+ }).eq('id', id)
543
+ if (error) throw new Error(error.message)
544
+ // Cascade: move deal to Lost stage
545
+ const quote = await provider.getQuoteById(id)
546
+ if (quote?.dealId) {
547
+ const deal = await provider.getDealById(quote.dealId)
548
+ if (deal) {
549
+ const stages = await provider.getPipelineStages(deal.pipelineId)
550
+ const lostStage = stages.find((s) => s.isLost)
551
+ if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id)
552
+ }
553
+ }
554
+ return quote!
555
+ },
556
+
557
+ async expireQuote(id: string): Promise<Quote> {
558
+ const { core } = getClients()
559
+ await core.from('orders').update({ status: 'expired' }).eq('id', id)
560
+ return (await provider.getQuoteById(id))!
561
+ },
562
+
563
+ // Cross-entity lookups
564
+ async getQuotesByDealId(dealId: string): Promise<Quote[]> {
565
+ const { core } = getClients()
566
+ const { data } = await core.from('orders').select('*').eq('kind', 'quote')
567
+ return (data ?? [])
568
+ .filter((r: any) => r.metadata?.dealId === dealId)
569
+ .map((r: any) => ({
570
+ id: r.id, quoteNumber: r.reference_number ?? '', quoteDate: r.created_at?.slice(0, 10) ?? '',
571
+ validUntil: r.due_at?.slice(0, 10) ?? '', status: r.status ?? 'draft',
572
+ totalAmount: r.total ?? 0, contactId: r.party_id,
573
+ contactName: r.metadata?.contactName, dealId: r.metadata?.dealId, leadId: r.metadata?.leadId, convertedInvoiceId: r.metadata?.convertedInvoiceId,
574
+ items: [], tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
575
+ } as Quote))
576
+ },
577
+
578
+ async getDealByLeadId(leadId: string): Promise<Deal | null> {
579
+ const { pub } = getClients()
580
+ const { data } = await pub.from('deal_extensions').select('order_id').eq('lead_id', leadId).limit(1)
581
+ if (!data || data.length === 0) return null
582
+ return provider.getDealById(data[0].order_id)
583
+ },
584
+
585
+ // --- Summary ---
586
+ async getSummary(): Promise<CrmSummary> {
587
+ const { core, pub } = getClients()
588
+ const monthStart = new Date().toISOString().slice(0, 7) + '-01'
589
+ const today = new Date().toISOString().slice(0, 10)
590
+
591
+ const { count: totalLeads } = await core.from('persons').select('*', { count: 'exact', head: true }).eq('kind', 'lead')
592
+ const { count: newLeads } = await core.from('persons').select('*', { count: 'exact', head: true }).eq('kind', 'lead').gte('created_at', monthStart)
593
+ const { data: deals } = await core.from('orders').select('status, total, updated_at').eq('kind', 'deal')
594
+ const allDeals = deals ?? []
595
+ const openDeals = allDeals.filter((d: any) => d.status === 'open')
596
+ const wonDeals = allDeals.filter((d: any) => d.status === 'won')
597
+ const wonThisMonth = wonDeals.filter((d: any) => d.updated_at >= monthStart)
598
+ const convertedLeads = allDeals.length // each deal came from a lead conversion
599
+
600
+ const { count: pendingActs } = await pub.from('crm_activities').select('*', { count: 'exact', head: true }).is('completed_at', null)
601
+ const { count: overdueActs } = await pub.from('crm_activities').select('*', { count: 'exact', head: true }).is('completed_at', null).lt('due_date', today)
602
+
603
+ return {
604
+ totalLeads: totalLeads ?? 0,
605
+ newLeadsThisMonth: newLeads ?? 0,
606
+ totalDeals: allDeals.length,
607
+ openDealsValue: openDeals.reduce((s: number, d: any) => s + (d.total ?? 0), 0),
608
+ wonDealsThisMonth: wonThisMonth.length,
609
+ wonDealsValueThisMonth: wonThisMonth.reduce((s: number, d: any) => s + (d.total ?? 0), 0),
610
+ conversionRate: (totalLeads ?? 0) > 0 ? (convertedLeads / (totalLeads ?? 1)) * 100 : 0,
611
+ averageDealValue: wonDeals.length > 0 ? wonDeals.reduce((s: number, d: any) => s + (d.total ?? 0), 0) / wonDeals.length : 0,
612
+ pendingActivities: pendingActs ?? 0,
613
+ overdueActivities: overdueActs ?? 0,
614
+ }
615
+ },
616
+
617
+ async getFunnel(pipelineId: string): Promise<FunnelStage[]> {
618
+ const { pub } = getClients()
619
+ const stages = await provider.getPipelineStages(pipelineId)
620
+ const deals = await provider.getDeals({ status: 'open' })
621
+
622
+ return stages.filter((s: any) => !s.isLost).map((stage) => {
623
+ const stageDeals = deals.data.filter((d: any) => d.stageId === stage.id)
624
+ return {
625
+ stageId: stage.id, stageName: stage.name, stageColor: stage.color,
626
+ dealCount: stageDeals.length,
627
+ totalValue: stageDeals.reduce((s, d) => s + d.value, 0),
628
+ }
629
+ })
630
+ },
631
+ }
632
+
633
+ return provider
634
+ }
@@ -0,0 +1,50 @@
1
+ import type {
2
+ Pipeline, PipelineStage, Lead, Deal, Activity, Quote,
3
+ CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
4
+ LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
5
+ PaginatedResult, CrmSummary, FunnelStage,
6
+ } from '../types'
7
+
8
+ export interface CrmDataProvider {
9
+ // Pipelines
10
+ getPipelines(): Promise<Pipeline[]>
11
+ getPipelineStages(pipelineId: string): Promise<PipelineStage[]>
12
+
13
+ // Leads
14
+ getLeads(query: LeadQuery): Promise<PaginatedResult<Lead>>
15
+ getLeadById(id: string): Promise<Lead | null>
16
+ createLead(input: CreateLeadInput): Promise<Lead>
17
+ updateLead(id: string, data: Partial<Lead>): Promise<Lead>
18
+ convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal>
19
+
20
+ // Deals
21
+ getDeals(query: DealQuery): Promise<PaginatedResult<Deal>>
22
+ getDealById(id: string): Promise<Deal | null>
23
+ getDealsByStage(pipelineId: string): Promise<Map<string, Deal[]>>
24
+ createDeal(input: CreateDealInput): Promise<Deal>
25
+ updateDeal(id: string, data: Partial<Deal>): Promise<Deal>
26
+ moveDealToStage(dealId: string, stageId: string): Promise<Deal>
27
+
28
+ // Activities
29
+ getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>>
30
+ createActivity(input: CreateActivityInput): Promise<Activity>
31
+ completeActivity(id: string): Promise<Activity>
32
+
33
+ // Quotes
34
+ getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>>
35
+ getQuoteById(id: string): Promise<Quote | null>
36
+ createQuote(input: CreateQuoteInput): Promise<Quote>
37
+ updateQuote(id: string, input: CreateQuoteInput): Promise<Quote>
38
+ sendQuote(id: string): Promise<Quote>
39
+ approveQuote(id: string): Promise<Quote>
40
+ rejectQuote(id: string, reason: string): Promise<Quote>
41
+ expireQuote(id: string): Promise<Quote>
42
+
43
+ // Cross-entity lookups
44
+ getQuotesByDealId(dealId: string): Promise<Quote[]>
45
+ getDealByLeadId(leadId: string): Promise<Deal | null>
46
+
47
+ // Summary
48
+ getSummary(): Promise<CrmSummary>
49
+ getFunnel(pipelineId: string): Promise<FunnelStage[]>
50
+ }