@fayz-ai/plugin-crm 0.9.0-next.1 → 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,928 +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, SystemActivityType,
7
- } from '../types'
8
- import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
9
- import { getCrmTenantId } from '../lib/tenant'
10
- import { deriveLeadStatus, deriveQuoteStatus } from '../cascade'
11
- import { T } from './tables'
12
-
13
- function getTenantId(): string | undefined {
14
- // Plugin-local override wins; otherwise use the app's active tenant (set on
15
- // org switch). Without this fallback, writes stamp tenant_id=undefined and
16
- // fail the people/orders RLS WITH CHECK (tenant_id IN user_tenant_ids()).
17
- return getCrmTenantId() ?? getActiveTenantId()
18
- }
19
-
20
- /** Mesmo rótulo que o `crm_tag_humanize` do banco produz, para os dois
21
- * caminhos (site público e admin) nomearem a tag igual. */
22
- function humanizeTagSlug(slug: string): string {
23
- return slug
24
- .replace(/^[a-z]+:/, '')
25
- .replace(/-/g, ' ')
26
- .replace(/\b\w/g, (c) => c.toUpperCase())
27
- }
28
-
29
- function snakeToCamel(obj: Record<string, unknown>): Record<string, unknown> {
30
- const result: Record<string, unknown> = {}
31
- for (const [key, value] of Object.entries(obj)) {
32
- result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = value
33
- }
34
- return result
35
- }
36
-
37
- function getClients() {
38
- const supabase = getSupabaseClientOptional() as any
39
- if (!supabase) throw new Error('Supabase not initialized')
40
- // Core tables now live in public alongside the plugin tables — a single public
41
- // client serves both core (people/orders) and plugin (plg_crm_*) tables.
42
- return { core: supabase, pub: supabase }
43
- }
44
-
45
- /**
46
- * Patch keys into people.metadata, preserving everything already there.
47
- *
48
- * people.metadata is a single opaque bag holding unrelated things: the lead's
49
- * pipeline `status`, plus `formId`/`fields`/`utm` — the public form's answers,
50
- * which are the entire content of a lead that arrived from a landing page.
51
- * A plain `.update({ metadata: {...} })` REPLACES the column, so any code that
52
- * only meant to set the status was deleting the enquiry. Two call sites did
53
- * exactly that.
54
- *
55
- * Read-merge-write rather than a `jsonb ||` RPC: it matches the pattern already
56
- * used elsewhere in this file, and these writes are single-operator actions
57
- * (dragging one card), not concurrent ones.
58
- */
59
- async function mergePersonMetadata(personId: string, patch: Record<string, unknown>): Promise<void> {
60
- const { core } = getClients()
61
- const { data: row } = await core.from('people').select('metadata').eq('id', personId).maybeSingle()
62
- const current = (row?.metadata ?? {}) as Record<string, unknown>
63
- await core.from('people').update({ metadata: { ...current, ...patch } }).eq('id', personId)
64
- }
65
-
66
- export function createSupabaseCrmProvider(options?: {
67
- clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
68
- /** Manual interaction types lazily seeded per tenant (settings-editable rows). */
69
- activityTypes?: Array<{ value: string; label: string; icon?: string }>
70
- }): CrmDataProvider {
71
- // System timeline event — written silently at every CRM write point.
72
- // completed_at is stamped so events never pollute the "pending" task filter,
73
- // and a log failure must never break the write it describes.
74
- async function logEvent(input: {
75
- activityType: SystemActivityType
76
- title: string
77
- description?: string
78
- leadId?: string
79
- dealId?: string
80
- contactId?: string
81
- contactName?: string
82
- }): Promise<void> {
83
- try {
84
- const { pub } = getClients()
85
- await pub.from(T.activities).insert({
86
- tenant_id: getTenantId(),
87
- deal_id: input.dealId ?? null,
88
- lead_id: input.leadId ?? null,
89
- contact_id: input.contactId ?? null,
90
- contact_name: input.contactName ?? null,
91
- activity_type: input.activityType,
92
- title: input.title,
93
- description: input.description ?? null,
94
- completed_at: new Date().toISOString(),
95
- })
96
- } catch { /* timeline is best-effort */ }
97
- }
98
-
99
- // Lazy per-tenant seed of manual interaction types (the type set comes from
100
- // app config — SQL can't know the vertical). Idempotent via (tenant, name).
101
- const typesSeeded = new Set<string>()
102
- async function ensureActivityTypes(tenantId: string): Promise<void> {
103
- const seed = options?.activityTypes
104
- if (!seed?.length || typesSeeded.has(tenantId)) return
105
- typesSeeded.add(tenantId)
106
- const { pub } = getClients()
107
- await pub.from(T.activityTypes).upsert(
108
- seed.map((t) => ({ tenant_id: tenantId, name: t.label, icon: t.icon ?? null, is_active: true })),
109
- { onConflict: 'tenant_id,name', ignoreDuplicates: true },
110
- )
111
- }
112
-
113
- /**
114
- * Registra no cadastro qualquer tag que ainda não exista.
115
- *
116
- * O caminho público (create_public_lead) já faz isto dentro do RPC; aqui é o
117
- * caminho do ADMIN — criar um lead/negócio com uma tag nova pela tela tem de
118
- * alimentar o mesmo cadastro, senão o chip nasce sem cor e a tag não aparece
119
- * como opção no filtro do funil.
120
- *
121
- * Upsert direto em vez do RPC `crm_register_tags`: aquele é SECURITY DEFINER e
122
- * recebe o tenant do caller, então fica interno ao caminho anônimo. Aqui a RLS
123
- * da própria tabela já autoriza — mesmo padrão de `ensureActivityTypes`.
124
- *
125
- * Best-effort: uma linha de cadastro não pode derrubar a criação do registro
126
- * que o operador acabou de fazer.
127
- */
128
- async function registerTags(tags?: string[]): Promise<void> {
129
- const tenantId = getTenantId()
130
- if (!tenantId || !tags?.length) return
131
- try {
132
- const { pub } = getClients()
133
- // name/color são só o ponto de partida: o trigger deriva o slug, e o
134
- // operador renomeia/recolore depois sem afetar registro nenhum.
135
- await pub.from(T.tags).upsert(
136
- [...new Set(tags)].map((slug) => ({
137
- tenant_id: tenantId,
138
- slug,
139
- name: humanizeTagSlug(slug),
140
- is_active: true,
141
- })),
142
- { onConflict: 'tenant_id,slug', ignoreDuplicates: true },
143
- )
144
- } catch { /* o chip cai no rótulo derivado do slug */ }
145
- }
146
-
147
- const provider: CrmDataProvider = {
148
- // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
149
- async getPipelines(): Promise<Pipeline[]> {
150
- const { pub } = getClients()
151
- const { data } = await pub.from(T.pipelines).select('*').eq('is_active', true).order('name')
152
- return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as Pipeline)
153
- },
154
-
155
- async getPipelineStages(pipelineId: string): Promise<PipelineStage[]> {
156
- const { pub } = getClients()
157
- const { data } = await pub.from(T.pipelineStages).select('*').eq('pipeline_id', pipelineId).order('order')
158
- return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as PipelineStage)
159
- },
160
-
161
- // --- Leads (via view — single query) ---
162
- async getLeads(query: LeadQuery): Promise<PaginatedResult<Lead>> {
163
- const { pub } = getClients()
164
- let qb = pub.from('v_leads').select('*', { count: 'exact' }).eq('is_active', true)
165
- if (query.search) qb = qb.ilike('name', `%${query.search}%`)
166
- if (query.status) {
167
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
168
- qb = qb.in('lead_status', statuses)
169
- }
170
- const page = query.page ?? 1
171
- const pageSize = query.pageSize ?? 50
172
- qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
173
- const { data, count } = await qb
174
- return {
175
- data: (data ?? []).map((r: any) => ({
176
- id: r.id, name: r.name, email: r.email, phone: r.phone,
177
- company: r.company, sourceId: r.source_id, sourceName: r.source_name,
178
- status: r.lead_status ?? 'new',
179
- assignedToId: r.assigned_to_id, value: r.lead_value ? Number(r.lead_value) : undefined,
180
- tags: r.tags ?? [], notes: r.notes,
181
- tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
182
- } as Lead)),
183
- total: count ?? 0,
184
- }
185
- },
186
-
187
- async getLeadById(id: string): Promise<Lead | null> {
188
- const { pub } = getClients()
189
- // maybeSingle: callers pass a person id that may be a customer (not a lead);
190
- // v_leads then returns 0 rows. single() would 406; maybeSingle() returns null.
191
- const { data: r } = await pub.from('v_leads').select('*').eq('id', id).maybeSingle()
192
- if (!r) return null
193
- return {
194
- id: r.id, name: r.name, email: r.email, phone: r.phone,
195
- company: r.company, status: r.lead_status ?? 'new',
196
- sourceName: r.source_name,
197
- tags: r.tags ?? [], notes: r.notes,
198
- // Answers from a public form. Kept as an opaque bag so a new landing
199
- // page needs no schema change; the detail view renders whatever is here.
200
- metadata: {
201
- formId: r.form_id ?? undefined,
202
- fields: r.custom_fields ?? {},
203
- utm: r.utm ?? {},
204
- // Ponteiros para o Storage (015). Sem esta linha o anexo é write-only:
205
- // chega no banco e nenhuma tela consegue mostrar.
206
- attachments: r.attachments ?? [],
207
- },
208
- tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
209
- } as Lead
210
- },
211
-
212
- async createLead(input: CreateLeadInput): Promise<Lead> {
213
- const { core } = getClients()
214
- const tenantId = getTenantId()
215
- const { data, error } = await core.from('people').insert({
216
- tenant_id: tenantId, kind: 'lead', name: input.name,
217
- email: input.email, phone: input.phone,
218
- notes: input.notes, tags: input.tags ?? [], is_active: true,
219
- metadata: { company: input.company, sourceId: input.sourceId, status: 'new', value: input.value },
220
- }).select().single()
221
- if (error) throw new Error(error.message)
222
- const p = snakeToCamel(data) as any
223
- await registerTags(input.tags)
224
- await logEvent({ activityType: 'lead_created', title: input.name, leadId: p.id, contactName: input.name })
225
- // `tags` sai do que foi GRAVADO: devolver [] fixo fazia o card recém-criado
226
- // nascer sem os chips que o formulário acabou de definir, até um refetch.
227
- return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: 'new', tags: p.tags ?? input.tags ?? [], tenantId: tenantId!, createdAt: p.createdAt, updatedAt: p.updatedAt } as Lead
228
- },
229
-
230
- async updateLead(id: string, partial: Partial<Lead>): Promise<Lead> {
231
- const { core } = getClients()
232
- const row: any = {}
233
- if (partial.name) row.name = partial.name
234
- if (partial.email !== undefined) row.email = partial.email
235
- if (partial.phone !== undefined) row.phone = partial.phone
236
- if (partial.notes !== undefined) row.notes = partial.notes
237
- const { error } = await core.from('people').update(row).eq('id', id).select().single()
238
- if (error) throw new Error(error.message)
239
- // The third call site that replaced the bag. Editing a lead's status from
240
- // the list wiped formId/fields/utm exactly as dragging its card did — the
241
- // same fix, applied here too rather than left for the next reader to find.
242
- if (partial.status) await mergePersonMetadata(id, { status: partial.status })
243
- return (await provider.getLeadById(id))!
244
- },
245
-
246
- async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
247
- // Update lead status to converted
248
- await mergePersonMetadata(leadId, { status: 'converted' })
249
- await logEvent({
250
- activityType: 'lead_converted',
251
- title: dealInput.contactName ?? dealInput.title,
252
- leadId,
253
- contactName: dealInput.contactName,
254
- })
255
- return provider.createDeal({ ...dealInput, leadId } as any)
256
- },
257
-
258
- // --- Deals (via view — single query with all joins) ---
259
- async getDeals(query: DealQuery): Promise<PaginatedResult<Deal>> {
260
- const { pub } = getClients()
261
- let qb = pub.from('v_deals').select('*', { count: 'exact' })
262
- if (query.status) {
263
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
264
- qb = qb.in('status', statuses)
265
- } else {
266
- qb = qb.neq('status', 'archived')
267
- }
268
- if (query.search) qb = qb.ilike('title', `%${query.search}%`)
269
- if (query.pipelineId) qb = qb.eq('pipeline_id', query.pipelineId)
270
- if (query.stageId) qb = qb.eq('stage_id', query.stageId)
271
- const page = query.page ?? 1
272
- const pageSize = query.pageSize ?? 50
273
- qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
274
- const { data, count } = await qb
275
-
276
- const deals: Deal[] = (data ?? []).map((r: any) => ({
277
- id: r.id,
278
- leadId: r.lead_id,
279
- title: r.title ?? 'Untitled Deal',
280
- value: r.value ?? 0,
281
- pipelineId: r.pipeline_id ?? '',
282
- stageId: r.stage_id ?? '',
283
- stageName: r.stage_name,
284
- stageColor: r.stage_color,
285
- probability: r.probability ?? 0,
286
- expectedCloseDate: r.expected_close_date,
287
- assignedToId: r.assigned_to_id,
288
- contactId: r.contact_id,
289
- contactName: r.contact_name,
290
- status: r.status ?? 'open',
291
- lostReason: r.lost_reason,
292
- tags: r.tags ?? [],
293
- notes: r.title,
294
- tenantId: r.tenant_id,
295
- createdAt: r.created_at,
296
- updatedAt: r.updated_at,
297
- } as Deal))
298
- return { data: deals, total: count ?? 0 }
299
- },
300
-
301
- async getDealById(id: string): Promise<Deal | null> {
302
- const { pub } = getClients()
303
- const { data: r } = await pub.from('v_deals').select('*').eq('id', id).maybeSingle()
304
- if (!r) return null
305
- return {
306
- id: r.id, title: r.title ?? '', value: r.value ?? 0,
307
- pipelineId: r.pipeline_id ?? '', stageId: r.stage_id ?? '',
308
- stageName: r.stage_name, stageColor: r.stage_color,
309
- probability: r.probability ?? 0, status: r.status ?? 'open',
310
- contactName: r.contact_name, tags: r.tags ?? [],
311
- // v_deals exposes de.lead_id and Deal declares leadId, but the mapping
312
- // dropped it — so DealSidebar's `if (d?.leadId)` never fired and the
313
- // card opened blank: no contact, no form answers. For a card that came
314
- // from a form, the lead IS the content.
315
- leadId: r.lead_id ?? undefined,
316
- tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
317
- } as Deal
318
- },
319
-
320
- async getDealsByStage(pipelineId: string, filter?: BoardFilter): Promise<Map<string, Deal[]>> {
321
- const { pub } = getClients()
322
- const stages = await provider.getPipelineStages(pipelineId)
323
- // Single query via view — already has stage info joined
324
- let qb = pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).not('status', 'in', '(lost,archived)')
325
- // `overlaps` = tem QUALQUER uma das tags. `contains` seria "tem todas",
326
- // que num multi-select de segmentos quase sempre volta vazio.
327
- if (filter?.tags?.length) qb = qb.overlaps('tags', filter.tags)
328
- if (filter?.createdFrom) qb = qb.gte('created_at', filter.createdFrom)
329
- if (filter?.createdTo) qb = qb.lte('created_at', filter.createdTo)
330
- const { data } = await qb
331
- const deals = (data ?? []).map((r: any) => ({
332
- id: r.id, title: r.title ?? '', value: r.value ?? 0,
333
- pipelineId: r.pipeline_id, stageId: r.stage_id,
334
- stageName: r.stage_name, stageColor: r.stage_color,
335
- probability: r.probability ?? 0, status: r.status ?? 'open',
336
- contactName: r.contact_name, tags: r.tags ?? [],
337
- leadId: r.lead_id ?? undefined,
338
- tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
339
- } as Deal))
340
-
341
- const map = new Map<string, Deal[]>()
342
- for (const stage of stages) map.set(stage.id, [])
343
- for (const deal of deals) {
344
- const arr = map.get(deal.stageId)
345
- if (arr) arr.push(deal)
346
- }
347
- return map
348
- },
349
-
350
- async createDeal(input: CreateDealInput): Promise<Deal> {
351
- const { core, pub } = getClients()
352
- const tenantId = getTenantId()
353
-
354
- // Create order in public.orders
355
- const { data: order, error } = await core.from('orders').insert({
356
- tenant_id: tenantId, kind: 'deal', status: 'open',
357
- total: input.value, party_id: input.contactId,
358
- assignee_id: input.assignedToId, notes: input.title,
359
- tags: input.tags ?? [], currency: 'BRL',
360
- metadata: { contactName: input.contactName },
361
- }).select().single()
362
- if (error) throw new Error(error.message)
363
-
364
- // Create deal extension with pipeline/stage info
365
- await pub.from(T.dealExtensions).insert({
366
- order_id: order.id, tenant_id: tenantId,
367
- pipeline_id: input.pipelineId, stage_id: input.stageId,
368
- probability: 0, expected_close_date: input.expectedCloseDate,
369
- lead_id: (input as any).leadId,
370
- })
371
-
372
- await registerTags(input.tags)
373
-
374
- await logEvent({
375
- activityType: 'deal_created',
376
- title: input.title,
377
- dealId: order.id,
378
- leadId: (input as any).leadId,
379
- contactId: input.contactId,
380
- contactName: input.contactName,
381
- })
382
-
383
- return {
384
- id: order.id, title: input.title, value: input.value,
385
- pipelineId: input.pipelineId, stageId: input.stageId,
386
- status: 'open', probability: 0, tags: input.tags ?? [],
387
- contactName: input.contactName,
388
- tenantId: tenantId!, createdAt: order.created_at, updatedAt: order.updated_at,
389
- } as Deal
390
- },
391
-
392
- async updateDeal(id: string, partial: Partial<Deal>): Promise<Deal> {
393
- const { core, pub } = getClients()
394
- if (partial.title || partial.value || partial.status) {
395
- const row: any = {}
396
- if (partial.title) row.notes = partial.title
397
- if (partial.value) row.total = partial.value
398
- if (partial.status) row.status = partial.status
399
- await core.from('orders').update(row).eq('id', id)
400
- }
401
- if (partial.stageId || partial.probability != null || partial.expectedCloseDate) {
402
- const row: any = {}
403
- if (partial.stageId) row.stage_id = partial.stageId
404
- if (partial.probability != null) row.probability = partial.probability
405
- if (partial.expectedCloseDate) row.expected_close_date = partial.expectedCloseDate
406
- await pub.from(T.dealExtensions).update(row).eq('order_id', id)
407
- }
408
- return (await provider.getDealById(id))!
409
- },
410
-
411
- async moveDealToStage(dealId: string, stageId: string): Promise<Deal> {
412
- const { core, pub } = getClients()
413
- const { data: stageRow } = await pub.from(T.pipelineStages).select('*').eq('id', stageId).single()
414
- await pub.from(T.dealExtensions).update({
415
- stage_id: stageId, probability: stageRow?.probability ?? 0,
416
- }).eq('order_id', dealId)
417
- if (stageRow?.is_won) await core.from('orders').update({ status: 'won' }).eq('id', dealId)
418
- if (stageRow?.is_lost) await core.from('orders').update({ status: 'lost' }).eq('id', dealId)
419
-
420
- // Cascade to lead + quotes
421
- if (stageRow) {
422
- const typedStage: import('../types').PipelineStage = {
423
- id: stageRow.id, pipelineId: stageRow.pipeline_id, name: stageRow.name,
424
- order: stageRow.order, color: stageRow.color, probability: stageRow.probability,
425
- isWon: stageRow.is_won, isLost: stageRow.is_lost,
426
- tenantId: stageRow.tenant_id, createdAt: stageRow.created_at,
427
- }
428
- // Update lead status
429
- const { data: ext } = await pub.from(T.dealExtensions).select('lead_id').eq('order_id', dealId).single()
430
- if (ext?.lead_id) {
431
- const newLeadStatus = deriveLeadStatus(typedStage)
432
- // MERGE, never replace. people.metadata is the lead's whole opaque
433
- // bag — formId, the public form's answers, utm. Writing a bare
434
- // { status } here silently destroyed all of it, so dragging a card to
435
- // another column erased the enquiry that created it. Same read-merge
436
- // pattern already used further down for personMeta/existingMeta.
437
- await mergePersonMetadata(ext.lead_id, { status: newLeadStatus })
438
- }
439
- // Update quote statuses
440
- const { data: quotes } = await core.from('orders').select('id, status').eq('kind', 'quote')
441
- for (const q of quotes ?? []) {
442
- const meta = (q as any).metadata
443
- if (meta?.dealId === dealId) {
444
- const newStatus = deriveQuoteStatus(typedStage, q.status)
445
- if (newStatus !== q.status) {
446
- await core.from('orders').update({ status: newStatus }).eq('id', q.id)
447
- }
448
- }
449
- }
450
- }
451
-
452
- const moved = (await provider.getDealById(dealId))!
453
- if (stageRow) {
454
- await logEvent({
455
- activityType: stageRow.is_won ? 'deal_won' : stageRow.is_lost ? 'deal_lost' : 'stage_changed',
456
- title: moved.title || 'Deal',
457
- description: stageRow.name,
458
- dealId,
459
- contactName: moved.contactName,
460
- })
461
- }
462
- return moved
463
- },
464
-
465
- async archiveDeal(dealId: string): Promise<void> {
466
- const { core } = getClients()
467
- const deal = await provider.getDealById(dealId)
468
- const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', dealId)
469
- if (error) throw new Error(error.message)
470
- await logEvent({
471
- activityType: 'deal_archived',
472
- title: deal?.title || 'Deal',
473
- dealId,
474
- contactName: deal?.contactName,
475
- })
476
- },
477
-
478
- async archiveLead(leadId: string): Promise<void> {
479
- const { core } = getClients()
480
- const lead = await provider.getLeadById(leadId)
481
- const { error } = await core.from('people').update({ is_active: false }).eq('id', leadId)
482
- if (error) throw new Error(error.message)
483
- // Its deal leaves the board too — an archived lead with a live card
484
- // would resurrect on the next drag.
485
- try {
486
- const deal = await provider.getDealByLeadId(leadId)
487
- if (deal && deal.status === 'open') await provider.archiveDeal(deal.id)
488
- } catch { /* non-blocking */ }
489
- await logEvent({
490
- activityType: 'lead_archived',
491
- title: lead?.name ?? 'Lead',
492
- leadId,
493
- contactName: lead?.name,
494
- })
495
- },
496
-
497
- // --- Activities (public.plg_crm_activities) ---
498
- async getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>> {
499
- const { pub } = getClients()
500
- let qb = pub.from(T.activities).select('*', { count: 'exact' })
501
- if (query.dealId) qb = qb.eq('deal_id', query.dealId)
502
- if (query.leadId) qb = qb.eq('lead_id', query.leadId)
503
- if (query.activityType) qb = qb.eq('activity_type', query.activityType)
504
- if (query.completed === true) qb = qb.not('completed_at', 'is', null)
505
- if (query.completed === false) qb = qb.is('completed_at', null)
506
- const page = query.page ?? 1
507
- const pageSize = query.pageSize ?? 50
508
- qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
509
- const { data, count } = await qb
510
- return { data: (data ?? []).map((r: any) => snakeToCamel(r) as unknown as Activity), total: count ?? 0 }
511
- },
512
-
513
- async createActivity(input: CreateActivityInput): Promise<Activity> {
514
- const { pub } = getClients()
515
- const tenantId = getTenantId()
516
- const { data, error } = await pub.from(T.activities).insert({
517
- tenant_id: tenantId, deal_id: input.dealId, lead_id: input.leadId,
518
- contact_id: input.contactId, activity_type: input.activityType,
519
- title: input.title, description: input.description,
520
- due_date: input.dueDate, assigned_to_id: input.assignedToId,
521
- }).select().single()
522
- if (error) throw new Error(error.message)
523
- return snakeToCamel(data) as unknown as Activity
524
- },
525
-
526
- async completeActivity(id: string): Promise<Activity> {
527
- const { pub } = getClients()
528
- const { data, error } = await pub.from(T.activities).update({ completed_at: new Date().toISOString() }).eq('id', id).select().single()
529
- if (error) throw new Error(error.message)
530
- return snakeToCamel(data) as unknown as Activity
531
- },
532
-
533
- async getActivityTypes(): Promise<ActivityTypeDef[]> {
534
- const { pub } = getClients()
535
- const tenantId = getTenantId()
536
- if (!tenantId) return []
537
- await ensureActivityTypes(tenantId)
538
- const { data } = await pub.from(T.activityTypes)
539
- .select('*').eq('tenant_id', tenantId).eq('is_active', true).order('name')
540
- return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as ActivityTypeDef)
541
- },
542
-
543
- async getTagDefs(): Promise<TagDef[]> {
544
- const { pub } = getClients()
545
- const tenantId = getTenantId()
546
- if (!tenantId) return []
547
- const { data } = await pub.from(T.tags)
548
- .select('*').eq('tenant_id', tenantId).eq('is_active', true).order('name')
549
- return (data ?? [])
550
- // Uma linha sem slug é de antes da 013 e não casa com registro nenhum;
551
- // deixá-la passar só produziria um chip que nunca aparece.
552
- .filter((r: any) => r.slug)
553
- .map((r: any) => snakeToCamel(r) as unknown as TagDef)
554
- },
555
-
556
- // --- Quotes (public.orders kind='quote' + order_items) ---
557
- async getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>> {
558
- const { core } = getClients()
559
- let qb = core.from('orders').select('*', { count: 'exact' }).eq('kind', 'quote')
560
- if (query.status) {
561
- const statuses = Array.isArray(query.status) ? query.status : [query.status]
562
- qb = qb.in('status', statuses)
563
- } else {
564
- qb = qb.neq('status', 'archived')
565
- }
566
- if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`)
567
- const page = query.page ?? 1
568
- const pageSize = query.pageSize ?? 50
569
- qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order('created_at', { ascending: false })
570
- const { data, count } = await qb
571
- const quotes: Quote[] = (data ?? []).map((r: any) => {
572
- // Show financial stage as status when quote has been promoted
573
- const stage = r.stage as string | undefined
574
- const financialStages = ['invoiced', 'paid', 'partial', 'overdue']
575
- const displayStatus = stage && financialStages.includes(stage) ? stage : (r.status ?? 'draft')
576
- return {
577
- id: r.id, quoteNumber: r.metadata?.quoteNumber ?? r.reference_number ?? '', quoteDate: r.created_at?.slice(0, 10) ?? '',
578
- validUntil: r.due_at?.slice(0, 10) ?? '', status: displayStatus,
579
- totalAmount: r.total ?? 0, contactId: r.party_id,
580
- contactName: r.metadata?.contactName, observations: r.notes,
581
- dealId: r.metadata?.dealId, leadId: r.metadata?.leadId, convertedInvoiceId: r.metadata?.convertedInvoiceId,
582
- items: [], tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
583
- } as Quote
584
- })
585
- return { data: quotes, total: count ?? 0 }
586
- },
587
-
588
- async getQuoteById(id: string): Promise<Quote | null> {
589
- const { core } = getClients()
590
- const { data: order } = await core.from('orders').select('*').eq('id', id).eq('kind', 'quote').maybeSingle()
591
- if (!order) return null
592
- const { data: items } = await core.from('order_items').select('*').eq('order_id', id).order('sort_order')
593
- const stage = order.stage as string | undefined
594
- const financialStages = ['invoiced', 'paid', 'partial', 'overdue']
595
- const displayStatus = stage && financialStages.includes(stage) ? stage : (order.status ?? 'draft')
596
- return {
597
- id: order.id, quoteNumber: order.metadata?.quoteNumber ?? order.reference_number ?? '', quoteDate: order.created_at?.slice(0, 10) ?? '',
598
- validUntil: order.due_at?.slice(0, 10) ?? '', status: displayStatus,
599
- totalAmount: order.total ?? 0, contactId: order.party_id,
600
- contactName: order.metadata?.contactName, observations: order.notes,
601
- dealId: order.metadata?.dealId, leadId: order.metadata?.leadId, convertedInvoiceId: order.metadata?.convertedInvoiceId,
602
- items: (items ?? []).map((i: any) => ({
603
- id: i.id, quoteId: id, itemKind: i.metadata?.itemKind ?? 'other',
604
- description: i.name ?? '', quantity: i.quantity ?? 1,
605
- unitPrice: i.unit_price ?? 0, discount: i.discount ?? 0,
606
- totalAmount: i.total ?? 0, createdAt: i.created_at,
607
- } as QuoteItem)),
608
- tenantId: order.tenant_id, createdAt: order.created_at, updatedAt: order.updated_at,
609
- } as Quote
610
- },
611
-
612
- async createQuote(input: CreateQuoteInput): Promise<Quote> {
613
- const { core } = getClients()
614
- const tenantId = getTenantId()
615
- const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0)
616
-
617
- // Derive next quote number from existing quotes
618
- const { count } = await core.from('orders').select('*', { count: 'exact', head: true }).eq('kind', 'quote')
619
- const nextNum = (count ?? 0) + 1
620
-
621
- const { data: order, error } = await core.from('orders').insert({
622
- tenant_id: tenantId, kind: 'quote', status: 'draft',
623
- reference_number: `Q-${String(nextNum).padStart(4, '0')}`,
624
- total: totalAmount, party_id: input.contactId,
625
- due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
626
- notes: input.observations, currency: 'BRL',
627
- metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId },
628
- }).select().single()
629
- if (error) throw new Error(error.message)
630
-
631
- if (input.items.length > 0) {
632
- const { error: itemsError } = await core.from('order_items').insert(
633
- input.items.map((item, i) => ({
634
- order_id: order.id, name: item.description,
635
- quantity: item.quantity, unit_price: item.unitPrice,
636
- discount: item.discount, total: item.totalAmount,
637
- sort_order: i, metadata: { itemKind: item.itemKind },
638
- }))
639
- )
640
- if (itemsError) throw new Error(itemsError.message)
641
- }
642
-
643
- // The deal card renders the DEAL's value — a quote without this sync
644
- // leaves R$ 0,00 on the board while the quote holds the real number.
645
- if (input.dealId && totalAmount > 0) {
646
- await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
647
- }
648
-
649
- await logEvent({
650
- activityType: 'quote_created',
651
- title: order.reference_number ?? 'Quote',
652
- description: input.contactName,
653
- dealId: input.dealId,
654
- leadId: input.leadId,
655
- contactId: input.contactId,
656
- contactName: input.contactName,
657
- })
658
-
659
- return {
660
- id: order.id, quoteNumber: order.reference_number,
661
- quoteDate: order.created_at?.slice(0, 10), validUntil: input.validUntil,
662
- status: 'draft', totalAmount, contactName: input.contactName,
663
- dealId: input.dealId, leadId: input.leadId,
664
- items: [], tenantId: tenantId!,
665
- createdAt: order.created_at, updatedAt: order.updated_at,
666
- } as unknown as Quote
667
- },
668
-
669
- async updateQuote(id: string, input: CreateQuoteInput): Promise<Quote> {
670
- const { core } = getClients()
671
- const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0)
672
-
673
- const { error } = await core.from('orders').update({
674
- total: totalAmount, party_id: input.contactId,
675
- due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
676
- notes: input.observations, metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId },
677
- }).eq('id', id)
678
- if (error) throw new Error(error.message)
679
-
680
- // Replace items: delete existing, insert new
681
- await core.from('order_items').delete().eq('order_id', id)
682
- if (input.items.length > 0) {
683
- const { error: itemsError } = await core.from('order_items').insert(
684
- input.items.map((item, i) => ({
685
- order_id: id, name: item.description,
686
- quantity: item.quantity, unit_price: item.unitPrice,
687
- discount: item.discount, total: item.totalAmount,
688
- sort_order: i, metadata: { itemKind: item.itemKind },
689
- }))
690
- )
691
- if (itemsError) throw new Error(itemsError.message)
692
- }
693
-
694
- if (input.dealId && totalAmount > 0) {
695
- await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
696
- }
697
-
698
- return (await provider.getQuoteById(id))!
699
- },
700
-
701
- async sendQuote(id: string): Promise<Quote> {
702
- const { core } = getClients()
703
- await core.from('orders').update({ status: 'sent' }).eq('id', id)
704
-
705
- // Move deal to Negotiation stage (only forward, never backward)
706
- try {
707
- const quote = await provider.getQuoteById(id)
708
- if (quote?.dealId) {
709
- const deal = await provider.getDealById(quote.dealId)
710
- if (deal) {
711
- const stages = await provider.getPipelineStages(deal.pipelineId)
712
- const negotiationStage = stages.find((s) => s.name === 'Negotiation')
713
- ?? stages.filter((s: any) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0]
714
- const currentStage = stages.find((s) => s.id === deal.stageId)
715
- if (negotiationStage && currentStage && negotiationStage.order > currentStage.order) {
716
- await provider.moveDealToStage(deal.id, negotiationStage.id)
717
- }
718
- }
719
- }
720
- } catch { /* non-blocking */ }
721
-
722
- const sent = (await provider.getQuoteById(id))!
723
- await logEvent({
724
- activityType: 'quote_sent',
725
- title: sent.quoteNumber ?? 'Quote',
726
- description: sent.contactName,
727
- dealId: sent.dealId,
728
- leadId: sent.leadId,
729
- contactName: sent.contactName,
730
- })
731
- return sent
732
- },
733
-
734
- async approveQuote(id: string): Promise<Quote> {
735
- const { core, pub } = getClients()
736
- const tenantId = getTenantId()
737
-
738
- const quote = await provider.getQuoteById(id)
739
- if (!quote) throw new Error('Quote not found')
740
-
741
- // 2-4. Atomic promotion (ref number + stage/direction + financial movement)
742
- // in one transaction via the shared DB function. Replaces the
743
- // multi-step write each plugin used to re-implement. Idempotent.
744
- const { error: promoteErr } = await pub.rpc('fn_invoice_from_order', {
745
- p_order_id: id,
746
- p_due_date: quote.validUntil ?? null,
747
- p_status: 'approved',
748
- })
749
- if (promoteErr) throw new Error(promoteErr.message)
750
-
751
- // 5. Cascade: move deal to Won stage
752
- if (quote.dealId) {
753
- try {
754
- const deal = await provider.getDealById(quote.dealId)
755
- if (deal) {
756
- const stages = await provider.getPipelineStages(deal.pipelineId)
757
- const wonStage = stages.find((s) => s.isWon)
758
- if (wonStage) await provider.moveDealToStage(deal.id, wonStage.id)
759
- }
760
- } catch { /* non-blocking */ }
761
- }
762
-
763
- // 6. Convert lead to client — use leadId or fall back to contactId (party_id)
764
- const personToConvert = quote.leadId ?? quote.contactId
765
- if (personToConvert) {
766
- const clientKind = options?.clientConversion?.archetypeKind ?? 'client'
767
- const { data: person } = await core.from('people')
768
- .select('kind, name, email, phone, tenant_id, metadata')
769
- .eq('id', personToConvert).single()
770
-
771
- // Only convert if they're actually a lead (not already a client/staff/etc.)
772
- const personKind = (person as any)?.kind as string | undefined
773
- if (person && (personKind === 'lead' || personKind === 'contact')) {
774
- const personMeta = (person as any)?.metadata ?? {}
775
- await core.from('people').update({
776
- kind: clientKind,
777
- metadata: { ...personMeta, convertedFromLead: true },
778
- }).eq('id', personToConvert)
779
-
780
- // Create extension table record
781
- if (options?.clientConversion) {
782
- const { extensionTable, fkColumn } = options.clientConversion
783
- await pub.from(extensionTable).upsert({
784
- [fkColumn]: personToConvert,
785
- tenant_id: (person as any).tenant_id,
786
- }, { onConflict: fkColumn })
787
- }
788
- }
789
- }
790
-
791
- const approved = (await provider.getQuoteById(id))!
792
- await logEvent({
793
- activityType: 'quote_approved',
794
- title: approved.quoteNumber ?? 'Quote',
795
- description: approved.contactName,
796
- dealId: approved.dealId,
797
- leadId: approved.leadId,
798
- contactName: approved.contactName,
799
- })
800
- return approved
801
- },
802
-
803
- async rejectQuote(id: string, reason: string): Promise<Quote> {
804
- const { core } = getClients()
805
- // Read existing metadata to merge
806
- const { data: existing } = await core.from('orders').select('metadata').eq('id', id).single()
807
- const existingMeta = (existing as any)?.metadata ?? {}
808
- const { error } = await core.from('orders').update({
809
- status: 'rejected',
810
- metadata: { ...existingMeta, rejectionReason: reason },
811
- }).eq('id', id)
812
- if (error) throw new Error(error.message)
813
- // Cascade: move deal to Lost stage
814
- const quote = await provider.getQuoteById(id)
815
- if (quote?.dealId) {
816
- const deal = await provider.getDealById(quote.dealId)
817
- if (deal) {
818
- const stages = await provider.getPipelineStages(deal.pipelineId)
819
- const lostStage = stages.find((s) => s.isLost)
820
- if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id)
821
- }
822
- }
823
- if (quote) {
824
- await logEvent({
825
- activityType: 'quote_rejected',
826
- title: quote.quoteNumber ?? 'Quote',
827
- description: reason,
828
- dealId: quote.dealId,
829
- leadId: quote.leadId,
830
- contactName: quote.contactName,
831
- })
832
- }
833
- return quote!
834
- },
835
-
836
- async expireQuote(id: string): Promise<Quote> {
837
- const { core } = getClients()
838
- await core.from('orders').update({ status: 'expired' }).eq('id', id)
839
- return (await provider.getQuoteById(id))!
840
- },
841
-
842
- async archiveQuote(id: string): Promise<void> {
843
- const { core } = getClients()
844
- const quote = await provider.getQuoteById(id)
845
- const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', id)
846
- if (error) throw new Error(error.message)
847
- await logEvent({
848
- activityType: 'quote_archived',
849
- title: quote?.quoteNumber ?? 'Quote',
850
- description: quote?.contactName,
851
- dealId: quote?.dealId,
852
- leadId: quote?.leadId,
853
- contactName: quote?.contactName,
854
- })
855
- },
856
-
857
- // Cross-entity lookups
858
- async getQuotesByDealId(dealId: string): Promise<Quote[]> {
859
- const { core } = getClients()
860
- const { data } = await core.from('orders').select('*').eq('kind', 'quote')
861
- return (data ?? [])
862
- .filter((r: any) => r.metadata?.dealId === dealId)
863
- .map((r: any) => ({
864
- id: r.id, quoteNumber: r.reference_number ?? '', quoteDate: r.created_at?.slice(0, 10) ?? '',
865
- validUntil: r.due_at?.slice(0, 10) ?? '', status: r.status ?? 'draft',
866
- totalAmount: r.total ?? 0, contactId: r.party_id,
867
- contactName: r.metadata?.contactName, dealId: r.metadata?.dealId, leadId: r.metadata?.leadId, convertedInvoiceId: r.metadata?.convertedInvoiceId,
868
- items: [], tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
869
- } as Quote))
870
- },
871
-
872
- async getDealByLeadId(leadId: string): Promise<Deal | null> {
873
- const { pub } = getClients()
874
- const { data } = await pub.from(T.dealExtensions).select('order_id').eq('lead_id', leadId).limit(1)
875
- if (!data || data.length === 0) return null
876
- return provider.getDealById(data[0].order_id)
877
- },
878
-
879
- // --- Summary ---
880
- async getSummary(): Promise<CrmSummary> {
881
- const { core, pub } = getClients()
882
- const monthStart = new Date().toISOString().slice(0, 7) + '-01'
883
- const today = new Date().toISOString().slice(0, 10)
884
-
885
- const { count: totalLeads } = await core.from('people').select('*', { count: 'exact', head: true }).eq('kind', 'lead')
886
- const { count: newLeads } = await core.from('people').select('*', { count: 'exact', head: true }).eq('kind', 'lead').gte('created_at', monthStart)
887
- const { data: deals } = await core.from('orders').select('status, total, updated_at').eq('kind', 'deal')
888
- const allDeals = deals ?? []
889
- const openDeals = allDeals.filter((d: any) => d.status === 'open')
890
- const wonDeals = allDeals.filter((d: any) => d.status === 'won')
891
- const wonThisMonth = wonDeals.filter((d: any) => d.updated_at >= monthStart)
892
- const convertedLeads = allDeals.length // each deal came from a lead conversion
893
-
894
- const { count: pendingActs } = await pub.from(T.activities).select('*', { count: 'exact', head: true }).is('completed_at', null)
895
- const { count: overdueActs } = await pub.from(T.activities).select('*', { count: 'exact', head: true }).is('completed_at', null).lt('due_date', today)
896
-
897
- return {
898
- totalLeads: totalLeads ?? 0,
899
- newLeadsThisMonth: newLeads ?? 0,
900
- totalDeals: allDeals.length,
901
- openDealsValue: openDeals.reduce((s: number, d: any) => s + (d.total ?? 0), 0),
902
- wonDealsThisMonth: wonThisMonth.length,
903
- wonDealsValueThisMonth: wonThisMonth.reduce((s: number, d: any) => s + (d.total ?? 0), 0),
904
- conversionRate: (totalLeads ?? 0) > 0 ? (convertedLeads / (totalLeads ?? 1)) * 100 : 0,
905
- averageDealValue: wonDeals.length > 0 ? wonDeals.reduce((s: number, d: any) => s + (d.total ?? 0), 0) / wonDeals.length : 0,
906
- pendingActivities: pendingActs ?? 0,
907
- overdueActivities: overdueActs ?? 0,
908
- }
909
- },
910
-
911
- async getFunnel(pipelineId: string): Promise<FunnelStage[]> {
912
- const { pub } = getClients()
913
- const stages = await provider.getPipelineStages(pipelineId)
914
- const deals = await provider.getDeals({ status: 'open' })
915
-
916
- return stages.filter((s: any) => !s.isLost).map((stage) => {
917
- const stageDeals = deals.data.filter((d: any) => d.stageId === stage.id)
918
- return {
919
- stageId: stage.id, stageName: stage.name, stageColor: stage.color,
920
- dealCount: stageDeals.length,
921
- totalValue: stageDeals.reduce((s, d) => s + d.value, 0),
922
- }
923
- })
924
- },
925
- }
926
-
927
- return provider
928
- }