@fayz-ai/plugin-crm 0.8.3 → 0.8.4

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 (63) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  3. package/dist/data/mock.d.ts +5 -0
  4. package/dist/data/mock.d.ts.map +1 -1
  5. package/dist/data/supabase.d.ts +6 -0
  6. package/dist/data/supabase.d.ts.map +1 -1
  7. package/dist/data/types.d.ts +9 -1
  8. package/dist/data/types.d.ts.map +1 -1
  9. package/dist/index.cjs +698 -103
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +701 -106
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/access.d.ts +8 -0
  15. package/dist/lib/access.d.ts.map +1 -0
  16. package/dist/locales/en.d.ts.map +1 -1
  17. package/dist/locales/pt-BR.d.ts.map +1 -1
  18. package/dist/migrations/index.d.ts +5 -1
  19. package/dist/migrations/index.d.ts.map +1 -1
  20. package/dist/public/index.cjs +1 -1
  21. package/dist/public/index.cjs.map +1 -1
  22. package/dist/public/index.js +2 -2
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/registries.d.ts +11 -0
  25. package/dist/registries.d.ts.map +1 -1
  26. package/dist/store.d.ts +5 -0
  27. package/dist/store.d.ts.map +1 -1
  28. package/dist/types.d.ts +14 -2
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/views/ActivityListView.d.ts +6 -1
  31. package/dist/views/ActivityListView.d.ts.map +1 -1
  32. package/dist/views/DealSidebar.d.ts.map +1 -1
  33. package/dist/views/LeadDetailView.d.ts.map +1 -1
  34. package/dist/views/PipelineView.d.ts.map +1 -1
  35. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  36. package/dist/views/QuoteListView.d.ts.map +1 -1
  37. package/package.json +5 -5
  38. package/src/CrmPage.tsx +1 -1
  39. package/src/cascade.ts +2 -0
  40. package/src/components/QuoteStatusDropdown.tsx +15 -3
  41. package/src/data/mock.ts +110 -4
  42. package/src/data/supabase.ts +186 -8
  43. package/src/data/types.ts +9 -1
  44. package/src/index.ts +85 -3
  45. package/src/lib/access.ts +11 -0
  46. package/src/locales/en.ts +4 -0
  47. package/src/locales/pt-BR.ts +9 -5
  48. package/src/migrations/003_crm_views_rls.sql +10 -2
  49. package/src/migrations/007_activity_log.sql +55 -0
  50. package/src/migrations/008_view_field_aliases.sql +43 -0
  51. package/src/migrations/009_deal_archived_status.sql +30 -0
  52. package/src/migrations/010_quote_archived_status.sql +40 -0
  53. package/src/migrations/index.ts +191 -3
  54. package/src/public/data.supabase.ts +2 -2
  55. package/src/registries.ts +32 -8
  56. package/src/store.ts +76 -0
  57. package/src/types.ts +19 -2
  58. package/src/views/ActivityListView.tsx +79 -11
  59. package/src/views/DealSidebar.tsx +39 -33
  60. package/src/views/LeadDetailView.tsx +29 -10
  61. package/src/views/PipelineView.tsx +22 -4
  62. package/src/views/QuoteDetailView.tsx +7 -3
  63. package/src/views/QuoteListView.tsx +26 -12
@@ -1,9 +1,9 @@
1
1
  import type { CrmDataProvider } from './types'
2
2
  import type {
3
- Pipeline, PipelineStage, Lead, Deal, Activity, Quote, QuoteItem,
3
+ Pipeline, PipelineStage, Lead, Deal, Activity, ActivityTypeDef, Quote, QuoteItem,
4
4
  CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
5
5
  LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
6
- PaginatedResult, CrmSummary, FunnelStage,
6
+ PaginatedResult, CrmSummary, FunnelStage, SystemActivityType,
7
7
  } from '../types'
8
8
  import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
9
9
  import { getCrmTenantId } from '../lib/tenant'
@@ -56,7 +56,51 @@ async function mergePersonMetadata(personId: string, patch: Record<string, unkno
56
56
 
57
57
  export function createSupabaseCrmProvider(options?: {
58
58
  clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
59
+ /** Manual interaction types lazily seeded per tenant (settings-editable rows). */
60
+ activityTypes?: Array<{ value: string; label: string; icon?: string }>
59
61
  }): CrmDataProvider {
62
+ // System timeline event — written silently at every CRM write point.
63
+ // completed_at is stamped so events never pollute the "pending" task filter,
64
+ // and a log failure must never break the write it describes.
65
+ async function logEvent(input: {
66
+ activityType: SystemActivityType
67
+ title: string
68
+ description?: string
69
+ leadId?: string
70
+ dealId?: string
71
+ contactId?: string
72
+ contactName?: string
73
+ }): Promise<void> {
74
+ try {
75
+ const { pub } = getClients()
76
+ await pub.from(T.activities).insert({
77
+ tenant_id: getTenantId(),
78
+ deal_id: input.dealId ?? null,
79
+ lead_id: input.leadId ?? null,
80
+ contact_id: input.contactId ?? null,
81
+ contact_name: input.contactName ?? null,
82
+ activity_type: input.activityType,
83
+ title: input.title,
84
+ description: input.description ?? null,
85
+ completed_at: new Date().toISOString(),
86
+ })
87
+ } catch { /* timeline is best-effort */ }
88
+ }
89
+
90
+ // Lazy per-tenant seed of manual interaction types (the type set comes from
91
+ // app config — SQL can't know the vertical). Idempotent via (tenant, name).
92
+ const typesSeeded = new Set<string>()
93
+ async function ensureActivityTypes(tenantId: string): Promise<void> {
94
+ const seed = options?.activityTypes
95
+ if (!seed?.length || typesSeeded.has(tenantId)) return
96
+ typesSeeded.add(tenantId)
97
+ const { pub } = getClients()
98
+ await pub.from(T.activityTypes).upsert(
99
+ seed.map((t) => ({ tenant_id: tenantId, name: t.label, icon: t.icon ?? null, is_active: true })),
100
+ { onConflict: 'tenant_id,name', ignoreDuplicates: true },
101
+ )
102
+ }
103
+
60
104
  const provider: CrmDataProvider = {
61
105
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
62
106
  async getPipelines(): Promise<Pipeline[]> {
@@ -74,7 +118,7 @@ export function createSupabaseCrmProvider(options?: {
74
118
  // --- Leads (via view — single query) ---
75
119
  async getLeads(query: LeadQuery): Promise<PaginatedResult<Lead>> {
76
120
  const { pub } = getClients()
77
- let qb = pub.from('v_leads').select('*', { count: 'exact' })
121
+ let qb = pub.from('v_leads').select('*', { count: 'exact' }).eq('is_active', true)
78
122
  if (query.search) qb = qb.ilike('name', `%${query.search}%`)
79
123
  if (query.status) {
80
124
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
@@ -130,6 +174,7 @@ export function createSupabaseCrmProvider(options?: {
130
174
  }).select().single()
131
175
  if (error) throw new Error(error.message)
132
176
  const p = snakeToCamel(data) as any
177
+ await logEvent({ activityType: 'lead_created', title: input.name, leadId: p.id, contactName: input.name })
133
178
  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
134
179
  },
135
180
 
@@ -150,9 +195,14 @@ export function createSupabaseCrmProvider(options?: {
150
195
  },
151
196
 
152
197
  async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
153
- const { core } = getClients()
154
198
  // Update lead status to converted
155
199
  await mergePersonMetadata(leadId, { status: 'converted' })
200
+ await logEvent({
201
+ activityType: 'lead_converted',
202
+ title: dealInput.contactName ?? dealInput.title,
203
+ leadId,
204
+ contactName: dealInput.contactName,
205
+ })
156
206
  return provider.createDeal({ ...dealInput, leadId } as any)
157
207
  },
158
208
 
@@ -163,6 +213,8 @@ export function createSupabaseCrmProvider(options?: {
163
213
  if (query.status) {
164
214
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
165
215
  qb = qb.in('status', statuses)
216
+ } else {
217
+ qb = qb.neq('status', 'archived')
166
218
  }
167
219
  if (query.search) qb = qb.ilike('title', `%${query.search}%`)
168
220
  if (query.pipelineId) qb = qb.eq('pipeline_id', query.pipelineId)
@@ -220,7 +272,7 @@ export function createSupabaseCrmProvider(options?: {
220
272
  const { pub } = getClients()
221
273
  const stages = await provider.getPipelineStages(pipelineId)
222
274
  // Single query via view — already has stage info joined
223
- const { data } = await pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).neq('status', 'lost')
275
+ const { data } = await pub.from('v_deals').select('*').eq('pipeline_id', pipelineId).not('status', 'in', '(lost,archived)')
224
276
  const deals = (data ?? []).map((r: any) => ({
225
277
  id: r.id, title: r.title ?? '', value: r.value ?? 0,
226
278
  pipelineId: r.pipeline_id, stageId: r.stage_id,
@@ -262,6 +314,15 @@ export function createSupabaseCrmProvider(options?: {
262
314
  lead_id: (input as any).leadId,
263
315
  })
264
316
 
317
+ await logEvent({
318
+ activityType: 'deal_created',
319
+ title: input.title,
320
+ dealId: order.id,
321
+ leadId: (input as any).leadId,
322
+ contactId: input.contactId,
323
+ contactName: input.contactName,
324
+ })
325
+
265
326
  return {
266
327
  id: order.id, title: input.title, value: input.value,
267
328
  pipelineId: input.pipelineId, stageId: input.stageId,
@@ -331,7 +392,49 @@ export function createSupabaseCrmProvider(options?: {
331
392
  }
332
393
  }
333
394
 
334
- return (await provider.getDealById(dealId))!
395
+ const moved = (await provider.getDealById(dealId))!
396
+ if (stageRow) {
397
+ await logEvent({
398
+ activityType: stageRow.is_won ? 'deal_won' : stageRow.is_lost ? 'deal_lost' : 'stage_changed',
399
+ title: moved.title || 'Deal',
400
+ description: stageRow.name,
401
+ dealId,
402
+ contactName: moved.contactName,
403
+ })
404
+ }
405
+ return moved
406
+ },
407
+
408
+ async archiveDeal(dealId: string): Promise<void> {
409
+ const { core } = getClients()
410
+ const deal = await provider.getDealById(dealId)
411
+ const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', dealId)
412
+ if (error) throw new Error(error.message)
413
+ await logEvent({
414
+ activityType: 'deal_archived',
415
+ title: deal?.title || 'Deal',
416
+ dealId,
417
+ contactName: deal?.contactName,
418
+ })
419
+ },
420
+
421
+ async archiveLead(leadId: string): Promise<void> {
422
+ const { core } = getClients()
423
+ const lead = await provider.getLeadById(leadId)
424
+ const { error } = await core.from('people').update({ is_active: false }).eq('id', leadId)
425
+ if (error) throw new Error(error.message)
426
+ // Its deal leaves the board too — an archived lead with a live card
427
+ // would resurrect on the next drag.
428
+ try {
429
+ const deal = await provider.getDealByLeadId(leadId)
430
+ if (deal && deal.status === 'open') await provider.archiveDeal(deal.id)
431
+ } catch { /* non-blocking */ }
432
+ await logEvent({
433
+ activityType: 'lead_archived',
434
+ title: lead?.name ?? 'Lead',
435
+ leadId,
436
+ contactName: lead?.name,
437
+ })
335
438
  },
336
439
 
337
440
  // --- Activities (public.plg_crm_activities) ---
@@ -370,6 +473,16 @@ export function createSupabaseCrmProvider(options?: {
370
473
  return snakeToCamel(data) as unknown as Activity
371
474
  },
372
475
 
476
+ async getActivityTypes(): Promise<ActivityTypeDef[]> {
477
+ const { pub } = getClients()
478
+ const tenantId = getTenantId()
479
+ if (!tenantId) return []
480
+ await ensureActivityTypes(tenantId)
481
+ const { data } = await pub.from(T.activityTypes)
482
+ .select('*').eq('tenant_id', tenantId).eq('is_active', true).order('name')
483
+ return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as ActivityTypeDef)
484
+ },
485
+
373
486
  // --- Quotes (public.orders kind='quote' + order_items) ---
374
487
  async getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>> {
375
488
  const { core } = getClients()
@@ -377,6 +490,8 @@ export function createSupabaseCrmProvider(options?: {
377
490
  if (query.status) {
378
491
  const statuses = Array.isArray(query.status) ? query.status : [query.status]
379
492
  qb = qb.in('status', statuses)
493
+ } else {
494
+ qb = qb.neq('status', 'archived')
380
495
  }
381
496
  if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`)
382
497
  const page = query.page ?? 1
@@ -455,6 +570,22 @@ export function createSupabaseCrmProvider(options?: {
455
570
  if (itemsError) throw new Error(itemsError.message)
456
571
  }
457
572
 
573
+ // The deal card renders the DEAL's value — a quote without this sync
574
+ // leaves R$ 0,00 on the board while the quote holds the real number.
575
+ if (input.dealId && totalAmount > 0) {
576
+ await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
577
+ }
578
+
579
+ await logEvent({
580
+ activityType: 'quote_created',
581
+ title: order.reference_number ?? 'Quote',
582
+ description: input.contactName,
583
+ dealId: input.dealId,
584
+ leadId: input.leadId,
585
+ contactId: input.contactId,
586
+ contactName: input.contactName,
587
+ })
588
+
458
589
  return {
459
590
  id: order.id, quoteNumber: order.reference_number,
460
591
  quoteDate: order.created_at?.slice(0, 10), validUntil: input.validUntil,
@@ -490,6 +621,10 @@ export function createSupabaseCrmProvider(options?: {
490
621
  if (itemsError) throw new Error(itemsError.message)
491
622
  }
492
623
 
624
+ if (input.dealId && totalAmount > 0) {
625
+ await core.from('orders').update({ total: totalAmount }).eq('id', input.dealId)
626
+ }
627
+
493
628
  return (await provider.getQuoteById(id))!
494
629
  },
495
630
 
@@ -514,7 +649,16 @@ export function createSupabaseCrmProvider(options?: {
514
649
  }
515
650
  } catch { /* non-blocking */ }
516
651
 
517
- return (await provider.getQuoteById(id))!
652
+ const sent = (await provider.getQuoteById(id))!
653
+ await logEvent({
654
+ activityType: 'quote_sent',
655
+ title: sent.quoteNumber ?? 'Quote',
656
+ description: sent.contactName,
657
+ dealId: sent.dealId,
658
+ leadId: sent.leadId,
659
+ contactName: sent.contactName,
660
+ })
661
+ return sent
518
662
  },
519
663
 
520
664
  async approveQuote(id: string): Promise<Quote> {
@@ -574,7 +718,16 @@ export function createSupabaseCrmProvider(options?: {
574
718
  }
575
719
  }
576
720
 
577
- return (await provider.getQuoteById(id))!
721
+ const approved = (await provider.getQuoteById(id))!
722
+ await logEvent({
723
+ activityType: 'quote_approved',
724
+ title: approved.quoteNumber ?? 'Quote',
725
+ description: approved.contactName,
726
+ dealId: approved.dealId,
727
+ leadId: approved.leadId,
728
+ contactName: approved.contactName,
729
+ })
730
+ return approved
578
731
  },
579
732
 
580
733
  async rejectQuote(id: string, reason: string): Promise<Quote> {
@@ -597,6 +750,16 @@ export function createSupabaseCrmProvider(options?: {
597
750
  if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id)
598
751
  }
599
752
  }
753
+ if (quote) {
754
+ await logEvent({
755
+ activityType: 'quote_rejected',
756
+ title: quote.quoteNumber ?? 'Quote',
757
+ description: reason,
758
+ dealId: quote.dealId,
759
+ leadId: quote.leadId,
760
+ contactName: quote.contactName,
761
+ })
762
+ }
600
763
  return quote!
601
764
  },
602
765
 
@@ -606,6 +769,21 @@ export function createSupabaseCrmProvider(options?: {
606
769
  return (await provider.getQuoteById(id))!
607
770
  },
608
771
 
772
+ async archiveQuote(id: string): Promise<void> {
773
+ const { core } = getClients()
774
+ const quote = await provider.getQuoteById(id)
775
+ const { error } = await core.from('orders').update({ status: 'archived' }).eq('id', id)
776
+ if (error) throw new Error(error.message)
777
+ await logEvent({
778
+ activityType: 'quote_archived',
779
+ title: quote?.quoteNumber ?? 'Quote',
780
+ description: quote?.contactName,
781
+ dealId: quote?.dealId,
782
+ leadId: quote?.leadId,
783
+ contactName: quote?.contactName,
784
+ })
785
+ },
786
+
609
787
  // Cross-entity lookups
610
788
  async getQuotesByDealId(dealId: string): Promise<Quote[]> {
611
789
  const { core } = getClients()
package/src/data/types.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type {
2
- Pipeline, PipelineStage, Lead, Deal, Activity, Quote,
2
+ Pipeline, PipelineStage, Lead, Deal, Activity, ActivityTypeDef, Quote,
3
3
  CreateLeadInput, CreateDealInput, CreateActivityInput, CreateQuoteInput,
4
4
  LeadQuery, DealQuery, ActivityQuery, QuoteQuery,
5
5
  PaginatedResult, CrmSummary, FunnelStage,
@@ -24,11 +24,19 @@ export interface CrmDataProvider {
24
24
  createDeal(input: CreateDealInput): Promise<Deal>
25
25
  updateDeal(id: string, data: Partial<Deal>): Promise<Deal>
26
26
  moveDealToStage(dealId: string, stageId: string): Promise<Deal>
27
+ /** Soft-remove from the board (status='archived') — never a hard delete. */
28
+ archiveDeal(dealId: string): Promise<void>
29
+ /** Soft-remove a lead (is_active=false) and archive its deal. */
30
+ archiveLead(leadId: string): Promise<void>
31
+ /** Soft-remove a quote (status='archived') — never a hard delete. */
32
+ archiveQuote(quoteId: string): Promise<void>
27
33
 
28
34
  // Activities
29
35
  getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>>
30
36
  createActivity(input: CreateActivityInput): Promise<Activity>
31
37
  completeActivity(id: string): Promise<Activity>
38
+ /** Tenant's manual interaction types (activity-types registry rows). */
39
+ getActivityTypes(): Promise<ActivityTypeDef[]>
32
40
 
33
41
  // Quotes
34
42
  getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>>
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@ import { createMockCrmProvider } from './data/mock'
9
9
  import { createSafeDataProvider, registerTranslations } from '@fayz-ai/core'
10
10
  import { createSupabaseCrmProvider } from './data/supabase'
11
11
  import { createCrmStore } from './store'
12
- import { crmRegistries } from './registries'
12
+ import { buildCrmRegistries, DEFAULT_ACTIVITY_TYPES } from './registries'
13
13
  import { crmLocales } from './locales'
14
14
  import { CrmGeneralSettings } from './components/CrmGeneralSettings'
15
15
 
@@ -119,9 +119,11 @@ function resolveConfig(options?: CrmPluginOptions): ResolvedCrmConfig {
119
119
  export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
120
120
  const config = resolveConfig(options)
121
121
  registerTranslations(crmLocales)
122
+ const activityTypes = options?.activityTypes ?? DEFAULT_ACTIVITY_TYPES
123
+ const crmRegistries = buildCrmRegistries(activityTypes)
122
124
  const provider = options?.dataProvider ?? createSafeDataProvider(
123
- () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
124
- () => createMockCrmProvider(),
125
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion, activityTypes }),
126
+ () => createMockCrmProvider({ activityTypes }),
125
127
  )
126
128
  const store = createCrmStore(provider)
127
129
 
@@ -157,6 +159,86 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
157
159
  { key: 'deals', label: 'Deals', table: 'orders', kindFilter: 'deal' },
158
160
  { key: 'quotes', label: 'Quotes', table: 'orders', kindFilter: 'quote' },
159
161
  ],
162
+ // Read-models for the agent's data primitives (searchRecords/queryData).
163
+ // Without these the assistant cannot see leads/deals/activities at all and
164
+ // guesses wrong entities ("quem tá aguardando contato?" → invented filter
165
+ // on Cliente). Keys are stable ASCII; fields are camelCase output shape.
166
+ queryEntities: [
167
+ {
168
+ key: 'crm:leads',
169
+ writable: false,
170
+ entity: {
171
+ name: 'Lead',
172
+ namePlural: 'Leads',
173
+ icon: 'UserPlus',
174
+ permission: { feature: 'crm.leads', action: 'read' as const },
175
+ fields: [
176
+ { key: 'name', label: 'Name', type: 'text' as const, searchable: true },
177
+ { key: 'email', label: 'Email', type: 'text' as const, searchable: true },
178
+ { key: 'phone', label: 'Phone', type: 'text' as const, searchable: true },
179
+ { key: 'company', label: 'Company', type: 'text' as const },
180
+ { key: 'status', label: 'Status (new=awaiting first contact, contacted, qualified, converted, lost)', type: 'text' as const },
181
+ { key: 'sourceName', label: 'Source', type: 'text' as const },
182
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
183
+ ],
184
+ data: {
185
+ table: 'v_leads',
186
+ tenantScoped: true,
187
+ searchColumns: ['name', 'email', 'phone'],
188
+ },
189
+ },
190
+ },
191
+ {
192
+ key: 'crm:deals',
193
+ writable: false,
194
+ entity: {
195
+ name: 'Deal',
196
+ namePlural: 'Deals',
197
+ icon: 'Target',
198
+ permission: { feature: 'crm.pipeline', action: 'read' as const },
199
+ fields: [
200
+ { key: 'title', label: 'Title', type: 'text' as const, searchable: true },
201
+ { key: 'value', label: 'Value', type: 'number' as const },
202
+ { key: 'status', label: 'Status (open/won/lost)', type: 'text' as const },
203
+ { key: 'stage', label: 'Pipeline stage name', type: 'text' as const },
204
+ { key: 'contactName', label: 'Contact', type: 'text' as const, searchable: true },
205
+ { key: 'probability', label: 'Probability %', type: 'number' as const },
206
+ { key: 'expectedCloseDate', label: 'Expected close', type: 'text' as const },
207
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
208
+ ],
209
+ data: {
210
+ table: 'v_deals',
211
+ tenantScoped: true,
212
+ searchColumns: ['title', 'contact_name'],
213
+ },
214
+ },
215
+ },
216
+ {
217
+ key: 'crm:activities',
218
+ writable: false,
219
+ entity: {
220
+ name: 'CRM activity',
221
+ namePlural: 'CRM activities',
222
+ icon: 'MessageCircle',
223
+ permission: { feature: 'sales', action: 'read' as const },
224
+ fields: [
225
+ { key: 'activityType', label: 'Type (call/email/note… or system events: lead_created, deal_won, quote_approved…)', type: 'text' as const },
226
+ { key: 'title', label: 'Title', type: 'text' as const, searchable: true },
227
+ { key: 'description', label: 'Description', type: 'text' as const, searchable: true },
228
+ { key: 'contactName', label: 'Contact', type: 'text' as const, searchable: true },
229
+ { key: 'dueDate', label: 'Due date', type: 'text' as const },
230
+ { key: 'completedAt', label: 'Completed at', type: 'text' as const },
231
+ { key: 'assignedToName', label: 'Assigned to', type: 'text' as const },
232
+ { key: 'createdAt', label: 'Created at', type: 'text' as const },
233
+ ],
234
+ data: {
235
+ table: 'plg_crm_activities',
236
+ tenantScoped: true,
237
+ searchColumns: ['title', 'contact_name', 'description'],
238
+ },
239
+ },
240
+ },
241
+ ],
160
242
  navigation: [
161
243
  {
162
244
  section: options?.navSection ?? 'main',
@@ -0,0 +1,11 @@
1
+ import { useAccessOptional } from '@fayz-ai/saas'
2
+
3
+ /**
4
+ * Single resolver for "can this user archive CRM records?" (deals, leads).
5
+ * One feature/action pair resolved in ONE place — call sites render or hide
6
+ * the affordance off this boolean and never repeat the check. Degrades to
7
+ * allow under a bare host shell (useAccessOptional's contract).
8
+ */
9
+ export function useCanArchive(): boolean {
10
+ return useAccessOptional().can('sales', 'delete').allowed
11
+ }
package/src/locales/en.ts CHANGED
@@ -10,6 +10,7 @@ export const en: Record<string, string> = {
10
10
  "crm.activities.overdueLabel": "Overdue",
11
11
  "crm.activities.pending": "pending",
12
12
  "crm.activities.pendingFilter": "Pending",
13
+ "crm.activities.systemEvents": "Events",
13
14
  "crm.activities.title": "Activities",
14
15
  "crm.dashboard.activeDeals": "{{count}} active deals",
15
16
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -56,6 +57,7 @@ export const en: Record<string, string> = {
56
57
  "crm.dealSidebar.value": "Value",
57
58
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
58
59
  "crm.leadDetail.assignedTo": "Assigned to",
60
+ "crm.leadDetail.archive": "Archive",
59
61
  "crm.leadDetail.backToList": "Back to list",
60
62
  "crm.leadDetail.formAnswers": "Form answers",
61
63
  "crm.leadDetail.company": "Company",
@@ -115,6 +117,7 @@ export const en: Record<string, string> = {
115
117
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
116
118
  "crm.page.settingsTitle": "Sales & CRM Settings",
117
119
  "crm.pipeline.dropHere": "Drop here",
120
+ "crm.pipeline.archive": "Archive",
118
121
  "crm.pipeline.moveFailed": "Failed to move deal",
119
122
  "crm.pipeline.movedTo": "Moved to {{stage}}",
120
123
  "crm.pipeline.noDeals": "No deals",
@@ -193,6 +196,7 @@ export const en: Record<string, string> = {
193
196
  "crm.quoteForm.unitPrice": "Unit Price",
194
197
  "crm.quoteForm.validUntil": "Valid Until",
195
198
  "crm.quotes.amount": "Amount",
199
+ "crm.quotes.archive": "Archive",
196
200
  "crm.quotes.contact": "Contact",
197
201
  "crm.quotes.createFirst": "Create your first quote",
198
202
  "crm.quotes.date": "Date",
@@ -10,6 +10,7 @@ export const ptBR: Record<string, string> = {
10
10
  "crm.activities.overdueLabel": "Atrasada",
11
11
  "crm.activities.pending": "pendente",
12
12
  "crm.activities.pendingFilter": "Pendentes",
13
+ "crm.activities.systemEvents": "Eventos",
13
14
  "crm.activities.title": "Atividades",
14
15
  "crm.dashboard.activeDeals": "{{count}} negócios ativos",
15
16
  "crm.dashboard.avgDealValue": "Valor médio do negócio",
@@ -56,6 +57,7 @@ export const ptBR: Record<string, string> = {
56
57
  "crm.dealSidebar.value": "Valor",
57
58
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
58
59
  "crm.leadDetail.assignedTo": "Atribuído a",
60
+ "crm.leadDetail.archive": "Arquivar",
59
61
  "crm.leadDetail.backToList": "Voltar à lista",
60
62
  "crm.leadDetail.formAnswers": "Dados do formulário",
61
63
  "crm.leadDetail.company": "Empresa",
@@ -111,10 +113,11 @@ export const ptBR: Record<string, string> = {
111
113
  "crm.page.newLead": "Novo Lead",
112
114
  "crm.page.newLeadDesc": "Capturar um novo lead",
113
115
  "crm.page.newQuote": "Novo Orçamento",
114
- "crm.page.newQuoteDesc": "Enviar uma proposta",
116
+ "crm.page.newQuoteDesc": "Enviar um orçamento",
115
117
  "crm.page.settingsSubtitle": "Configure pipeline, gestão de leads e cadastros",
116
118
  "crm.page.settingsTitle": "Configurações de Vendas e CRM",
117
119
  "crm.pipeline.dropHere": "Solte aqui",
120
+ "crm.pipeline.archive": "Arquivar",
118
121
  "crm.pipeline.moveFailed": "Falha ao mover negócio",
119
122
  "crm.pipeline.movedTo": "Movido para {{stage}}",
120
123
  "crm.pipeline.noDeals": "Nenhum negócio",
@@ -160,12 +163,12 @@ export const ptBR: Record<string, string> = {
160
163
  "crm.quoteForm.description": "Descrição",
161
164
  "crm.quoteForm.discount": "Desconto",
162
165
  "crm.quoteForm.done": "Concluído",
163
- "crm.quoteForm.editSubtitle": "Atualizar esta proposta",
166
+ "crm.quoteForm.editSubtitle": "Atualizar este orçamento",
164
167
  "crm.quoteForm.editTitle": "Editar Orçamento",
165
168
  "crm.quoteForm.itemCount": "{{count}} itens",
166
169
  "crm.quoteForm.itemDescriptionPlaceholder": "Descrição do item",
167
170
  "crm.quoteForm.loading": "Carregando...",
168
- "crm.quoteForm.newSubtitle": "Criar uma proposta para seu cliente",
171
+ "crm.quoteForm.newSubtitle": "Criar um orçamento para seu cliente",
169
172
  "crm.quoteForm.newTitle": "Novo Orçamento",
170
173
  "crm.quoteForm.noDescription": "Sem descrição",
171
174
  "crm.quoteForm.noItems": "Nenhum item adicionado",
@@ -193,6 +196,7 @@ export const ptBR: Record<string, string> = {
193
196
  "crm.quoteForm.unitPrice": "Preço Unitário",
194
197
  "crm.quoteForm.validUntil": "Válido Até",
195
198
  "crm.quotes.amount": "Valor",
199
+ "crm.quotes.archive": "Arquivar",
196
200
  "crm.quotes.contact": "Contato",
197
201
  "crm.quotes.createFirst": "Crie seu primeiro orçamento",
198
202
  "crm.quotes.date": "Data",
@@ -206,7 +210,7 @@ export const ptBR: Record<string, string> = {
206
210
  "crm.quickActions.newDeal": "Novo Negócio",
207
211
  "crm.quickActions.newDealDesc": "Criar um negócio no pipeline",
208
212
  "crm.quickActions.newQuote": "Novo Orçamento",
209
- "crm.quickActions.newQuoteDesc": "Enviar uma proposta",
213
+ "crm.quickActions.newQuoteDesc": "Enviar um orçamento",
210
214
  "crm.quickActions.logActivity": "Registrar Atividade",
211
215
  "crm.quickActions.logActivityDesc": "Registrar ligação, e-mail ou nota",
212
216
  "crm.settingsPage.title": "Configurações de Vendas e CRM",
@@ -243,7 +247,7 @@ export const ptBR: Record<string, string> = {
243
247
  "crm.settings.weightedPipeline": "Valor ponderado do pipeline",
244
248
  "crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do estágio",
245
249
  "crm.settings.quotes": "Orçamentos",
246
- "crm.settings.quotesDesc": "Comportamento de orçamentos e propostas",
250
+ "crm.settings.quotesDesc": "Comportamento de orçamentos",
247
251
  "crm.settings.autoNumberQuotes": "Numeração automática de orçamentos",
248
252
  "crm.settings.autoNumberQuotesDesc": "Gerar automaticamente números sequenciais de orçamentos",
249
253
  "crm.settings.defaultValidity": "Validade padrão (30 dias)",
@@ -29,7 +29,12 @@ BEGIN
29
29
  END $$;
30
30
 
31
31
  -- v_leads: public.people (kind='lead')
32
- CREATE OR REPLACE VIEW public.v_leads WITH (security_invoker=true) AS
32
+ -- DROP first: 005 widens this view (form_id/custom_fields/utm), and CREATE OR
33
+ -- REPLACE cannot narrow a live view — replaying 003 on a pool that already ran
34
+ -- 005 would fail with "cannot drop columns from view". 005 replays right after
35
+ -- and widens it again, so the net result is unchanged.
36
+ DROP VIEW IF EXISTS public.v_leads;
37
+ CREATE VIEW public.v_leads WITH (security_invoker=true) AS
33
38
  SELECT
34
39
  p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
35
40
  p.metadata->>'company' AS company,
@@ -44,7 +49,10 @@ WHERE p.kind = 'lead';
44
49
  GRANT SELECT ON public.v_leads TO authenticated;
45
50
 
46
51
  -- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages
47
- CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS
52
+ -- DROP first for the same reason as v_leads above: 008 appends the `stage`
53
+ -- alias, and CREATE OR REPLACE cannot narrow a live view on replay.
54
+ DROP VIEW IF EXISTS public.v_deals;
55
+ CREATE VIEW public.v_deals WITH (security_invoker=true) AS
48
56
  SELECT
49
57
  o.id, o.tenant_id, o.status,
50
58
  o.total AS value, o.notes AS title,
@@ -0,0 +1,55 @@
1
+ -- CRM plugin — activity log foundation.
2
+ -- Activity types become tenant-editable (icon column) and upsertable by the
3
+ -- provider's lazy per-tenant seed (unique tenant+name). System timeline events
4
+ -- (lead_created, stage_changed, quote_*…) are written by the data provider
5
+ -- into plg_crm_activities with completed_at = now(); they are product-defined
6
+ -- and do NOT live in the types catalog.
7
+ -- Idempotent / replay-safe.
8
+
9
+ ALTER TABLE public.plg_crm_activity_types ADD COLUMN IF NOT EXISTS icon text;
10
+
11
+ -- Guarded: a pre-existing pool could hold duplicate names; skip rather than fail.
12
+ DO $$
13
+ BEGIN
14
+ CREATE UNIQUE INDEX IF NOT EXISTS uq_plg_crm_activity_types_tenant_name
15
+ ON public.plg_crm_activity_types(tenant_id, name);
16
+ EXCEPTION WHEN OTHERS THEN
17
+ RAISE NOTICE 'skipping uq_plg_crm_activity_types_tenant_name: %', SQLERRM;
18
+ END $$;
19
+
20
+ -- Backfill: records created BEFORE auto-logging existed get their timeline
21
+ -- events retroactively (stamped at the record's created_at), so the Activities
22
+ -- view isn't empty on day one. Idempotent via NOT EXISTS per record+type.
23
+ INSERT INTO public.plg_crm_activities
24
+ (tenant_id, lead_id, contact_name, activity_type, title, completed_at, created_at)
25
+ SELECT p.tenant_id, p.id, p.name, 'lead_created', p.name, p.created_at, p.created_at
26
+ FROM public.people p
27
+ WHERE p.kind = 'lead'
28
+ AND NOT EXISTS (
29
+ SELECT 1 FROM public.plg_crm_activities a
30
+ WHERE a.lead_id = p.id AND a.activity_type = 'lead_created'
31
+ );
32
+
33
+ INSERT INTO public.plg_crm_activities
34
+ (tenant_id, deal_id, contact_name, activity_type, title, completed_at, created_at)
35
+ SELECT o.tenant_id, o.id, o.metadata->>'contactName', 'deal_created',
36
+ COALESCE(NULLIF(o.notes, ''), 'Deal'), o.created_at, o.created_at
37
+ FROM public.orders o
38
+ WHERE o.kind = 'deal'
39
+ AND NOT EXISTS (
40
+ SELECT 1 FROM public.plg_crm_activities a
41
+ WHERE a.deal_id = o.id AND a.activity_type = 'deal_created'
42
+ );
43
+
44
+ INSERT INTO public.plg_crm_activities
45
+ (tenant_id, contact_name, activity_type, title, description, completed_at, created_at)
46
+ SELECT o.tenant_id, o.metadata->>'contactName', 'quote_created',
47
+ COALESCE(o.reference_number, 'Quote'), o.metadata->>'contactName',
48
+ o.created_at, o.created_at
49
+ FROM public.orders o
50
+ WHERE o.kind = 'quote'
51
+ AND NOT EXISTS (
52
+ SELECT 1 FROM public.plg_crm_activities a
53
+ WHERE a.activity_type = 'quote_created' AND a.title = COALESCE(o.reference_number, 'Quote')
54
+ AND a.tenant_id = o.tenant_id
55
+ );