@fayz-ai/plugin-crm 0.8.3 → 0.8.5

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 (84) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/BoardFilters.d.ts +23 -0
  3. package/dist/components/BoardFilters.d.ts.map +1 -0
  4. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  5. package/dist/components/TagChips.d.ts +16 -0
  6. package/dist/components/TagChips.d.ts.map +1 -0
  7. package/dist/data/mock.d.ts +5 -0
  8. package/dist/data/mock.d.ts.map +1 -1
  9. package/dist/data/supabase.d.ts +6 -0
  10. package/dist/data/supabase.d.ts.map +1 -1
  11. package/dist/data/types.d.ts +12 -2
  12. package/dist/data/types.d.ts.map +1 -1
  13. package/dist/index.d.ts +3 -0
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1136 -164
  16. package/dist/index.js.map +1 -1
  17. package/dist/lib/access.d.ts +8 -0
  18. package/dist/lib/access.d.ts.map +1 -0
  19. package/dist/locales/en.d.ts.map +1 -1
  20. package/dist/locales/pt-BR.d.ts.map +1 -1
  21. package/dist/migrations/index.d.ts +9 -1
  22. package/dist/migrations/index.d.ts.map +1 -1
  23. package/dist/public/context.d.ts +3 -3
  24. package/dist/public/context.d.ts.map +1 -1
  25. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  26. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  27. package/dist/public/data.supabase.d.ts.map +1 -1
  28. package/dist/public/index.js +31 -7
  29. package/dist/public/index.js.map +1 -1
  30. package/dist/public/types.d.ts +27 -0
  31. package/dist/public/types.d.ts.map +1 -1
  32. package/dist/registries.d.ts +11 -0
  33. package/dist/registries.d.ts.map +1 -1
  34. package/dist/store.d.ts +12 -2
  35. package/dist/store.d.ts.map +1 -1
  36. package/dist/types.d.ts +51 -2
  37. package/dist/types.d.ts.map +1 -1
  38. package/dist/views/ActivityListView.d.ts +6 -1
  39. package/dist/views/ActivityListView.d.ts.map +1 -1
  40. package/dist/views/DealSidebar.d.ts.map +1 -1
  41. package/dist/views/LeadDetailView.d.ts.map +1 -1
  42. package/dist/views/PipelineView.d.ts.map +1 -1
  43. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  44. package/dist/views/QuoteListView.d.ts.map +1 -1
  45. package/package.json +15 -14
  46. package/src/CrmPage.tsx +1 -1
  47. package/src/cascade.ts +2 -0
  48. package/src/components/BoardFilters.tsx +190 -0
  49. package/src/components/QuoteStatusDropdown.tsx +15 -3
  50. package/src/components/TagChips.tsx +80 -0
  51. package/src/data/mock.ts +140 -7
  52. package/src/data/supabase.ts +256 -11
  53. package/src/data/types.ts +14 -3
  54. package/src/index.ts +179 -3
  55. package/src/lib/access.ts +11 -0
  56. package/src/locales/en.ts +13 -0
  57. package/src/locales/pt-BR.ts +18 -5
  58. package/src/migrations/003_crm_views_rls.sql +10 -2
  59. package/src/migrations/007_activity_log.sql +55 -0
  60. package/src/migrations/008_view_field_aliases.sql +43 -0
  61. package/src/migrations/009_deal_archived_status.sql +30 -0
  62. package/src/migrations/010_quote_archived_status.sql +40 -0
  63. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  64. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  65. package/src/migrations/013_tag_slugs.sql +177 -0
  66. package/src/migrations/014_public_lead_tags.sql +172 -0
  67. package/src/migrations/index.ts +833 -3
  68. package/src/public/context.tsx +4 -4
  69. package/src/public/createPublicFormsPlugin.ts +72 -2
  70. package/src/public/data.supabase.ts +3 -2
  71. package/src/public/types.ts +28 -0
  72. package/src/registries.ts +44 -11
  73. package/src/store.ts +135 -38
  74. package/src/types.ts +59 -2
  75. package/src/views/ActivityListView.tsx +79 -11
  76. package/src/views/DealSidebar.tsx +48 -39
  77. package/src/views/LeadDetailView.tsx +29 -10
  78. package/src/views/PipelineView.tsx +112 -11
  79. package/src/views/QuoteDetailView.tsx +7 -3
  80. package/src/views/QuoteListView.tsx +26 -12
  81. package/dist/index.cjs +0 -4759
  82. package/dist/index.cjs.map +0 -1
  83. package/dist/public/index.cjs +0 -306
  84. package/dist/public/index.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import React14, { useState, useMemo, useRef, useEffect } from 'react';
2
- import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, useLimitGuard, formatCurrency, PersonLink, invalidateLimit } from '@fayz-ai/saas';
3
- import { registerTranslations, createSafeDataProvider, useTranslation, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
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
- import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
6
- import { Filter, Globe, Target, Check, ChevronRight, UserPlus, Plus, FileText, MessageCircle, CheckSquare, Users, Mail, Phone, Clock, Calendar, Send, ChevronDown, Printer, X, Pencil, User, Hash, CircleCheckBig, ArrowRight, Ban, Trash2, CircleAlert, CircleDashed, Loader2, DollarSign } from 'lucide-react';
1
+ import React15, { useState, useMemo, useRef, useEffect } from 'react';
2
+ import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, useLimitGuard, formatCurrency, PersonLink, useAccessOptional, invalidateLimit } from '@fayz-ai/saas';
3
+ import { registerTranslations, createSafeDataProvider, useTranslation, useActiveTenantId, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
4
+ import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, DashboardCanvas, SegmentedControl, 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
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
6
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, MoveRight, Target, ArrowRightLeft, UserPlus, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight, Plus, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, User, Hash, CircleCheckBig, Ban, Tag, Trash2, Receipt, CircleAlert, CircleDashed, Loader2, DollarSign } from 'lucide-react';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
9
9
 
@@ -95,19 +95,28 @@ function CrmOnboarding({ onComplete }) {
95
95
  function DashboardView() {
96
96
  return /* @__PURE__ */ jsx(DashboardCanvas, { surface: "plugin-home", domain: "crm", showHeader: false, className: "space-y-6" });
97
97
  }
98
+ function useCanArchive() {
99
+ return useAccessOptional().can("sales", "delete").allowed;
100
+ }
98
101
  var STATUS_CONFIG = {
99
102
  draft: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: CircleDashed, label: "Draft" },
100
103
  sent: { bg: "bg-info-soft text-info-soft-foreground", dot: "bg-info", icon: Send, label: "Sent" },
101
104
  approved: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: CircleCheckBig, label: "Approved" },
102
105
  rejected: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Ban, label: "Rejected" },
103
- expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: CircleAlert, label: "Expired" }
106
+ expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: CircleAlert, label: "Expired" },
107
+ archived: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: Archive, label: "Archived" },
108
+ invoiced: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: "Invoiced" },
109
+ paid: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: Receipt, label: "Paid" },
110
+ partial: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: "Partial" },
111
+ overdue: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Receipt, label: "Overdue" }
104
112
  };
105
113
  var TRANSITIONS = {
106
114
  draft: ["sent", "expired"],
107
115
  sent: ["approved", "rejected", "expired"],
108
116
  approved: [],
109
117
  rejected: [],
110
- expired: []
118
+ expired: [],
119
+ archived: []
111
120
  };
112
121
  function RejectModal({ onConfirm, onCancel }) {
113
122
  const [reason, setReason] = useState("");
@@ -263,6 +272,46 @@ function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
263
272
  showReject && /* @__PURE__ */ jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
264
273
  ] });
265
274
  }
275
+ function humanizeTag(slug) {
276
+ return slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
277
+ }
278
+ function chipStyle(color) {
279
+ if (!color || !/^#[0-9a-f]{6}$/i.test(color)) return void 0;
280
+ return { backgroundColor: `${color}1f`, color, borderColor: `${color}59` };
281
+ }
282
+ function TagChips({ tags, defs, max, size = "xs", className }) {
283
+ if (!tags?.length) return null;
284
+ const shown = max ? tags.slice(0, max) : tags;
285
+ const hidden = max ? tags.length - shown.length : 0;
286
+ const text = size === "xs" ? "text-[9px] px-1.5 py-px" : "text-[10px] px-2 py-0.5";
287
+ return /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-1 ${className ?? ""}`, children: [
288
+ shown.map((slug) => {
289
+ const def = defs?.get(slug);
290
+ const style = chipStyle(def?.color);
291
+ return /* @__PURE__ */ jsx(
292
+ "span",
293
+ {
294
+ title: def?.name ?? humanizeTag(slug),
295
+ className: `inline-flex max-w-[10rem] items-center truncate rounded-full border font-medium ${text} ${style ? "" : "border-border bg-muted text-muted-foreground"}`,
296
+ style,
297
+ children: def?.name ?? humanizeTag(slug)
298
+ },
299
+ slug
300
+ );
301
+ }),
302
+ hidden > 0 && /* @__PURE__ */ jsxs(
303
+ "span",
304
+ {
305
+ title: tags.slice(shown.length).map((s) => defs?.get(s)?.name ?? humanizeTag(s)).join(", "),
306
+ className: `inline-flex items-center rounded-full border border-border bg-muted font-medium text-muted-foreground ${text}`,
307
+ children: [
308
+ "+",
309
+ hidden
310
+ ]
311
+ }
312
+ )
313
+ ] });
314
+ }
266
315
 
267
316
  // src/lib/form-answers.tsx
268
317
  function humanizeKey(key) {
@@ -286,27 +335,40 @@ var TYPE_ICONS = {
286
335
  meeting: Users,
287
336
  note: FileText,
288
337
  task: CheckSquare,
289
- whatsapp: MessageCircle
338
+ whatsapp: MessageCircle,
339
+ // System timeline events (auto-logged by the provider)
340
+ lead_created: UserPlus,
341
+ lead_converted: ArrowRightLeft,
342
+ deal_created: Target,
343
+ stage_changed: MoveRight,
344
+ deal_won: Trophy,
345
+ deal_lost: XCircle,
346
+ quote_created: FilePlus2,
347
+ quote_sent: Send,
348
+ quote_approved: FileCheck2,
349
+ quote_rejected: FileX2,
350
+ lead_archived: Archive,
351
+ deal_archived: Archive,
352
+ quote_archived: Archive
290
353
  };
291
354
  function TabBar({ active, counts, onChange }) {
292
355
  const t2 = useTranslation();
293
- const tabs = [
294
- { id: "overview", label: t2("crm.dealSidebar.overview") },
295
- { id: "activity", label: t2("crm.dealSidebar.activity"), count: counts.activity },
296
- { id: "quotes", label: t2("crm.dealSidebar.quotes"), count: counts.quotes }
297
- ];
298
- return /* @__PURE__ */ jsx("div", { className: "flex items-center gap-0.5 px-5 py-2 border-b shrink-0 bg-muted/20", children: tabs.map((tab) => /* @__PURE__ */ jsxs(
299
- "button",
356
+ const label = (text, count, isActive) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
357
+ text,
358
+ count != null && count > 0 && /* @__PURE__ */ jsx("span", { className: `inline-flex items-center justify-center min-w-[16px] h-4 rounded-full px-1 text-[10px] font-semibold ${isActive ? "bg-background/20 text-background" : "bg-muted text-muted-foreground"}`, children: count })
359
+ ] });
360
+ return /* @__PURE__ */ jsx("div", { className: "px-5 py-2 border-b shrink-0", children: /* @__PURE__ */ jsx(
361
+ SegmentedControl,
300
362
  {
301
- onClick: () => onChange(tab.id),
302
- className: `relative px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${active === tab.id ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
303
- children: [
304
- tab.label,
305
- tab.count != null && tab.count > 0 && /* @__PURE__ */ jsx("span", { className: `ml-1 inline-flex items-center justify-center min-w-[16px] h-4 rounded-full px-1 text-[10px] font-semibold ${active === tab.id ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`, children: tab.count })
363
+ value: active,
364
+ onChange,
365
+ options: [
366
+ { value: "overview", label: label(t2("crm.dealSidebar.overview"), void 0, active === "overview") },
367
+ { value: "activity", label: label(t2("crm.dealSidebar.activity"), counts.activity, active === "activity") },
368
+ { value: "quotes", label: label(t2("crm.dealSidebar.quotes"), counts.quotes, active === "quotes") }
306
369
  ]
307
- },
308
- tab.id
309
- )) });
370
+ }
371
+ ) });
310
372
  }
311
373
  function FormAnswers({ lead }) {
312
374
  const t2 = useTranslation();
@@ -324,6 +386,11 @@ function FormAnswers({ lead }) {
324
386
  function OverviewTab({ deal, lead, currency }) {
325
387
  const t2 = useTranslation();
326
388
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase();
389
+ const tagDefs = useCrmStore((s) => s.tagDefs);
390
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
391
+ useEffect(() => {
392
+ fetchTagDefs();
393
+ }, []);
327
394
  return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
328
395
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
329
396
  /* @__PURE__ */ jsx("div", { className: "flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary text-xl font-bold", children: initial }),
@@ -389,23 +456,11 @@ function OverviewTab({ deal, lead, currency }) {
389
456
  /* @__PURE__ */ jsx(FormAnswers, { lead }),
390
457
  deal.tags && deal.tags.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
391
458
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.tags") }),
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)) })
459
+ /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, size: "sm", className: "gap-1.5" })
393
460
  ] }),
394
461
  deal.notes && deal.notes !== deal.title && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
395
462
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
396
463
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed", children: deal.notes })
397
- ] }),
398
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-4 pt-3 border-t text-[10px] text-muted-foreground", children: [
399
- /* @__PURE__ */ jsxs("span", { children: [
400
- t2("crm.dealSidebar.created"),
401
- " ",
402
- deal.createdAt?.slice(0, 10)
403
- ] }),
404
- deal.updatedAt && /* @__PURE__ */ jsxs("span", { children: [
405
- t2("crm.dealSidebar.updated"),
406
- " ",
407
- deal.updatedAt?.slice(0, 10)
408
- ] })
409
464
  ] })
410
465
  ] });
411
466
  }
@@ -557,6 +612,12 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
557
612
  onClose();
558
613
  }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
559
614
  ] }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.dealNotFound") }) }) }),
615
+ deal && /* @__PURE__ */ jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
616
+ t2("crm.dealSidebar.created"),
617
+ " ",
618
+ deal.createdAt?.slice(0, 10),
619
+ deal.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${deal.updatedAt.slice(0, 10)}` : ""
620
+ ] }),
560
621
  deal && lead && onViewLead && /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsxs(
561
622
  "button",
562
623
  {
@@ -574,6 +635,145 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
574
635
  ) })
575
636
  ] }) });
576
637
  }
638
+ function periodToRange(period, customFrom, customTo) {
639
+ if (period === "all") return {};
640
+ if (period === "24h") {
641
+ return { createdFrom: new Date(Date.now() - 24 * 60 * 60 * 1e3).toISOString() };
642
+ }
643
+ if (period === "7d") {
644
+ return { createdFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3).toISOString() };
645
+ }
646
+ return {
647
+ ...customFrom ? { createdFrom: (/* @__PURE__ */ new Date(`${customFrom}T00:00:00`)).toISOString() } : {},
648
+ ...customTo ? { createdTo: (/* @__PURE__ */ new Date(`${customTo}T23:59:59.999`)).toISOString() } : {}
649
+ };
650
+ }
651
+ function BoardFilters({
652
+ period,
653
+ onPeriodChange,
654
+ customFrom,
655
+ customTo,
656
+ onCustomChange,
657
+ selectedTags,
658
+ onTagsChange,
659
+ tagDefs,
660
+ availableTags,
661
+ className
662
+ }) {
663
+ const t2 = useTranslation();
664
+ const [tagsOpen, setTagsOpen] = useState(false);
665
+ const tagsRef = useRef(null);
666
+ useEffect(() => {
667
+ if (!tagsOpen) return;
668
+ const onDown = (e) => {
669
+ if (!tagsRef.current?.contains(e.target)) setTagsOpen(false);
670
+ };
671
+ document.addEventListener("mousedown", onDown);
672
+ return () => document.removeEventListener("mousedown", onDown);
673
+ }, [tagsOpen]);
674
+ const options = useMemo(() => {
675
+ const all = /* @__PURE__ */ new Set([...availableTags, ...selectedTags]);
676
+ return [...all].sort(
677
+ (a, b) => (tagDefs.get(a)?.name ?? humanizeTag(a)).localeCompare(tagDefs.get(b)?.name ?? humanizeTag(b))
678
+ );
679
+ }, [availableTags, selectedTags, tagDefs]);
680
+ const toggle = (slug) => {
681
+ onTagsChange(
682
+ selectedTags.includes(slug) ? selectedTags.filter((s) => s !== slug) : [...selectedTags, slug]
683
+ );
684
+ };
685
+ return /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-2 ${className ?? ""}`, children: [
686
+ /* @__PURE__ */ jsx(
687
+ SegmentedControl,
688
+ {
689
+ options: [
690
+ { value: "all", label: t2("crm.filters.periodAll") },
691
+ { value: "24h", label: t2("crm.filters.period24h") },
692
+ { value: "7d", label: t2("crm.filters.period7d") },
693
+ { value: "custom", label: t2("crm.filters.periodCustom") }
694
+ ],
695
+ value: period,
696
+ onChange: onPeriodChange,
697
+ "aria-label": t2("crm.filters.period")
698
+ }
699
+ ),
700
+ period === "custom" && // As duas pontas usam a MESMA chrome do segmentado ao lado (variant
701
+ // toolbar), com a seta ligando uma à outra — antes eram dois campos de
702
+ // formulário em altura cheia no meio de uma barra de pills.
703
+ /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-1.5", children: [
704
+ /* @__PURE__ */ jsx(
705
+ DatePicker,
706
+ {
707
+ variant: "toolbar",
708
+ value: customFrom,
709
+ onChange: (v) => onCustomChange(v, v > customTo ? v : customTo)
710
+ }
711
+ ),
712
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3 shrink-0 text-muted-foreground", "aria-hidden": true }),
713
+ /* @__PURE__ */ jsx(
714
+ DatePicker,
715
+ {
716
+ variant: "toolbar",
717
+ value: customTo,
718
+ onChange: (v) => onCustomChange(v < customFrom ? v : customFrom, v)
719
+ }
720
+ )
721
+ ] }),
722
+ options.length > 0 && /* @__PURE__ */ jsxs("div", { className: "relative", ref: tagsRef, children: [
723
+ /* @__PURE__ */ jsxs(
724
+ "button",
725
+ {
726
+ type: "button",
727
+ onClick: () => setTagsOpen((o) => !o),
728
+ className: `inline-flex h-[26px] items-center gap-1.5 rounded-button border px-2.5 text-xs font-medium shadow-button transition-colors ${selectedTags.length ? "border-primary/40 bg-primary/10 text-primary" : "border-border bg-card text-muted-foreground hover:bg-muted/60"}`,
729
+ children: [
730
+ /* @__PURE__ */ jsx(Tag, { className: "h-3 w-3" }),
731
+ selectedTags.length ? t2("crm.filters.tagsSelected", { count: selectedTags.length }) : t2("crm.filters.tags")
732
+ ]
733
+ }
734
+ ),
735
+ tagsOpen && /* @__PURE__ */ jsx("div", { className: "absolute left-0 z-50 mt-1 max-h-72 w-56 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md", children: options.map((slug) => {
736
+ const def = tagDefs.get(slug);
737
+ const checked = selectedTags.includes(slug);
738
+ return /* @__PURE__ */ jsxs(
739
+ "button",
740
+ {
741
+ type: "button",
742
+ onClick: () => toggle(slug),
743
+ className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-muted",
744
+ children: [
745
+ /* @__PURE__ */ jsx(
746
+ "span",
747
+ {
748
+ className: `flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border ${checked ? "border-primary bg-primary text-primary-foreground" : "border-border"}`,
749
+ children: checked && /* @__PURE__ */ jsx("span", { className: "text-[9px] leading-none", children: "\u2713" })
750
+ }
751
+ ),
752
+ def?.color && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 shrink-0 rounded-full", style: { backgroundColor: def.color } }),
753
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: def?.name ?? humanizeTag(slug) })
754
+ ]
755
+ },
756
+ slug
757
+ );
758
+ }) })
759
+ ] }),
760
+ selectedTags.length > 0 && /* @__PURE__ */ jsx(
761
+ "button",
762
+ {
763
+ type: "button",
764
+ onClick: () => onTagsChange([]),
765
+ className: "inline-flex h-[26px] items-center gap-1 rounded-md px-1.5 text-xs text-muted-foreground hover:text-foreground",
766
+ title: t2("crm.filters.clearTags"),
767
+ children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
768
+ }
769
+ )
770
+ ] });
771
+ }
772
+ function localDate(offsetDays = 0) {
773
+ const d = /* @__PURE__ */ new Date();
774
+ if (offsetDays) d.setDate(d.getDate() + offsetDays);
775
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
776
+ }
577
777
  function PipelineSkeleton() {
578
778
  return /* @__PURE__ */ jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: [1, 2, 3, 4, 5].map((col) => /* @__PURE__ */ jsxs("div", { className: "min-w-[240px] max-w-[280px] flex-shrink-0", children: [
579
779
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2 px-1", children: [
@@ -591,7 +791,8 @@ function PipelineSkeleton() {
591
791
  ] }, i)) })
592
792
  ] }, col)) });
593
793
  }
594
- function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
794
+ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragStart, onDragEnd }) {
795
+ const t2 = useTranslation();
595
796
  return /* @__PURE__ */ jsxs(
596
797
  "div",
597
798
  {
@@ -599,13 +800,26 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
599
800
  onDragStart,
600
801
  onDragEnd,
601
802
  onClick,
602
- className: `rounded-lg border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
803
+ className: `group rounded-lg border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
603
804
  children: [
604
805
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
605
806
  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: deal.title }),
606
- saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" })
807
+ saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" }),
808
+ !saving && onArchive && /* @__PURE__ */ jsx(
809
+ "button",
810
+ {
811
+ onClick: (e) => {
812
+ e.stopPropagation();
813
+ onArchive();
814
+ },
815
+ title: t2("crm.pipeline.archive"),
816
+ className: "flex h-5 w-5 shrink-0 items-center justify-center rounded text-muted-foreground opacity-0 transition-opacity hover:bg-muted hover:text-foreground group-hover:opacity-100",
817
+ children: /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" })
818
+ }
819
+ )
607
820
  ] }),
608
821
  deal.contactName && /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground mt-0.5", children: deal.contactName }),
822
+ /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, max: 3, className: "mt-1.5" }),
609
823
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-2", children: [
610
824
  /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold", children: formatCurrency(deal.value, currency) }),
611
825
  /* @__PURE__ */ jsxs("span", { className: "text-[10px] text-muted-foreground", children: [
@@ -617,7 +831,7 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
617
831
  }
618
832
  );
619
833
  }
620
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
834
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, tagDefs, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
621
835
  const t2 = useTranslation();
622
836
  const isOver = dragOverStageId === stageId;
623
837
  const [hovered, setHovered] = useState(false);
@@ -660,7 +874,9 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
660
874
  deal,
661
875
  saving: savingDealIds.has(deal.id),
662
876
  currency,
877
+ tagDefs,
663
878
  onClick: () => onDealClick?.(deal.id),
879
+ onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
664
880
  onDragStart: (e) => {
665
881
  e.dataTransfer.effectAllowed = "move";
666
882
  onDragStart(deal.id, stageId);
@@ -682,33 +898,59 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
682
898
  const dealsByStage = useCrmStore((s) => s.dealsByStage);
683
899
  const dealsLoading = useCrmStore((s) => s.dealsLoading);
684
900
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
901
+ const tagDefs = useCrmStore((s) => s.tagDefs);
902
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
685
903
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage);
904
+ const refreshBoard = useCrmStore((s) => s.refreshBoard);
686
905
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
906
+ const archiveDeal = useCrmStore((s) => s.archiveDeal);
907
+ const canArchive = useCanArchive();
908
+ const [period, setPeriod] = useState("all");
909
+ const [customFrom, setCustomFrom] = useState(() => localDate(-30));
910
+ const [customTo, setCustomTo] = useState(() => localDate());
911
+ const [selectedTags, setSelectedTags] = useState([]);
687
912
  const [dragOverStageId, setDragOverStageId] = useState(null);
688
913
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
689
914
  const [optimisticBoard, setOptimisticBoard] = useState(null);
690
915
  const t2 = useTranslation();
691
916
  const [selectedDealId, setSelectedDealId] = useState(null);
692
917
  const dragRef = useRef(null);
918
+ const savingRef = useRef(savingDealIds);
919
+ savingRef.current = savingDealIds;
920
+ const boardFilter = useMemo(() => ({
921
+ ...selectedTags.length ? { tags: selectedTags } : {},
922
+ ...periodToRange(period, customFrom, customTo)
923
+ }), [selectedTags, period, customFrom, customTo]);
924
+ const filterKey = JSON.stringify(boardFilter);
925
+ const availableTags = useMemo(() => [...tagDefs.keys()], [tagDefs]);
926
+ const tenantId = useActiveTenantId();
693
927
  useEffect(() => {
694
928
  fetchPipelines();
695
- }, []);
929
+ fetchTagDefs();
930
+ }, [tenantId]);
696
931
  useEffect(() => {
697
- if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id);
698
- }, [pipelines]);
932
+ if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id, boardFilter);
933
+ }, [pipelines, filterKey]);
699
934
  const pipelineId = pipelines[0]?.id;
700
935
  useEffect(() => {
701
936
  if (!pipelineId) return;
702
937
  const supabase = getSupabaseClientOptional();
703
938
  if (!supabase) return;
939
+ let timer;
940
+ const onChange = () => {
941
+ if (savingRef.current.size > 0) return;
942
+ clearTimeout(timer);
943
+ timer = setTimeout(() => {
944
+ void refreshBoard();
945
+ }, 300);
946
+ };
704
947
  const channel = supabase.channel(`crm:board:${pipelineId}`).on(
705
948
  "postgres_changes",
706
949
  { event: "*", schema: "public", table: "plg_crm_deal_extensions" },
707
- () => {
708
- void fetchDealsByStage(pipelineId);
709
- }
950
+ onChange
710
951
  ).subscribe();
711
952
  return () => {
953
+ clearTimeout(timer);
712
954
  supabase.removeChannel(channel);
713
955
  };
714
956
  }, [pipelineId]);
@@ -772,6 +1014,23 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
772
1014
  }
773
1015
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
774
1016
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.pipeline.title"), subtitle: t2("crm.pipeline.subtitle") }),
1017
+ /* @__PURE__ */ jsx(
1018
+ BoardFilters,
1019
+ {
1020
+ period,
1021
+ onPeriodChange: setPeriod,
1022
+ customFrom,
1023
+ customTo,
1024
+ onCustomChange: (from, to) => {
1025
+ setCustomFrom(from);
1026
+ setCustomTo(to);
1027
+ },
1028
+ selectedTags,
1029
+ onTagsChange: setSelectedTags,
1030
+ tagDefs,
1031
+ availableTags
1032
+ }
1033
+ ),
775
1034
  dealsLoading && dealsByStage.size === 0 ? /* @__PURE__ */ jsx(PipelineSkeleton, {}) : /* @__PURE__ */ jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: visibleStages.map((stage) => {
776
1035
  const deals = displayBoard.get(stage.id) ?? [];
777
1036
  return /* @__PURE__ */ jsx(
@@ -783,8 +1042,12 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
783
1042
  deals,
784
1043
  savingDealIds,
785
1044
  currency,
1045
+ tagDefs,
786
1046
  dragOverStageId,
787
1047
  onDealClick: handleDealClick,
1048
+ onArchiveDeal: canArchive ? (id) => {
1049
+ void archiveDeal(id);
1050
+ } : void 0,
788
1051
  onAddLead,
789
1052
  onDragStart: handleDragStart,
790
1053
  onDragEnd: handleDragEnd,
@@ -976,7 +1239,7 @@ var STATUS_COLORS = {
976
1239
  overdue: "bg-destructive-soft text-destructive-soft-foreground",
977
1240
  cancelled: "bg-muted text-muted-foreground"
978
1241
  };
979
- function useQuoteColumns(currency, onEditQuote) {
1242
+ function useQuoteColumns(currency, onEditQuote, onArchive) {
980
1243
  const t2 = useTranslation();
981
1244
  const cols = [
982
1245
  { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
@@ -996,22 +1259,36 @@ function useQuoteColumns(currency, onEditQuote) {
996
1259
  }
997
1260
  }
998
1261
  ];
999
- if (onEditQuote) {
1262
+ if (onEditQuote || onArchive) {
1000
1263
  cols.push({
1001
1264
  id: "actions",
1002
1265
  header: "",
1003
- cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: "text-right", children: /* @__PURE__ */ jsx(
1004
- "button",
1005
- {
1006
- onClick: (e) => {
1007
- e.stopPropagation();
1008
- onEditQuote(row.original.id);
1009
- },
1010
- className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1011
- title: "Edit quote",
1012
- children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
1013
- }
1014
- ) })
1266
+ cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
1267
+ onEditQuote && /* @__PURE__ */ jsx(
1268
+ "button",
1269
+ {
1270
+ onClick: (e) => {
1271
+ e.stopPropagation();
1272
+ onEditQuote(row.original.id);
1273
+ },
1274
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1275
+ title: "Edit quote",
1276
+ children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
1277
+ }
1278
+ ),
1279
+ onArchive && /* @__PURE__ */ jsx(
1280
+ "button",
1281
+ {
1282
+ onClick: (e) => {
1283
+ e.stopPropagation();
1284
+ onArchive(row.original.id);
1285
+ },
1286
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1287
+ title: t2("crm.quotes.archive"),
1288
+ children: /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" })
1289
+ }
1290
+ )
1291
+ ] })
1015
1292
  });
1016
1293
  }
1017
1294
  return cols;
@@ -1022,10 +1299,14 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1022
1299
  const quotes = useCrmStore((s) => s.quotes);
1023
1300
  const quotesLoading = useCrmStore((s) => s.quotesLoading);
1024
1301
  const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
1302
+ const archiveQuote = useCrmStore((s) => s.archiveQuote);
1303
+ const canArchive = useCanArchive();
1025
1304
  useEffect(() => {
1026
1305
  fetchQuotes({});
1027
1306
  }, []);
1028
- const columns2 = useQuoteColumns(currency, onEditQuote);
1307
+ const columns2 = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
1308
+ void archiveQuote(id);
1309
+ } : void 0);
1029
1310
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1030
1311
  /* @__PURE__ */ jsx(
1031
1312
  SubpageHeader,
@@ -1292,7 +1573,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1292
1573
  observations,
1293
1574
  items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
1294
1575
  };
1295
- const snapshot = React14.useRef(null);
1576
+ const snapshot = React15.useRef(null);
1296
1577
  useEffect(() => {
1297
1578
  if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
1298
1579
  }, [loadingExisting]);
@@ -1723,7 +2004,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1723
2004
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap", children: quote.observations })
1724
2005
  ] })
1725
2006
  ] }),
1726
- quote.status === "approved" && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
2007
+ ["approved", "invoiced", "paid", "partial", "overdue"].includes(quote.status) && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
1727
2008
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1728
2009
  /* @__PURE__ */ jsx(CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
1729
2010
  /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t2("crm.quoteDetail.invoiceCreated") })
@@ -1731,7 +2012,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1731
2012
  /* @__PURE__ */ jsxs(
1732
2013
  "a",
1733
2014
  {
1734
- href: `#/financial/receivables/detail/${quote.id}`,
2015
+ href: "#/financial/receivables/list",
1735
2016
  className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",
1736
2017
  children: [
1737
2018
  t2("crm.quoteDetail.viewInvoice"),
@@ -1813,6 +2094,9 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1813
2094
  const provider = useCrmProvider();
1814
2095
  const { currency } = useCrmConfig();
1815
2096
  const t2 = useTranslation();
2097
+ const archiveLead = useCrmStore((s) => s.archiveLead);
2098
+ const canArchive = useCanArchive();
2099
+ const [archiving, setArchiving] = useState(false);
1816
2100
  const [lead, setLead] = useState(null);
1817
2101
  const [deal, setDeal] = useState(null);
1818
2102
  const [quotes, setQuotes] = useState([]);
@@ -1876,18 +2160,37 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1876
2160
  lead.sourceName && /* @__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: lead.sourceName })
1877
2161
  ] })
1878
2162
  ] }),
1879
- onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxs(
1880
- "button",
1881
- {
1882
- onClick: () => onCreateQuote(leadId),
1883
- className: "inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors shrink-0",
1884
- children: [
1885
- /* @__PURE__ */ jsx(FileText, { className: "h-3 w-3" }),
1886
- " ",
1887
- t2("crm.leadDetail.createQuote")
1888
- ]
1889
- }
1890
- )
2163
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 shrink-0", children: [
2164
+ canArchive && /* @__PURE__ */ jsxs(
2165
+ "button",
2166
+ {
2167
+ onClick: () => {
2168
+ setArchiving(true);
2169
+ archiveLead(leadId).then(onBack).catch(() => setArchiving(false));
2170
+ },
2171
+ disabled: archiving,
2172
+ title: t2("crm.leadDetail.archive"),
2173
+ className: "inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground bg-card shadow-button active:shadow-button-inset transition-colors disabled:opacity-60",
2174
+ children: [
2175
+ /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" }),
2176
+ " ",
2177
+ t2("crm.leadDetail.archive")
2178
+ ]
2179
+ }
2180
+ ),
2181
+ onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxs(
2182
+ "button",
2183
+ {
2184
+ onClick: () => onCreateQuote(leadId),
2185
+ className: "inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors",
2186
+ children: [
2187
+ /* @__PURE__ */ jsx(FileText, { className: "h-3 w-3" }),
2188
+ " ",
2189
+ t2("crm.leadDetail.createQuote")
2190
+ ]
2191
+ }
2192
+ )
2193
+ ] })
1891
2194
  ] }),
1892
2195
  /* @__PURE__ */ jsx("div", { className: "border-t" }),
1893
2196
  /* @__PURE__ */ jsxs("div", { children: [
@@ -1972,14 +2275,47 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1972
2275
  ] })
1973
2276
  ] });
1974
2277
  }
2278
+
2279
+ // src/types.ts
2280
+ var SYSTEM_ACTIVITY_TYPES = [
2281
+ "lead_created",
2282
+ "lead_converted",
2283
+ "lead_archived",
2284
+ "deal_created",
2285
+ "stage_changed",
2286
+ "deal_won",
2287
+ "deal_lost",
2288
+ "deal_archived",
2289
+ "quote_created",
2290
+ "quote_sent",
2291
+ "quote_approved",
2292
+ "quote_rejected",
2293
+ "quote_archived"
2294
+ ];
1975
2295
  var TYPE_CONFIG = {
1976
2296
  call: { icon: Phone, color: "bg-info/15 text-info dark:bg-info/20", label: "Call" },
1977
2297
  email: { icon: Mail, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Email" },
1978
2298
  meeting: { icon: Users, color: "bg-success-soft text-success-soft-foreground", label: "Meeting" },
1979
2299
  note: { icon: FileText, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Note" },
1980
2300
  task: { icon: CheckSquare, color: "bg-pink-100 text-pink-600 dark:bg-pink-500/20 dark:text-pink-400", label: "Task" },
1981
- whatsapp: { icon: MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" }
2301
+ whatsapp: { icon: MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" },
2302
+ // System timeline events (auto-logged by the data provider on every CRM write)
2303
+ lead_created: { icon: UserPlus, color: "bg-info/15 text-info dark:bg-info/20", label: "Lead created" },
2304
+ lead_converted: { icon: ArrowRightLeft, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Lead converted" },
2305
+ deal_created: { icon: Target, color: "bg-info/15 text-info dark:bg-info/20", label: "Deal created" },
2306
+ stage_changed: { icon: MoveRight, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Stage changed" },
2307
+ deal_won: { icon: Trophy, color: "bg-success/15 text-success dark:bg-success/20", label: "Deal won" },
2308
+ deal_lost: { icon: XCircle, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Deal lost" },
2309
+ quote_created: { icon: FilePlus2, color: "bg-info/15 text-info dark:bg-info/20", label: "Quote created" },
2310
+ quote_sent: { icon: Send, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Quote sent" },
2311
+ quote_approved: { icon: FileCheck2, color: "bg-success/15 text-success dark:bg-success/20", label: "Quote approved" },
2312
+ quote_rejected: { icon: FileX2, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Quote rejected" },
2313
+ lead_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Lead archived" },
2314
+ deal_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Deal archived" },
2315
+ quote_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Quote archived" }
1982
2316
  };
2317
+ var SYSTEM_TYPES = new Set(SYSTEM_ACTIVITY_TYPES);
2318
+ var MANUAL_TYPES = Object.keys(TYPE_CONFIG).filter((t2) => !SYSTEM_TYPES.has(t2));
1983
2319
  function ActivitySkeleton() {
1984
2320
  return /* @__PURE__ */ jsx("div", { className: "space-y-2", children: [1, 2, 3, 4, 5].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 rounded-lg border bg-card shadow-sm p-4", children: [
1985
2321
  /* @__PURE__ */ jsx("div", { className: "h-9 w-9 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
@@ -1994,20 +2330,23 @@ function ActivitySkeleton() {
1994
2330
  /* @__PURE__ */ jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse shrink-0" })
1995
2331
  ] }, i)) });
1996
2332
  }
1997
- function ActivityListView() {
2333
+ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
1998
2334
  const t2 = useTranslation();
2335
+ const provider = useCrmProvider();
2336
+ const [selectedDealId, setSelectedDealId] = useState(null);
1999
2337
  const activities = useCrmStore((s) => s.activities);
2000
2338
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
2001
2339
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
2002
2340
  const [typeFilter, setTypeFilter] = useState(null);
2003
2341
  const [showCompleted, setShowCompleted] = useState(null);
2342
+ const eventsFilter = typeFilter === "events";
2004
2343
  useEffect(() => {
2005
2344
  fetchActivities({
2006
- activityType: typeFilter,
2007
- completed: showCompleted ?? void 0
2345
+ activityType: eventsFilter ? void 0 : typeFilter,
2346
+ completed: eventsFilter ? void 0 : showCompleted ?? void 0
2008
2347
  });
2009
2348
  }, [typeFilter, showCompleted]);
2010
- const filtered = activities;
2349
+ const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities;
2011
2350
  const pendingCount = activities.filter((a) => !a.completedAt).length;
2012
2351
  const overdueCount = activities.filter((a) => !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)).length;
2013
2352
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
@@ -2028,7 +2367,8 @@ function ActivityListView() {
2028
2367
  children: t2("crm.activities.all")
2029
2368
  }
2030
2369
  ),
2031
- Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
2370
+ MANUAL_TYPES.map((type) => {
2371
+ const cfg = TYPE_CONFIG[type];
2032
2372
  const Icon = cfg.icon;
2033
2373
  return /* @__PURE__ */ jsxs(
2034
2374
  "button",
@@ -2042,7 +2382,18 @@ function ActivityListView() {
2042
2382
  },
2043
2383
  type
2044
2384
  );
2045
- })
2385
+ }),
2386
+ /* @__PURE__ */ jsxs(
2387
+ "button",
2388
+ {
2389
+ onClick: () => setTypeFilter(eventsFilter ? null : "events"),
2390
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${eventsFilter ? "bg-primary/15 text-primary" : "bg-muted/50 text-muted-foreground hover:bg-muted"}`,
2391
+ children: [
2392
+ /* @__PURE__ */ jsx(Sparkles, { className: "h-3 w-3" }),
2393
+ t2("crm.activities.systemEvents")
2394
+ ]
2395
+ }
2396
+ )
2046
2397
  ] }),
2047
2398
  /* @__PURE__ */ jsx("div", { className: "flex-1" }),
2048
2399
  /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5", children: [
@@ -2079,17 +2430,26 @@ function ActivityListView() {
2079
2430
  ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: filtered.map((a) => {
2080
2431
  const cfg = TYPE_CONFIG[a.activityType] ?? { icon: FileText, color: "bg-muted text-muted-foreground", label: a.activityType };
2081
2432
  const Icon = cfg.icon;
2433
+ const isSystem = SYSTEM_TYPES.has(a.activityType);
2082
2434
  const isOverdue = !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2435
+ const openRecord = a.dealId ? () => setSelectedDealId(a.dealId) : a.leadId ? () => {
2436
+ void provider.getDealByLeadId(a.leadId).then((deal) => {
2437
+ if (deal) setSelectedDealId(deal.id);
2438
+ else onOpenLead?.(a.leadId);
2439
+ });
2440
+ } : void 0;
2083
2441
  return /* @__PURE__ */ jsxs(
2084
2442
  "div",
2085
2443
  {
2086
- className: `flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""}`,
2444
+ onClick: openRecord,
2445
+ role: openRecord ? "button" : void 0,
2446
+ className: `group flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""} ${openRecord ? "cursor-pointer hover:bg-muted/30" : ""}`,
2087
2447
  children: [
2088
2448
  /* @__PURE__ */ jsx("div", { className: `flex h-9 w-9 items-center justify-center rounded-lg shrink-0 ${cfg.color}`, children: /* @__PURE__ */ jsx(Icon, { className: "h-4 w-4" }) }),
2089
2449
  /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
2090
2450
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2091
2451
  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: a.title }),
2092
- a.completedAt && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-0.5 rounded-full bg-success/15 px-1.5 py-0.5 text-[9px] font-medium text-success dark:bg-success/20", children: [
2452
+ a.completedAt && !isSystem && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-0.5 rounded-full bg-success/15 px-1.5 py-0.5 text-[9px] font-medium text-success dark:bg-success/20", children: [
2093
2453
  /* @__PURE__ */ jsx(Check, { className: "h-2.5 w-2.5" }),
2094
2454
  " ",
2095
2455
  t2("crm.activities.done")
@@ -2116,12 +2476,25 @@ function ActivityListView() {
2116
2476
  ] })
2117
2477
  ] })
2118
2478
  ] }),
2119
- /* @__PURE__ */ jsx("span", { className: "text-[10px] text-muted-foreground shrink-0 pt-1", children: new Date(a.createdAt).toLocaleDateString() })
2479
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 text-[10px] text-muted-foreground shrink-0 pt-1", children: [
2480
+ new Date(a.createdAt).toLocaleDateString(),
2481
+ openRecord && /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" })
2482
+ ] })
2120
2483
  ]
2121
2484
  },
2122
2485
  a.id
2123
2486
  );
2124
- }) })
2487
+ }) }),
2488
+ /* @__PURE__ */ jsx(
2489
+ DealSidebar,
2490
+ {
2491
+ dealId: selectedDealId ?? "",
2492
+ open: !!selectedDealId,
2493
+ onClose: () => setSelectedDealId(null),
2494
+ onViewLead: onOpenLead,
2495
+ onViewQuote: onOpenQuote
2496
+ }
2497
+ )
2125
2498
  ] });
2126
2499
  }
2127
2500
  function buildNav(config, view, navigate) {
@@ -2215,7 +2588,7 @@ function CrmPage({ config, provider, store, registries }) {
2215
2588
  return /* @__PURE__ */ jsx(QuoteFormView, { leadId: lid, onSaved: (id) => id ? navigate(`quotes-detail:${id}`) : navigate("quotes-list") });
2216
2589
  } },
2217
2590
  { id: "quotes-list", render: () => /* @__PURE__ */ jsx(QuoteListView, { onNew: () => navigate("quotes-new"), onEdit: (id) => navigate(`quotes-detail:${id}`), onEditQuote: (id) => navigate(`quotes-edit:${id}`) }) },
2218
- { id: "activities", render: () => /* @__PURE__ */ jsx(ActivityListView, {}) },
2591
+ { id: "activities", render: () => /* @__PURE__ */ jsx(ActivityListView, { onOpenLead: (id) => navigate(`leads-detail:${id}`), onOpenQuote: (id) => navigate(`quotes-detail:${id}`) }) },
2219
2592
  { id: "leads-detail", render: ({ id }) => /* @__PURE__ */ jsx(LeadDetailView, { leadId: id, onBack: () => navigate("leads-list"), onCreateQuote: (lid) => navigate("quotes-new", `/sales/quotes/new?leadId=${lid}`), onViewQuote: (qid) => navigate(`quotes-detail:${qid}`) }) },
2220
2593
  { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
2221
2594
  window.location.hash = `/financial/receivables/detail/${invoiceId}`;
@@ -2458,6 +2831,7 @@ function deriveLeadStatus(stage) {
2458
2831
  return "qualified";
2459
2832
  }
2460
2833
  function deriveQuoteStatus(stage, current) {
2834
+ if (current === "archived") return current;
2461
2835
  if (stage.isWon) return "approved";
2462
2836
  if (stage.isLost) return "rejected";
2463
2837
  return current;
@@ -2474,6 +2848,7 @@ function now() {
2474
2848
  function today() {
2475
2849
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2476
2850
  }
2851
+ var MOCK_TAG_COLORS = ["#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444", "#ec4899", "#8b5cf6", "#14b8a6"];
2477
2852
  function paginate(items, page, pageSize) {
2478
2853
  const p = page ?? 1;
2479
2854
  const ps = pageSize ?? 50;
@@ -2483,7 +2858,7 @@ function paginate(items, page, pageSize) {
2483
2858
  function createStore(seedStages) {
2484
2859
  const tenantId = "mock-tenant";
2485
2860
  const pipelineId = uid();
2486
- const defaultStages = [
2861
+ const defaultStages = seedStages ?? [
2487
2862
  { name: "New", color: "#6366f1", probability: 10 },
2488
2863
  { name: "Contacted", color: "#3b82f6", probability: 25 },
2489
2864
  { name: "Qualified", color: "#f59e0b", probability: 50 },
@@ -2522,8 +2897,23 @@ function createStore(seedStages) {
2522
2897
  };
2523
2898
  }
2524
2899
  function createMockCrmProvider(options) {
2525
- const store = createStore();
2900
+ const store = createStore(options?.dealStages);
2526
2901
  const tenantId = "mock-tenant";
2902
+ function logEvent(input) {
2903
+ store.activities.push({
2904
+ id: uid(),
2905
+ dealId: input.dealId,
2906
+ leadId: input.leadId,
2907
+ contactId: input.contactId,
2908
+ contactName: input.contactName,
2909
+ activityType: input.activityType,
2910
+ title: input.title,
2911
+ description: input.description,
2912
+ completedAt: now(),
2913
+ tenantId,
2914
+ createdAt: now()
2915
+ });
2916
+ }
2527
2917
  function cascadeFromStage(deal, stage) {
2528
2918
  if (deal.leadId) {
2529
2919
  const lead = store.leads.find((l) => l.id === deal.leadId);
@@ -2548,7 +2938,7 @@ function createMockCrmProvider(options) {
2548
2938
  },
2549
2939
  // Leads
2550
2940
  async getLeads(query) {
2551
- let results = [...store.leads];
2941
+ let results = store.leads.filter((l) => l.isActive !== false);
2552
2942
  if (query.status) {
2553
2943
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2554
2944
  results = results.filter((l) => statuses.includes(l.status));
@@ -2582,6 +2972,7 @@ function createMockCrmProvider(options) {
2582
2972
  updatedAt: now()
2583
2973
  };
2584
2974
  store.leads.push(lead);
2975
+ logEvent({ activityType: "lead_created", title: lead.name, leadId: lead.id, contactName: lead.name });
2585
2976
  return lead;
2586
2977
  },
2587
2978
  async updateLead(id, data) {
@@ -2595,6 +2986,7 @@ function createMockCrmProvider(options) {
2595
2986
  if (!lead) throw new Error(`Lead ${leadId} not found`);
2596
2987
  lead.status = "converted";
2597
2988
  lead.updatedAt = now();
2989
+ logEvent({ activityType: "lead_converted", title: lead.name, leadId, contactName: lead.name });
2598
2990
  const deal = await provider.createDeal({ ...dealInput, leadId });
2599
2991
  return deal;
2600
2992
  },
@@ -2606,6 +2998,8 @@ function createMockCrmProvider(options) {
2606
2998
  if (query.status) {
2607
2999
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2608
3000
  results = results.filter((d) => statuses.includes(d.status));
3001
+ } else {
3002
+ results = results.filter((d) => d.status !== "archived");
2609
3003
  }
2610
3004
  if (query.search) {
2611
3005
  const s = query.search.toLowerCase();
@@ -2617,11 +3011,17 @@ function createMockCrmProvider(options) {
2617
3011
  async getDealById(id) {
2618
3012
  return store.deals.find((d) => d.id === id) ?? null;
2619
3013
  },
2620
- async getDealsByStage(pipelineId) {
3014
+ async getDealsByStage(pipelineId, filter) {
2621
3015
  const stages = store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
3016
+ const matches = (d) => {
3017
+ if (filter?.tags?.length && !filter.tags.some((t2) => (d.tags ?? []).includes(t2))) return false;
3018
+ if (filter?.createdFrom && d.createdAt < filter.createdFrom) return false;
3019
+ if (filter?.createdTo && d.createdAt > filter.createdTo) return false;
3020
+ return true;
3021
+ };
2622
3022
  const map = /* @__PURE__ */ new Map();
2623
3023
  for (const stage of stages) {
2624
- map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open"));
3024
+ map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches(d)));
2625
3025
  }
2626
3026
  return map;
2627
3027
  },
@@ -2649,6 +3049,14 @@ function createMockCrmProvider(options) {
2649
3049
  updatedAt: now()
2650
3050
  };
2651
3051
  store.deals.push(deal);
3052
+ logEvent({
3053
+ activityType: "deal_created",
3054
+ title: deal.title,
3055
+ dealId: deal.id,
3056
+ leadId: deal.leadId,
3057
+ contactId: deal.contactId,
3058
+ contactName: deal.contactName
3059
+ });
2652
3060
  return deal;
2653
3061
  },
2654
3062
  async updateDeal(id, data) {
@@ -2670,8 +3078,31 @@ function createMockCrmProvider(options) {
2670
3078
  if (stage.isLost) deal.status = "lost";
2671
3079
  deal.updatedAt = now();
2672
3080
  cascadeFromStage(deal, stage);
3081
+ logEvent({
3082
+ activityType: stage.isWon ? "deal_won" : stage.isLost ? "deal_lost" : "stage_changed",
3083
+ title: deal.title || "Deal",
3084
+ description: stage.name,
3085
+ dealId: deal.id,
3086
+ contactName: deal.contactName
3087
+ });
2673
3088
  return deal;
2674
3089
  },
3090
+ async archiveDeal(dealId) {
3091
+ const deal = store.deals.find((d) => d.id === dealId);
3092
+ if (!deal) throw new Error(`Deal ${dealId} not found`);
3093
+ deal.status = "archived";
3094
+ deal.updatedAt = now();
3095
+ logEvent({ activityType: "deal_archived", title: deal.title || "Deal", dealId, contactName: deal.contactName });
3096
+ },
3097
+ async archiveLead(leadId) {
3098
+ const lead = store.leads.find((l) => l.id === leadId);
3099
+ if (!lead) throw new Error(`Lead ${leadId} not found`);
3100
+ lead.isActive = false;
3101
+ lead.updatedAt = now();
3102
+ const deal = store.deals.find((d) => d.leadId === leadId && d.status === "open");
3103
+ if (deal) await provider.archiveDeal(deal.id);
3104
+ logEvent({ activityType: "lead_archived", title: lead.name, leadId, contactName: lead.name });
3105
+ },
2675
3106
  // Activities
2676
3107
  async getActivities(query) {
2677
3108
  let results = [...store.activities];
@@ -2707,9 +3138,32 @@ function createMockCrmProvider(options) {
2707
3138
  activity.completedAt = now();
2708
3139
  return activity;
2709
3140
  },
3141
+ async getActivityTypes() {
3142
+ const seed = options?.activityTypes ?? [
3143
+ { value: "call", label: "Call", icon: "Phone" },
3144
+ { value: "email", label: "Email", icon: "Mail" },
3145
+ { value: "meeting", label: "Meeting", icon: "Users" },
3146
+ { value: "note", label: "Note", icon: "FileText" },
3147
+ { value: "task", label: "Task", icon: "CheckSquare" },
3148
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
3149
+ ];
3150
+ return seed.map((t2, i) => ({ id: `at-${i}`, name: t2.label, icon: t2.icon, isActive: true }));
3151
+ },
3152
+ async getTagDefs() {
3153
+ const used = /* @__PURE__ */ new Set();
3154
+ for (const l of store.leads) for (const t2 of l.tags ?? []) used.add(t2);
3155
+ for (const d of store.deals) for (const t2 of d.tags ?? []) used.add(t2);
3156
+ return [...used].sort().map((slug, i) => ({
3157
+ id: `tag-${i}`,
3158
+ slug,
3159
+ name: slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
3160
+ color: MOCK_TAG_COLORS[i % MOCK_TAG_COLORS.length],
3161
+ isActive: true
3162
+ }));
3163
+ },
2710
3164
  // Quotes
2711
3165
  async getQuotes(query) {
2712
- let results = [...store.quotes];
3166
+ let results = store.quotes.filter((q) => q.status !== "archived" || query.status && (Array.isArray(query.status) ? query.status : [query.status]).includes("archived"));
2713
3167
  if (query.status) {
2714
3168
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2715
3169
  results = results.filter((q) => statuses.includes(q.status));
@@ -2753,6 +3207,22 @@ function createMockCrmProvider(options) {
2753
3207
  updatedAt: now()
2754
3208
  };
2755
3209
  store.quotes.push(quote);
3210
+ if (quote.dealId && totalAmount > 0) {
3211
+ const deal = store.deals.find((d) => d.id === quote.dealId);
3212
+ if (deal) {
3213
+ deal.value = totalAmount;
3214
+ deal.updatedAt = now();
3215
+ }
3216
+ }
3217
+ logEvent({
3218
+ activityType: "quote_created",
3219
+ title: quote.quoteNumber ?? "Quote",
3220
+ description: quote.contactName,
3221
+ dealId: quote.dealId,
3222
+ leadId: quote.leadId,
3223
+ contactId: quote.contactId,
3224
+ contactName: quote.contactName
3225
+ });
2756
3226
  return quote;
2757
3227
  },
2758
3228
  async updateQuote(id, input) {
@@ -2776,6 +3246,13 @@ function createMockCrmProvider(options) {
2776
3246
  quote.items = items;
2777
3247
  quote.totalAmount = totalAmount;
2778
3248
  quote.updatedAt = now();
3249
+ if (quote.dealId && totalAmount > 0) {
3250
+ const deal = store.deals.find((d) => d.id === quote.dealId);
3251
+ if (deal) {
3252
+ deal.value = totalAmount;
3253
+ deal.updatedAt = now();
3254
+ }
3255
+ }
2779
3256
  return quote;
2780
3257
  },
2781
3258
  async sendQuote(id) {
@@ -2783,6 +3260,14 @@ function createMockCrmProvider(options) {
2783
3260
  if (!quote) throw new Error(`Quote ${id} not found`);
2784
3261
  quote.status = "sent";
2785
3262
  quote.updatedAt = now();
3263
+ logEvent({
3264
+ activityType: "quote_sent",
3265
+ title: quote.quoteNumber ?? "Quote",
3266
+ description: quote.contactName,
3267
+ dealId: quote.dealId,
3268
+ leadId: quote.leadId,
3269
+ contactName: quote.contactName
3270
+ });
2786
3271
  return quote;
2787
3272
  },
2788
3273
  async approveQuote(id) {
@@ -2806,6 +3291,14 @@ function createMockCrmProvider(options) {
2806
3291
  lead.metadata = { ...lead.metadata, convertedFromLead: true };
2807
3292
  }
2808
3293
  }
3294
+ logEvent({
3295
+ activityType: "quote_approved",
3296
+ title: quote.quoteNumber ?? "Quote",
3297
+ description: quote.contactName,
3298
+ dealId: quote.dealId,
3299
+ leadId: quote.leadId,
3300
+ contactName: quote.contactName
3301
+ });
2809
3302
  return quote;
2810
3303
  },
2811
3304
  async rejectQuote(id, reason) {
@@ -2823,6 +3316,14 @@ function createMockCrmProvider(options) {
2823
3316
  }
2824
3317
  }
2825
3318
  }
3319
+ logEvent({
3320
+ activityType: "quote_rejected",
3321
+ title: quote.quoteNumber ?? "Quote",
3322
+ description: reason,
3323
+ dealId: quote.dealId,
3324
+ leadId: quote.leadId,
3325
+ contactName: quote.contactName
3326
+ });
2826
3327
  return quote;
2827
3328
  },
2828
3329
  async expireQuote(id) {
@@ -2832,6 +3333,20 @@ function createMockCrmProvider(options) {
2832
3333
  quote.updatedAt = now();
2833
3334
  return quote;
2834
3335
  },
3336
+ async archiveQuote(id) {
3337
+ const quote = store.quotes.find((q) => q.id === id);
3338
+ if (!quote) throw new Error(`Quote ${id} not found`);
3339
+ quote.status = "archived";
3340
+ quote.updatedAt = now();
3341
+ logEvent({
3342
+ activityType: "quote_archived",
3343
+ title: quote.quoteNumber ?? "Quote",
3344
+ description: quote.contactName,
3345
+ dealId: quote.dealId,
3346
+ leadId: quote.leadId,
3347
+ contactName: quote.contactName
3348
+ });
3349
+ },
2835
3350
  // Cross-entity lookups
2836
3351
  async getQuotesByDealId(dealId) {
2837
3352
  return store.quotes.filter((q) => q.dealId === dealId);
@@ -2894,6 +3409,9 @@ var T = {
2894
3409
  function getTenantId() {
2895
3410
  return getActiveTenantId();
2896
3411
  }
3412
+ function humanizeTagSlug(slug) {
3413
+ return slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
3414
+ }
2897
3415
  function snakeToCamel(obj) {
2898
3416
  const result = {};
2899
3417
  for (const [key, value] of Object.entries(obj)) {
@@ -2913,6 +3431,51 @@ async function mergePersonMetadata(personId, patch) {
2913
3431
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
2914
3432
  }
2915
3433
  function createSupabaseCrmProvider(options) {
3434
+ async function logEvent(input) {
3435
+ try {
3436
+ const { pub } = getClients();
3437
+ await pub.from(T.activities).insert({
3438
+ tenant_id: getTenantId(),
3439
+ deal_id: input.dealId ?? null,
3440
+ lead_id: input.leadId ?? null,
3441
+ contact_id: input.contactId ?? null,
3442
+ contact_name: input.contactName ?? null,
3443
+ activity_type: input.activityType,
3444
+ title: input.title,
3445
+ description: input.description ?? null,
3446
+ completed_at: (/* @__PURE__ */ new Date()).toISOString()
3447
+ });
3448
+ } catch {
3449
+ }
3450
+ }
3451
+ const typesSeeded = /* @__PURE__ */ new Set();
3452
+ async function ensureActivityTypes(tenantId) {
3453
+ const seed = options?.activityTypes;
3454
+ if (!seed?.length || typesSeeded.has(tenantId)) return;
3455
+ typesSeeded.add(tenantId);
3456
+ const { pub } = getClients();
3457
+ await pub.from(T.activityTypes).upsert(
3458
+ seed.map((t2) => ({ tenant_id: tenantId, name: t2.label, icon: t2.icon ?? null, is_active: true })),
3459
+ { onConflict: "tenant_id,name", ignoreDuplicates: true }
3460
+ );
3461
+ }
3462
+ async function registerTags(tags) {
3463
+ const tenantId = getTenantId();
3464
+ if (!tenantId || !tags?.length) return;
3465
+ try {
3466
+ const { pub } = getClients();
3467
+ await pub.from(T.tags).upsert(
3468
+ [...new Set(tags)].map((slug) => ({
3469
+ tenant_id: tenantId,
3470
+ slug,
3471
+ name: humanizeTagSlug(slug),
3472
+ is_active: true
3473
+ })),
3474
+ { onConflict: "tenant_id,slug", ignoreDuplicates: true }
3475
+ );
3476
+ } catch {
3477
+ }
3478
+ }
2916
3479
  const provider = {
2917
3480
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
2918
3481
  async getPipelines() {
@@ -2928,7 +3491,7 @@ function createSupabaseCrmProvider(options) {
2928
3491
  // --- Leads (via view — single query) ---
2929
3492
  async getLeads(query) {
2930
3493
  const { pub } = getClients();
2931
- let qb = pub.from("v_leads").select("*", { count: "exact" });
3494
+ let qb = pub.from("v_leads").select("*", { count: "exact" }).eq("is_active", true);
2932
3495
  if (query.search) qb = qb.ilike("name", `%${query.search}%`);
2933
3496
  if (query.status) {
2934
3497
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
@@ -3001,7 +3564,9 @@ function createSupabaseCrmProvider(options) {
3001
3564
  }).select().single();
3002
3565
  if (error) throw new Error(error.message);
3003
3566
  const p = snakeToCamel(data);
3004
- return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3567
+ await registerTags(input.tags);
3568
+ await logEvent({ activityType: "lead_created", title: input.name, leadId: p.id, contactName: input.name });
3569
+ return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: p.tags ?? input.tags ?? [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3005
3570
  },
3006
3571
  async updateLead(id, partial) {
3007
3572
  const { core } = getClients();
@@ -3016,8 +3581,13 @@ function createSupabaseCrmProvider(options) {
3016
3581
  return await provider.getLeadById(id);
3017
3582
  },
3018
3583
  async convertLeadToDeal(leadId, dealInput) {
3019
- getClients();
3020
3584
  await mergePersonMetadata(leadId, { status: "converted" });
3585
+ await logEvent({
3586
+ activityType: "lead_converted",
3587
+ title: dealInput.contactName ?? dealInput.title,
3588
+ leadId,
3589
+ contactName: dealInput.contactName
3590
+ });
3021
3591
  return provider.createDeal({ ...dealInput, leadId });
3022
3592
  },
3023
3593
  // --- Deals (via view — single query with all joins) ---
@@ -3027,6 +3597,8 @@ function createSupabaseCrmProvider(options) {
3027
3597
  if (query.status) {
3028
3598
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3029
3599
  qb = qb.in("status", statuses);
3600
+ } else {
3601
+ qb = qb.neq("status", "archived");
3030
3602
  }
3031
3603
  if (query.search) qb = qb.ilike("title", `%${query.search}%`);
3032
3604
  if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
@@ -3085,10 +3657,14 @@ function createSupabaseCrmProvider(options) {
3085
3657
  updatedAt: r.updated_at
3086
3658
  };
3087
3659
  },
3088
- async getDealsByStage(pipelineId) {
3660
+ async getDealsByStage(pipelineId, filter) {
3089
3661
  const { pub } = getClients();
3090
3662
  const stages = await provider.getPipelineStages(pipelineId);
3091
- const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).neq("status", "lost");
3663
+ let qb = pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).not("status", "in", "(lost,archived)");
3664
+ if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
3665
+ if (filter?.createdFrom) qb = qb.gte("created_at", filter.createdFrom);
3666
+ if (filter?.createdTo) qb = qb.lte("created_at", filter.createdTo);
3667
+ const { data } = await qb;
3092
3668
  const deals = (data ?? []).map((r) => ({
3093
3669
  id: r.id,
3094
3670
  title: r.title ?? "",
@@ -3139,6 +3715,15 @@ function createSupabaseCrmProvider(options) {
3139
3715
  expected_close_date: input.expectedCloseDate,
3140
3716
  lead_id: input.leadId
3141
3717
  });
3718
+ await registerTags(input.tags);
3719
+ await logEvent({
3720
+ activityType: "deal_created",
3721
+ title: input.title,
3722
+ dealId: order.id,
3723
+ leadId: input.leadId,
3724
+ contactId: input.contactId,
3725
+ contactName: input.contactName
3726
+ });
3142
3727
  return {
3143
3728
  id: order.id,
3144
3729
  title: input.title,
@@ -3210,7 +3795,46 @@ function createSupabaseCrmProvider(options) {
3210
3795
  }
3211
3796
  }
3212
3797
  }
3213
- return await provider.getDealById(dealId);
3798
+ const moved = await provider.getDealById(dealId);
3799
+ if (stageRow) {
3800
+ await logEvent({
3801
+ activityType: stageRow.is_won ? "deal_won" : stageRow.is_lost ? "deal_lost" : "stage_changed",
3802
+ title: moved.title || "Deal",
3803
+ description: stageRow.name,
3804
+ dealId,
3805
+ contactName: moved.contactName
3806
+ });
3807
+ }
3808
+ return moved;
3809
+ },
3810
+ async archiveDeal(dealId) {
3811
+ const { core } = getClients();
3812
+ const deal = await provider.getDealById(dealId);
3813
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", dealId);
3814
+ if (error) throw new Error(error.message);
3815
+ await logEvent({
3816
+ activityType: "deal_archived",
3817
+ title: deal?.title || "Deal",
3818
+ dealId,
3819
+ contactName: deal?.contactName
3820
+ });
3821
+ },
3822
+ async archiveLead(leadId) {
3823
+ const { core } = getClients();
3824
+ const lead = await provider.getLeadById(leadId);
3825
+ const { error } = await core.from("people").update({ is_active: false }).eq("id", leadId);
3826
+ if (error) throw new Error(error.message);
3827
+ try {
3828
+ const deal = await provider.getDealByLeadId(leadId);
3829
+ if (deal && deal.status === "open") await provider.archiveDeal(deal.id);
3830
+ } catch {
3831
+ }
3832
+ await logEvent({
3833
+ activityType: "lead_archived",
3834
+ title: lead?.name ?? "Lead",
3835
+ leadId,
3836
+ contactName: lead?.name
3837
+ });
3214
3838
  },
3215
3839
  // --- Activities (public.plg_crm_activities) ---
3216
3840
  async getActivities(query) {
@@ -3250,6 +3874,21 @@ function createSupabaseCrmProvider(options) {
3250
3874
  if (error) throw new Error(error.message);
3251
3875
  return snakeToCamel(data);
3252
3876
  },
3877
+ async getActivityTypes() {
3878
+ const { pub } = getClients();
3879
+ const tenantId = getTenantId();
3880
+ if (!tenantId) return [];
3881
+ await ensureActivityTypes(tenantId);
3882
+ const { data } = await pub.from(T.activityTypes).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3883
+ return (data ?? []).map((r) => snakeToCamel(r));
3884
+ },
3885
+ async getTagDefs() {
3886
+ const { pub } = getClients();
3887
+ const tenantId = getTenantId();
3888
+ if (!tenantId) return [];
3889
+ const { data } = await pub.from(T.tags).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3890
+ return (data ?? []).filter((r) => r.slug).map((r) => snakeToCamel(r));
3891
+ },
3253
3892
  // --- Quotes (public.orders kind='quote' + order_items) ---
3254
3893
  async getQuotes(query) {
3255
3894
  const { core } = getClients();
@@ -3257,6 +3896,8 @@ function createSupabaseCrmProvider(options) {
3257
3896
  if (query.status) {
3258
3897
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3259
3898
  qb = qb.in("status", statuses);
3899
+ } else {
3900
+ qb = qb.neq("status", "archived");
3260
3901
  }
3261
3902
  if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`);
3262
3903
  const page = query.page ?? 1;
@@ -3359,6 +4000,18 @@ function createSupabaseCrmProvider(options) {
3359
4000
  );
3360
4001
  if (itemsError) throw new Error(itemsError.message);
3361
4002
  }
4003
+ if (input.dealId && totalAmount > 0) {
4004
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
4005
+ }
4006
+ await logEvent({
4007
+ activityType: "quote_created",
4008
+ title: order.reference_number ?? "Quote",
4009
+ description: input.contactName,
4010
+ dealId: input.dealId,
4011
+ leadId: input.leadId,
4012
+ contactId: input.contactId,
4013
+ contactName: input.contactName
4014
+ });
3362
4015
  return {
3363
4016
  id: order.id,
3364
4017
  quoteNumber: order.reference_number,
@@ -3402,6 +4055,9 @@ function createSupabaseCrmProvider(options) {
3402
4055
  );
3403
4056
  if (itemsError) throw new Error(itemsError.message);
3404
4057
  }
4058
+ if (input.dealId && totalAmount > 0) {
4059
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
4060
+ }
3405
4061
  return await provider.getQuoteById(id);
3406
4062
  },
3407
4063
  async sendQuote(id) {
@@ -3422,7 +4078,16 @@ function createSupabaseCrmProvider(options) {
3422
4078
  }
3423
4079
  } catch {
3424
4080
  }
3425
- return await provider.getQuoteById(id);
4081
+ const sent = await provider.getQuoteById(id);
4082
+ await logEvent({
4083
+ activityType: "quote_sent",
4084
+ title: sent.quoteNumber ?? "Quote",
4085
+ description: sent.contactName,
4086
+ dealId: sent.dealId,
4087
+ leadId: sent.leadId,
4088
+ contactName: sent.contactName
4089
+ });
4090
+ return sent;
3426
4091
  },
3427
4092
  async approveQuote(id) {
3428
4093
  const { core, pub } = getClients();
@@ -3466,7 +4131,16 @@ function createSupabaseCrmProvider(options) {
3466
4131
  }
3467
4132
  }
3468
4133
  }
3469
- return await provider.getQuoteById(id);
4134
+ const approved = await provider.getQuoteById(id);
4135
+ await logEvent({
4136
+ activityType: "quote_approved",
4137
+ title: approved.quoteNumber ?? "Quote",
4138
+ description: approved.contactName,
4139
+ dealId: approved.dealId,
4140
+ leadId: approved.leadId,
4141
+ contactName: approved.contactName
4142
+ });
4143
+ return approved;
3470
4144
  },
3471
4145
  async rejectQuote(id, reason) {
3472
4146
  const { core } = getClients();
@@ -3486,6 +4160,16 @@ function createSupabaseCrmProvider(options) {
3486
4160
  if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id);
3487
4161
  }
3488
4162
  }
4163
+ if (quote) {
4164
+ await logEvent({
4165
+ activityType: "quote_rejected",
4166
+ title: quote.quoteNumber ?? "Quote",
4167
+ description: reason,
4168
+ dealId: quote.dealId,
4169
+ leadId: quote.leadId,
4170
+ contactName: quote.contactName
4171
+ });
4172
+ }
3489
4173
  return quote;
3490
4174
  },
3491
4175
  async expireQuote(id) {
@@ -3493,6 +4177,20 @@ function createSupabaseCrmProvider(options) {
3493
4177
  await core.from("orders").update({ status: "expired" }).eq("id", id);
3494
4178
  return await provider.getQuoteById(id);
3495
4179
  },
4180
+ async archiveQuote(id) {
4181
+ const { core } = getClients();
4182
+ const quote = await provider.getQuoteById(id);
4183
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", id);
4184
+ if (error) throw new Error(error.message);
4185
+ await logEvent({
4186
+ activityType: "quote_archived",
4187
+ title: quote?.quoteNumber ?? "Quote",
4188
+ description: quote?.contactName,
4189
+ dealId: quote?.dealId,
4190
+ leadId: quote?.leadId,
4191
+ contactName: quote?.contactName
4192
+ });
4193
+ },
3496
4194
  // Cross-entity lookups
3497
4195
  async getQuotesByDealId(dealId) {
3498
4196
  const { core } = getClients();
@@ -3568,6 +4266,8 @@ function createSupabaseCrmProvider(options) {
3568
4266
  return provider;
3569
4267
  }
3570
4268
  function createCrmStore(provider) {
4269
+ let lastActivitiesQuery = {};
4270
+ let lastBoard = null;
3571
4271
  return createStore$1((set, get) => ({
3572
4272
  pipelines: [],
3573
4273
  stages: [],
@@ -3587,6 +4287,7 @@ function createCrmStore(provider) {
3587
4287
  summary: null,
3588
4288
  summaryLoading: false,
3589
4289
  funnel: [],
4290
+ tagDefs: /* @__PURE__ */ new Map(),
3590
4291
  async fetchPipelines() {
3591
4292
  return dedup("crm:pipelines", async () => {
3592
4293
  const pipelines = await provider.getPipelines();
@@ -3594,6 +4295,15 @@ function createCrmStore(provider) {
3594
4295
  set({ pipelines, stages });
3595
4296
  });
3596
4297
  },
4298
+ async fetchTagDefs() {
4299
+ return dedup("crm:tag-defs", async () => {
4300
+ try {
4301
+ const defs = await provider.getTagDefs();
4302
+ set({ tagDefs: new Map(defs.map((d) => [d.slug, d])) });
4303
+ } catch {
4304
+ }
4305
+ });
4306
+ },
3597
4307
  async fetchSummary() {
3598
4308
  return dedup("crm:summary", async () => {
3599
4309
  set({ summaryLoading: true });
@@ -3621,20 +4331,34 @@ function createCrmStore(provider) {
3621
4331
  set({ deals: result.data, dealsTotal: result.total, dealsLoading: false });
3622
4332
  });
3623
4333
  },
3624
- async fetchDealsByStage(pipelineId) {
3625
- return dedup("crm:dealsByStage:" + pipelineId, async () => {
4334
+ async fetchDealsByStage(pipelineId, filter) {
4335
+ lastBoard = { pipelineId, filter };
4336
+ const key = "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {});
4337
+ return dedup(key, async () => {
3626
4338
  set({ dealsLoading: true });
3627
- const dealsByStage = await provider.getDealsByStage(pipelineId);
4339
+ const dealsByStage = await provider.getDealsByStage(pipelineId, filter);
3628
4340
  set({ dealsByStage, dealsLoading: false });
3629
4341
  });
3630
4342
  },
4343
+ async refreshBoard() {
4344
+ if (!lastBoard) return;
4345
+ return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter);
4346
+ },
3631
4347
  async fetchActivities(query) {
4348
+ lastActivitiesQuery = query;
3632
4349
  return dedup("crm:activities:" + JSON.stringify(query), async () => {
3633
4350
  set({ activitiesLoading: true });
3634
4351
  const result = await provider.getActivities(query);
3635
4352
  set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false });
3636
4353
  });
3637
4354
  },
4355
+ async refreshActivities() {
4356
+ try {
4357
+ const result = await provider.getActivities(lastActivitiesQuery);
4358
+ set({ activities: result.data, activitiesTotal: result.total });
4359
+ } catch {
4360
+ }
4361
+ },
3638
4362
  async fetchQuotes(query) {
3639
4363
  return dedup("crm:quotes:" + JSON.stringify(query), async () => {
3640
4364
  set({ quotesLoading: true });
@@ -3668,6 +4392,7 @@ function createCrmStore(provider) {
3668
4392
  }
3669
4393
  const summary = await provider.getSummary();
3670
4394
  set({ summary });
4395
+ void get().refreshActivities();
3671
4396
  toast.success("Lead captured");
3672
4397
  return lead;
3673
4398
  } catch (err) {
@@ -3680,6 +4405,7 @@ function createCrmStore(provider) {
3680
4405
  const deal = await provider.createDeal(input);
3681
4406
  const [summary] = await Promise.all([provider.getSummary()]);
3682
4407
  set({ summary });
4408
+ void get().refreshActivities();
3683
4409
  toast.success("Deal created");
3684
4410
  return deal;
3685
4411
  } catch (err) {
@@ -3763,13 +4489,11 @@ function createCrmStore(provider) {
3763
4489
  }
3764
4490
  }
3765
4491
  set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }));
3766
- if (defaultPipeline) {
3767
- try {
3768
- const dealsByStage = await provider.getDealsByStage(defaultPipeline.id);
3769
- set({ dealsByStage });
3770
- } catch {
3771
- }
4492
+ try {
4493
+ await get().refreshBoard();
4494
+ } catch {
3772
4495
  }
4496
+ void get().refreshActivities();
3773
4497
  toast.success("Quote created");
3774
4498
  return quote;
3775
4499
  } catch (err) {
@@ -3792,6 +4516,7 @@ function createCrmStore(provider) {
3792
4516
  try {
3793
4517
  const quote = await provider.sendQuote(id);
3794
4518
  set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
4519
+ void get().refreshActivities();
3795
4520
  toast.success("Quote sent");
3796
4521
  return quote;
3797
4522
  } catch (err) {
@@ -3802,16 +4527,14 @@ function createCrmStore(provider) {
3802
4527
  async approveQuote(id) {
3803
4528
  try {
3804
4529
  const quote = await provider.approveQuote(id);
3805
- const { pipelines } = get();
3806
- if (pipelines.length > 0) {
3807
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3808
- provider.getDealsByStage(pipelines[0].id),
3809
- provider.getSummary(),
3810
- provider.getLeads({}),
3811
- provider.getQuotes({})
3812
- ]);
3813
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3814
- }
4530
+ const [summary, leadsResult, quotesResult] = await Promise.all([
4531
+ provider.getSummary(),
4532
+ provider.getLeads({}),
4533
+ provider.getQuotes({}),
4534
+ get().refreshBoard()
4535
+ ]);
4536
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4537
+ void get().refreshActivities();
3815
4538
  toast.success("Quote approved \u2014 invoice created");
3816
4539
  return quote;
3817
4540
  } catch (err) {
@@ -3822,16 +4545,14 @@ function createCrmStore(provider) {
3822
4545
  async rejectQuote(id, reason) {
3823
4546
  try {
3824
4547
  const quote = await provider.rejectQuote(id, reason);
3825
- const { pipelines } = get();
3826
- if (pipelines.length > 0) {
3827
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3828
- provider.getDealsByStage(pipelines[0].id),
3829
- provider.getSummary(),
3830
- provider.getLeads({}),
3831
- provider.getQuotes({})
3832
- ]);
3833
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3834
- }
4548
+ const [summary, leadsResult, quotesResult] = await Promise.all([
4549
+ provider.getSummary(),
4550
+ provider.getLeads({}),
4551
+ provider.getQuotes({}),
4552
+ get().refreshBoard()
4553
+ ]);
4554
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4555
+ void get().refreshActivities();
3835
4556
  toast.success("Quote rejected");
3836
4557
  return quote;
3837
4558
  } catch (err) {
@@ -3852,15 +4573,52 @@ function createCrmStore(provider) {
3852
4573
  },
3853
4574
  async moveDealToStage(dealId, stageId) {
3854
4575
  await provider.moveDealToStage(dealId, stageId);
3855
- const { pipelines } = get();
3856
- if (pipelines.length > 0) {
3857
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3858
- provider.getDealsByStage(pipelines[0].id),
3859
- provider.getSummary(),
4576
+ await get().refreshBoard();
4577
+ void get().refreshActivities();
4578
+ },
4579
+ async archiveDeal(dealId) {
4580
+ try {
4581
+ await provider.archiveDeal(dealId);
4582
+ const [, summary] = await Promise.all([
4583
+ get().refreshBoard(),
4584
+ provider.getSummary()
4585
+ ]);
4586
+ set({ summary });
4587
+ void get().refreshActivities();
4588
+ toast.success("Deal archived");
4589
+ } catch (err) {
4590
+ toast.error("Failed to archive deal", { description: err?.message });
4591
+ throw err;
4592
+ }
4593
+ },
4594
+ async archiveLead(leadId) {
4595
+ try {
4596
+ await provider.archiveLead(leadId);
4597
+ const [leadsResult, summary] = await Promise.all([
3860
4598
  provider.getLeads({}),
3861
- provider.getQuotes({})
4599
+ provider.getSummary(),
4600
+ get().refreshBoard()
3862
4601
  ]);
3863
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4602
+ set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary });
4603
+ void get().refreshActivities();
4604
+ toast.success("Lead archived");
4605
+ } catch (err) {
4606
+ toast.error("Failed to archive lead", { description: err?.message });
4607
+ throw err;
4608
+ }
4609
+ },
4610
+ async archiveQuote(quoteId) {
4611
+ try {
4612
+ await provider.archiveQuote(quoteId);
4613
+ set((state) => ({
4614
+ quotes: state.quotes.filter((q) => q.id !== quoteId),
4615
+ quotesTotal: Math.max(0, state.quotesTotal - 1)
4616
+ }));
4617
+ void get().refreshActivities();
4618
+ toast.success("Quote archived");
4619
+ } catch (err) {
4620
+ toast.error("Failed to archive quote", { description: err?.message });
4621
+ throw err;
3864
4622
  }
3865
4623
  }
3866
4624
  }));
@@ -3887,6 +4645,11 @@ var tagEntity = {
3887
4645
  defaultSort: "name",
3888
4646
  fields: [
3889
4647
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
4648
+ // O slug é o que vive em people.tags/orders.tags — renomear a tag NÃO o
4649
+ // muda (o trigger só o deriva quando está vazio), e é por isso que renomear
4650
+ // não órfã registro. Exposto porque, quando um chip não aparece onde
4651
+ // deveria, a resposta está sempre aqui.
4652
+ { key: "slug", label: "Slug", type: "text", showInTable: true },
3890
4653
  { key: "color", label: "Color", type: "color", showInTable: true, defaultValue: "#6366f1" },
3891
4654
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3892
4655
  ],
@@ -3924,10 +4687,19 @@ var activityTypeEntity = {
3924
4687
  defaultSort: "name",
3925
4688
  fields: [
3926
4689
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3927
- { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
4690
+ { key: "icon", label: "Icon", type: "text", showInTable: true },
4691
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
3928
4692
  ],
3929
4693
  data: { table: T.activityTypes, tenantScoped: true }
3930
4694
  };
4695
+ var DEFAULT_ACTIVITY_TYPES = [
4696
+ { value: "call", label: "Call", icon: "Phone" },
4697
+ { value: "email", label: "Email", icon: "Mail" },
4698
+ { value: "meeting", label: "Meeting", icon: "Users" },
4699
+ { value: "note", label: "Note", icon: "FileText" },
4700
+ { value: "task", label: "Task", icon: "CheckSquare" },
4701
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
4702
+ ];
3931
4703
  var crmRegistries = [
3932
4704
  {
3933
4705
  id: "stages",
@@ -3965,10 +4737,14 @@ var crmRegistries = [
3965
4737
  icon: "Tag",
3966
4738
  description: "Tags for organizing leads and deals",
3967
4739
  display: "table",
4740
+ // Só alimenta o provider MOCK (apps sem Supabase). Contra o banco, o
4741
+ // cadastro se alimenta do uso: `crm_register_tags` insere a linha quando
4742
+ // uma tag é gravada num lead. Semear vocabulário aqui encheria a tela de
4743
+ // tags que nenhum registro carrega.
3968
4744
  seedData: [
3969
- { id: "tag-vip", name: "VIP", color: "#f59e0b", isActive: true },
3970
- { id: "tag-hot", name: "Hot Lead", color: "#ef4444", isActive: true },
3971
- { id: "tag-followup", name: "Follow-up", color: "#3b82f6", isActive: true }
4745
+ { id: "tag-vip", name: "VIP", slug: "vip", color: "#f59e0b", isActive: true },
4746
+ { id: "tag-hot", name: "Hot Lead", slug: "hot-lead", color: "#ef4444", isActive: true },
4747
+ { id: "tag-followup", name: "Follow-up", slug: "follow-up", color: "#3b82f6", isActive: true }
3972
4748
  ]
3973
4749
  },
3974
4750
  {
@@ -3977,17 +4753,25 @@ var crmRegistries = [
3977
4753
  icon: "MessageCircle",
3978
4754
  description: "Types of activities and interactions",
3979
4755
  display: "table",
3980
- readOnly: true,
4756
+ // Tenant-editable (the provider lazily seeds the app's set per tenant);
4757
+ // system timeline events (lead_created, stage_changed…) are product-defined
4758
+ // and never appear here.
3981
4759
  seedData: [
3982
- { id: "at-call", name: "Call", isActive: true },
3983
- { id: "at-email", name: "Email", isActive: true },
3984
- { id: "at-meeting", name: "Meeting", isActive: true },
3985
- { id: "at-note", name: "Note", isActive: true },
3986
- { id: "at-task", name: "Task", isActive: true },
3987
- { id: "at-whatsapp", name: "WhatsApp", isActive: true }
4760
+ ...DEFAULT_ACTIVITY_TYPES.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
3988
4761
  ]
3989
4762
  }
3990
4763
  ];
4764
+ function buildCrmRegistries(activityTypes) {
4765
+ if (!activityTypes?.length) return crmRegistries;
4766
+ return crmRegistries.map(
4767
+ (registry) => registry.id === "activity-types" ? {
4768
+ ...registry,
4769
+ seedData: [
4770
+ ...activityTypes.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
4771
+ ]
4772
+ } : registry
4773
+ );
4774
+ }
3991
4775
 
3992
4776
  // src/locales/en.ts
3993
4777
  var en = {
@@ -4001,6 +4785,7 @@ var en = {
4001
4785
  "crm.activities.overdueLabel": "Overdue",
4002
4786
  "crm.activities.pending": "pending",
4003
4787
  "crm.activities.pendingFilter": "Pending",
4788
+ "crm.activities.systemEvents": "Events",
4004
4789
  "crm.activities.title": "Activities",
4005
4790
  "crm.dashboard.activeDeals": "{{count}} active deals",
4006
4791
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -4047,6 +4832,7 @@ var en = {
4047
4832
  "crm.dealSidebar.value": "Value",
4048
4833
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
4049
4834
  "crm.leadDetail.assignedTo": "Assigned to",
4835
+ "crm.leadDetail.archive": "Archive",
4050
4836
  "crm.leadDetail.backToList": "Back to list",
4051
4837
  "crm.leadDetail.formAnswers": "Form answers",
4052
4838
  "crm.leadDetail.company": "Company",
@@ -4105,7 +4891,17 @@ var en = {
4105
4891
  "crm.page.newQuoteDesc": "Send a proposal",
4106
4892
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
4107
4893
  "crm.page.settingsTitle": "Sales & CRM Settings",
4894
+ "crm.filters.period": "Period",
4895
+ "crm.filters.periodAll": "All",
4896
+ "crm.filters.period24h": "24 hours",
4897
+ "crm.filters.period7d": "7 days",
4898
+ "crm.filters.periodCustom": "Custom",
4899
+ "crm.filters.tags": "Tags",
4900
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
4901
+ "crm.filters.clearTags": "Clear tags",
4902
+ "crm.filters.noResults": "No deals match the current filter",
4108
4903
  "crm.pipeline.dropHere": "Drop here",
4904
+ "crm.pipeline.archive": "Archive",
4109
4905
  "crm.pipeline.moveFailed": "Failed to move deal",
4110
4906
  "crm.pipeline.movedTo": "Moved to {{stage}}",
4111
4907
  "crm.pipeline.noDeals": "No deals",
@@ -4184,6 +4980,7 @@ var en = {
4184
4980
  "crm.quoteForm.unitPrice": "Unit Price",
4185
4981
  "crm.quoteForm.validUntil": "Valid Until",
4186
4982
  "crm.quotes.amount": "Amount",
4983
+ "crm.quotes.archive": "Archive",
4187
4984
  "crm.quotes.contact": "Contact",
4188
4985
  "crm.quotes.createFirst": "Create your first quote",
4189
4986
  "crm.quotes.date": "Date",
@@ -4295,6 +5092,7 @@ var ptBR = {
4295
5092
  "crm.activities.overdueLabel": "Atrasada",
4296
5093
  "crm.activities.pending": "pendente",
4297
5094
  "crm.activities.pendingFilter": "Pendentes",
5095
+ "crm.activities.systemEvents": "Eventos",
4298
5096
  "crm.activities.title": "Atividades",
4299
5097
  "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
4300
5098
  "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
@@ -4341,6 +5139,7 @@ var ptBR = {
4341
5139
  "crm.dealSidebar.value": "Valor",
4342
5140
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
4343
5141
  "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
5142
+ "crm.leadDetail.archive": "Arquivar",
4344
5143
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
4345
5144
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
4346
5145
  "crm.leadDetail.company": "Empresa",
@@ -4396,10 +5195,20 @@ var ptBR = {
4396
5195
  "crm.page.newLead": "Novo Lead",
4397
5196
  "crm.page.newLeadDesc": "Capturar um novo lead",
4398
5197
  "crm.page.newQuote": "Novo Or\xE7amento",
4399
- "crm.page.newQuoteDesc": "Enviar uma proposta",
5198
+ "crm.page.newQuoteDesc": "Enviar um or\xE7amento",
4400
5199
  "crm.page.settingsSubtitle": "Configure pipeline, gest\xE3o de leads e cadastros",
4401
5200
  "crm.page.settingsTitle": "Configura\xE7\xF5es de Vendas e CRM",
5201
+ "crm.filters.period": "Per\xEDodo",
5202
+ "crm.filters.periodAll": "Tudo",
5203
+ "crm.filters.period24h": "24 horas",
5204
+ "crm.filters.period7d": "7 dias",
5205
+ "crm.filters.periodCustom": "Personalizado",
5206
+ "crm.filters.tags": "Tags",
5207
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
5208
+ "crm.filters.clearTags": "Limpar tags",
5209
+ "crm.filters.noResults": "Nenhum neg\xF3cio no filtro atual",
4402
5210
  "crm.pipeline.dropHere": "Solte aqui",
5211
+ "crm.pipeline.archive": "Arquivar",
4403
5212
  "crm.pipeline.moveFailed": "Falha ao mover neg\xF3cio",
4404
5213
  "crm.pipeline.movedTo": "Movido para {{stage}}",
4405
5214
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
@@ -4445,12 +5254,12 @@ var ptBR = {
4445
5254
  "crm.quoteForm.description": "Descri\xE7\xE3o",
4446
5255
  "crm.quoteForm.discount": "Desconto",
4447
5256
  "crm.quoteForm.done": "Conclu\xEDdo",
4448
- "crm.quoteForm.editSubtitle": "Atualizar esta proposta",
5257
+ "crm.quoteForm.editSubtitle": "Atualizar este or\xE7amento",
4449
5258
  "crm.quoteForm.editTitle": "Editar Or\xE7amento",
4450
5259
  "crm.quoteForm.itemCount": "{{count}} itens",
4451
5260
  "crm.quoteForm.itemDescriptionPlaceholder": "Descri\xE7\xE3o do item",
4452
5261
  "crm.quoteForm.loading": "Carregando...",
4453
- "crm.quoteForm.newSubtitle": "Criar uma proposta para seu cliente",
5262
+ "crm.quoteForm.newSubtitle": "Criar um or\xE7amento para seu cliente",
4454
5263
  "crm.quoteForm.newTitle": "Novo Or\xE7amento",
4455
5264
  "crm.quoteForm.noDescription": "Sem descri\xE7\xE3o",
4456
5265
  "crm.quoteForm.noItems": "Nenhum item adicionado",
@@ -4478,6 +5287,7 @@ var ptBR = {
4478
5287
  "crm.quoteForm.unitPrice": "Pre\xE7o Unit\xE1rio",
4479
5288
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
4480
5289
  "crm.quotes.amount": "Valor",
5290
+ "crm.quotes.archive": "Arquivar",
4481
5291
  "crm.quotes.contact": "Contato",
4482
5292
  "crm.quotes.createFirst": "Crie seu primeiro or\xE7amento",
4483
5293
  "crm.quotes.date": "Data",
@@ -4491,7 +5301,7 @@ var ptBR = {
4491
5301
  "crm.quickActions.newDeal": "Novo Neg\xF3cio",
4492
5302
  "crm.quickActions.newDealDesc": "Criar um neg\xF3cio no pipeline",
4493
5303
  "crm.quickActions.newQuote": "Novo Or\xE7amento",
4494
- "crm.quickActions.newQuoteDesc": "Enviar uma proposta",
5304
+ "crm.quickActions.newQuoteDesc": "Enviar um or\xE7amento",
4495
5305
  "crm.quickActions.logActivity": "Registrar Atividade",
4496
5306
  "crm.quickActions.logActivityDesc": "Registrar liga\xE7\xE3o, e-mail ou nota",
4497
5307
  "crm.settingsPage.title": "Configura\xE7\xF5es de Vendas e CRM",
@@ -4528,7 +5338,7 @@ var ptBR = {
4528
5338
  "crm.settings.weightedPipeline": "Valor ponderado do pipeline",
4529
5339
  "crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do est\xE1gio",
4530
5340
  "crm.settings.quotes": "Or\xE7amentos",
4531
- "crm.settings.quotesDesc": "Comportamento de or\xE7amentos e propostas",
5341
+ "crm.settings.quotesDesc": "Comportamento de or\xE7amentos",
4532
5342
  "crm.settings.autoNumberQuotes": "Numera\xE7\xE3o autom\xE1tica de or\xE7amentos",
4533
5343
  "crm.settings.autoNumberQuotesDesc": "Gerar automaticamente n\xFAmeros sequenciais de or\xE7amentos",
4534
5344
  "crm.settings.defaultValidity": "Validade padr\xE3o (30 dias)",
@@ -4621,12 +5431,14 @@ function resolveConfig(options) {
4621
5431
  function createCrmPlugin(options) {
4622
5432
  const config = resolveConfig(options);
4623
5433
  registerTranslations(crmLocales);
5434
+ const activityTypes = options?.activityTypes ?? DEFAULT_ACTIVITY_TYPES;
5435
+ const crmRegistries2 = buildCrmRegistries(activityTypes);
4624
5436
  const provider = options?.dataProvider ?? createSafeDataProvider(
4625
- () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
4626
- () => createMockCrmProvider()
5437
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion, activityTypes }),
5438
+ () => createMockCrmProvider({ activityTypes })
4627
5439
  );
4628
5440
  const store = createCrmStore(provider);
4629
- const PageComponent = () => React14.createElement(CrmPage, { config, provider, store, registries: crmRegistries });
5441
+ const PageComponent = () => React15.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
4630
5442
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
4631
5443
  return {
4632
5444
  id: "crm",
@@ -4655,6 +5467,86 @@ function createCrmPlugin(options) {
4655
5467
  { key: "deals", label: "Deals", table: "orders", kindFilter: "deal" },
4656
5468
  { key: "quotes", label: "Quotes", table: "orders", kindFilter: "quote" }
4657
5469
  ],
5470
+ // Read-models for the agent's data primitives (searchRecords/queryData).
5471
+ // Without these the assistant cannot see leads/deals/activities at all and
5472
+ // guesses wrong entities ("quem tá aguardando contato?" → invented filter
5473
+ // on Cliente). Keys are stable ASCII; fields are camelCase output shape.
5474
+ queryEntities: [
5475
+ {
5476
+ key: "crm:leads",
5477
+ writable: false,
5478
+ entity: {
5479
+ name: "Lead",
5480
+ namePlural: "Leads",
5481
+ icon: "UserPlus",
5482
+ permission: { feature: "crm.leads", action: "read" },
5483
+ fields: [
5484
+ { key: "name", label: "Name", type: "text", searchable: true },
5485
+ { key: "email", label: "Email", type: "text", searchable: true },
5486
+ { key: "phone", label: "Phone", type: "text", searchable: true },
5487
+ { key: "company", label: "Company", type: "text" },
5488
+ { key: "status", label: "Status (new=awaiting first contact, contacted, qualified, converted, lost)", type: "text" },
5489
+ { key: "sourceName", label: "Source", type: "text" },
5490
+ { key: "createdAt", label: "Created at", type: "text" }
5491
+ ],
5492
+ data: {
5493
+ table: "v_leads",
5494
+ tenantScoped: true,
5495
+ searchColumns: ["name", "email", "phone"]
5496
+ }
5497
+ }
5498
+ },
5499
+ {
5500
+ key: "crm:deals",
5501
+ writable: false,
5502
+ entity: {
5503
+ name: "Deal",
5504
+ namePlural: "Deals",
5505
+ icon: "Target",
5506
+ permission: { feature: "crm.pipeline", action: "read" },
5507
+ fields: [
5508
+ { key: "title", label: "Title", type: "text", searchable: true },
5509
+ { key: "value", label: "Value", type: "number" },
5510
+ { key: "status", label: "Status (open/won/lost)", type: "text" },
5511
+ { key: "stage", label: "Pipeline stage name", type: "text" },
5512
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5513
+ { key: "probability", label: "Probability %", type: "number" },
5514
+ { key: "expectedCloseDate", label: "Expected close", type: "text" },
5515
+ { key: "createdAt", label: "Created at", type: "text" }
5516
+ ],
5517
+ data: {
5518
+ table: "v_deals",
5519
+ tenantScoped: true,
5520
+ searchColumns: ["title", "contact_name"]
5521
+ }
5522
+ }
5523
+ },
5524
+ {
5525
+ key: "crm:activities",
5526
+ writable: false,
5527
+ entity: {
5528
+ name: "CRM activity",
5529
+ namePlural: "CRM activities",
5530
+ icon: "MessageCircle",
5531
+ permission: { feature: "sales", action: "read" },
5532
+ fields: [
5533
+ { key: "activityType", label: "Type (call/email/note\u2026 or system events: lead_created, deal_won, quote_approved\u2026)", type: "text" },
5534
+ { key: "title", label: "Title", type: "text", searchable: true },
5535
+ { key: "description", label: "Description", type: "text", searchable: true },
5536
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5537
+ { key: "dueDate", label: "Due date", type: "text" },
5538
+ { key: "completedAt", label: "Completed at", type: "text" },
5539
+ { key: "assignedToName", label: "Assigned to", type: "text" },
5540
+ { key: "createdAt", label: "Created at", type: "text" }
5541
+ ],
5542
+ data: {
5543
+ table: "plg_crm_activities",
5544
+ tenantScoped: true,
5545
+ searchColumns: ["title", "contact_name", "description"]
5546
+ }
5547
+ }
5548
+ }
5549
+ ],
4658
5550
  navigation: [
4659
5551
  {
4660
5552
  section: options?.navSection ?? "main",
@@ -4716,23 +5608,103 @@ function createCrmPlugin(options) {
4716
5608
  { label: "Which leads need follow-up?" },
4717
5609
  { label: "What's our conversion rate?" }
4718
5610
  ]
5611
+ },
5612
+ {
5613
+ id: "crm.create-lead",
5614
+ name: "createLead",
5615
+ description: 'Opens a NEW lead. This is the ONLY way to create one \u2014 the leads entity is a read-only view, so createRecord cannot. Only `name` is required; send whatever else the user gave and omit the rest. Status defaults to "new" and belongs to a closed set: new, contacted, qualified, converted, lost. A lead whose e-mail or phone already exists is NOT duplicated \u2014 the existing one comes back with deduped:true, and changing it is updateLead. The user confirms before anything is written.',
5616
+ icon: "UserPlus",
5617
+ mode: "persist",
5618
+ limitKey: "leads",
5619
+ execution: { plane: "server", kind: "rpc", rpc: "agent_crm_create_lead" },
5620
+ category: "Sales",
5621
+ parameters: {
5622
+ type: "object",
5623
+ properties: {
5624
+ name: { type: "string", description: "The person's name" },
5625
+ email: { type: "string", description: "E-mail" },
5626
+ phone: { type: "string", description: "Phone" },
5627
+ company: { type: "string", description: "Company" },
5628
+ status: {
5629
+ type: "string",
5630
+ description: 'Funnel stage \u2014 defaults to "new"',
5631
+ enum: ["new", "contacted", "qualified", "converted", "lost"]
5632
+ },
5633
+ value: { type: "string", description: "Estimated value" },
5634
+ source_name: { type: "string", description: "Where the lead came from" },
5635
+ assigned_to_id: { type: "string", description: "Person the lead is assigned to (id)" },
5636
+ notes: { type: "string", description: "Notes" }
5637
+ },
5638
+ required: ["name"]
5639
+ },
5640
+ suggestions: [
5641
+ { label: "Cria um lead Noronha, interessado em tratamento facial" }
5642
+ ],
5643
+ permission: { feature: "sales", action: "create" }
5644
+ },
5645
+ {
5646
+ id: "crm.update-lead",
5647
+ name: "updateLead",
5648
+ description: 'Changes a lead that ALREADY EXISTS: move its status through the funnel, reassign it, or fix its data (name, email, phone, company, value, notes). This is the ONLY way to change a lead \u2014 the leads entity is a read-only view, so updateRecord cannot touch it. Status is a closed set: new (awaiting first contact), contacted, qualified, converted, lost. A proposal that went out is usually "qualified"; a closed sale is "converted". Takes the lead id from a previous search. The user confirms before anything changes.',
5649
+ icon: "UserCheck",
5650
+ mode: "persist",
5651
+ execution: { plane: "server", kind: "rpc", rpc: "agent_crm_update_lead" },
5652
+ category: "Sales",
5653
+ parameters: {
5654
+ type: "object",
5655
+ properties: {
5656
+ lead_id: { type: "string", description: "Id of the lead to change (from a search)" },
5657
+ status: {
5658
+ type: "string",
5659
+ description: "New funnel stage",
5660
+ enum: ["new", "contacted", "qualified", "converted", "lost"]
5661
+ },
5662
+ name: { type: "string", description: "Corrected name" },
5663
+ email: { type: "string", description: "Corrected e-mail" },
5664
+ phone: { type: "string", description: "Corrected phone" },
5665
+ company: { type: "string", description: "Company" },
5666
+ value: { type: "string", description: "Estimated value" },
5667
+ assigned_to_id: { type: "string", description: "Person the lead is assigned to (id)" },
5668
+ notes: { type: "string", description: "Notes" }
5669
+ },
5670
+ required: ["lead_id"]
5671
+ },
5672
+ suggestions: [
5673
+ { label: "Mandei a proposta pro Vini, atualiza o status" },
5674
+ { label: "Marca esse lead como perdido" }
5675
+ ],
5676
+ permission: { feature: "sales", action: "edit" }
5677
+ }
5678
+ ],
5679
+ declaredRpcs: [
5680
+ {
5681
+ name: "agent_crm_create_lead",
5682
+ kind: "write",
5683
+ description: "Guarded lead create: agent_guard (role\u2192plan\u2192leads cap), closed status set, e-mail/phone dedupe, audited.",
5684
+ audits: true
5685
+ },
5686
+ {
5687
+ name: "agent_crm_update_lead",
5688
+ kind: "write",
5689
+ description: "Guarded lead update: agent_guard (role\u2192plan, no cap), closed status set, tenant+kind checked, audited.",
5690
+ audits: true
4719
5691
  }
4720
5692
  ],
4721
- registries: crmRegistries,
5693
+ registries: crmRegistries2,
4722
5694
  settings: [
4723
5695
  {
4724
5696
  id: "crm",
4725
5697
  label: "Sales & CRM",
4726
5698
  icon: "Filter",
4727
5699
  component: (() => {
4728
- const Tab = () => React14.createElement(
5700
+ const Tab = () => React15.createElement(
4729
5701
  CrmContextProvider,
4730
5702
  { config, provider, store },
4731
- React14.createElement(PluginSettingsPanel, {
5703
+ React15.createElement(PluginSettingsPanel, {
4732
5704
  title: "Sales & CRM",
4733
5705
  subtitle: "Pipeline, lead management, and CRM properties",
4734
- generalSettings: React14.createElement(CrmGeneralSettings),
4735
- registries: crmRegistries,
5706
+ generalSettings: React15.createElement(CrmGeneralSettings),
5707
+ registries: crmRegistries2,
4736
5708
  hostPluginId: "crm",
4737
5709
  routeBase: "/settings/crm"
4738
5710
  })
@@ -4748,6 +5720,6 @@ function createCrmPlugin(options) {
4748
5720
  };
4749
5721
  }
4750
5722
 
4751
- export { createCrmPlugin };
5723
+ export { TagChips, createCrmPlugin, humanizeTag };
4752
5724
  //# sourceMappingURL=index.js.map
4753
5725
  //# sourceMappingURL=index.js.map