@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
package/dist/index.d.ts CHANGED
@@ -55,14 +55,14 @@ export interface CrmPluginOptions {
55
55
  /** Contact/person lookup for client search in quotes and leads */
56
56
  contactLookup?: import('@fayz-ai/saas').EntityLookup;
57
57
  /** Client conversion config — when a lead is approved, CRM converts the person
58
- * to a client by updating `persons.kind` and creating the extension table record.
58
+ * to a client by updating `people.kind` and creating the extension table record.
59
59
  * @example { archetypeKind: 'customer', extensionTable: 'clients', fkColumn: 'person_id' } */
60
60
  clientConversion?: {
61
- /** The archetype kind to set on persons.kind (e.g., 'customer') */
61
+ /** The archetype kind to set on people.kind (e.g., 'customer') */
62
62
  archetypeKind: string;
63
63
  /** Extension table name (e.g., 'clients') in public schema */
64
64
  extensionTable: string;
65
- /** FK column pointing to persons.id (e.g., 'person_id') */
65
+ /** FK column pointing to people.id (e.g., 'person_id') */
66
66
  fkColumn: string;
67
67
  };
68
68
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,eAAe,CAAA;AAC5E,OAAO,EAAuB,KAAK,eAAe,EAAE,MAAM,eAAe,CAAA;AAIzE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA;AAanD,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,MAAM,CAAA;IACjB,YAAY,EAAE,MAAM,CAAA;IACpB,SAAS,EAAE,MAAM,CAAA;IACjB,QAAQ,EAAE,MAAM,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,MAAM,CAAA;IAChB,SAAS,EAAE,MAAM,CAAA;IACjB,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;IAClB,UAAU,EAAE,MAAM,CAAA;CACnB;AAED,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE;QACR,MAAM,CAAC,EAAE,OAAO,CAAA;QAChB,UAAU,CAAC,EAAE,OAAO,CAAA;QACpB,QAAQ,CAAC,EAAE,OAAO,CAAA;KACnB,CAAA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Ref, useEffect } from 'react';
2
- import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, SettingsGroup, ToggleRow, formatCurrency, PersonLink } from '@fayz-ai/saas';
2
+ import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, useLimitGuard, formatCurrency, PersonLink, invalidateLimit } from '@fayz-ai/saas';
3
3
  import { registerTranslations, createSafeDataProvider, useTranslation, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
4
4
  import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, DashboardCanvas, Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetBody, SheetFooter, CurrencyInput, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, ConfirmDialog, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
5
5
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -13,44 +13,47 @@ var CrmContextProvider = ctx.ContextProvider;
13
13
  var useCrmConfig = ctx.useConfig;
14
14
  var useCrmProvider = ctx.useProvider;
15
15
  var useCrmStore = ctx.useStore;
16
+ var CRM_DEFAULTS = {
17
+ autoAssign: false,
18
+ requireSource: true,
19
+ leadScoring: false,
20
+ duplicateDetection: true,
21
+ autoCreateDeal: true,
22
+ requireCloseDate: false,
23
+ rottingDeals: true,
24
+ weightedPipeline: true,
25
+ autoNumberQuotes: true,
26
+ defaultValidity: true,
27
+ requireApproval: false,
28
+ overdueAlerts: true,
29
+ stageChangeAlerts: false,
30
+ newLeadNotif: true
31
+ };
16
32
  function CrmGeneralSettings() {
17
33
  const t2 = useTranslation();
34
+ const s = useTenantPluginSettings("crm", CRM_DEFAULTS);
18
35
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
19
36
  /* @__PURE__ */ jsxs(SettingsGroup, { title: t2("crm.settings.leadManagement"), description: t2("crm.settings.leadManagementDesc"), children: [
20
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoAssign"), description: t2("crm.settings.autoAssignDesc"), checked: false, onChange: () => {
21
- } }),
22
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireSource"), description: t2("crm.settings.requireSourceDesc"), checked: true, onChange: () => {
23
- } }),
24
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.leadScoring"), description: t2("crm.settings.leadScoringDesc"), checked: false, onChange: () => {
25
- } }),
26
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.duplicateDetection"), description: t2("crm.settings.duplicateDetectionDesc"), checked: true, onChange: () => {
27
- } })
37
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoAssign"), description: t2("crm.settings.autoAssignDesc"), checked: s.get("autoAssign"), onChange: (v) => s.set("autoAssign", v) }),
38
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireSource"), description: t2("crm.settings.requireSourceDesc"), checked: s.get("requireSource"), onChange: (v) => s.set("requireSource", v) }),
39
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.leadScoring"), description: t2("crm.settings.leadScoringDesc"), checked: s.get("leadScoring"), onChange: (v) => s.set("leadScoring", v) }),
40
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.duplicateDetection"), description: t2("crm.settings.duplicateDetectionDesc"), checked: s.get("duplicateDetection"), onChange: (v) => s.set("duplicateDetection", v) })
28
41
  ] }),
29
42
  /* @__PURE__ */ jsxs(SettingsGroup, { title: t2("crm.settings.deals"), description: t2("crm.settings.dealsDesc"), children: [
30
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoCreateDeal"), description: t2("crm.settings.autoCreateDealDesc"), checked: true, onChange: () => {
31
- } }),
32
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireCloseDate"), description: t2("crm.settings.requireCloseDateDesc"), checked: false, onChange: () => {
33
- } }),
34
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.rottingDeals"), description: t2("crm.settings.rottingDealsDesc"), checked: true, onChange: () => {
35
- } }),
36
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.weightedPipeline"), description: t2("crm.settings.weightedPipelineDesc"), checked: true, onChange: () => {
37
- } })
43
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoCreateDeal"), description: t2("crm.settings.autoCreateDealDesc"), checked: s.get("autoCreateDeal"), onChange: (v) => s.set("autoCreateDeal", v) }),
44
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireCloseDate"), description: t2("crm.settings.requireCloseDateDesc"), checked: s.get("requireCloseDate"), onChange: (v) => s.set("requireCloseDate", v) }),
45
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.rottingDeals"), description: t2("crm.settings.rottingDealsDesc"), checked: s.get("rottingDeals"), onChange: (v) => s.set("rottingDeals", v) }),
46
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.weightedPipeline"), description: t2("crm.settings.weightedPipelineDesc"), checked: s.get("weightedPipeline"), onChange: (v) => s.set("weightedPipeline", v) })
38
47
  ] }),
39
48
  /* @__PURE__ */ jsxs(SettingsGroup, { title: t2("crm.settings.quotes"), description: t2("crm.settings.quotesDesc"), children: [
40
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoNumberQuotes"), description: t2("crm.settings.autoNumberQuotesDesc"), checked: true, onChange: () => {
41
- } }),
42
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.defaultValidity"), description: t2("crm.settings.defaultValidityDesc"), checked: true, onChange: () => {
43
- } }),
44
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireApproval"), description: t2("crm.settings.requireApprovalDesc"), checked: false, onChange: () => {
45
- } })
49
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.autoNumberQuotes"), description: t2("crm.settings.autoNumberQuotesDesc"), checked: s.get("autoNumberQuotes"), onChange: (v) => s.set("autoNumberQuotes", v) }),
50
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.defaultValidity"), description: t2("crm.settings.defaultValidityDesc"), checked: s.get("defaultValidity"), onChange: (v) => s.set("defaultValidity", v) }),
51
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireApproval"), description: t2("crm.settings.requireApprovalDesc"), checked: s.get("requireApproval"), onChange: (v) => s.set("requireApproval", v) })
46
52
  ] }),
47
53
  /* @__PURE__ */ jsxs(SettingsGroup, { title: t2("crm.settings.notifications"), description: t2("crm.settings.notificationsDesc"), children: [
48
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.overdueAlerts"), description: t2("crm.settings.overdueAlertsDesc"), checked: true, onChange: () => {
49
- } }),
50
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.stageChangeAlerts"), description: t2("crm.settings.stageChangeAlertsDesc"), checked: false, onChange: () => {
51
- } }),
52
- /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.newLeadNotif"), description: t2("crm.settings.newLeadNotifDesc"), checked: true, onChange: () => {
53
- } })
54
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.overdueAlerts"), description: t2("crm.settings.overdueAlertsDesc"), checked: s.get("overdueAlerts"), onChange: (v) => s.set("overdueAlerts", v) }),
55
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.stageChangeAlerts"), description: t2("crm.settings.stageChangeAlertsDesc"), checked: s.get("stageChangeAlerts"), onChange: (v) => s.set("stageChangeAlerts", v) }),
56
+ /* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.newLeadNotif"), description: t2("crm.settings.newLeadNotifDesc"), checked: s.get("newLeadNotif"), onChange: (v) => s.set("newLeadNotif", v) })
54
57
  ] })
55
58
  ] });
56
59
  }
@@ -260,6 +263,23 @@ function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
260
263
  showReject && /* @__PURE__ */ jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
261
264
  ] });
262
265
  }
266
+
267
+ // src/lib/form-answers.tsx
268
+ function humanizeKey(key) {
269
+ const spaced = key.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
270
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
271
+ }
272
+ function renderFieldValue(value) {
273
+ if (value === null || value === void 0 || value === "") return null;
274
+ if (Array.isArray(value)) return value.length ? value.join(", ") : null;
275
+ if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
276
+ if (typeof value === "object") return JSON.stringify(value);
277
+ return String(value);
278
+ }
279
+ function answerEntries(fields) {
280
+ if (!fields || typeof fields !== "object" || Array.isArray(fields)) return [];
281
+ return Object.entries(fields).filter(([, v]) => v !== null && v !== void 0 && v !== "");
282
+ }
263
283
  var TYPE_ICONS = {
264
284
  call: Phone,
265
285
  email: Mail,
@@ -288,6 +308,19 @@ function TabBar({ active, counts, onChange }) {
288
308
  tab.id
289
309
  )) });
290
310
  }
311
+ function FormAnswers({ lead }) {
312
+ const t2 = useTranslation();
313
+ const entries = answerEntries(lead?.metadata?.fields);
314
+ if (entries.length === 0) return null;
315
+ const formId = lead?.metadata?.formId;
316
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
317
+ /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: formId ? `${t2("crm.leadDetail.formAnswers")} \xB7 ${formId}` : t2("crm.leadDetail.formAnswers") }),
318
+ /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: entries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 px-4 py-2.5", children: [
319
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground shrink-0 min-w-24", children: humanizeKey(key) }),
320
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-right flex-1 break-words", children: renderFieldValue(value) ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
321
+ ] }, key)) })
322
+ ] });
323
+ }
291
324
  function OverviewTab({ deal, lead, currency }) {
292
325
  const t2 = useTranslation();
293
326
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase();
@@ -353,6 +386,7 @@ function OverviewTab({ deal, lead, currency }) {
353
386
  ] })
354
387
  ] })
355
388
  ] }),
389
+ /* @__PURE__ */ jsx(FormAnswers, { lead }),
356
390
  deal.tags && deal.tags.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
357
391
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.tags") }),
358
392
  /* @__PURE__ */ jsx("div", { className: "flex gap-1.5 flex-wrap", children: deal.tags.map((tag) => /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) })
@@ -662,6 +696,22 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
662
696
  useEffect(() => {
663
697
  if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id);
664
698
  }, [pipelines]);
699
+ const pipelineId = pipelines[0]?.id;
700
+ useEffect(() => {
701
+ if (!pipelineId) return;
702
+ const supabase = getSupabaseClientOptional();
703
+ if (!supabase) return;
704
+ const channel = supabase.channel(`crm:board:${pipelineId}`).on(
705
+ "postgres_changes",
706
+ { event: "*", schema: "public", table: "plg_crm_deal_extensions" },
707
+ () => {
708
+ void fetchDealsByStage(pipelineId);
709
+ }
710
+ ).subscribe();
711
+ return () => {
712
+ supabase.removeChannel(channel);
713
+ };
714
+ }, [pipelineId]);
665
715
  useEffect(() => {
666
716
  if (savingDealIds.size === 0) setOptimisticBoard(null);
667
717
  }, [dealsByStage, savingDealIds]);
@@ -786,6 +836,24 @@ var columns = [
786
836
  const opt = STATUS_OPTIONS.find((o) => o.value === status);
787
837
  return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${opt?.color ?? "bg-muted text-muted-foreground"}`, children: opt?.label ?? status });
788
838
  }
839
+ },
840
+ {
841
+ // When the lead came in. The list is already sorted by it (provider orders
842
+ // created_at desc) but never showed it, so "is this enquiry from today or
843
+ // from March?" was unanswerable without opening the record.
844
+ accessorKey: "createdAt",
845
+ header: "Entrada",
846
+ cell: ({ getValue }) => {
847
+ const raw = getValue();
848
+ if (!raw) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: "\u2014" });
849
+ const at = new Date(raw);
850
+ if (Number.isNaN(at.getTime())) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground text-xs", children: "\u2014" });
851
+ return /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground text-xs whitespace-nowrap", title: at.toLocaleString(), children: [
852
+ at.toLocaleDateString(void 0, { day: "2-digit", month: "2-digit", year: "2-digit" }),
853
+ " \xB7 ",
854
+ at.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit" })
855
+ ] });
856
+ }
789
857
  }
790
858
  ];
791
859
  function LeadListView({ onNew, onEdit }) {
@@ -828,6 +896,7 @@ function LeadListView({ onNew, onEdit }) {
828
896
  function LeadFormView({ onSaved }) {
829
897
  const t2 = useTranslation();
830
898
  const createLead = useCrmStore((s) => s.createLead);
899
+ const guardLeads = useLimitGuard("leads");
831
900
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
832
901
  const pipelines = useCrmStore((s) => s.pipelines);
833
902
  useEffect(() => {
@@ -844,9 +913,12 @@ function LeadFormView({ onSaved }) {
844
913
  toast.error(t2("common.formIncomplete"));
845
914
  return;
846
915
  }
916
+ if (await guardLeads() === "blocked") return;
847
917
  setSaving(true);
848
918
  try {
849
919
  const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0 });
920
+ invalidateLimit("leads");
921
+ invalidateLimit("deals");
850
922
  onSaved?.(lead.id);
851
923
  } finally {
852
924
  setSaving(false);
@@ -1096,6 +1168,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1096
1168
  const { currency, itemTypes } = config;
1097
1169
  const createQuote = useCrmStore((s) => s.createQuote);
1098
1170
  const updateQuote = useCrmStore((s) => s.updateQuote);
1171
+ const guardQuotes = useLimitGuard("quotes");
1099
1172
  const isEdit = !!quoteId;
1100
1173
  const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId);
1101
1174
  const [linkedLeadId, setLinkedLeadId] = useState(leadId ?? "");
@@ -1174,6 +1247,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1174
1247
  toast.error(t2("crm.quoteForm.errNoItems"));
1175
1248
  return;
1176
1249
  }
1250
+ if (!isEdit && await guardQuotes() === "blocked") return;
1177
1251
  setSaving(true);
1178
1252
  try {
1179
1253
  const input = {
@@ -1199,6 +1273,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1199
1273
  onSaved?.(quoteId);
1200
1274
  } else {
1201
1275
  const created = await createQuote(input);
1276
+ invalidateLimit("quotes");
1202
1277
  onSaved?.(created?.id);
1203
1278
  }
1204
1279
  } finally {
@@ -1717,6 +1792,17 @@ var STATUS_COLORS2 = {
1717
1792
  converted: "bg-warning-soft text-warning-soft-foreground",
1718
1793
  lost: "bg-destructive-soft text-destructive-soft-foreground"
1719
1794
  };
1795
+ function humanizeKey2(key) {
1796
+ const spaced = key.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
1797
+ return spaced.charAt(0).toUpperCase() + spaced.slice(1);
1798
+ }
1799
+ function renderFieldValue2(value) {
1800
+ if (value === null || value === void 0 || value === "") return null;
1801
+ if (Array.isArray(value)) return value.length ? value.join(", ") : null;
1802
+ if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
1803
+ if (typeof value === "object") return JSON.stringify(value);
1804
+ return String(value);
1805
+ }
1720
1806
  function FieldRow({ label, value }) {
1721
1807
  return /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-4 py-3", children: [
1722
1808
  /* @__PURE__ */ jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: label }),
@@ -1813,6 +1899,24 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1813
1899
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.source"), value: lead.sourceName }) })
1814
1900
  ] }) })
1815
1901
  ] }),
1902
+ (() => {
1903
+ const meta = lead.metadata ?? {};
1904
+ const fields = Object.entries(meta.fields ?? {}).filter(([, v]) => renderFieldValue2(v) !== null);
1905
+ const utm = Object.entries(meta.utm ?? {}).filter(([, v]) => renderFieldValue2(v) !== null);
1906
+ if (!fields.length && !utm.length) return null;
1907
+ return /* @__PURE__ */ jsxs("div", { children: [
1908
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.formAnswers") }),
1909
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border bg-card shadow-sm", children: [
1910
+ /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: fields.map(([key, value]) => /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: humanizeKey2(key), value: renderFieldValue2(value) }) }, key)) }),
1911
+ utm.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1", children: utm.map(([key, value]) => /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
1912
+ humanizeKey2(key.replace(/^utm_/, "")),
1913
+ ":",
1914
+ " ",
1915
+ /* @__PURE__ */ jsx("span", { className: "text-foreground", children: renderFieldValue2(value) })
1916
+ ] }, key)) })
1917
+ ] })
1918
+ ] });
1919
+ })(),
1816
1920
  deal && /* @__PURE__ */ jsxs("div", { children: [
1817
1921
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.pipeline") }),
1818
1922
  /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
@@ -2775,6 +2879,17 @@ function createMockCrmProvider(options) {
2775
2879
  return provider;
2776
2880
  }
2777
2881
 
2882
+ // src/data/tables.ts
2883
+ var T = {
2884
+ activities: "plg_crm_activities",
2885
+ tags: "plg_crm_tags",
2886
+ activityTypes: "plg_crm_activity_types",
2887
+ pipelines: "plg_crm_pipelines",
2888
+ pipelineStages: "plg_crm_pipeline_stages",
2889
+ dealExtensions: "plg_crm_deal_extensions",
2890
+ leadSources: "plg_crm_lead_sources"
2891
+ };
2892
+
2778
2893
  // src/data/supabase.ts
2779
2894
  function getTenantId() {
2780
2895
  return getActiveTenantId();
@@ -2789,19 +2904,25 @@ function snakeToCamel(obj) {
2789
2904
  function getClients() {
2790
2905
  const supabase = getSupabaseClientOptional();
2791
2906
  if (!supabase) throw new Error("Supabase not initialized");
2792
- return { core: supabase.schema("saas_core"), pub: supabase };
2907
+ return { core: supabase, pub: supabase };
2908
+ }
2909
+ async function mergePersonMetadata(personId, patch) {
2910
+ const { core } = getClients();
2911
+ const { data: row } = await core.from("people").select("metadata").eq("id", personId).maybeSingle();
2912
+ const current = row?.metadata ?? {};
2913
+ await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
2793
2914
  }
2794
2915
  function createSupabaseCrmProvider(options) {
2795
2916
  const provider = {
2796
- // --- Pipelines (public.pipelines + pipeline_stages) ---
2917
+ // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
2797
2918
  async getPipelines() {
2798
2919
  const { pub } = getClients();
2799
- const { data } = await pub.from("pipelines").select("*").eq("is_active", true).order("name");
2920
+ const { data } = await pub.from(T.pipelines).select("*").eq("is_active", true).order("name");
2800
2921
  return (data ?? []).map((r) => snakeToCamel(r));
2801
2922
  },
2802
2923
  async getPipelineStages(pipelineId) {
2803
2924
  const { pub } = getClients();
2804
- const { data } = await pub.from("pipeline_stages").select("*").eq("pipeline_id", pipelineId).order("order");
2925
+ const { data } = await pub.from(T.pipelineStages).select("*").eq("pipeline_id", pipelineId).order("order");
2805
2926
  return (data ?? []).map((r) => snakeToCamel(r));
2806
2927
  },
2807
2928
  // --- Leads (via view — single query) ---
@@ -2849,8 +2970,16 @@ function createSupabaseCrmProvider(options) {
2849
2970
  phone: r.phone,
2850
2971
  company: r.company,
2851
2972
  status: r.lead_status ?? "new",
2973
+ sourceName: r.source_name,
2852
2974
  tags: r.tags ?? [],
2853
2975
  notes: r.notes,
2976
+ // Answers from a public form. Kept as an opaque bag so a new landing
2977
+ // page needs no schema change; the detail view renders whatever is here.
2978
+ metadata: {
2979
+ formId: r.form_id ?? void 0,
2980
+ fields: r.custom_fields ?? {},
2981
+ utm: r.utm ?? {}
2982
+ },
2854
2983
  tenantId: r.tenant_id,
2855
2984
  createdAt: r.created_at,
2856
2985
  updatedAt: r.updated_at
@@ -2859,7 +2988,7 @@ function createSupabaseCrmProvider(options) {
2859
2988
  async createLead(input) {
2860
2989
  const { core } = getClients();
2861
2990
  const tenantId = getTenantId();
2862
- const { data, error } = await core.from("persons").insert({
2991
+ const { data, error } = await core.from("people").insert({
2863
2992
  tenant_id: tenantId,
2864
2993
  kind: "lead",
2865
2994
  name: input.name,
@@ -2881,14 +3010,14 @@ function createSupabaseCrmProvider(options) {
2881
3010
  if (partial.email !== void 0) row.email = partial.email;
2882
3011
  if (partial.phone !== void 0) row.phone = partial.phone;
2883
3012
  if (partial.notes !== void 0) row.notes = partial.notes;
2884
- if (partial.status) row.metadata = { status: partial.status };
2885
- const { data, error } = await core.from("persons").update(row).eq("id", id).select().single();
3013
+ const { error } = await core.from("people").update(row).eq("id", id).select().single();
2886
3014
  if (error) throw new Error(error.message);
3015
+ if (partial.status) await mergePersonMetadata(id, { status: partial.status });
2887
3016
  return await provider.getLeadById(id);
2888
3017
  },
2889
3018
  async convertLeadToDeal(leadId, dealInput) {
2890
- const { core } = getClients();
2891
- await core.from("persons").update({ metadata: { status: "converted" } }).eq("id", leadId);
3019
+ getClients();
3020
+ await mergePersonMetadata(leadId, { status: "converted" });
2892
3021
  return provider.createDeal({ ...dealInput, leadId });
2893
3022
  },
2894
3023
  // --- Deals (via view — single query with all joins) ---
@@ -2946,6 +3075,11 @@ function createSupabaseCrmProvider(options) {
2946
3075
  status: r.status ?? "open",
2947
3076
  contactName: r.contact_name,
2948
3077
  tags: r.tags ?? [],
3078
+ // v_deals exposes de.lead_id and Deal declares leadId, but the mapping
3079
+ // dropped it — so DealSidebar's `if (d?.leadId)` never fired and the
3080
+ // card opened blank: no contact, no form answers. For a card that came
3081
+ // from a form, the lead IS the content.
3082
+ leadId: r.lead_id ?? void 0,
2949
3083
  tenantId: r.tenant_id,
2950
3084
  createdAt: r.created_at,
2951
3085
  updatedAt: r.updated_at
@@ -2967,6 +3101,7 @@ function createSupabaseCrmProvider(options) {
2967
3101
  status: r.status ?? "open",
2968
3102
  contactName: r.contact_name,
2969
3103
  tags: r.tags ?? [],
3104
+ leadId: r.lead_id ?? void 0,
2970
3105
  tenantId: r.tenant_id,
2971
3106
  createdAt: r.created_at,
2972
3107
  updatedAt: r.updated_at
@@ -2995,7 +3130,7 @@ function createSupabaseCrmProvider(options) {
2995
3130
  metadata: { contactName: input.contactName }
2996
3131
  }).select().single();
2997
3132
  if (error) throw new Error(error.message);
2998
- await pub.from("deal_extensions").insert({
3133
+ await pub.from(T.dealExtensions).insert({
2999
3134
  order_id: order.id,
3000
3135
  tenant_id: tenantId,
3001
3136
  pipeline_id: input.pipelineId,
@@ -3033,14 +3168,14 @@ function createSupabaseCrmProvider(options) {
3033
3168
  if (partial.stageId) row.stage_id = partial.stageId;
3034
3169
  if (partial.probability != null) row.probability = partial.probability;
3035
3170
  if (partial.expectedCloseDate) row.expected_close_date = partial.expectedCloseDate;
3036
- await pub.from("deal_extensions").update(row).eq("order_id", id);
3171
+ await pub.from(T.dealExtensions).update(row).eq("order_id", id);
3037
3172
  }
3038
3173
  return await provider.getDealById(id);
3039
3174
  },
3040
3175
  async moveDealToStage(dealId, stageId) {
3041
3176
  const { core, pub } = getClients();
3042
- const { data: stageRow } = await pub.from("pipeline_stages").select("*").eq("id", stageId).single();
3043
- await pub.from("deal_extensions").update({
3177
+ const { data: stageRow } = await pub.from(T.pipelineStages).select("*").eq("id", stageId).single();
3178
+ await pub.from(T.dealExtensions).update({
3044
3179
  stage_id: stageId,
3045
3180
  probability: stageRow?.probability ?? 0
3046
3181
  }).eq("order_id", dealId);
@@ -3059,10 +3194,10 @@ function createSupabaseCrmProvider(options) {
3059
3194
  tenantId: stageRow.tenant_id,
3060
3195
  createdAt: stageRow.created_at
3061
3196
  };
3062
- const { data: ext } = await pub.from("deal_extensions").select("lead_id").eq("order_id", dealId).single();
3197
+ const { data: ext } = await pub.from(T.dealExtensions).select("lead_id").eq("order_id", dealId).single();
3063
3198
  if (ext?.lead_id) {
3064
3199
  const newLeadStatus = deriveLeadStatus(typedStage);
3065
- await core.from("persons").update({ metadata: { status: newLeadStatus } }).eq("id", ext.lead_id);
3200
+ await mergePersonMetadata(ext.lead_id, { status: newLeadStatus });
3066
3201
  }
3067
3202
  const { data: quotes } = await core.from("orders").select("id, status").eq("kind", "quote");
3068
3203
  for (const q of quotes ?? []) {
@@ -3077,10 +3212,10 @@ function createSupabaseCrmProvider(options) {
3077
3212
  }
3078
3213
  return await provider.getDealById(dealId);
3079
3214
  },
3080
- // --- Activities (public.crm_activities) ---
3215
+ // --- Activities (public.plg_crm_activities) ---
3081
3216
  async getActivities(query) {
3082
3217
  const { pub } = getClients();
3083
- let qb = pub.from("crm_activities").select("*", { count: "exact" });
3218
+ let qb = pub.from(T.activities).select("*", { count: "exact" });
3084
3219
  if (query.dealId) qb = qb.eq("deal_id", query.dealId);
3085
3220
  if (query.leadId) qb = qb.eq("lead_id", query.leadId);
3086
3221
  if (query.activityType) qb = qb.eq("activity_type", query.activityType);
@@ -3095,7 +3230,7 @@ function createSupabaseCrmProvider(options) {
3095
3230
  async createActivity(input) {
3096
3231
  const { pub } = getClients();
3097
3232
  const tenantId = getTenantId();
3098
- const { data, error } = await pub.from("crm_activities").insert({
3233
+ const { data, error } = await pub.from(T.activities).insert({
3099
3234
  tenant_id: tenantId,
3100
3235
  deal_id: input.dealId,
3101
3236
  lead_id: input.leadId,
@@ -3111,11 +3246,11 @@ function createSupabaseCrmProvider(options) {
3111
3246
  },
3112
3247
  async completeActivity(id) {
3113
3248
  const { pub } = getClients();
3114
- const { data, error } = await pub.from("crm_activities").update({ completed_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
3249
+ const { data, error } = await pub.from(T.activities).update({ completed_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
3115
3250
  if (error) throw new Error(error.message);
3116
3251
  return snakeToCamel(data);
3117
3252
  },
3118
- // --- Quotes (saas_core.orders kind='quote' + order_items) ---
3253
+ // --- Quotes (public.orders kind='quote' + order_items) ---
3119
3254
  async getQuotes(query) {
3120
3255
  const { core } = getClients();
3121
3256
  let qb = core.from("orders").select("*", { count: "exact" }).eq("kind", "quote");
@@ -3314,11 +3449,11 @@ function createSupabaseCrmProvider(options) {
3314
3449
  const personToConvert = quote.leadId ?? quote.contactId;
3315
3450
  if (personToConvert) {
3316
3451
  const clientKind = options?.clientConversion?.archetypeKind ?? "client";
3317
- const { data: person } = await core.from("persons").select("kind, name, email, phone, tenant_id, metadata").eq("id", personToConvert).single();
3452
+ const { data: person } = await core.from("people").select("kind, name, email, phone, tenant_id, metadata").eq("id", personToConvert).single();
3318
3453
  const personKind = person?.kind;
3319
3454
  if (person && (personKind === "lead" || personKind === "contact")) {
3320
3455
  const personMeta = person?.metadata ?? {};
3321
- await core.from("persons").update({
3456
+ await core.from("people").update({
3322
3457
  kind: clientKind,
3323
3458
  metadata: { ...personMeta, convertedFromLead: true }
3324
3459
  }).eq("id", personToConvert);
@@ -3382,7 +3517,7 @@ function createSupabaseCrmProvider(options) {
3382
3517
  },
3383
3518
  async getDealByLeadId(leadId) {
3384
3519
  const { pub } = getClients();
3385
- const { data } = await pub.from("deal_extensions").select("order_id").eq("lead_id", leadId).limit(1);
3520
+ const { data } = await pub.from(T.dealExtensions).select("order_id").eq("lead_id", leadId).limit(1);
3386
3521
  if (!data || data.length === 0) return null;
3387
3522
  return provider.getDealById(data[0].order_id);
3388
3523
  },
@@ -3391,16 +3526,16 @@ function createSupabaseCrmProvider(options) {
3391
3526
  const { core, pub } = getClients();
3392
3527
  const monthStart = (/* @__PURE__ */ new Date()).toISOString().slice(0, 7) + "-01";
3393
3528
  const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
3394
- const { count: totalLeads } = await core.from("persons").select("*", { count: "exact", head: true }).eq("kind", "lead");
3395
- const { count: newLeads } = await core.from("persons").select("*", { count: "exact", head: true }).eq("kind", "lead").gte("created_at", monthStart);
3529
+ const { count: totalLeads } = await core.from("people").select("*", { count: "exact", head: true }).eq("kind", "lead");
3530
+ const { count: newLeads } = await core.from("people").select("*", { count: "exact", head: true }).eq("kind", "lead").gte("created_at", monthStart);
3396
3531
  const { data: deals } = await core.from("orders").select("status, total, updated_at").eq("kind", "deal");
3397
3532
  const allDeals = deals ?? [];
3398
3533
  const openDeals = allDeals.filter((d) => d.status === "open");
3399
3534
  const wonDeals = allDeals.filter((d) => d.status === "won");
3400
3535
  const wonThisMonth = wonDeals.filter((d) => d.updated_at >= monthStart);
3401
3536
  const convertedLeads = allDeals.length;
3402
- const { count: pendingActs } = await pub.from("crm_activities").select("*", { count: "exact", head: true }).is("completed_at", null);
3403
- const { count: overdueActs } = await pub.from("crm_activities").select("*", { count: "exact", head: true }).is("completed_at", null).lt("due_date", today2);
3537
+ const { count: pendingActs } = await pub.from(T.activities).select("*", { count: "exact", head: true }).is("completed_at", null);
3538
+ const { count: overdueActs } = await pub.from(T.activities).select("*", { count: "exact", head: true }).is("completed_at", null).lt("due_date", today2);
3404
3539
  return {
3405
3540
  totalLeads: totalLeads ?? 0,
3406
3541
  newLeadsThisMonth: newLeads ?? 0,
@@ -3742,7 +3877,7 @@ var leadSourceEntity = {
3742
3877
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3743
3878
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3744
3879
  ],
3745
- data: { table: "lead_sources", tenantScoped: true }
3880
+ data: { table: T.leadSources, tenantScoped: true }
3746
3881
  };
3747
3882
  var tagEntity = {
3748
3883
  name: "Tag",
@@ -3755,7 +3890,7 @@ var tagEntity = {
3755
3890
  { key: "color", label: "Color", type: "color", showInTable: true, defaultValue: "#6366f1" },
3756
3891
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3757
3892
  ],
3758
- data: { table: "crm_tags", tenantScoped: true }
3893
+ data: { table: T.tags, tenantScoped: true }
3759
3894
  };
3760
3895
  var pipelineStageEntity = {
3761
3896
  name: "Stage",
@@ -3769,7 +3904,7 @@ var pipelineStageEntity = {
3769
3904
  key: "pipelineId",
3770
3905
  label: "Pipeline",
3771
3906
  type: "relation",
3772
- relation: { table: "pipelines", labelField: "name" },
3907
+ relation: { table: T.pipelines, labelField: "name" },
3773
3908
  required: true,
3774
3909
  showInTable: true
3775
3910
  },
@@ -3779,7 +3914,7 @@ var pipelineStageEntity = {
3779
3914
  { key: "isWon", label: "Won Stage", type: "boolean", showInTable: true, defaultValue: false },
3780
3915
  { key: "isLost", label: "Lost Stage", type: "boolean", showInTable: true, defaultValue: false }
3781
3916
  ],
3782
- data: { table: "pipeline_stages", tenantScoped: true }
3917
+ data: { table: T.pipelineStages, tenantScoped: true }
3783
3918
  };
3784
3919
  var activityTypeEntity = {
3785
3920
  name: "Activity Type",
@@ -3791,7 +3926,7 @@ var activityTypeEntity = {
3791
3926
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3792
3927
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3793
3928
  ],
3794
- data: { table: "crm_activity_types", tenantScoped: true }
3929
+ data: { table: T.activityTypes, tenantScoped: true }
3795
3930
  };
3796
3931
  var crmRegistries = [
3797
3932
  {
@@ -3913,6 +4048,7 @@ var en = {
3913
4048
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
3914
4049
  "crm.leadDetail.assignedTo": "Assigned to",
3915
4050
  "crm.leadDetail.backToList": "Back to list",
4051
+ "crm.leadDetail.formAnswers": "Form answers",
3916
4052
  "crm.leadDetail.company": "Company",
3917
4053
  "crm.leadDetail.contactInfo": "Contact Information",
3918
4054
  "crm.leadDetail.createQuote": "Create Quote",
@@ -4206,6 +4342,7 @@ var ptBR = {
4206
4342
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
4207
4343
  "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
4208
4344
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
4345
+ "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
4209
4346
  "crm.leadDetail.company": "Empresa",
4210
4347
  "crm.leadDetail.contactInfo": "Informa\xE7\xF5es de Contato",
4211
4348
  "crm.leadDetail.createQuote": "Criar Or\xE7amento",
@@ -4498,6 +4635,9 @@ function createCrmPlugin(options) {
4498
4635
  version: "1.0.0",
4499
4636
  scope: options?.scope ?? "universal",
4500
4637
  verticalId: options?.verticalId,
4638
+ // Sales-pipeline/lead-management is a business-ops tool — targets the
4639
+ // saas/admin Panel world, not the ecommerce storefront.
4640
+ scaffolds: ["saas"],
4501
4641
  defaultEnabled: true,
4502
4642
  dependencies: [],
4503
4643
  declaredFeatures: [
@@ -4506,6 +4646,15 @@ function createCrmPlugin(options) {
4506
4646
  { id: "crm.quotes", label: config.labels.quotes, group: config.labels.pageTitle },
4507
4647
  { id: "crm.pipeline", label: config.labels.pipeline, group: config.labels.pageTitle }
4508
4648
  ],
4649
+ // Stock quantity caps. leads/deals/quotes share core tables partitioned by
4650
+ // `kind` (people/orders), so each declaration carries a kindFilter. A lead
4651
+ // create auto-spawns a deal, so the lead guard also gates deal creation;
4652
+ // `deals` has no standalone create UI (declared for usage banners/counts).
4653
+ declaredLimits: [
4654
+ { key: "leads", label: "Leads", table: "people", kindFilter: "lead" },
4655
+ { key: "deals", label: "Deals", table: "orders", kindFilter: "deal" },
4656
+ { key: "quotes", label: "Quotes", table: "orders", kindFilter: "quote" }
4657
+ ],
4509
4658
  navigation: [
4510
4659
  {
4511
4660
  section: options?.navSection ?? "main",