@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
@@ -2,28 +2,28 @@
2
2
  // pgTable/uuid directly from drizzle-orm/pg-core. See MIGRATION-ARCHITECTURE §6.
3
3
  import {
4
4
  pgTable, uuid, text, boolean, integer, numeric, date, timestamp, index,
5
- tenantId, timestamps, createdAt, persons, orders,
5
+ tenantId, timestamps, createdAt, people, orders,
6
6
  } from '@fayz-ai/db'
7
7
 
8
8
  // ---------------------------------------------------------------------------
9
9
  // CRM plugin — Ring-1 schema (schema-as-code).
10
10
  //
11
- // Leads live on saas_core.persons (kind='lead'); deals/quotes on saas_core.orders.
11
+ // Leads live on public.people (kind='lead'); deals/quotes on public.orders.
12
12
  // These tables extend that spine with pipeline, tagging and activity data.
13
13
  // RLS policies, grants and the v_leads/v_deals read-views are companion SQL
14
14
  // (Drizzle doesn't diff grants/views) — see the app's drizzle/companion/.
15
15
  // ---------------------------------------------------------------------------
16
16
 
17
- export const pipelines = pgTable('pipelines', {
17
+ export const pipelines = pgTable('plg_crm_pipelines', {
18
18
  id: uuid('id').primaryKey().defaultRandom(),
19
19
  tenantId: tenantId(),
20
20
  name: text('name').notNull(),
21
21
  isDefault: boolean('is_default').default(false),
22
22
  isActive: boolean('is_active').notNull().default(true),
23
23
  ...timestamps,
24
- }, (t) => [index('idx_pipelines_tenant').on(t.tenantId)])
24
+ }, (t) => [index('idx_plg_crm_pipelines_tenant').on(t.tenantId)])
25
25
 
26
- export const pipelineStages = pgTable('pipeline_stages', {
26
+ export const pipelineStages = pgTable('plg_crm_pipeline_stages', {
27
27
  id: uuid('id').primaryKey().defaultRandom(),
28
28
  tenantId: tenantId(),
29
29
  pipelineId: uuid('pipeline_id').notNull().references(() => pipelines.id, { onDelete: 'cascade' }),
@@ -35,28 +35,28 @@ export const pipelineStages = pgTable('pipeline_stages', {
35
35
  isLost: boolean('is_lost').default(false),
36
36
  ...createdAt,
37
37
  }, (t) => [
38
- index('idx_pipeline_stages_tenant').on(t.tenantId),
39
- index('idx_pipeline_stages_pipeline').on(t.pipelineId),
38
+ index('idx_plg_crm_pipeline_stages_tenant').on(t.tenantId),
39
+ index('idx_plg_crm_pipeline_stages_pipeline').on(t.pipelineId),
40
40
  ])
41
41
 
42
- export const leadSources = pgTable('lead_sources', {
42
+ export const leadSources = pgTable('plg_crm_lead_sources', {
43
43
  id: uuid('id').primaryKey().defaultRandom(),
44
44
  tenantId: tenantId(),
45
45
  name: text('name').notNull(),
46
46
  isActive: boolean('is_active').notNull().default(true),
47
47
  ...createdAt,
48
- }, (t) => [index('idx_lead_sources_tenant').on(t.tenantId)])
48
+ }, (t) => [index('idx_plg_crm_lead_sources_tenant').on(t.tenantId)])
49
49
 
50
- export const crmTags = pgTable('crm_tags', {
50
+ export const crmTags = pgTable('plg_crm_tags', {
51
51
  id: uuid('id').primaryKey().defaultRandom(),
52
52
  tenantId: tenantId(),
53
53
  name: text('name').notNull(),
54
54
  color: text('color').default('#6366f1'),
55
55
  isActive: boolean('is_active').notNull().default(true),
56
56
  ...createdAt,
57
- }, (t) => [index('idx_crm_tags_tenant').on(t.tenantId)])
57
+ }, (t) => [index('idx_plg_crm_tags_tenant').on(t.tenantId)])
58
58
 
59
- export const dealExtensions = pgTable('deal_extensions', {
59
+ export const dealExtensions = pgTable('plg_crm_deal_extensions', {
60
60
  id: uuid('id').primaryKey().defaultRandom(),
61
61
  orderId: uuid('order_id').notNull().references(() => orders.id, { onDelete: 'cascade' }),
62
62
  tenantId: tenantId(),
@@ -64,29 +64,29 @@ export const dealExtensions = pgTable('deal_extensions', {
64
64
  stageId: uuid('stage_id').references(() => pipelineStages.id),
65
65
  probability: numeric('probability', { precision: 5, scale: 2 }).default('0'),
66
66
  expectedCloseDate: date('expected_close_date'),
67
- leadId: uuid('lead_id').references(() => persons.id),
67
+ leadId: uuid('lead_id').references(() => people.id),
68
68
  lostReason: text('lost_reason'),
69
69
  ...timestamps,
70
70
  }, (t) => [
71
- index('idx_deal_extensions_tenant').on(t.tenantId),
72
- index('idx_deal_extensions_order').on(t.orderId),
73
- index('idx_deal_extensions_stage').on(t.stageId),
71
+ index('idx_plg_crm_deal_extensions_tenant').on(t.tenantId),
72
+ index('idx_plg_crm_deal_extensions_order').on(t.orderId),
73
+ index('idx_plg_crm_deal_extensions_stage').on(t.stageId),
74
74
  ])
75
75
 
76
- export const crmActivityTypes = pgTable('crm_activity_types', {
76
+ export const crmActivityTypes = pgTable('plg_crm_activity_types', {
77
77
  id: uuid('id').primaryKey().defaultRandom(),
78
78
  tenantId: tenantId(),
79
79
  name: text('name').notNull(),
80
80
  isActive: boolean('is_active').notNull().default(true),
81
81
  ...createdAt,
82
- }, (t) => [index('idx_crm_activity_types_tenant').on(t.tenantId)])
82
+ }, (t) => [index('idx_plg_crm_activity_types_tenant').on(t.tenantId)])
83
83
 
84
- export const crmActivities = pgTable('crm_activities', {
84
+ export const crmActivities = pgTable('plg_crm_activities', {
85
85
  id: uuid('id').primaryKey().defaultRandom(),
86
86
  tenantId: tenantId(),
87
87
  dealId: uuid('deal_id').references(() => orders.id),
88
- leadId: uuid('lead_id').references(() => persons.id),
89
- contactId: uuid('contact_id').references(() => persons.id),
88
+ leadId: uuid('lead_id').references(() => people.id),
89
+ contactId: uuid('contact_id').references(() => people.id),
90
90
  contactName: text('contact_name'),
91
91
  activityType: text('activity_type').notNull(),
92
92
  title: text('title').notNull(),
@@ -97,8 +97,8 @@ export const crmActivities = pgTable('crm_activities', {
97
97
  assignedToName: text('assigned_to_name'),
98
98
  ...createdAt,
99
99
  }, (t) => [
100
- index('idx_crm_activities_tenant').on(t.tenantId),
101
- index('idx_crm_activities_deal').on(t.dealId),
102
- index('idx_crm_activities_lead').on(t.leadId),
103
- index('idx_crm_activities_due').on(t.tenantId, t.dueDate),
100
+ index('idx_plg_crm_activities_tenant').on(t.tenantId),
101
+ index('idx_plg_crm_activities_deal').on(t.dealId),
102
+ index('idx_plg_crm_activities_lead').on(t.leadId),
103
+ index('idx_plg_crm_activities_due').on(t.tenantId, t.dueDate),
104
104
  ])
@@ -5,6 +5,7 @@ import { Sheet, SheetContent, SheetHeader, SheetBody, SheetFooter, SheetTitle, S
5
5
  import { PersonLink } from '@fayz-ai/saas'
6
6
  import { useCrmProvider, useCrmConfig, formatCurrency } from '../CrmContext'
7
7
  import { QuoteStatusDropdown } from '../components/QuoteStatusDropdown'
8
+ import { answerEntries, humanizeKey, renderFieldValue } from '../lib/form-answers'
8
9
  import type { Deal, Lead, Quote, Activity } from '../types'
9
10
 
10
11
  // ---------------------------------------------------------------------------
@@ -60,6 +61,33 @@ function TabBar({ active, counts, onChange }: { active: TabId; counts: { activit
60
61
  // Overview tab
61
62
  // ---------------------------------------------------------------------------
62
63
 
64
+ /** Whatever the public form captured, in the card. Same opaque-bag rendering
65
+ * the lead detail page uses — shared so the two cannot drift. */
66
+ function FormAnswers({ lead }: { lead: Lead | null }) {
67
+ const t = useTranslation()
68
+ const entries = answerEntries(lead?.metadata?.fields)
69
+ if (entries.length === 0) return null
70
+
71
+ const formId = lead?.metadata?.formId
72
+ return (
73
+ <div className="space-y-2">
74
+ <h4 className="text-[11px] font-semibold text-muted-foreground uppercase tracking-wider">
75
+ {formId ? `${t('crm.leadDetail.formAnswers')} · ${formId}` : t('crm.leadDetail.formAnswers')}
76
+ </h4>
77
+ <div className="rounded-xl border divide-y">
78
+ {entries.map(([key, value]) => (
79
+ <div key={key} className="flex items-start gap-3 px-4 py-2.5">
80
+ <span className="text-[11px] text-muted-foreground shrink-0 min-w-24">{humanizeKey(key)}</span>
81
+ <span className="text-xs text-right flex-1 break-words">
82
+ {renderFieldValue(value) ?? <span className="text-muted-foreground/50">—</span>}
83
+ </span>
84
+ </div>
85
+ ))}
86
+ </div>
87
+ </div>
88
+ )
89
+ }
90
+
63
91
  function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null; currency: { code: string; locale: string; symbol: string } }) {
64
92
  const t = useTranslation()
65
93
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase()
@@ -143,6 +171,9 @@ function OverviewTab({ deal, lead, currency }: { deal: Deal; lead: Lead | null;
143
171
  </div>
144
172
  )}
145
173
 
174
+ {/* Form answers */}
175
+ <FormAnswers lead={lead} />
176
+
146
177
  {/* Tags */}
147
178
  {deal.tags && deal.tags.length > 0 && (
148
179
  <div className="space-y-2">
@@ -16,6 +16,21 @@ const STATUS_COLORS: Record<string, string> = {
16
16
  }
17
17
 
18
18
 
19
+ /** "hair_remaining" → "Hair remaining". Form answers arrive keyed by whatever
20
+ * the landing page called them, so they get humanized rather than shown raw. */
21
+ function humanizeKey(key: string): string {
22
+ const spaced = key.replace(/[_-]+/g, ' ').replace(/([a-z\d])([A-Z])/g, '$1 $2')
23
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1)
24
+ }
25
+
26
+ 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
+
19
34
  function FieldRow({ label, value }: { label: string; value: React.ReactNode }) {
20
35
  return (
21
36
  <div className="grid grid-cols-3 gap-4 py-3">
@@ -159,6 +174,44 @@ export function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }: {
159
174
  </div>
160
175
  </div>
161
176
 
177
+ {/* Form answers — whatever the landing page asked. Rendered generically
178
+ so a new form never needs a change here. */}
179
+ {(() => {
180
+ const meta = (lead.metadata ?? {}) as {
181
+ fields?: Record<string, unknown>
182
+ utm?: Record<string, unknown>
183
+ }
184
+ const fields = Object.entries(meta.fields ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
185
+ const utm = Object.entries(meta.utm ?? {}).filter(([, v]) => renderFieldValue(v) !== null)
186
+ if (!fields.length && !utm.length) return null
187
+ return (
188
+ <div>
189
+ <h3 className="text-sm font-semibold text-foreground mb-1">
190
+ {t('crm.leadDetail.formAnswers')}
191
+ </h3>
192
+ <div className="rounded-xl border bg-card shadow-sm">
193
+ <dl className="grid divide-y md:grid-cols-2 md:divide-y-0">
194
+ {fields.map(([key, value]) => (
195
+ <div key={key} className="px-5 md:border-b md:last:border-b-0">
196
+ <FieldRow label={humanizeKey(key)} value={renderFieldValue(value)} />
197
+ </div>
198
+ ))}
199
+ </dl>
200
+ {utm.length > 0 && (
201
+ <div className="border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1">
202
+ {utm.map(([key, value]) => (
203
+ <span key={key} className="text-xs text-muted-foreground">
204
+ {humanizeKey(key.replace(/^utm_/, ''))}:{' '}
205
+ <span className="text-foreground">{renderFieldValue(value)}</span>
206
+ </span>
207
+ ))}
208
+ </div>
209
+ )}
210
+ </div>
211
+ </div>
212
+ )
213
+ })()}
214
+
162
215
  {/* Pipeline / Deal */}
163
216
  {deal && (
164
217
  <div>
@@ -1,11 +1,15 @@
1
1
  import React, { useState, useEffect } from 'react'
2
2
  import { useCrmStore } from '../CrmContext'
3
3
  import { useTranslation } from '@fayz-ai/core'
4
+ import { useLimitGuard, invalidateLimit } from '@fayz-ai/saas'
4
5
  import { SubpageHeader, useSaveBar, toast } from '@fayz-ai/ui'
5
6
 
6
7
  export function LeadFormView({ onSaved }: { onSaved?: (id?: string) => void }) {
7
8
  const t = useTranslation()
8
9
  const createLead = useCrmStore((s) => s.createLead)
10
+ // Creating a lead also auto-creates a deal (store.createLead), so this path is
11
+ // the create surface for both the pipeline board ("+ Add") and the lead form.
12
+ const guardLeads = useLimitGuard('leads')
9
13
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines)
10
14
  const pipelines = useCrmStore((s) => s.pipelines)
11
15
 
@@ -21,9 +25,15 @@ export function LeadFormView({ onSaved }: { onSaved?: (id?: string) => void }) {
21
25
 
22
26
  async function handleSave() {
23
27
  if (!name.trim()) { toast.error(t('common.formIncomplete')); return }
28
+ // Plan quantity guard (client-side, before the store call): opens the global
29
+ // UpgradeModal and aborts when the lead cap is reached.
30
+ if ((await guardLeads()) === 'blocked') return
24
31
  setSaving(true)
25
32
  try {
26
33
  const lead = await createLead({ name, email: email || undefined, phone: phone || undefined, company: company || undefined, notes: notes || undefined })
34
+ // A lead spawns a deal too — refresh both live counts.
35
+ invalidateLimit('leads')
36
+ invalidateLimit('deals')
27
37
  onSaved?.(lead.id)
28
38
  } finally { setSaving(false) }
29
39
  }
@@ -37,6 +37,25 @@ const columns: ColumnDef<Lead, any>[] = [
37
37
  )
38
38
  },
39
39
  },
40
+ {
41
+ // When the lead came in. The list is already sorted by it (provider orders
42
+ // created_at desc) but never showed it, so "is this enquiry from today or
43
+ // from March?" was unanswerable without opening the record.
44
+ accessorKey: 'createdAt', header: 'Entrada',
45
+ cell: ({ getValue }) => {
46
+ const raw = getValue() as string | undefined
47
+ if (!raw) return <span className="text-muted-foreground text-xs">—</span>
48
+ const at = new Date(raw)
49
+ if (Number.isNaN(at.getTime())) return <span className="text-muted-foreground text-xs">—</span>
50
+ return (
51
+ <span className="text-muted-foreground text-xs whitespace-nowrap" title={at.toLocaleString()}>
52
+ {at.toLocaleDateString(undefined, { day: '2-digit', month: '2-digit', year: '2-digit' })}
53
+ {' · '}
54
+ {at.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' })}
55
+ </span>
56
+ )
57
+ },
58
+ },
40
59
  ]
41
60
 
42
61
  export function LeadListView({ onNew, onEdit }: { onNew?: () => void; onEdit?: (id: string) => void }) {
@@ -2,7 +2,7 @@ import React, { useEffect, useRef, useState } from 'react'
2
2
  import { Loader2, Plus } from 'lucide-react'
3
3
  import { toast } from '@fayz-ai/ui'
4
4
  import { useCrmStore, useCrmConfig, formatCurrency } from '../CrmContext'
5
- import { useTranslation } from '@fayz-ai/core'
5
+ import { useTranslation, getSupabaseClientOptional } from '@fayz-ai/core'
6
6
  import { SubpageHeader } from '@fayz-ai/ui'
7
7
  import { DealSidebar } from './DealSidebar'
8
8
  import type { Deal } from '../types'
@@ -177,6 +177,39 @@ export function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }
177
177
  useEffect(() => { fetchPipelines() }, [])
178
178
  useEffect(() => { if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id) }, [pipelines])
179
179
 
180
+ // Live board. The card for an incoming lead is created by a DB trigger
181
+ // (plugin-crm 006), so it appears with no client code involved at all — and
182
+ // without this subscription the only way to see it was a page reload. A
183
+ // pipeline left open on a screen all day is the normal case here, which is
184
+ // exactly when a stale board is worst.
185
+ //
186
+ // Subscribes to plg_crm_deal_extensions rather than orders: it is the row
187
+ // carrying pipeline_id/stage_id, so every board-visible change (card created,
188
+ // moved, removed) touches it and nothing else does. A refetch rather than a
189
+ // local patch — the payload alone lacks the joined stage/contact fields the
190
+ // board renders, and refetching keeps one source of truth for the board.
191
+ const pipelineId = pipelines[0]?.id
192
+ useEffect(() => {
193
+ if (!pipelineId) return
194
+ const supabase = getSupabaseClientOptional() as {
195
+ channel: (name: string) => { on: (...a: unknown[]) => { subscribe: () => unknown } }
196
+ removeChannel: (channel: unknown) => void
197
+ } | null
198
+ if (!supabase) return
199
+
200
+ // RLS scopes the stream to the caller's own tenants — no tenant filter here.
201
+ const channel = supabase
202
+ .channel(`crm:board:${pipelineId}`)
203
+ .on(
204
+ 'postgres_changes',
205
+ { event: '*', schema: 'public', table: 'plg_crm_deal_extensions' },
206
+ () => { void fetchDealsByStage(pipelineId) },
207
+ )
208
+ .subscribe()
209
+
210
+ return () => { supabase.removeChannel(channel) }
211
+ }, [pipelineId])
212
+
180
213
  // Clear optimistic state when real data arrives and no moves are in-flight
181
214
  useEffect(() => {
182
215
  if (savingDealIds.size === 0) setOptimisticBoard(null)
@@ -3,6 +3,7 @@ import { Plus, Trash2, X, Check, ChevronDown } from 'lucide-react'
3
3
  import { useCrmConfig, useCrmStore, useCrmProvider, formatCurrency } from '../CrmContext'
4
4
  import { useTranslation } from '@fayz-ai/core'
5
5
  import type { EntityLookupMap } from '@fayz-ai/saas'
6
+ import { useLimitGuard, invalidateLimit } from '@fayz-ai/saas'
6
7
  import { SubpageHeader, useSaveBar, toast } from '@fayz-ai/ui'
7
8
  import { SearchSelect, type SearchSelectOption } from '@fayz-ai/ui'
8
9
  import { CurrencyInput } from '@fayz-ai/ui'
@@ -195,6 +196,7 @@ export function QuoteFormView({ quoteId, leadId, onSaved }: { quoteId?: string;
195
196
  const { currency, itemTypes } = config
196
197
  const createQuote = useCrmStore((s) => s.createQuote)
197
198
  const updateQuote = useCrmStore((s) => s.updateQuote)
199
+ const guardQuotes = useLimitGuard('quotes')
198
200
 
199
201
  const isEdit = !!quoteId
200
202
  const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId)
@@ -281,6 +283,8 @@ export function QuoteFormView({ quoteId, leadId, onSaved }: { quoteId?: string;
281
283
 
282
284
  async function handleSave() {
283
285
  if (items.length === 0) { toast.error(t('crm.quoteForm.errNoItems')); return }
286
+ // Plan quantity guard (client-side) — only a new quote consumes a slot.
287
+ if (!isEdit && (await guardQuotes()) === 'blocked') return
284
288
  setSaving(true)
285
289
  try {
286
290
  const input = {
@@ -306,6 +310,7 @@ export function QuoteFormView({ quoteId, leadId, onSaved }: { quoteId?: string;
306
310
  onSaved?.(quoteId)
307
311
  } else {
308
312
  const created = await createQuote(input)
313
+ invalidateLimit('quotes')
309
314
  onSaved?.(created?.id)
310
315
  }
311
316
  } finally { setSaving(false) }