@fayz-ai/plugin-crm 0.3.0 → 0.8.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 (76) hide show
  1. package/README.md +2 -0
  2. package/dist/components/CrmGeneralSettings.d.ts.map +1 -1
  3. package/dist/data/supabase.d.ts.map +1 -1
  4. package/dist/data/tables.d.ts +10 -0
  5. package/dist/data/tables.d.ts.map +1 -0
  6. package/dist/index.cjs +209 -60
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.d.ts +3 -3
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +210 -61
  11. package/dist/index.js.map +1 -1
  12. package/dist/lib/form-answers.d.ts +10 -0
  13. package/dist/lib/form-answers.d.ts.map +1 -0
  14. package/dist/locales/en.d.ts.map +1 -1
  15. package/dist/locales/pt-BR.d.ts.map +1 -1
  16. package/dist/migrations/index.d.ts +12 -0
  17. package/dist/migrations/index.d.ts.map +1 -0
  18. package/dist/public/context.d.ts +23 -0
  19. package/dist/public/context.d.ts.map +1 -0
  20. package/dist/public/createPublicFormsPlugin.d.ts +38 -0
  21. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -0
  22. package/dist/public/data.supabase.d.ts +7 -0
  23. package/dist/public/data.supabase.d.ts.map +1 -0
  24. package/dist/public/inbox.d.ts +22 -0
  25. package/dist/public/inbox.d.ts.map +1 -0
  26. package/dist/public/index.cjs +306 -0
  27. package/dist/public/index.cjs.map +1 -0
  28. package/dist/public/index.d.ts +10 -0
  29. package/dist/public/index.d.ts.map +1 -0
  30. package/dist/public/index.js +298 -0
  31. package/dist/public/index.js.map +1 -0
  32. package/dist/public/types.d.ts +92 -0
  33. package/dist/public/types.d.ts.map +1 -0
  34. package/dist/registries.d.ts.map +1 -1
  35. package/dist/schema/index.d.ts +65 -65
  36. package/dist/schema/index.d.ts.map +1 -1
  37. package/dist/schema.cjs +23 -23
  38. package/dist/schema.cjs.map +1 -1
  39. package/dist/schema.js +24 -24
  40. package/dist/schema.js.map +1 -1
  41. package/dist/views/DealSidebar.d.ts.map +1 -1
  42. package/dist/views/LeadDetailView.d.ts.map +1 -1
  43. package/dist/views/LeadFormView.d.ts.map +1 -1
  44. package/dist/views/LeadListView.d.ts.map +1 -1
  45. package/dist/views/PipelineView.d.ts.map +1 -1
  46. package/dist/views/QuoteFormView.d.ts.map +1 -1
  47. package/package.json +17 -5
  48. package/src/components/CrmGeneralSettings.tsx +35 -15
  49. package/src/data/supabase.ts +74 -28
  50. package/src/data/tables.ts +11 -0
  51. package/src/index.ts +15 -3
  52. package/src/lib/form-answers.tsx +39 -0
  53. package/src/locales/en.ts +1 -0
  54. package/src/locales/pt-BR.ts +1 -0
  55. package/src/migrations/000_plg_rename.sql +28 -0
  56. package/src/migrations/001_crm_base.sql +32 -32
  57. package/src/migrations/002_activities.sql +14 -14
  58. package/src/migrations/003_crm_views_rls.sql +8 -8
  59. package/src/migrations/004_seed_default_pipeline.sql +5 -5
  60. package/src/migrations/005_public_lead.sql +189 -0
  61. package/src/migrations/006_lead_enters_pipeline.sql +265 -0
  62. package/src/migrations/index.ts +707 -0
  63. package/src/public/context.tsx +69 -0
  64. package/src/public/createPublicFormsPlugin.ts +188 -0
  65. package/src/public/data.supabase.ts +86 -0
  66. package/src/public/inbox.ts +136 -0
  67. package/src/public/index.ts +30 -0
  68. package/src/public/types.ts +113 -0
  69. package/src/registries.ts +6 -5
  70. package/src/schema/index.ts +25 -25
  71. package/src/views/DealSidebar.tsx +31 -0
  72. package/src/views/LeadDetailView.tsx +53 -0
  73. package/src/views/LeadFormView.tsx +10 -0
  74. package/src/views/LeadListView.tsx +19 -0
  75. package/src/views/PipelineView.tsx +34 -1
  76. package/src/views/QuoteFormView.tsx +5 -0
@@ -8,11 +8,12 @@ import type {
8
8
  import { getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core'
9
9
  import { getCrmTenantId } from '../lib/tenant'
10
10
  import { deriveLeadStatus, deriveQuoteStatus } from '../cascade'
11
+ import { T } from './tables'
11
12
 
12
13
  function getTenantId(): string | undefined {
13
14
  // Plugin-local override wins; otherwise use the app's active tenant (set on
14
15
  // 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
+ // fail the people/orders RLS WITH CHECK (tenant_id IN user_tenant_ids()).
16
17
  return getCrmTenantId() ?? getActiveTenantId()
17
18
  }
18
19
 
@@ -27,23 +28,46 @@ function snakeToCamel(obj: Record<string, unknown>): Record<string, unknown> {
27
28
  function getClients() {
28
29
  const supabase = getSupabaseClientOptional() as any
29
30
  if (!supabase) throw new Error('Supabase not initialized')
30
- return { core: supabase.schema('saas_core'), pub: supabase }
31
+ // Core tables now live in public alongside the plugin tables — a single public
32
+ // client serves both core (people/orders) and plugin (plg_crm_*) tables.
33
+ return { core: supabase, pub: supabase }
34
+ }
35
+
36
+ /**
37
+ * Patch keys into people.metadata, preserving everything already there.
38
+ *
39
+ * people.metadata is a single opaque bag holding unrelated things: the lead's
40
+ * pipeline `status`, plus `formId`/`fields`/`utm` — the public form's answers,
41
+ * which are the entire content of a lead that arrived from a landing page.
42
+ * A plain `.update({ metadata: {...} })` REPLACES the column, so any code that
43
+ * only meant to set the status was deleting the enquiry. Two call sites did
44
+ * exactly that.
45
+ *
46
+ * Read-merge-write rather than a `jsonb ||` RPC: it matches the pattern already
47
+ * used elsewhere in this file, and these writes are single-operator actions
48
+ * (dragging one card), not concurrent ones.
49
+ */
50
+ async function mergePersonMetadata(personId: string, patch: Record<string, unknown>): Promise<void> {
51
+ const { core } = getClients()
52
+ const { data: row } = await core.from('people').select('metadata').eq('id', personId).maybeSingle()
53
+ const current = (row?.metadata ?? {}) as Record<string, unknown>
54
+ await core.from('people').update({ metadata: { ...current, ...patch } }).eq('id', personId)
31
55
  }
32
56
 
33
57
  export function createSupabaseCrmProvider(options?: {
34
58
  clientConversion?: { archetypeKind: string; extensionTable: string; fkColumn: string }
35
59
  }): CrmDataProvider {
36
60
  const provider: CrmDataProvider = {
37
- // --- Pipelines (public.pipelines + pipeline_stages) ---
61
+ // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
38
62
  async getPipelines(): Promise<Pipeline[]> {
39
63
  const { pub } = getClients()
40
- const { data } = await pub.from('pipelines').select('*').eq('is_active', true).order('name')
64
+ const { data } = await pub.from(T.pipelines).select('*').eq('is_active', true).order('name')
41
65
  return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as Pipeline)
42
66
  },
43
67
 
44
68
  async getPipelineStages(pipelineId: string): Promise<PipelineStage[]> {
45
69
  const { pub } = getClients()
46
- const { data } = await pub.from('pipeline_stages').select('*').eq('pipeline_id', pipelineId).order('order')
70
+ const { data } = await pub.from(T.pipelineStages).select('*').eq('pipeline_id', pipelineId).order('order')
47
71
  return (data ?? []).map((r: any) => snakeToCamel(r) as unknown as PipelineStage)
48
72
  },
49
73
 
@@ -82,7 +106,15 @@ export function createSupabaseCrmProvider(options?: {
82
106
  return {
83
107
  id: r.id, name: r.name, email: r.email, phone: r.phone,
84
108
  company: r.company, status: r.lead_status ?? 'new',
109
+ sourceName: r.source_name,
85
110
  tags: r.tags ?? [], notes: r.notes,
111
+ // Answers from a public form. Kept as an opaque bag so a new landing
112
+ // page needs no schema change; the detail view renders whatever is here.
113
+ metadata: {
114
+ formId: r.form_id ?? undefined,
115
+ fields: r.custom_fields ?? {},
116
+ utm: r.utm ?? {},
117
+ },
86
118
  tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
87
119
  } as Lead
88
120
  },
@@ -90,7 +122,7 @@ export function createSupabaseCrmProvider(options?: {
90
122
  async createLead(input: CreateLeadInput): Promise<Lead> {
91
123
  const { core } = getClients()
92
124
  const tenantId = getTenantId()
93
- const { data, error } = await core.from('persons').insert({
125
+ const { data, error } = await core.from('people').insert({
94
126
  tenant_id: tenantId, kind: 'lead', name: input.name,
95
127
  email: input.email, phone: input.phone,
96
128
  notes: input.notes, tags: input.tags ?? [], is_active: true,
@@ -108,16 +140,19 @@ export function createSupabaseCrmProvider(options?: {
108
140
  if (partial.email !== undefined) row.email = partial.email
109
141
  if (partial.phone !== undefined) row.phone = partial.phone
110
142
  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()
143
+ const { error } = await core.from('people').update(row).eq('id', id).select().single()
113
144
  if (error) throw new Error(error.message)
145
+ // The third call site that replaced the bag. Editing a lead's status from
146
+ // the list wiped formId/fields/utm exactly as dragging its card did — the
147
+ // same fix, applied here too rather than left for the next reader to find.
148
+ if (partial.status) await mergePersonMetadata(id, { status: partial.status })
114
149
  return (await provider.getLeadById(id))!
115
150
  },
116
151
 
117
152
  async convertLeadToDeal(leadId: string, dealInput: CreateDealInput): Promise<Deal> {
118
153
  const { core } = getClients()
119
154
  // Update lead status to converted
120
- await core.from('persons').update({ metadata: { status: 'converted' } }).eq('id', leadId)
155
+ await mergePersonMetadata(leadId, { status: 'converted' })
121
156
  return provider.createDeal({ ...dealInput, leadId } as any)
122
157
  },
123
158
 
@@ -172,6 +207,11 @@ export function createSupabaseCrmProvider(options?: {
172
207
  stageName: r.stage_name, stageColor: r.stage_color,
173
208
  probability: r.probability ?? 0, status: r.status ?? 'open',
174
209
  contactName: r.contact_name, tags: r.tags ?? [],
210
+ // v_deals exposes de.lead_id and Deal declares leadId, but the mapping
211
+ // dropped it — so DealSidebar's `if (d?.leadId)` never fired and the
212
+ // card opened blank: no contact, no form answers. For a card that came
213
+ // from a form, the lead IS the content.
214
+ leadId: r.lead_id ?? undefined,
175
215
  tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
176
216
  } as Deal
177
217
  },
@@ -187,6 +227,7 @@ export function createSupabaseCrmProvider(options?: {
187
227
  stageName: r.stage_name, stageColor: r.stage_color,
188
228
  probability: r.probability ?? 0, status: r.status ?? 'open',
189
229
  contactName: r.contact_name, tags: r.tags ?? [],
230
+ leadId: r.lead_id ?? undefined,
190
231
  tenantId: r.tenant_id, createdAt: r.created_at, updatedAt: r.updated_at,
191
232
  } as Deal))
192
233
 
@@ -203,7 +244,7 @@ export function createSupabaseCrmProvider(options?: {
203
244
  const { core, pub } = getClients()
204
245
  const tenantId = getTenantId()
205
246
 
206
- // Create order in saas_core
247
+ // Create order in public.orders
207
248
  const { data: order, error } = await core.from('orders').insert({
208
249
  tenant_id: tenantId, kind: 'deal', status: 'open',
209
250
  total: input.value, party_id: input.contactId,
@@ -214,7 +255,7 @@ export function createSupabaseCrmProvider(options?: {
214
255
  if (error) throw new Error(error.message)
215
256
 
216
257
  // Create deal extension with pipeline/stage info
217
- await pub.from('deal_extensions').insert({
258
+ await pub.from(T.dealExtensions).insert({
218
259
  order_id: order.id, tenant_id: tenantId,
219
260
  pipeline_id: input.pipelineId, stage_id: input.stageId,
220
261
  probability: 0, expected_close_date: input.expectedCloseDate,
@@ -244,15 +285,15 @@ export function createSupabaseCrmProvider(options?: {
244
285
  if (partial.stageId) row.stage_id = partial.stageId
245
286
  if (partial.probability != null) row.probability = partial.probability
246
287
  if (partial.expectedCloseDate) row.expected_close_date = partial.expectedCloseDate
247
- await pub.from('deal_extensions').update(row).eq('order_id', id)
288
+ await pub.from(T.dealExtensions).update(row).eq('order_id', id)
248
289
  }
249
290
  return (await provider.getDealById(id))!
250
291
  },
251
292
 
252
293
  async moveDealToStage(dealId: string, stageId: string): Promise<Deal> {
253
294
  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({
295
+ const { data: stageRow } = await pub.from(T.pipelineStages).select('*').eq('id', stageId).single()
296
+ await pub.from(T.dealExtensions).update({
256
297
  stage_id: stageId, probability: stageRow?.probability ?? 0,
257
298
  }).eq('order_id', dealId)
258
299
  if (stageRow?.is_won) await core.from('orders').update({ status: 'won' }).eq('id', dealId)
@@ -267,10 +308,15 @@ export function createSupabaseCrmProvider(options?: {
267
308
  tenantId: stageRow.tenant_id, createdAt: stageRow.created_at,
268
309
  }
269
310
  // Update lead status
270
- const { data: ext } = await pub.from('deal_extensions').select('lead_id').eq('order_id', dealId).single()
311
+ const { data: ext } = await pub.from(T.dealExtensions).select('lead_id').eq('order_id', dealId).single()
271
312
  if (ext?.lead_id) {
272
313
  const newLeadStatus = deriveLeadStatus(typedStage)
273
- await core.from('persons').update({ metadata: { status: newLeadStatus } }).eq('id', ext.lead_id)
314
+ // MERGE, never replace. people.metadata is the lead's whole opaque
315
+ // bag — formId, the public form's answers, utm. Writing a bare
316
+ // { status } here silently destroyed all of it, so dragging a card to
317
+ // another column erased the enquiry that created it. Same read-merge
318
+ // pattern already used further down for personMeta/existingMeta.
319
+ await mergePersonMetadata(ext.lead_id, { status: newLeadStatus })
274
320
  }
275
321
  // Update quote statuses
276
322
  const { data: quotes } = await core.from('orders').select('id, status').eq('kind', 'quote')
@@ -288,10 +334,10 @@ export function createSupabaseCrmProvider(options?: {
288
334
  return (await provider.getDealById(dealId))!
289
335
  },
290
336
 
291
- // --- Activities (public.crm_activities) ---
337
+ // --- Activities (public.plg_crm_activities) ---
292
338
  async getActivities(query: ActivityQuery): Promise<PaginatedResult<Activity>> {
293
339
  const { pub } = getClients()
294
- let qb = pub.from('crm_activities').select('*', { count: 'exact' })
340
+ let qb = pub.from(T.activities).select('*', { count: 'exact' })
295
341
  if (query.dealId) qb = qb.eq('deal_id', query.dealId)
296
342
  if (query.leadId) qb = qb.eq('lead_id', query.leadId)
297
343
  if (query.activityType) qb = qb.eq('activity_type', query.activityType)
@@ -307,7 +353,7 @@ export function createSupabaseCrmProvider(options?: {
307
353
  async createActivity(input: CreateActivityInput): Promise<Activity> {
308
354
  const { pub } = getClients()
309
355
  const tenantId = getTenantId()
310
- const { data, error } = await pub.from('crm_activities').insert({
356
+ const { data, error } = await pub.from(T.activities).insert({
311
357
  tenant_id: tenantId, deal_id: input.dealId, lead_id: input.leadId,
312
358
  contact_id: input.contactId, activity_type: input.activityType,
313
359
  title: input.title, description: input.description,
@@ -319,12 +365,12 @@ export function createSupabaseCrmProvider(options?: {
319
365
 
320
366
  async completeActivity(id: string): Promise<Activity> {
321
367
  const { pub } = getClients()
322
- const { data, error } = await pub.from('crm_activities').update({ completed_at: new Date().toISOString() }).eq('id', id).select().single()
368
+ const { data, error } = await pub.from(T.activities).update({ completed_at: new Date().toISOString() }).eq('id', id).select().single()
323
369
  if (error) throw new Error(error.message)
324
370
  return snakeToCamel(data) as unknown as Activity
325
371
  },
326
372
 
327
- // --- Quotes (saas_core.orders kind='quote' + order_items) ---
373
+ // --- Quotes (public.orders kind='quote' + order_items) ---
328
374
  async getQuotes(query: QuoteQuery): Promise<PaginatedResult<Quote>> {
329
375
  const { core } = getClients()
330
376
  let qb = core.from('orders').select('*', { count: 'exact' }).eq('kind', 'quote')
@@ -504,7 +550,7 @@ export function createSupabaseCrmProvider(options?: {
504
550
  const personToConvert = quote.leadId ?? quote.contactId
505
551
  if (personToConvert) {
506
552
  const clientKind = options?.clientConversion?.archetypeKind ?? 'client'
507
- const { data: person } = await core.from('persons')
553
+ const { data: person } = await core.from('people')
508
554
  .select('kind, name, email, phone, tenant_id, metadata')
509
555
  .eq('id', personToConvert).single()
510
556
 
@@ -512,7 +558,7 @@ export function createSupabaseCrmProvider(options?: {
512
558
  const personKind = (person as any)?.kind as string | undefined
513
559
  if (person && (personKind === 'lead' || personKind === 'contact')) {
514
560
  const personMeta = (person as any)?.metadata ?? {}
515
- await core.from('persons').update({
561
+ await core.from('people').update({
516
562
  kind: clientKind,
517
563
  metadata: { ...personMeta, convertedFromLead: true },
518
564
  }).eq('id', personToConvert)
@@ -577,7 +623,7 @@ export function createSupabaseCrmProvider(options?: {
577
623
 
578
624
  async getDealByLeadId(leadId: string): Promise<Deal | null> {
579
625
  const { pub } = getClients()
580
- const { data } = await pub.from('deal_extensions').select('order_id').eq('lead_id', leadId).limit(1)
626
+ const { data } = await pub.from(T.dealExtensions).select('order_id').eq('lead_id', leadId).limit(1)
581
627
  if (!data || data.length === 0) return null
582
628
  return provider.getDealById(data[0].order_id)
583
629
  },
@@ -588,8 +634,8 @@ export function createSupabaseCrmProvider(options?: {
588
634
  const monthStart = new Date().toISOString().slice(0, 7) + '-01'
589
635
  const today = new Date().toISOString().slice(0, 10)
590
636
 
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)
637
+ const { count: totalLeads } = await core.from('people').select('*', { count: 'exact', head: true }).eq('kind', 'lead')
638
+ const { count: newLeads } = await core.from('people').select('*', { count: 'exact', head: true }).eq('kind', 'lead').gte('created_at', monthStart)
593
639
  const { data: deals } = await core.from('orders').select('status, total, updated_at').eq('kind', 'deal')
594
640
  const allDeals = deals ?? []
595
641
  const openDeals = allDeals.filter((d: any) => d.status === 'open')
@@ -597,8 +643,8 @@ export function createSupabaseCrmProvider(options?: {
597
643
  const wonThisMonth = wonDeals.filter((d: any) => d.updated_at >= monthStart)
598
644
  const convertedLeads = allDeals.length // each deal came from a lead conversion
599
645
 
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)
646
+ const { count: pendingActs } = await pub.from(T.activities).select('*', { count: 'exact', head: true }).is('completed_at', null)
647
+ const { count: overdueActs } = await pub.from(T.activities).select('*', { count: 'exact', head: true }).is('completed_at', null).lt('due_date', today)
602
648
 
603
649
  return {
604
650
  totalLeads: totalLeads ?? 0,
@@ -0,0 +1,11 @@
1
+ // Central physical-table-name registry for plugin-crm. Providers import T and
2
+ // never hardcode the plg_crm_* strings, so a future rename touches one file.
3
+ export const T = {
4
+ activities: 'plg_crm_activities',
5
+ tags: 'plg_crm_tags',
6
+ activityTypes: 'plg_crm_activity_types',
7
+ pipelines: 'plg_crm_pipelines',
8
+ pipelineStages: 'plg_crm_pipeline_stages',
9
+ dealExtensions: 'plg_crm_deal_extensions',
10
+ leadSources: 'plg_crm_lead_sources',
11
+ } as const
package/src/index.ts CHANGED
@@ -54,14 +54,14 @@ export interface CrmPluginOptions {
54
54
  /** Contact/person lookup for client search in quotes and leads */
55
55
  contactLookup?: import('@fayz-ai/saas').EntityLookup
56
56
  /** Client conversion config — when a lead is approved, CRM converts the person
57
- * to a client by updating `persons.kind` and creating the extension table record.
57
+ * to a client by updating `people.kind` and creating the extension table record.
58
58
  * @example { archetypeKind: 'customer', extensionTable: 'clients', fkColumn: 'person_id' } */
59
59
  clientConversion?: {
60
- /** The archetype kind to set on persons.kind (e.g., 'customer') */
60
+ /** The archetype kind to set on people.kind (e.g., 'customer') */
61
61
  archetypeKind: string
62
62
  /** Extension table name (e.g., 'clients') in public schema */
63
63
  extensionTable: string
64
- /** FK column pointing to persons.id (e.g., 'person_id') */
64
+ /** FK column pointing to people.id (e.g., 'person_id') */
65
65
  fkColumn: string
66
66
  }
67
67
  }
@@ -137,6 +137,9 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
137
137
  version: '1.0.0',
138
138
  scope: options?.scope ?? 'universal',
139
139
  verticalId: options?.verticalId,
140
+ // Sales-pipeline/lead-management is a business-ops tool — targets the
141
+ // saas/admin Panel world, not the ecommerce storefront.
142
+ scaffolds: ['saas'],
140
143
  defaultEnabled: true,
141
144
  dependencies: [],
142
145
  declaredFeatures: [
@@ -145,6 +148,15 @@ export function createCrmPlugin(options?: CrmPluginOptions): PluginManifest {
145
148
  { id: 'crm.quotes', label: config.labels.quotes, group: config.labels.pageTitle },
146
149
  { id: 'crm.pipeline', label: config.labels.pipeline, group: config.labels.pageTitle },
147
150
  ],
151
+ // Stock quantity caps. leads/deals/quotes share core tables partitioned by
152
+ // `kind` (people/orders), so each declaration carries a kindFilter. A lead
153
+ // create auto-spawns a deal, so the lead guard also gates deal creation;
154
+ // `deals` has no standalone create UI (declared for usage banners/counts).
155
+ declaredLimits: [
156
+ { key: 'leads', label: 'Leads', table: 'people', kindFilter: 'lead' },
157
+ { key: 'deals', label: 'Deals', table: 'orders', kindFilter: 'deal' },
158
+ { key: 'quotes', label: 'Quotes', table: 'orders', kindFilter: 'quote' },
159
+ ],
148
160
  navigation: [
149
161
  {
150
162
  section: options?.navSection ?? 'main',
@@ -0,0 +1,39 @@
1
+ import React from 'react'
2
+
3
+ // ---------------------------------------------------------------------------
4
+ // Rendering whatever a public form captured.
5
+ //
6
+ // Deliberately schema-free. Every landing page asks something different — hair
7
+ // coverage on one, a coupon on another, subject/message on a third — and the
8
+ // capture side (create_public_lead) already stores the answers as an opaque bag
9
+ // so a new campaign ships with no migration. The display side needs the same
10
+ // property: anything typed here makes the NEXT form invisible.
11
+ //
12
+ // Shared because two views show the same data and had drifted: the lead detail
13
+ // page rendered answers with private helpers, while the pipeline card rendered
14
+ // none at all.
15
+ // ---------------------------------------------------------------------------
16
+
17
+ /** `hair_remaining` / `hairRemaining` → "Hair remaining". Keys that arrive
18
+ * already humanized ("Assunto") come back unchanged. */
19
+ export function humanizeKey(key: string): string {
20
+ const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\d])([A-Z])/g, '$1 $2')
21
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
22
+ }
23
+
24
+ /** Arrays are joined rather than dropped: a multi-select ("Preocupações") is
25
+ * often the most qualifying answer on the form. */
26
+ export function renderFieldValue(value: unknown): React.ReactNode {
27
+ if (value === null || value === undefined || value === '') return null
28
+ if (Array.isArray(value)) return value.length ? value.join(', ') : null
29
+ if (typeof value === 'boolean') return value ? 'Sim' : 'Não'
30
+ if (typeof value === 'object') return JSON.stringify(value)
31
+ return String(value)
32
+ }
33
+
34
+ /** Answer entries worth showing, empty values already removed. */
35
+ export function answerEntries(fields: unknown): Array<[string, unknown]> {
36
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return []
37
+ return Object.entries(fields as Record<string, unknown>)
38
+ .filter(([, v]) => v !== null && v !== undefined && v !== '')
39
+ }
package/src/locales/en.ts CHANGED
@@ -57,6 +57,7 @@ export const en: Record<string, string> = {
57
57
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
58
58
  "crm.leadDetail.assignedTo": "Assigned to",
59
59
  "crm.leadDetail.backToList": "Back to list",
60
+ "crm.leadDetail.formAnswers": "Form answers",
60
61
  "crm.leadDetail.company": "Company",
61
62
  "crm.leadDetail.contactInfo": "Contact Information",
62
63
  "crm.leadDetail.createQuote": "Create Quote",
@@ -57,6 +57,7 @@ export const ptBR: Record<string, string> = {
57
57
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
58
58
  "crm.leadDetail.assignedTo": "Atribuído a",
59
59
  "crm.leadDetail.backToList": "Voltar à lista",
60
+ "crm.leadDetail.formAnswers": "Dados do formulário",
60
61
  "crm.leadDetail.company": "Empresa",
61
62
  "crm.leadDetail.contactInfo": "Informações de Contato",
62
63
  "crm.leadDetail.createQuote": "Criar Orçamento",
@@ -0,0 +1,28 @@
1
+ -- 000_plg_rename.sql — rename legacy CRM tables to the plg_crm_* convention for
2
+ -- pools provisioned before the industry-pool rename. Guarded: only fires when the
3
+ -- legacy name exists and the target does not, so fresh pools skip every branch and
4
+ -- the create-table migrations below build clean.
5
+ DO $$
6
+ BEGIN
7
+ IF to_regclass('public.crm_activities') IS NOT NULL AND to_regclass('public.plg_crm_activities') IS NULL THEN
8
+ ALTER TABLE public.crm_activities RENAME TO plg_crm_activities;
9
+ END IF;
10
+ IF to_regclass('public.crm_tags') IS NOT NULL AND to_regclass('public.plg_crm_tags') IS NULL THEN
11
+ ALTER TABLE public.crm_tags RENAME TO plg_crm_tags;
12
+ END IF;
13
+ IF to_regclass('public.crm_activity_types') IS NOT NULL AND to_regclass('public.plg_crm_activity_types') IS NULL THEN
14
+ ALTER TABLE public.crm_activity_types RENAME TO plg_crm_activity_types;
15
+ END IF;
16
+ IF to_regclass('public.pipelines') IS NOT NULL AND to_regclass('public.plg_crm_pipelines') IS NULL THEN
17
+ ALTER TABLE public.pipelines RENAME TO plg_crm_pipelines;
18
+ END IF;
19
+ IF to_regclass('public.pipeline_stages') IS NOT NULL AND to_regclass('public.plg_crm_pipeline_stages') IS NULL THEN
20
+ ALTER TABLE public.pipeline_stages RENAME TO plg_crm_pipeline_stages;
21
+ END IF;
22
+ IF to_regclass('public.deal_extensions') IS NOT NULL AND to_regclass('public.plg_crm_deal_extensions') IS NULL THEN
23
+ ALTER TABLE public.deal_extensions RENAME TO plg_crm_deal_extensions;
24
+ END IF;
25
+ IF to_regclass('public.lead_sources') IS NOT NULL AND to_regclass('public.plg_crm_lead_sources') IS NULL THEN
26
+ ALTER TABLE public.lead_sources RENAME TO plg_crm_lead_sources;
27
+ END IF;
28
+ END $$;
@@ -1,25 +1,25 @@
1
1
  -- CRM Plugin: Base Tables
2
- -- Leads use saas_core.persons (kind='lead')
3
- -- Deals use saas_core.orders (kind='deal')
4
- -- Quotes use saas_core.orders (kind='quote') + saas_core.order_items
2
+ -- Leads use public.people (kind='lead')
3
+ -- Deals use public.orders (kind='deal')
4
+ -- Quotes use public.orders (kind='quote') + public.order_items
5
5
  -- These are plugin-specific extension tables
6
6
 
7
- CREATE TABLE IF NOT EXISTS public.pipelines (
7
+ CREATE TABLE IF NOT EXISTS public.plg_crm_pipelines (
8
8
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
9
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
9
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
10
10
  name text NOT NULL,
11
11
  is_default boolean DEFAULT false,
12
12
  is_active boolean NOT NULL DEFAULT true,
13
13
  created_at timestamptz NOT NULL DEFAULT now(),
14
14
  updated_at timestamptz NOT NULL DEFAULT now()
15
15
  );
16
- ALTER TABLE public.pipelines ENABLE ROW LEVEL SECURITY;
17
- CREATE INDEX IF NOT EXISTS idx_pipelines_tenant ON public.pipelines(tenant_id);
16
+ ALTER TABLE public.plg_crm_pipelines ENABLE ROW LEVEL SECURITY;
17
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_pipelines_tenant ON public.plg_crm_pipelines(tenant_id);
18
18
 
19
- CREATE TABLE IF NOT EXISTS public.pipeline_stages (
19
+ CREATE TABLE IF NOT EXISTS public.plg_crm_pipeline_stages (
20
20
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
21
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
22
- pipeline_id uuid NOT NULL REFERENCES public.pipelines(id) ON DELETE CASCADE,
21
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
22
+ pipeline_id uuid NOT NULL REFERENCES public.plg_crm_pipelines(id) ON DELETE CASCADE,
23
23
  name text NOT NULL,
24
24
  "order" integer NOT NULL DEFAULT 0,
25
25
  color text DEFAULT '#6366f1',
@@ -28,46 +28,46 @@ CREATE TABLE IF NOT EXISTS public.pipeline_stages (
28
28
  is_lost boolean DEFAULT false,
29
29
  created_at timestamptz NOT NULL DEFAULT now()
30
30
  );
31
- ALTER TABLE public.pipeline_stages ENABLE ROW LEVEL SECURITY;
32
- CREATE INDEX IF NOT EXISTS idx_pipeline_stages_tenant ON public.pipeline_stages(tenant_id);
33
- CREATE INDEX IF NOT EXISTS idx_pipeline_stages_pipeline ON public.pipeline_stages(pipeline_id);
31
+ ALTER TABLE public.plg_crm_pipeline_stages ENABLE ROW LEVEL SECURITY;
32
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_pipeline_stages_tenant ON public.plg_crm_pipeline_stages(tenant_id);
33
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_pipeline_stages_pipeline ON public.plg_crm_pipeline_stages(pipeline_id);
34
34
 
35
- CREATE TABLE IF NOT EXISTS public.lead_sources (
35
+ CREATE TABLE IF NOT EXISTS public.plg_crm_lead_sources (
36
36
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
37
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
37
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
38
38
  name text NOT NULL,
39
39
  is_active boolean NOT NULL DEFAULT true,
40
40
  created_at timestamptz NOT NULL DEFAULT now()
41
41
  );
42
- ALTER TABLE public.lead_sources ENABLE ROW LEVEL SECURITY;
43
- CREATE INDEX IF NOT EXISTS idx_lead_sources_tenant ON public.lead_sources(tenant_id);
42
+ ALTER TABLE public.plg_crm_lead_sources ENABLE ROW LEVEL SECURITY;
43
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_lead_sources_tenant ON public.plg_crm_lead_sources(tenant_id);
44
44
 
45
- CREATE TABLE IF NOT EXISTS public.crm_tags (
45
+ CREATE TABLE IF NOT EXISTS public.plg_crm_tags (
46
46
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
47
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
47
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
48
48
  name text NOT NULL,
49
49
  color text DEFAULT '#6366f1',
50
50
  is_active boolean NOT NULL DEFAULT true,
51
51
  created_at timestamptz NOT NULL DEFAULT now()
52
52
  );
53
- ALTER TABLE public.crm_tags ENABLE ROW LEVEL SECURITY;
54
- CREATE INDEX IF NOT EXISTS idx_crm_tags_tenant ON public.crm_tags(tenant_id);
53
+ ALTER TABLE public.plg_crm_tags ENABLE ROW LEVEL SECURITY;
54
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_tags_tenant ON public.plg_crm_tags(tenant_id);
55
55
 
56
- -- Deal extension: links saas_core.orders (kind='deal') to pipeline stage
57
- CREATE TABLE IF NOT EXISTS public.deal_extensions (
56
+ -- Deal extension: links public.orders (kind='deal') to pipeline stage
57
+ CREATE TABLE IF NOT EXISTS public.plg_crm_deal_extensions (
58
58
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
59
- order_id uuid NOT NULL REFERENCES saas_core.orders(id) ON DELETE CASCADE,
60
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
61
- pipeline_id uuid REFERENCES public.pipelines(id),
62
- stage_id uuid REFERENCES public.pipeline_stages(id),
59
+ order_id uuid NOT NULL REFERENCES public.orders(id) ON DELETE CASCADE,
60
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
61
+ pipeline_id uuid REFERENCES public.plg_crm_pipelines(id),
62
+ stage_id uuid REFERENCES public.plg_crm_pipeline_stages(id),
63
63
  probability numeric(5,2) DEFAULT 0,
64
64
  expected_close_date date,
65
- lead_id uuid REFERENCES saas_core.persons(id),
65
+ lead_id uuid REFERENCES public.people(id),
66
66
  lost_reason text,
67
67
  created_at timestamptz NOT NULL DEFAULT now(),
68
68
  updated_at timestamptz NOT NULL DEFAULT now()
69
69
  );
70
- ALTER TABLE public.deal_extensions ENABLE ROW LEVEL SECURITY;
71
- CREATE INDEX IF NOT EXISTS idx_deal_extensions_tenant ON public.deal_extensions(tenant_id);
72
- CREATE INDEX IF NOT EXISTS idx_deal_extensions_order ON public.deal_extensions(order_id);
73
- CREATE INDEX IF NOT EXISTS idx_deal_extensions_stage ON public.deal_extensions(stage_id);
70
+ ALTER TABLE public.plg_crm_deal_extensions ENABLE ROW LEVEL SECURITY;
71
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_tenant ON public.plg_crm_deal_extensions(tenant_id);
72
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_order ON public.plg_crm_deal_extensions(order_id);
73
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_deal_extensions_stage ON public.plg_crm_deal_extensions(stage_id);
@@ -1,21 +1,21 @@
1
1
  -- CRM Plugin: Activities & Tasks
2
2
 
3
- CREATE TABLE IF NOT EXISTS public.crm_activity_types (
3
+ CREATE TABLE IF NOT EXISTS public.plg_crm_activity_types (
4
4
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
5
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
5
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
6
6
  name text NOT NULL,
7
7
  is_active boolean NOT NULL DEFAULT true,
8
8
  created_at timestamptz NOT NULL DEFAULT now()
9
9
  );
10
- ALTER TABLE public.crm_activity_types ENABLE ROW LEVEL SECURITY;
11
- CREATE INDEX IF NOT EXISTS idx_crm_activity_types_tenant ON public.crm_activity_types(tenant_id);
10
+ ALTER TABLE public.plg_crm_activity_types ENABLE ROW LEVEL SECURITY;
11
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_activity_types_tenant ON public.plg_crm_activity_types(tenant_id);
12
12
 
13
- CREATE TABLE IF NOT EXISTS public.crm_activities (
13
+ CREATE TABLE IF NOT EXISTS public.plg_crm_activities (
14
14
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
15
- tenant_id uuid NOT NULL REFERENCES saas_core.tenants(id) ON DELETE CASCADE,
16
- deal_id uuid REFERENCES saas_core.orders(id),
17
- lead_id uuid REFERENCES saas_core.persons(id),
18
- contact_id uuid REFERENCES saas_core.persons(id),
15
+ tenant_id uuid NOT NULL REFERENCES public.tenants(id) ON DELETE CASCADE,
16
+ deal_id uuid REFERENCES public.orders(id),
17
+ lead_id uuid REFERENCES public.people(id),
18
+ contact_id uuid REFERENCES public.people(id),
19
19
  contact_name text,
20
20
  activity_type text NOT NULL,
21
21
  title text NOT NULL,
@@ -26,8 +26,8 @@ CREATE TABLE IF NOT EXISTS public.crm_activities (
26
26
  assigned_to_name text,
27
27
  created_at timestamptz NOT NULL DEFAULT now()
28
28
  );
29
- ALTER TABLE public.crm_activities ENABLE ROW LEVEL SECURITY;
30
- CREATE INDEX IF NOT EXISTS idx_crm_activities_tenant ON public.crm_activities(tenant_id);
31
- CREATE INDEX IF NOT EXISTS idx_crm_activities_deal ON public.crm_activities(deal_id);
32
- CREATE INDEX IF NOT EXISTS idx_crm_activities_lead ON public.crm_activities(lead_id);
33
- CREATE INDEX IF NOT EXISTS idx_crm_activities_due ON public.crm_activities(tenant_id, due_date);
29
+ ALTER TABLE public.plg_crm_activities ENABLE ROW LEVEL SECURITY;
30
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_activities_tenant ON public.plg_crm_activities(tenant_id);
31
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_activities_deal ON public.plg_crm_activities(deal_id);
32
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_activities_lead ON public.plg_crm_activities(lead_id);
33
+ CREATE INDEX IF NOT EXISTS idx_plg_crm_activities_due ON public.plg_crm_activities(tenant_id, due_date);
@@ -7,8 +7,8 @@ DO $$
7
7
  DECLARE t text;
8
8
  BEGIN
9
9
  FOR t IN SELECT unnest(ARRAY[
10
- 'pipelines','pipeline_stages','lead_sources','crm_tags',
11
- 'deal_extensions','crm_activity_types','crm_activities'
10
+ 'plg_crm_pipelines','plg_crm_pipeline_stages','plg_crm_lead_sources','plg_crm_tags',
11
+ 'plg_crm_deal_extensions','plg_crm_activity_types','plg_crm_activities'
12
12
  ])
13
13
  LOOP
14
14
  EXECUTE format('ALTER TABLE public.%I ENABLE ROW LEVEL SECURITY', t);
@@ -28,7 +28,7 @@ BEGIN
28
28
  END LOOP;
29
29
  END $$;
30
30
 
31
- -- v_leads: saas_core.persons (kind='lead')
31
+ -- v_leads: public.people (kind='lead')
32
32
  CREATE OR REPLACE VIEW public.v_leads WITH (security_invoker=true) AS
33
33
  SELECT
34
34
  p.id, p.tenant_id, p.name, p.email, p.phone, p.notes, p.tags, p.is_active,
@@ -39,11 +39,11 @@ SELECT
39
39
  p.metadata->>'value' AS lead_value,
40
40
  p.metadata->>'assignedToId' AS assigned_to_id,
41
41
  p.created_at, p.updated_at
42
- FROM saas_core.persons p
42
+ FROM public.people p
43
43
  WHERE p.kind = 'lead';
44
44
  GRANT SELECT ON public.v_leads TO authenticated;
45
45
 
46
- -- v_deals: saas_core.orders (kind='deal') JOIN deal_extensions JOIN pipeline_stages
46
+ -- v_deals: public.orders (kind='deal') JOIN plg_crm_deal_extensions JOIN plg_crm_pipeline_stages
47
47
  CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker=true) AS
48
48
  SELECT
49
49
  o.id, o.tenant_id, o.status,
@@ -54,8 +54,8 @@ SELECT
54
54
  de.pipeline_id, de.stage_id, de.probability, de.expected_close_date,
55
55
  de.lead_id, de.lost_reason,
56
56
  ps.name AS stage_name, ps.color AS stage_color, ps."order" AS stage_order
57
- FROM saas_core.orders o
58
- LEFT JOIN public.deal_extensions de ON de.order_id = o.id
59
- LEFT JOIN public.pipeline_stages ps ON ps.id = de.stage_id
57
+ FROM public.orders o
58
+ LEFT JOIN public.plg_crm_deal_extensions de ON de.order_id = o.id
59
+ LEFT JOIN public.plg_crm_pipeline_stages ps ON ps.id = de.stage_id
60
60
  WHERE o.kind = 'deal';
61
61
  GRANT SELECT ON public.v_deals TO authenticated;
@@ -1,5 +1,5 @@
1
1
  -- CRM plugin — seed: default "Sales Pipeline" + canonical stages.
2
- -- The pipeline board (#/sales/pipeline) reads public.pipelines / pipeline_stages
2
+ -- The pipeline board (#/sales/pipeline) reads public.plg_crm_pipelines / plg_crm_pipeline_stages
3
3
  -- directly; a fresh tenant has zero rows and the board renders blank. This
4
4
  -- backfills the default pipeline (matching the plugin's mock/offline provider)
5
5
  -- for every tenant that has none. Idempotent — tenants with a pipeline are skipped.
@@ -11,15 +11,15 @@ DECLARE
11
11
  p_id uuid;
12
12
  BEGIN
13
13
  FOR t_id IN (
14
- SELECT id FROM saas_core.tenants
15
- WHERE id NOT IN (SELECT tenant_id FROM public.pipelines)
14
+ SELECT id FROM public.tenants
15
+ WHERE id NOT IN (SELECT tenant_id FROM public.plg_crm_pipelines)
16
16
  )
17
17
  LOOP
18
- INSERT INTO public.pipelines (tenant_id, name, is_default, is_active)
18
+ INSERT INTO public.plg_crm_pipelines (tenant_id, name, is_default, is_active)
19
19
  VALUES (t_id, 'Sales Pipeline', true, true)
20
20
  RETURNING id INTO p_id;
21
21
 
22
- INSERT INTO public.pipeline_stages (tenant_id, pipeline_id, name, "order", color, probability, is_won, is_lost) VALUES
22
+ INSERT INTO public.plg_crm_pipeline_stages (tenant_id, pipeline_id, name, "order", color, probability, is_won, is_lost) VALUES
23
23
  (t_id, p_id, 'New', 0, '#6366f1', 10, false, false),
24
24
  (t_id, p_id, 'Contacted', 1, '#3b82f6', 25, false, false),
25
25
  (t_id, p_id, 'Qualified', 2, '#f59e0b', 50, false, false),