@fayz-ai/plugin-crm 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/dist/cascade.d.ts.map +1 -1
  2. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  3. package/dist/data/mock.d.ts +5 -0
  4. package/dist/data/mock.d.ts.map +1 -1
  5. package/dist/data/supabase.d.ts +6 -0
  6. package/dist/data/supabase.d.ts.map +1 -1
  7. package/dist/data/types.d.ts +9 -1
  8. package/dist/data/types.d.ts.map +1 -1
  9. package/dist/index.cjs +698 -103
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +701 -106
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/access.d.ts +8 -0
  15. package/dist/lib/access.d.ts.map +1 -0
  16. package/dist/locales/en.d.ts.map +1 -1
  17. package/dist/locales/pt-BR.d.ts.map +1 -1
  18. package/dist/migrations/index.d.ts +5 -1
  19. package/dist/migrations/index.d.ts.map +1 -1
  20. package/dist/public/index.cjs +1 -1
  21. package/dist/public/index.cjs.map +1 -1
  22. package/dist/public/index.js +2 -2
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/registries.d.ts +11 -0
  25. package/dist/registries.d.ts.map +1 -1
  26. package/dist/store.d.ts +5 -0
  27. package/dist/store.d.ts.map +1 -1
  28. package/dist/types.d.ts +14 -2
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/views/ActivityListView.d.ts +6 -1
  31. package/dist/views/ActivityListView.d.ts.map +1 -1
  32. package/dist/views/DealSidebar.d.ts.map +1 -1
  33. package/dist/views/LeadDetailView.d.ts.map +1 -1
  34. package/dist/views/PipelineView.d.ts.map +1 -1
  35. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  36. package/dist/views/QuoteListView.d.ts.map +1 -1
  37. package/package.json +5 -5
  38. package/src/CrmPage.tsx +1 -1
  39. package/src/cascade.ts +2 -0
  40. package/src/components/QuoteStatusDropdown.tsx +15 -3
  41. package/src/data/mock.ts +110 -4
  42. package/src/data/supabase.ts +186 -8
  43. package/src/data/types.ts +9 -1
  44. package/src/index.ts +85 -3
  45. package/src/lib/access.ts +11 -0
  46. package/src/locales/en.ts +4 -0
  47. package/src/locales/pt-BR.ts +9 -5
  48. package/src/migrations/003_crm_views_rls.sql +10 -2
  49. package/src/migrations/007_activity_log.sql +55 -0
  50. package/src/migrations/008_view_field_aliases.sql +43 -0
  51. package/src/migrations/009_deal_archived_status.sql +30 -0
  52. package/src/migrations/010_quote_archived_status.sql +40 -0
  53. package/src/migrations/index.ts +191 -3
  54. package/src/public/data.supabase.ts +2 -2
  55. package/src/registries.ts +32 -8
  56. package/src/store.ts +76 -0
  57. package/src/types.ts +19 -2
  58. package/src/views/ActivityListView.tsx +79 -11
  59. package/src/views/DealSidebar.tsx +39 -33
  60. package/src/views/LeadDetailView.tsx +29 -10
  61. package/src/views/PipelineView.tsx +22 -4
  62. package/src/views/QuoteDetailView.tsx +7 -3
  63. package/src/views/QuoteListView.tsx +26 -12
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
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';
2
+ import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, useLimitGuard, formatCurrency, PersonLink, useAccessOptional, invalidateLimit } from '@fayz-ai/saas';
3
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';
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, SegmentedControl, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
5
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';
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, 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("");
@@ -286,27 +295,40 @@ var TYPE_ICONS = {
286
295
  meeting: Users,
287
296
  note: FileText,
288
297
  task: CheckSquare,
289
- whatsapp: MessageCircle
298
+ whatsapp: MessageCircle,
299
+ // System timeline events (auto-logged by the provider)
300
+ lead_created: UserPlus,
301
+ lead_converted: ArrowRightLeft,
302
+ deal_created: Target,
303
+ stage_changed: MoveRight,
304
+ deal_won: Trophy,
305
+ deal_lost: XCircle,
306
+ quote_created: FilePlus2,
307
+ quote_sent: Send,
308
+ quote_approved: FileCheck2,
309
+ quote_rejected: FileX2,
310
+ lead_archived: Archive,
311
+ deal_archived: Archive,
312
+ quote_archived: Archive
290
313
  };
291
314
  function TabBar({ active, counts, onChange }) {
292
315
  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",
316
+ const label = (text, count, isActive) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
317
+ text,
318
+ 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 })
319
+ ] });
320
+ return /* @__PURE__ */ jsx("div", { className: "px-5 py-2 border-b shrink-0", children: /* @__PURE__ */ jsx(
321
+ SegmentedControl,
300
322
  {
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 })
323
+ value: active,
324
+ onChange,
325
+ options: [
326
+ { value: "overview", label: label(t2("crm.dealSidebar.overview"), void 0, active === "overview") },
327
+ { value: "activity", label: label(t2("crm.dealSidebar.activity"), counts.activity, active === "activity") },
328
+ { value: "quotes", label: label(t2("crm.dealSidebar.quotes"), counts.quotes, active === "quotes") }
306
329
  ]
307
- },
308
- tab.id
309
- )) });
330
+ }
331
+ ) });
310
332
  }
311
333
  function FormAnswers({ lead }) {
312
334
  const t2 = useTranslation();
@@ -394,18 +416,6 @@ function OverviewTab({ deal, lead, currency }) {
394
416
  deal.notes && deal.notes !== deal.title && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
395
417
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
396
418
  /* @__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
419
  ] })
410
420
  ] });
411
421
  }
@@ -557,6 +567,12 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
557
567
  onClose();
558
568
  }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
559
569
  ] }) : /* @__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") }) }) }),
570
+ deal && /* @__PURE__ */ jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
571
+ t2("crm.dealSidebar.created"),
572
+ " ",
573
+ deal.createdAt?.slice(0, 10),
574
+ deal.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${deal.updatedAt.slice(0, 10)}` : ""
575
+ ] }),
560
576
  deal && lead && onViewLead && /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsxs(
561
577
  "button",
562
578
  {
@@ -591,7 +607,8 @@ function PipelineSkeleton() {
591
607
  ] }, i)) })
592
608
  ] }, col)) });
593
609
  }
594
- function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
610
+ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onDragEnd }) {
611
+ const t2 = useTranslation();
595
612
  return /* @__PURE__ */ jsxs(
596
613
  "div",
597
614
  {
@@ -599,11 +616,23 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
599
616
  onDragStart,
600
617
  onDragEnd,
601
618
  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"}`,
619
+ 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
620
  children: [
604
621
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
605
622
  /* @__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" })
623
+ saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" }),
624
+ !saving && onArchive && /* @__PURE__ */ jsx(
625
+ "button",
626
+ {
627
+ onClick: (e) => {
628
+ e.stopPropagation();
629
+ onArchive();
630
+ },
631
+ title: t2("crm.pipeline.archive"),
632
+ 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",
633
+ children: /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" })
634
+ }
635
+ )
607
636
  ] }),
608
637
  deal.contactName && /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground mt-0.5", children: deal.contactName }),
609
638
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-2", children: [
@@ -617,7 +646,7 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
617
646
  }
618
647
  );
619
648
  }
620
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
649
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
621
650
  const t2 = useTranslation();
622
651
  const isOver = dragOverStageId === stageId;
623
652
  const [hovered, setHovered] = useState(false);
@@ -661,6 +690,7 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
661
690
  saving: savingDealIds.has(deal.id),
662
691
  currency,
663
692
  onClick: () => onDealClick?.(deal.id),
693
+ onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
664
694
  onDragStart: (e) => {
665
695
  e.dataTransfer.effectAllowed = "move";
666
696
  onDragStart(deal.id, stageId);
@@ -684,6 +714,8 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
684
714
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
685
715
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage);
686
716
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
717
+ const archiveDeal = useCrmStore((s) => s.archiveDeal);
718
+ const canArchive = useCanArchive();
687
719
  const [dragOverStageId, setDragOverStageId] = useState(null);
688
720
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
689
721
  const [optimisticBoard, setOptimisticBoard] = useState(null);
@@ -785,6 +817,9 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
785
817
  currency,
786
818
  dragOverStageId,
787
819
  onDealClick: handleDealClick,
820
+ onArchiveDeal: canArchive ? (id) => {
821
+ void archiveDeal(id);
822
+ } : void 0,
788
823
  onAddLead,
789
824
  onDragStart: handleDragStart,
790
825
  onDragEnd: handleDragEnd,
@@ -976,7 +1011,7 @@ var STATUS_COLORS = {
976
1011
  overdue: "bg-destructive-soft text-destructive-soft-foreground",
977
1012
  cancelled: "bg-muted text-muted-foreground"
978
1013
  };
979
- function useQuoteColumns(currency, onEditQuote) {
1014
+ function useQuoteColumns(currency, onEditQuote, onArchive) {
980
1015
  const t2 = useTranslation();
981
1016
  const cols = [
982
1017
  { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
@@ -996,22 +1031,36 @@ function useQuoteColumns(currency, onEditQuote) {
996
1031
  }
997
1032
  }
998
1033
  ];
999
- if (onEditQuote) {
1034
+ if (onEditQuote || onArchive) {
1000
1035
  cols.push({
1001
1036
  id: "actions",
1002
1037
  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
- ) })
1038
+ cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
1039
+ onEditQuote && /* @__PURE__ */ jsx(
1040
+ "button",
1041
+ {
1042
+ onClick: (e) => {
1043
+ e.stopPropagation();
1044
+ onEditQuote(row.original.id);
1045
+ },
1046
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1047
+ title: "Edit quote",
1048
+ children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
1049
+ }
1050
+ ),
1051
+ onArchive && /* @__PURE__ */ jsx(
1052
+ "button",
1053
+ {
1054
+ onClick: (e) => {
1055
+ e.stopPropagation();
1056
+ onArchive(row.original.id);
1057
+ },
1058
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1059
+ title: t2("crm.quotes.archive"),
1060
+ children: /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" })
1061
+ }
1062
+ )
1063
+ ] })
1015
1064
  });
1016
1065
  }
1017
1066
  return cols;
@@ -1022,10 +1071,14 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1022
1071
  const quotes = useCrmStore((s) => s.quotes);
1023
1072
  const quotesLoading = useCrmStore((s) => s.quotesLoading);
1024
1073
  const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
1074
+ const archiveQuote = useCrmStore((s) => s.archiveQuote);
1075
+ const canArchive = useCanArchive();
1025
1076
  useEffect(() => {
1026
1077
  fetchQuotes({});
1027
1078
  }, []);
1028
- const columns2 = useQuoteColumns(currency, onEditQuote);
1079
+ const columns2 = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
1080
+ void archiveQuote(id);
1081
+ } : void 0);
1029
1082
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1030
1083
  /* @__PURE__ */ jsx(
1031
1084
  SubpageHeader,
@@ -1723,7 +1776,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1723
1776
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap", children: quote.observations })
1724
1777
  ] })
1725
1778
  ] }),
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: [
1779
+ ["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
1780
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1728
1781
  /* @__PURE__ */ jsx(CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
1729
1782
  /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t2("crm.quoteDetail.invoiceCreated") })
@@ -1731,7 +1784,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1731
1784
  /* @__PURE__ */ jsxs(
1732
1785
  "a",
1733
1786
  {
1734
- href: `#/financial/receivables/detail/${quote.id}`,
1787
+ href: "#/financial/receivables/list",
1735
1788
  className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",
1736
1789
  children: [
1737
1790
  t2("crm.quoteDetail.viewInvoice"),
@@ -1813,6 +1866,9 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1813
1866
  const provider = useCrmProvider();
1814
1867
  const { currency } = useCrmConfig();
1815
1868
  const t2 = useTranslation();
1869
+ const archiveLead = useCrmStore((s) => s.archiveLead);
1870
+ const canArchive = useCanArchive();
1871
+ const [archiving, setArchiving] = useState(false);
1816
1872
  const [lead, setLead] = useState(null);
1817
1873
  const [deal, setDeal] = useState(null);
1818
1874
  const [quotes, setQuotes] = useState([]);
@@ -1876,18 +1932,37 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1876
1932
  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
1933
  ] })
1878
1934
  ] }),
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
- )
1935
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 shrink-0", children: [
1936
+ canArchive && /* @__PURE__ */ jsxs(
1937
+ "button",
1938
+ {
1939
+ onClick: () => {
1940
+ setArchiving(true);
1941
+ archiveLead(leadId).then(onBack).catch(() => setArchiving(false));
1942
+ },
1943
+ disabled: archiving,
1944
+ title: t2("crm.leadDetail.archive"),
1945
+ 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",
1946
+ children: [
1947
+ /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" }),
1948
+ " ",
1949
+ t2("crm.leadDetail.archive")
1950
+ ]
1951
+ }
1952
+ ),
1953
+ onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxs(
1954
+ "button",
1955
+ {
1956
+ onClick: () => onCreateQuote(leadId),
1957
+ 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",
1958
+ children: [
1959
+ /* @__PURE__ */ jsx(FileText, { className: "h-3 w-3" }),
1960
+ " ",
1961
+ t2("crm.leadDetail.createQuote")
1962
+ ]
1963
+ }
1964
+ )
1965
+ ] })
1891
1966
  ] }),
1892
1967
  /* @__PURE__ */ jsx("div", { className: "border-t" }),
1893
1968
  /* @__PURE__ */ jsxs("div", { children: [
@@ -1972,14 +2047,47 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1972
2047
  ] })
1973
2048
  ] });
1974
2049
  }
2050
+
2051
+ // src/types.ts
2052
+ var SYSTEM_ACTIVITY_TYPES = [
2053
+ "lead_created",
2054
+ "lead_converted",
2055
+ "lead_archived",
2056
+ "deal_created",
2057
+ "stage_changed",
2058
+ "deal_won",
2059
+ "deal_lost",
2060
+ "deal_archived",
2061
+ "quote_created",
2062
+ "quote_sent",
2063
+ "quote_approved",
2064
+ "quote_rejected",
2065
+ "quote_archived"
2066
+ ];
1975
2067
  var TYPE_CONFIG = {
1976
2068
  call: { icon: Phone, color: "bg-info/15 text-info dark:bg-info/20", label: "Call" },
1977
2069
  email: { icon: Mail, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Email" },
1978
2070
  meeting: { icon: Users, color: "bg-success-soft text-success-soft-foreground", label: "Meeting" },
1979
2071
  note: { icon: FileText, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Note" },
1980
2072
  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" }
2073
+ whatsapp: { icon: MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" },
2074
+ // System timeline events (auto-logged by the data provider on every CRM write)
2075
+ lead_created: { icon: UserPlus, color: "bg-info/15 text-info dark:bg-info/20", label: "Lead created" },
2076
+ lead_converted: { icon: ArrowRightLeft, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Lead converted" },
2077
+ deal_created: { icon: Target, color: "bg-info/15 text-info dark:bg-info/20", label: "Deal created" },
2078
+ stage_changed: { icon: MoveRight, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Stage changed" },
2079
+ deal_won: { icon: Trophy, color: "bg-success/15 text-success dark:bg-success/20", label: "Deal won" },
2080
+ deal_lost: { icon: XCircle, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Deal lost" },
2081
+ quote_created: { icon: FilePlus2, color: "bg-info/15 text-info dark:bg-info/20", label: "Quote created" },
2082
+ quote_sent: { icon: Send, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Quote sent" },
2083
+ quote_approved: { icon: FileCheck2, color: "bg-success/15 text-success dark:bg-success/20", label: "Quote approved" },
2084
+ quote_rejected: { icon: FileX2, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Quote rejected" },
2085
+ lead_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Lead archived" },
2086
+ deal_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Deal archived" },
2087
+ quote_archived: { icon: Archive, color: "bg-muted text-muted-foreground", label: "Quote archived" }
1982
2088
  };
2089
+ var SYSTEM_TYPES = new Set(SYSTEM_ACTIVITY_TYPES);
2090
+ var MANUAL_TYPES = Object.keys(TYPE_CONFIG).filter((t2) => !SYSTEM_TYPES.has(t2));
1983
2091
  function ActivitySkeleton() {
1984
2092
  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
2093
  /* @__PURE__ */ jsx("div", { className: "h-9 w-9 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
@@ -1994,20 +2102,23 @@ function ActivitySkeleton() {
1994
2102
  /* @__PURE__ */ jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse shrink-0" })
1995
2103
  ] }, i)) });
1996
2104
  }
1997
- function ActivityListView() {
2105
+ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
1998
2106
  const t2 = useTranslation();
2107
+ const provider = useCrmProvider();
2108
+ const [selectedDealId, setSelectedDealId] = useState(null);
1999
2109
  const activities = useCrmStore((s) => s.activities);
2000
2110
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
2001
2111
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
2002
2112
  const [typeFilter, setTypeFilter] = useState(null);
2003
2113
  const [showCompleted, setShowCompleted] = useState(null);
2114
+ const eventsFilter = typeFilter === "events";
2004
2115
  useEffect(() => {
2005
2116
  fetchActivities({
2006
- activityType: typeFilter,
2007
- completed: showCompleted ?? void 0
2117
+ activityType: eventsFilter ? void 0 : typeFilter,
2118
+ completed: eventsFilter ? void 0 : showCompleted ?? void 0
2008
2119
  });
2009
2120
  }, [typeFilter, showCompleted]);
2010
- const filtered = activities;
2121
+ const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities;
2011
2122
  const pendingCount = activities.filter((a) => !a.completedAt).length;
2012
2123
  const overdueCount = activities.filter((a) => !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)).length;
2013
2124
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
@@ -2028,7 +2139,8 @@ function ActivityListView() {
2028
2139
  children: t2("crm.activities.all")
2029
2140
  }
2030
2141
  ),
2031
- Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
2142
+ MANUAL_TYPES.map((type) => {
2143
+ const cfg = TYPE_CONFIG[type];
2032
2144
  const Icon = cfg.icon;
2033
2145
  return /* @__PURE__ */ jsxs(
2034
2146
  "button",
@@ -2042,7 +2154,18 @@ function ActivityListView() {
2042
2154
  },
2043
2155
  type
2044
2156
  );
2045
- })
2157
+ }),
2158
+ /* @__PURE__ */ jsxs(
2159
+ "button",
2160
+ {
2161
+ onClick: () => setTypeFilter(eventsFilter ? null : "events"),
2162
+ 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"}`,
2163
+ children: [
2164
+ /* @__PURE__ */ jsx(Sparkles, { className: "h-3 w-3" }),
2165
+ t2("crm.activities.systemEvents")
2166
+ ]
2167
+ }
2168
+ )
2046
2169
  ] }),
2047
2170
  /* @__PURE__ */ jsx("div", { className: "flex-1" }),
2048
2171
  /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5", children: [
@@ -2079,17 +2202,26 @@ function ActivityListView() {
2079
2202
  ] }) : /* @__PURE__ */ jsx("div", { className: "space-y-2", children: filtered.map((a) => {
2080
2203
  const cfg = TYPE_CONFIG[a.activityType] ?? { icon: FileText, color: "bg-muted text-muted-foreground", label: a.activityType };
2081
2204
  const Icon = cfg.icon;
2205
+ const isSystem = SYSTEM_TYPES.has(a.activityType);
2082
2206
  const isOverdue = !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2207
+ const openRecord = a.dealId ? () => setSelectedDealId(a.dealId) : a.leadId ? () => {
2208
+ void provider.getDealByLeadId(a.leadId).then((deal) => {
2209
+ if (deal) setSelectedDealId(deal.id);
2210
+ else onOpenLead?.(a.leadId);
2211
+ });
2212
+ } : void 0;
2083
2213
  return /* @__PURE__ */ jsxs(
2084
2214
  "div",
2085
2215
  {
2086
- className: `flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""}`,
2216
+ onClick: openRecord,
2217
+ role: openRecord ? "button" : void 0,
2218
+ 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
2219
  children: [
2088
2220
  /* @__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
2221
  /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
2090
2222
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
2091
2223
  /* @__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: [
2224
+ 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
2225
  /* @__PURE__ */ jsx(Check, { className: "h-2.5 w-2.5" }),
2094
2226
  " ",
2095
2227
  t2("crm.activities.done")
@@ -2116,12 +2248,25 @@ function ActivityListView() {
2116
2248
  ] })
2117
2249
  ] })
2118
2250
  ] }),
2119
- /* @__PURE__ */ jsx("span", { className: "text-[10px] text-muted-foreground shrink-0 pt-1", children: new Date(a.createdAt).toLocaleDateString() })
2251
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5 text-[10px] text-muted-foreground shrink-0 pt-1", children: [
2252
+ new Date(a.createdAt).toLocaleDateString(),
2253
+ openRecord && /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" })
2254
+ ] })
2120
2255
  ]
2121
2256
  },
2122
2257
  a.id
2123
2258
  );
2124
- }) })
2259
+ }) }),
2260
+ /* @__PURE__ */ jsx(
2261
+ DealSidebar,
2262
+ {
2263
+ dealId: selectedDealId ?? "",
2264
+ open: !!selectedDealId,
2265
+ onClose: () => setSelectedDealId(null),
2266
+ onViewLead: onOpenLead,
2267
+ onViewQuote: onOpenQuote
2268
+ }
2269
+ )
2125
2270
  ] });
2126
2271
  }
2127
2272
  function buildNav(config, view, navigate) {
@@ -2215,7 +2360,7 @@ function CrmPage({ config, provider, store, registries }) {
2215
2360
  return /* @__PURE__ */ jsx(QuoteFormView, { leadId: lid, onSaved: (id) => id ? navigate(`quotes-detail:${id}`) : navigate("quotes-list") });
2216
2361
  } },
2217
2362
  { 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, {}) },
2363
+ { id: "activities", render: () => /* @__PURE__ */ jsx(ActivityListView, { onOpenLead: (id) => navigate(`leads-detail:${id}`), onOpenQuote: (id) => navigate(`quotes-detail:${id}`) }) },
2219
2364
  { 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
2365
  { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
2221
2366
  window.location.hash = `/financial/receivables/detail/${invoiceId}`;
@@ -2458,6 +2603,7 @@ function deriveLeadStatus(stage) {
2458
2603
  return "qualified";
2459
2604
  }
2460
2605
  function deriveQuoteStatus(stage, current) {
2606
+ if (current === "archived") return current;
2461
2607
  if (stage.isWon) return "approved";
2462
2608
  if (stage.isLost) return "rejected";
2463
2609
  return current;
@@ -2483,7 +2629,7 @@ function paginate(items, page, pageSize) {
2483
2629
  function createStore(seedStages) {
2484
2630
  const tenantId = "mock-tenant";
2485
2631
  const pipelineId = uid();
2486
- const defaultStages = [
2632
+ const defaultStages = seedStages ?? [
2487
2633
  { name: "New", color: "#6366f1", probability: 10 },
2488
2634
  { name: "Contacted", color: "#3b82f6", probability: 25 },
2489
2635
  { name: "Qualified", color: "#f59e0b", probability: 50 },
@@ -2522,8 +2668,23 @@ function createStore(seedStages) {
2522
2668
  };
2523
2669
  }
2524
2670
  function createMockCrmProvider(options) {
2525
- const store = createStore();
2671
+ const store = createStore(options?.dealStages);
2526
2672
  const tenantId = "mock-tenant";
2673
+ function logEvent(input) {
2674
+ store.activities.push({
2675
+ id: uid(),
2676
+ dealId: input.dealId,
2677
+ leadId: input.leadId,
2678
+ contactId: input.contactId,
2679
+ contactName: input.contactName,
2680
+ activityType: input.activityType,
2681
+ title: input.title,
2682
+ description: input.description,
2683
+ completedAt: now(),
2684
+ tenantId,
2685
+ createdAt: now()
2686
+ });
2687
+ }
2527
2688
  function cascadeFromStage(deal, stage) {
2528
2689
  if (deal.leadId) {
2529
2690
  const lead = store.leads.find((l) => l.id === deal.leadId);
@@ -2548,7 +2709,7 @@ function createMockCrmProvider(options) {
2548
2709
  },
2549
2710
  // Leads
2550
2711
  async getLeads(query) {
2551
- let results = [...store.leads];
2712
+ let results = store.leads.filter((l) => l.isActive !== false);
2552
2713
  if (query.status) {
2553
2714
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2554
2715
  results = results.filter((l) => statuses.includes(l.status));
@@ -2582,6 +2743,7 @@ function createMockCrmProvider(options) {
2582
2743
  updatedAt: now()
2583
2744
  };
2584
2745
  store.leads.push(lead);
2746
+ logEvent({ activityType: "lead_created", title: lead.name, leadId: lead.id, contactName: lead.name });
2585
2747
  return lead;
2586
2748
  },
2587
2749
  async updateLead(id, data) {
@@ -2595,6 +2757,7 @@ function createMockCrmProvider(options) {
2595
2757
  if (!lead) throw new Error(`Lead ${leadId} not found`);
2596
2758
  lead.status = "converted";
2597
2759
  lead.updatedAt = now();
2760
+ logEvent({ activityType: "lead_converted", title: lead.name, leadId, contactName: lead.name });
2598
2761
  const deal = await provider.createDeal({ ...dealInput, leadId });
2599
2762
  return deal;
2600
2763
  },
@@ -2606,6 +2769,8 @@ function createMockCrmProvider(options) {
2606
2769
  if (query.status) {
2607
2770
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2608
2771
  results = results.filter((d) => statuses.includes(d.status));
2772
+ } else {
2773
+ results = results.filter((d) => d.status !== "archived");
2609
2774
  }
2610
2775
  if (query.search) {
2611
2776
  const s = query.search.toLowerCase();
@@ -2649,6 +2814,14 @@ function createMockCrmProvider(options) {
2649
2814
  updatedAt: now()
2650
2815
  };
2651
2816
  store.deals.push(deal);
2817
+ logEvent({
2818
+ activityType: "deal_created",
2819
+ title: deal.title,
2820
+ dealId: deal.id,
2821
+ leadId: deal.leadId,
2822
+ contactId: deal.contactId,
2823
+ contactName: deal.contactName
2824
+ });
2652
2825
  return deal;
2653
2826
  },
2654
2827
  async updateDeal(id, data) {
@@ -2670,8 +2843,31 @@ function createMockCrmProvider(options) {
2670
2843
  if (stage.isLost) deal.status = "lost";
2671
2844
  deal.updatedAt = now();
2672
2845
  cascadeFromStage(deal, stage);
2846
+ logEvent({
2847
+ activityType: stage.isWon ? "deal_won" : stage.isLost ? "deal_lost" : "stage_changed",
2848
+ title: deal.title || "Deal",
2849
+ description: stage.name,
2850
+ dealId: deal.id,
2851
+ contactName: deal.contactName
2852
+ });
2673
2853
  return deal;
2674
2854
  },
2855
+ async archiveDeal(dealId) {
2856
+ const deal = store.deals.find((d) => d.id === dealId);
2857
+ if (!deal) throw new Error(`Deal ${dealId} not found`);
2858
+ deal.status = "archived";
2859
+ deal.updatedAt = now();
2860
+ logEvent({ activityType: "deal_archived", title: deal.title || "Deal", dealId, contactName: deal.contactName });
2861
+ },
2862
+ async archiveLead(leadId) {
2863
+ const lead = store.leads.find((l) => l.id === leadId);
2864
+ if (!lead) throw new Error(`Lead ${leadId} not found`);
2865
+ lead.isActive = false;
2866
+ lead.updatedAt = now();
2867
+ const deal = store.deals.find((d) => d.leadId === leadId && d.status === "open");
2868
+ if (deal) await provider.archiveDeal(deal.id);
2869
+ logEvent({ activityType: "lead_archived", title: lead.name, leadId, contactName: lead.name });
2870
+ },
2675
2871
  // Activities
2676
2872
  async getActivities(query) {
2677
2873
  let results = [...store.activities];
@@ -2707,9 +2903,20 @@ function createMockCrmProvider(options) {
2707
2903
  activity.completedAt = now();
2708
2904
  return activity;
2709
2905
  },
2906
+ async getActivityTypes() {
2907
+ const seed = options?.activityTypes ?? [
2908
+ { value: "call", label: "Call", icon: "Phone" },
2909
+ { value: "email", label: "Email", icon: "Mail" },
2910
+ { value: "meeting", label: "Meeting", icon: "Users" },
2911
+ { value: "note", label: "Note", icon: "FileText" },
2912
+ { value: "task", label: "Task", icon: "CheckSquare" },
2913
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
2914
+ ];
2915
+ return seed.map((t2, i) => ({ id: `at-${i}`, name: t2.label, icon: t2.icon, isActive: true }));
2916
+ },
2710
2917
  // Quotes
2711
2918
  async getQuotes(query) {
2712
- let results = [...store.quotes];
2919
+ let results = store.quotes.filter((q) => q.status !== "archived" || query.status && (Array.isArray(query.status) ? query.status : [query.status]).includes("archived"));
2713
2920
  if (query.status) {
2714
2921
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2715
2922
  results = results.filter((q) => statuses.includes(q.status));
@@ -2753,6 +2960,22 @@ function createMockCrmProvider(options) {
2753
2960
  updatedAt: now()
2754
2961
  };
2755
2962
  store.quotes.push(quote);
2963
+ if (quote.dealId && totalAmount > 0) {
2964
+ const deal = store.deals.find((d) => d.id === quote.dealId);
2965
+ if (deal) {
2966
+ deal.value = totalAmount;
2967
+ deal.updatedAt = now();
2968
+ }
2969
+ }
2970
+ logEvent({
2971
+ activityType: "quote_created",
2972
+ title: quote.quoteNumber ?? "Quote",
2973
+ description: quote.contactName,
2974
+ dealId: quote.dealId,
2975
+ leadId: quote.leadId,
2976
+ contactId: quote.contactId,
2977
+ contactName: quote.contactName
2978
+ });
2756
2979
  return quote;
2757
2980
  },
2758
2981
  async updateQuote(id, input) {
@@ -2776,6 +2999,13 @@ function createMockCrmProvider(options) {
2776
2999
  quote.items = items;
2777
3000
  quote.totalAmount = totalAmount;
2778
3001
  quote.updatedAt = now();
3002
+ if (quote.dealId && totalAmount > 0) {
3003
+ const deal = store.deals.find((d) => d.id === quote.dealId);
3004
+ if (deal) {
3005
+ deal.value = totalAmount;
3006
+ deal.updatedAt = now();
3007
+ }
3008
+ }
2779
3009
  return quote;
2780
3010
  },
2781
3011
  async sendQuote(id) {
@@ -2783,6 +3013,14 @@ function createMockCrmProvider(options) {
2783
3013
  if (!quote) throw new Error(`Quote ${id} not found`);
2784
3014
  quote.status = "sent";
2785
3015
  quote.updatedAt = now();
3016
+ logEvent({
3017
+ activityType: "quote_sent",
3018
+ title: quote.quoteNumber ?? "Quote",
3019
+ description: quote.contactName,
3020
+ dealId: quote.dealId,
3021
+ leadId: quote.leadId,
3022
+ contactName: quote.contactName
3023
+ });
2786
3024
  return quote;
2787
3025
  },
2788
3026
  async approveQuote(id) {
@@ -2806,6 +3044,14 @@ function createMockCrmProvider(options) {
2806
3044
  lead.metadata = { ...lead.metadata, convertedFromLead: true };
2807
3045
  }
2808
3046
  }
3047
+ logEvent({
3048
+ activityType: "quote_approved",
3049
+ title: quote.quoteNumber ?? "Quote",
3050
+ description: quote.contactName,
3051
+ dealId: quote.dealId,
3052
+ leadId: quote.leadId,
3053
+ contactName: quote.contactName
3054
+ });
2809
3055
  return quote;
2810
3056
  },
2811
3057
  async rejectQuote(id, reason) {
@@ -2823,6 +3069,14 @@ function createMockCrmProvider(options) {
2823
3069
  }
2824
3070
  }
2825
3071
  }
3072
+ logEvent({
3073
+ activityType: "quote_rejected",
3074
+ title: quote.quoteNumber ?? "Quote",
3075
+ description: reason,
3076
+ dealId: quote.dealId,
3077
+ leadId: quote.leadId,
3078
+ contactName: quote.contactName
3079
+ });
2826
3080
  return quote;
2827
3081
  },
2828
3082
  async expireQuote(id) {
@@ -2832,6 +3086,20 @@ function createMockCrmProvider(options) {
2832
3086
  quote.updatedAt = now();
2833
3087
  return quote;
2834
3088
  },
3089
+ async archiveQuote(id) {
3090
+ const quote = store.quotes.find((q) => q.id === id);
3091
+ if (!quote) throw new Error(`Quote ${id} not found`);
3092
+ quote.status = "archived";
3093
+ quote.updatedAt = now();
3094
+ logEvent({
3095
+ activityType: "quote_archived",
3096
+ title: quote.quoteNumber ?? "Quote",
3097
+ description: quote.contactName,
3098
+ dealId: quote.dealId,
3099
+ leadId: quote.leadId,
3100
+ contactName: quote.contactName
3101
+ });
3102
+ },
2835
3103
  // Cross-entity lookups
2836
3104
  async getQuotesByDealId(dealId) {
2837
3105
  return store.quotes.filter((q) => q.dealId === dealId);
@@ -2913,6 +3181,34 @@ async function mergePersonMetadata(personId, patch) {
2913
3181
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
2914
3182
  }
2915
3183
  function createSupabaseCrmProvider(options) {
3184
+ async function logEvent(input) {
3185
+ try {
3186
+ const { pub } = getClients();
3187
+ await pub.from(T.activities).insert({
3188
+ tenant_id: getTenantId(),
3189
+ deal_id: input.dealId ?? null,
3190
+ lead_id: input.leadId ?? null,
3191
+ contact_id: input.contactId ?? null,
3192
+ contact_name: input.contactName ?? null,
3193
+ activity_type: input.activityType,
3194
+ title: input.title,
3195
+ description: input.description ?? null,
3196
+ completed_at: (/* @__PURE__ */ new Date()).toISOString()
3197
+ });
3198
+ } catch {
3199
+ }
3200
+ }
3201
+ const typesSeeded = /* @__PURE__ */ new Set();
3202
+ async function ensureActivityTypes(tenantId) {
3203
+ const seed = options?.activityTypes;
3204
+ if (!seed?.length || typesSeeded.has(tenantId)) return;
3205
+ typesSeeded.add(tenantId);
3206
+ const { pub } = getClients();
3207
+ await pub.from(T.activityTypes).upsert(
3208
+ seed.map((t2) => ({ tenant_id: tenantId, name: t2.label, icon: t2.icon ?? null, is_active: true })),
3209
+ { onConflict: "tenant_id,name", ignoreDuplicates: true }
3210
+ );
3211
+ }
2916
3212
  const provider = {
2917
3213
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
2918
3214
  async getPipelines() {
@@ -2928,7 +3224,7 @@ function createSupabaseCrmProvider(options) {
2928
3224
  // --- Leads (via view — single query) ---
2929
3225
  async getLeads(query) {
2930
3226
  const { pub } = getClients();
2931
- let qb = pub.from("v_leads").select("*", { count: "exact" });
3227
+ let qb = pub.from("v_leads").select("*", { count: "exact" }).eq("is_active", true);
2932
3228
  if (query.search) qb = qb.ilike("name", `%${query.search}%`);
2933
3229
  if (query.status) {
2934
3230
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
@@ -3001,6 +3297,7 @@ function createSupabaseCrmProvider(options) {
3001
3297
  }).select().single();
3002
3298
  if (error) throw new Error(error.message);
3003
3299
  const p = snakeToCamel(data);
3300
+ await logEvent({ activityType: "lead_created", title: input.name, leadId: p.id, contactName: input.name });
3004
3301
  return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3005
3302
  },
3006
3303
  async updateLead(id, partial) {
@@ -3016,8 +3313,13 @@ function createSupabaseCrmProvider(options) {
3016
3313
  return await provider.getLeadById(id);
3017
3314
  },
3018
3315
  async convertLeadToDeal(leadId, dealInput) {
3019
- getClients();
3020
3316
  await mergePersonMetadata(leadId, { status: "converted" });
3317
+ await logEvent({
3318
+ activityType: "lead_converted",
3319
+ title: dealInput.contactName ?? dealInput.title,
3320
+ leadId,
3321
+ contactName: dealInput.contactName
3322
+ });
3021
3323
  return provider.createDeal({ ...dealInput, leadId });
3022
3324
  },
3023
3325
  // --- Deals (via view — single query with all joins) ---
@@ -3027,6 +3329,8 @@ function createSupabaseCrmProvider(options) {
3027
3329
  if (query.status) {
3028
3330
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3029
3331
  qb = qb.in("status", statuses);
3332
+ } else {
3333
+ qb = qb.neq("status", "archived");
3030
3334
  }
3031
3335
  if (query.search) qb = qb.ilike("title", `%${query.search}%`);
3032
3336
  if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
@@ -3088,7 +3392,7 @@ function createSupabaseCrmProvider(options) {
3088
3392
  async getDealsByStage(pipelineId) {
3089
3393
  const { pub } = getClients();
3090
3394
  const stages = await provider.getPipelineStages(pipelineId);
3091
- const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).neq("status", "lost");
3395
+ const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).not("status", "in", "(lost,archived)");
3092
3396
  const deals = (data ?? []).map((r) => ({
3093
3397
  id: r.id,
3094
3398
  title: r.title ?? "",
@@ -3139,6 +3443,14 @@ function createSupabaseCrmProvider(options) {
3139
3443
  expected_close_date: input.expectedCloseDate,
3140
3444
  lead_id: input.leadId
3141
3445
  });
3446
+ await logEvent({
3447
+ activityType: "deal_created",
3448
+ title: input.title,
3449
+ dealId: order.id,
3450
+ leadId: input.leadId,
3451
+ contactId: input.contactId,
3452
+ contactName: input.contactName
3453
+ });
3142
3454
  return {
3143
3455
  id: order.id,
3144
3456
  title: input.title,
@@ -3210,7 +3522,46 @@ function createSupabaseCrmProvider(options) {
3210
3522
  }
3211
3523
  }
3212
3524
  }
3213
- return await provider.getDealById(dealId);
3525
+ const moved = await provider.getDealById(dealId);
3526
+ if (stageRow) {
3527
+ await logEvent({
3528
+ activityType: stageRow.is_won ? "deal_won" : stageRow.is_lost ? "deal_lost" : "stage_changed",
3529
+ title: moved.title || "Deal",
3530
+ description: stageRow.name,
3531
+ dealId,
3532
+ contactName: moved.contactName
3533
+ });
3534
+ }
3535
+ return moved;
3536
+ },
3537
+ async archiveDeal(dealId) {
3538
+ const { core } = getClients();
3539
+ const deal = await provider.getDealById(dealId);
3540
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", dealId);
3541
+ if (error) throw new Error(error.message);
3542
+ await logEvent({
3543
+ activityType: "deal_archived",
3544
+ title: deal?.title || "Deal",
3545
+ dealId,
3546
+ contactName: deal?.contactName
3547
+ });
3548
+ },
3549
+ async archiveLead(leadId) {
3550
+ const { core } = getClients();
3551
+ const lead = await provider.getLeadById(leadId);
3552
+ const { error } = await core.from("people").update({ is_active: false }).eq("id", leadId);
3553
+ if (error) throw new Error(error.message);
3554
+ try {
3555
+ const deal = await provider.getDealByLeadId(leadId);
3556
+ if (deal && deal.status === "open") await provider.archiveDeal(deal.id);
3557
+ } catch {
3558
+ }
3559
+ await logEvent({
3560
+ activityType: "lead_archived",
3561
+ title: lead?.name ?? "Lead",
3562
+ leadId,
3563
+ contactName: lead?.name
3564
+ });
3214
3565
  },
3215
3566
  // --- Activities (public.plg_crm_activities) ---
3216
3567
  async getActivities(query) {
@@ -3250,6 +3601,14 @@ function createSupabaseCrmProvider(options) {
3250
3601
  if (error) throw new Error(error.message);
3251
3602
  return snakeToCamel(data);
3252
3603
  },
3604
+ async getActivityTypes() {
3605
+ const { pub } = getClients();
3606
+ const tenantId = getTenantId();
3607
+ if (!tenantId) return [];
3608
+ await ensureActivityTypes(tenantId);
3609
+ const { data } = await pub.from(T.activityTypes).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3610
+ return (data ?? []).map((r) => snakeToCamel(r));
3611
+ },
3253
3612
  // --- Quotes (public.orders kind='quote' + order_items) ---
3254
3613
  async getQuotes(query) {
3255
3614
  const { core } = getClients();
@@ -3257,6 +3616,8 @@ function createSupabaseCrmProvider(options) {
3257
3616
  if (query.status) {
3258
3617
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3259
3618
  qb = qb.in("status", statuses);
3619
+ } else {
3620
+ qb = qb.neq("status", "archived");
3260
3621
  }
3261
3622
  if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`);
3262
3623
  const page = query.page ?? 1;
@@ -3359,6 +3720,18 @@ function createSupabaseCrmProvider(options) {
3359
3720
  );
3360
3721
  if (itemsError) throw new Error(itemsError.message);
3361
3722
  }
3723
+ if (input.dealId && totalAmount > 0) {
3724
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
3725
+ }
3726
+ await logEvent({
3727
+ activityType: "quote_created",
3728
+ title: order.reference_number ?? "Quote",
3729
+ description: input.contactName,
3730
+ dealId: input.dealId,
3731
+ leadId: input.leadId,
3732
+ contactId: input.contactId,
3733
+ contactName: input.contactName
3734
+ });
3362
3735
  return {
3363
3736
  id: order.id,
3364
3737
  quoteNumber: order.reference_number,
@@ -3402,6 +3775,9 @@ function createSupabaseCrmProvider(options) {
3402
3775
  );
3403
3776
  if (itemsError) throw new Error(itemsError.message);
3404
3777
  }
3778
+ if (input.dealId && totalAmount > 0) {
3779
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
3780
+ }
3405
3781
  return await provider.getQuoteById(id);
3406
3782
  },
3407
3783
  async sendQuote(id) {
@@ -3422,7 +3798,16 @@ function createSupabaseCrmProvider(options) {
3422
3798
  }
3423
3799
  } catch {
3424
3800
  }
3425
- return await provider.getQuoteById(id);
3801
+ const sent = await provider.getQuoteById(id);
3802
+ await logEvent({
3803
+ activityType: "quote_sent",
3804
+ title: sent.quoteNumber ?? "Quote",
3805
+ description: sent.contactName,
3806
+ dealId: sent.dealId,
3807
+ leadId: sent.leadId,
3808
+ contactName: sent.contactName
3809
+ });
3810
+ return sent;
3426
3811
  },
3427
3812
  async approveQuote(id) {
3428
3813
  const { core, pub } = getClients();
@@ -3466,7 +3851,16 @@ function createSupabaseCrmProvider(options) {
3466
3851
  }
3467
3852
  }
3468
3853
  }
3469
- return await provider.getQuoteById(id);
3854
+ const approved = await provider.getQuoteById(id);
3855
+ await logEvent({
3856
+ activityType: "quote_approved",
3857
+ title: approved.quoteNumber ?? "Quote",
3858
+ description: approved.contactName,
3859
+ dealId: approved.dealId,
3860
+ leadId: approved.leadId,
3861
+ contactName: approved.contactName
3862
+ });
3863
+ return approved;
3470
3864
  },
3471
3865
  async rejectQuote(id, reason) {
3472
3866
  const { core } = getClients();
@@ -3486,6 +3880,16 @@ function createSupabaseCrmProvider(options) {
3486
3880
  if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id);
3487
3881
  }
3488
3882
  }
3883
+ if (quote) {
3884
+ await logEvent({
3885
+ activityType: "quote_rejected",
3886
+ title: quote.quoteNumber ?? "Quote",
3887
+ description: reason,
3888
+ dealId: quote.dealId,
3889
+ leadId: quote.leadId,
3890
+ contactName: quote.contactName
3891
+ });
3892
+ }
3489
3893
  return quote;
3490
3894
  },
3491
3895
  async expireQuote(id) {
@@ -3493,6 +3897,20 @@ function createSupabaseCrmProvider(options) {
3493
3897
  await core.from("orders").update({ status: "expired" }).eq("id", id);
3494
3898
  return await provider.getQuoteById(id);
3495
3899
  },
3900
+ async archiveQuote(id) {
3901
+ const { core } = getClients();
3902
+ const quote = await provider.getQuoteById(id);
3903
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", id);
3904
+ if (error) throw new Error(error.message);
3905
+ await logEvent({
3906
+ activityType: "quote_archived",
3907
+ title: quote?.quoteNumber ?? "Quote",
3908
+ description: quote?.contactName,
3909
+ dealId: quote?.dealId,
3910
+ leadId: quote?.leadId,
3911
+ contactName: quote?.contactName
3912
+ });
3913
+ },
3496
3914
  // Cross-entity lookups
3497
3915
  async getQuotesByDealId(dealId) {
3498
3916
  const { core } = getClients();
@@ -3568,6 +3986,7 @@ function createSupabaseCrmProvider(options) {
3568
3986
  return provider;
3569
3987
  }
3570
3988
  function createCrmStore(provider) {
3989
+ let lastActivitiesQuery = {};
3571
3990
  return createStore$1((set, get) => ({
3572
3991
  pipelines: [],
3573
3992
  stages: [],
@@ -3629,12 +4048,20 @@ function createCrmStore(provider) {
3629
4048
  });
3630
4049
  },
3631
4050
  async fetchActivities(query) {
4051
+ lastActivitiesQuery = query;
3632
4052
  return dedup("crm:activities:" + JSON.stringify(query), async () => {
3633
4053
  set({ activitiesLoading: true });
3634
4054
  const result = await provider.getActivities(query);
3635
4055
  set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false });
3636
4056
  });
3637
4057
  },
4058
+ async refreshActivities() {
4059
+ try {
4060
+ const result = await provider.getActivities(lastActivitiesQuery);
4061
+ set({ activities: result.data, activitiesTotal: result.total });
4062
+ } catch {
4063
+ }
4064
+ },
3638
4065
  async fetchQuotes(query) {
3639
4066
  return dedup("crm:quotes:" + JSON.stringify(query), async () => {
3640
4067
  set({ quotesLoading: true });
@@ -3668,6 +4095,7 @@ function createCrmStore(provider) {
3668
4095
  }
3669
4096
  const summary = await provider.getSummary();
3670
4097
  set({ summary });
4098
+ void get().refreshActivities();
3671
4099
  toast.success("Lead captured");
3672
4100
  return lead;
3673
4101
  } catch (err) {
@@ -3680,6 +4108,7 @@ function createCrmStore(provider) {
3680
4108
  const deal = await provider.createDeal(input);
3681
4109
  const [summary] = await Promise.all([provider.getSummary()]);
3682
4110
  set({ summary });
4111
+ void get().refreshActivities();
3683
4112
  toast.success("Deal created");
3684
4113
  return deal;
3685
4114
  } catch (err) {
@@ -3770,6 +4199,7 @@ function createCrmStore(provider) {
3770
4199
  } catch {
3771
4200
  }
3772
4201
  }
4202
+ void get().refreshActivities();
3773
4203
  toast.success("Quote created");
3774
4204
  return quote;
3775
4205
  } catch (err) {
@@ -3792,6 +4222,7 @@ function createCrmStore(provider) {
3792
4222
  try {
3793
4223
  const quote = await provider.sendQuote(id);
3794
4224
  set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
4225
+ void get().refreshActivities();
3795
4226
  toast.success("Quote sent");
3796
4227
  return quote;
3797
4228
  } catch (err) {
@@ -3812,6 +4243,7 @@ function createCrmStore(provider) {
3812
4243
  ]);
3813
4244
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3814
4245
  }
4246
+ void get().refreshActivities();
3815
4247
  toast.success("Quote approved \u2014 invoice created");
3816
4248
  return quote;
3817
4249
  } catch (err) {
@@ -3832,6 +4264,7 @@ function createCrmStore(provider) {
3832
4264
  ]);
3833
4265
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3834
4266
  }
4267
+ void get().refreshActivities();
3835
4268
  toast.success("Quote rejected");
3836
4269
  return quote;
3837
4270
  } catch (err) {
@@ -3862,6 +4295,61 @@ function createCrmStore(provider) {
3862
4295
  ]);
3863
4296
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3864
4297
  }
4298
+ void get().refreshActivities();
4299
+ },
4300
+ async archiveDeal(dealId) {
4301
+ try {
4302
+ await provider.archiveDeal(dealId);
4303
+ const { pipelines } = get();
4304
+ if (pipelines.length > 0) {
4305
+ const [dealsByStage, summary] = await Promise.all([
4306
+ provider.getDealsByStage(pipelines[0].id),
4307
+ provider.getSummary()
4308
+ ]);
4309
+ set({ dealsByStage, summary });
4310
+ }
4311
+ void get().refreshActivities();
4312
+ toast.success("Deal archived");
4313
+ } catch (err) {
4314
+ toast.error("Failed to archive deal", { description: err?.message });
4315
+ throw err;
4316
+ }
4317
+ },
4318
+ async archiveLead(leadId) {
4319
+ try {
4320
+ await provider.archiveLead(leadId);
4321
+ const { pipelines } = get();
4322
+ const [leadsResult, summary, dealsByStage] = await Promise.all([
4323
+ provider.getLeads({}),
4324
+ provider.getSummary(),
4325
+ pipelines.length > 0 ? provider.getDealsByStage(pipelines[0].id) : Promise.resolve(null)
4326
+ ]);
4327
+ set({
4328
+ leads: leadsResult.data,
4329
+ leadsTotal: leadsResult.total,
4330
+ summary,
4331
+ ...dealsByStage ? { dealsByStage } : {}
4332
+ });
4333
+ void get().refreshActivities();
4334
+ toast.success("Lead archived");
4335
+ } catch (err) {
4336
+ toast.error("Failed to archive lead", { description: err?.message });
4337
+ throw err;
4338
+ }
4339
+ },
4340
+ async archiveQuote(quoteId) {
4341
+ try {
4342
+ await provider.archiveQuote(quoteId);
4343
+ set((state) => ({
4344
+ quotes: state.quotes.filter((q) => q.id !== quoteId),
4345
+ quotesTotal: Math.max(0, state.quotesTotal - 1)
4346
+ }));
4347
+ void get().refreshActivities();
4348
+ toast.success("Quote archived");
4349
+ } catch (err) {
4350
+ toast.error("Failed to archive quote", { description: err?.message });
4351
+ throw err;
4352
+ }
3865
4353
  }
3866
4354
  }));
3867
4355
  }
@@ -3924,10 +4412,19 @@ var activityTypeEntity = {
3924
4412
  defaultSort: "name",
3925
4413
  fields: [
3926
4414
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3927
- { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
4415
+ { key: "icon", label: "Icon", type: "text", showInTable: true },
4416
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
3928
4417
  ],
3929
4418
  data: { table: T.activityTypes, tenantScoped: true }
3930
4419
  };
4420
+ var DEFAULT_ACTIVITY_TYPES = [
4421
+ { value: "call", label: "Call", icon: "Phone" },
4422
+ { value: "email", label: "Email", icon: "Mail" },
4423
+ { value: "meeting", label: "Meeting", icon: "Users" },
4424
+ { value: "note", label: "Note", icon: "FileText" },
4425
+ { value: "task", label: "Task", icon: "CheckSquare" },
4426
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
4427
+ ];
3931
4428
  var crmRegistries = [
3932
4429
  {
3933
4430
  id: "stages",
@@ -3977,17 +4474,25 @@ var crmRegistries = [
3977
4474
  icon: "MessageCircle",
3978
4475
  description: "Types of activities and interactions",
3979
4476
  display: "table",
3980
- readOnly: true,
4477
+ // Tenant-editable (the provider lazily seeds the app's set per tenant);
4478
+ // system timeline events (lead_created, stage_changed…) are product-defined
4479
+ // and never appear here.
3981
4480
  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 }
4481
+ ...DEFAULT_ACTIVITY_TYPES.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
3988
4482
  ]
3989
4483
  }
3990
4484
  ];
4485
+ function buildCrmRegistries(activityTypes) {
4486
+ if (!activityTypes?.length) return crmRegistries;
4487
+ return crmRegistries.map(
4488
+ (registry) => registry.id === "activity-types" ? {
4489
+ ...registry,
4490
+ seedData: [
4491
+ ...activityTypes.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
4492
+ ]
4493
+ } : registry
4494
+ );
4495
+ }
3991
4496
 
3992
4497
  // src/locales/en.ts
3993
4498
  var en = {
@@ -4001,6 +4506,7 @@ var en = {
4001
4506
  "crm.activities.overdueLabel": "Overdue",
4002
4507
  "crm.activities.pending": "pending",
4003
4508
  "crm.activities.pendingFilter": "Pending",
4509
+ "crm.activities.systemEvents": "Events",
4004
4510
  "crm.activities.title": "Activities",
4005
4511
  "crm.dashboard.activeDeals": "{{count}} active deals",
4006
4512
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -4047,6 +4553,7 @@ var en = {
4047
4553
  "crm.dealSidebar.value": "Value",
4048
4554
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
4049
4555
  "crm.leadDetail.assignedTo": "Assigned to",
4556
+ "crm.leadDetail.archive": "Archive",
4050
4557
  "crm.leadDetail.backToList": "Back to list",
4051
4558
  "crm.leadDetail.formAnswers": "Form answers",
4052
4559
  "crm.leadDetail.company": "Company",
@@ -4106,6 +4613,7 @@ var en = {
4106
4613
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
4107
4614
  "crm.page.settingsTitle": "Sales & CRM Settings",
4108
4615
  "crm.pipeline.dropHere": "Drop here",
4616
+ "crm.pipeline.archive": "Archive",
4109
4617
  "crm.pipeline.moveFailed": "Failed to move deal",
4110
4618
  "crm.pipeline.movedTo": "Moved to {{stage}}",
4111
4619
  "crm.pipeline.noDeals": "No deals",
@@ -4184,6 +4692,7 @@ var en = {
4184
4692
  "crm.quoteForm.unitPrice": "Unit Price",
4185
4693
  "crm.quoteForm.validUntil": "Valid Until",
4186
4694
  "crm.quotes.amount": "Amount",
4695
+ "crm.quotes.archive": "Archive",
4187
4696
  "crm.quotes.contact": "Contact",
4188
4697
  "crm.quotes.createFirst": "Create your first quote",
4189
4698
  "crm.quotes.date": "Date",
@@ -4295,6 +4804,7 @@ var ptBR = {
4295
4804
  "crm.activities.overdueLabel": "Atrasada",
4296
4805
  "crm.activities.pending": "pendente",
4297
4806
  "crm.activities.pendingFilter": "Pendentes",
4807
+ "crm.activities.systemEvents": "Eventos",
4298
4808
  "crm.activities.title": "Atividades",
4299
4809
  "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
4300
4810
  "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
@@ -4341,6 +4851,7 @@ var ptBR = {
4341
4851
  "crm.dealSidebar.value": "Valor",
4342
4852
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
4343
4853
  "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
4854
+ "crm.leadDetail.archive": "Arquivar",
4344
4855
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
4345
4856
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
4346
4857
  "crm.leadDetail.company": "Empresa",
@@ -4396,10 +4907,11 @@ var ptBR = {
4396
4907
  "crm.page.newLead": "Novo Lead",
4397
4908
  "crm.page.newLeadDesc": "Capturar um novo lead",
4398
4909
  "crm.page.newQuote": "Novo Or\xE7amento",
4399
- "crm.page.newQuoteDesc": "Enviar uma proposta",
4910
+ "crm.page.newQuoteDesc": "Enviar um or\xE7amento",
4400
4911
  "crm.page.settingsSubtitle": "Configure pipeline, gest\xE3o de leads e cadastros",
4401
4912
  "crm.page.settingsTitle": "Configura\xE7\xF5es de Vendas e CRM",
4402
4913
  "crm.pipeline.dropHere": "Solte aqui",
4914
+ "crm.pipeline.archive": "Arquivar",
4403
4915
  "crm.pipeline.moveFailed": "Falha ao mover neg\xF3cio",
4404
4916
  "crm.pipeline.movedTo": "Movido para {{stage}}",
4405
4917
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
@@ -4445,12 +4957,12 @@ var ptBR = {
4445
4957
  "crm.quoteForm.description": "Descri\xE7\xE3o",
4446
4958
  "crm.quoteForm.discount": "Desconto",
4447
4959
  "crm.quoteForm.done": "Conclu\xEDdo",
4448
- "crm.quoteForm.editSubtitle": "Atualizar esta proposta",
4960
+ "crm.quoteForm.editSubtitle": "Atualizar este or\xE7amento",
4449
4961
  "crm.quoteForm.editTitle": "Editar Or\xE7amento",
4450
4962
  "crm.quoteForm.itemCount": "{{count}} itens",
4451
4963
  "crm.quoteForm.itemDescriptionPlaceholder": "Descri\xE7\xE3o do item",
4452
4964
  "crm.quoteForm.loading": "Carregando...",
4453
- "crm.quoteForm.newSubtitle": "Criar uma proposta para seu cliente",
4965
+ "crm.quoteForm.newSubtitle": "Criar um or\xE7amento para seu cliente",
4454
4966
  "crm.quoteForm.newTitle": "Novo Or\xE7amento",
4455
4967
  "crm.quoteForm.noDescription": "Sem descri\xE7\xE3o",
4456
4968
  "crm.quoteForm.noItems": "Nenhum item adicionado",
@@ -4478,6 +4990,7 @@ var ptBR = {
4478
4990
  "crm.quoteForm.unitPrice": "Pre\xE7o Unit\xE1rio",
4479
4991
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
4480
4992
  "crm.quotes.amount": "Valor",
4993
+ "crm.quotes.archive": "Arquivar",
4481
4994
  "crm.quotes.contact": "Contato",
4482
4995
  "crm.quotes.createFirst": "Crie seu primeiro or\xE7amento",
4483
4996
  "crm.quotes.date": "Data",
@@ -4491,7 +5004,7 @@ var ptBR = {
4491
5004
  "crm.quickActions.newDeal": "Novo Neg\xF3cio",
4492
5005
  "crm.quickActions.newDealDesc": "Criar um neg\xF3cio no pipeline",
4493
5006
  "crm.quickActions.newQuote": "Novo Or\xE7amento",
4494
- "crm.quickActions.newQuoteDesc": "Enviar uma proposta",
5007
+ "crm.quickActions.newQuoteDesc": "Enviar um or\xE7amento",
4495
5008
  "crm.quickActions.logActivity": "Registrar Atividade",
4496
5009
  "crm.quickActions.logActivityDesc": "Registrar liga\xE7\xE3o, e-mail ou nota",
4497
5010
  "crm.settingsPage.title": "Configura\xE7\xF5es de Vendas e CRM",
@@ -4528,7 +5041,7 @@ var ptBR = {
4528
5041
  "crm.settings.weightedPipeline": "Valor ponderado do pipeline",
4529
5042
  "crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do est\xE1gio",
4530
5043
  "crm.settings.quotes": "Or\xE7amentos",
4531
- "crm.settings.quotesDesc": "Comportamento de or\xE7amentos e propostas",
5044
+ "crm.settings.quotesDesc": "Comportamento de or\xE7amentos",
4532
5045
  "crm.settings.autoNumberQuotes": "Numera\xE7\xE3o autom\xE1tica de or\xE7amentos",
4533
5046
  "crm.settings.autoNumberQuotesDesc": "Gerar automaticamente n\xFAmeros sequenciais de or\xE7amentos",
4534
5047
  "crm.settings.defaultValidity": "Validade padr\xE3o (30 dias)",
@@ -4621,12 +5134,14 @@ function resolveConfig(options) {
4621
5134
  function createCrmPlugin(options) {
4622
5135
  const config = resolveConfig(options);
4623
5136
  registerTranslations(crmLocales);
5137
+ const activityTypes = options?.activityTypes ?? DEFAULT_ACTIVITY_TYPES;
5138
+ const crmRegistries2 = buildCrmRegistries(activityTypes);
4624
5139
  const provider = options?.dataProvider ?? createSafeDataProvider(
4625
- () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
4626
- () => createMockCrmProvider()
5140
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion, activityTypes }),
5141
+ () => createMockCrmProvider({ activityTypes })
4627
5142
  );
4628
5143
  const store = createCrmStore(provider);
4629
- const PageComponent = () => React14.createElement(CrmPage, { config, provider, store, registries: crmRegistries });
5144
+ const PageComponent = () => React14.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
4630
5145
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
4631
5146
  return {
4632
5147
  id: "crm",
@@ -4655,6 +5170,86 @@ function createCrmPlugin(options) {
4655
5170
  { key: "deals", label: "Deals", table: "orders", kindFilter: "deal" },
4656
5171
  { key: "quotes", label: "Quotes", table: "orders", kindFilter: "quote" }
4657
5172
  ],
5173
+ // Read-models for the agent's data primitives (searchRecords/queryData).
5174
+ // Without these the assistant cannot see leads/deals/activities at all and
5175
+ // guesses wrong entities ("quem tá aguardando contato?" → invented filter
5176
+ // on Cliente). Keys are stable ASCII; fields are camelCase output shape.
5177
+ queryEntities: [
5178
+ {
5179
+ key: "crm:leads",
5180
+ writable: false,
5181
+ entity: {
5182
+ name: "Lead",
5183
+ namePlural: "Leads",
5184
+ icon: "UserPlus",
5185
+ permission: { feature: "crm.leads", action: "read" },
5186
+ fields: [
5187
+ { key: "name", label: "Name", type: "text", searchable: true },
5188
+ { key: "email", label: "Email", type: "text", searchable: true },
5189
+ { key: "phone", label: "Phone", type: "text", searchable: true },
5190
+ { key: "company", label: "Company", type: "text" },
5191
+ { key: "status", label: "Status (new=awaiting first contact, contacted, qualified, converted, lost)", type: "text" },
5192
+ { key: "sourceName", label: "Source", type: "text" },
5193
+ { key: "createdAt", label: "Created at", type: "text" }
5194
+ ],
5195
+ data: {
5196
+ table: "v_leads",
5197
+ tenantScoped: true,
5198
+ searchColumns: ["name", "email", "phone"]
5199
+ }
5200
+ }
5201
+ },
5202
+ {
5203
+ key: "crm:deals",
5204
+ writable: false,
5205
+ entity: {
5206
+ name: "Deal",
5207
+ namePlural: "Deals",
5208
+ icon: "Target",
5209
+ permission: { feature: "crm.pipeline", action: "read" },
5210
+ fields: [
5211
+ { key: "title", label: "Title", type: "text", searchable: true },
5212
+ { key: "value", label: "Value", type: "number" },
5213
+ { key: "status", label: "Status (open/won/lost)", type: "text" },
5214
+ { key: "stage", label: "Pipeline stage name", type: "text" },
5215
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5216
+ { key: "probability", label: "Probability %", type: "number" },
5217
+ { key: "expectedCloseDate", label: "Expected close", type: "text" },
5218
+ { key: "createdAt", label: "Created at", type: "text" }
5219
+ ],
5220
+ data: {
5221
+ table: "v_deals",
5222
+ tenantScoped: true,
5223
+ searchColumns: ["title", "contact_name"]
5224
+ }
5225
+ }
5226
+ },
5227
+ {
5228
+ key: "crm:activities",
5229
+ writable: false,
5230
+ entity: {
5231
+ name: "CRM activity",
5232
+ namePlural: "CRM activities",
5233
+ icon: "MessageCircle",
5234
+ permission: { feature: "sales", action: "read" },
5235
+ fields: [
5236
+ { key: "activityType", label: "Type (call/email/note\u2026 or system events: lead_created, deal_won, quote_approved\u2026)", type: "text" },
5237
+ { key: "title", label: "Title", type: "text", searchable: true },
5238
+ { key: "description", label: "Description", type: "text", searchable: true },
5239
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5240
+ { key: "dueDate", label: "Due date", type: "text" },
5241
+ { key: "completedAt", label: "Completed at", type: "text" },
5242
+ { key: "assignedToName", label: "Assigned to", type: "text" },
5243
+ { key: "createdAt", label: "Created at", type: "text" }
5244
+ ],
5245
+ data: {
5246
+ table: "plg_crm_activities",
5247
+ tenantScoped: true,
5248
+ searchColumns: ["title", "contact_name", "description"]
5249
+ }
5250
+ }
5251
+ }
5252
+ ],
4658
5253
  navigation: [
4659
5254
  {
4660
5255
  section: options?.navSection ?? "main",
@@ -4718,7 +5313,7 @@ function createCrmPlugin(options) {
4718
5313
  ]
4719
5314
  }
4720
5315
  ],
4721
- registries: crmRegistries,
5316
+ registries: crmRegistries2,
4722
5317
  settings: [
4723
5318
  {
4724
5319
  id: "crm",
@@ -4732,7 +5327,7 @@ function createCrmPlugin(options) {
4732
5327
  title: "Sales & CRM",
4733
5328
  subtitle: "Pipeline, lead management, and CRM properties",
4734
5329
  generalSettings: React14.createElement(CrmGeneralSettings),
4735
- registries: crmRegistries,
5330
+ registries: crmRegistries2,
4736
5331
  hostPluginId: "crm",
4737
5332
  routeBase: "/settings/crm"
4738
5333
  })