@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.cjs CHANGED
@@ -101,19 +101,28 @@ function CrmOnboarding({ onComplete }) {
101
101
  function DashboardView() {
102
102
  return /* @__PURE__ */ jsxRuntime.jsx(ui.DashboardCanvas, { surface: "plugin-home", domain: "crm", showHeader: false, className: "space-y-6" });
103
103
  }
104
+ function useCanArchive() {
105
+ return saas.useAccessOptional().can("sales", "delete").allowed;
106
+ }
104
107
  var STATUS_CONFIG = {
105
108
  draft: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: lucideReact.CircleDashed, label: "Draft" },
106
109
  sent: { bg: "bg-info-soft text-info-soft-foreground", dot: "bg-info", icon: lucideReact.Send, label: "Sent" },
107
110
  approved: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: lucideReact.CircleCheckBig, label: "Approved" },
108
111
  rejected: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: lucideReact.Ban, label: "Rejected" },
109
- expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: lucideReact.CircleAlert, label: "Expired" }
112
+ expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: lucideReact.CircleAlert, label: "Expired" },
113
+ archived: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: lucideReact.Archive, label: "Archived" },
114
+ invoiced: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: lucideReact.Receipt, label: "Invoiced" },
115
+ paid: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: lucideReact.Receipt, label: "Paid" },
116
+ partial: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: lucideReact.Receipt, label: "Partial" },
117
+ overdue: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: lucideReact.Receipt, label: "Overdue" }
110
118
  };
111
119
  var TRANSITIONS = {
112
120
  draft: ["sent", "expired"],
113
121
  sent: ["approved", "rejected", "expired"],
114
122
  approved: [],
115
123
  rejected: [],
116
- expired: []
124
+ expired: [],
125
+ archived: []
117
126
  };
118
127
  function RejectModal({ onConfirm, onCancel }) {
119
128
  const [reason, setReason] = React14.useState("");
@@ -292,27 +301,40 @@ var TYPE_ICONS = {
292
301
  meeting: lucideReact.Users,
293
302
  note: lucideReact.FileText,
294
303
  task: lucideReact.CheckSquare,
295
- whatsapp: lucideReact.MessageCircle
304
+ whatsapp: lucideReact.MessageCircle,
305
+ // System timeline events (auto-logged by the provider)
306
+ lead_created: lucideReact.UserPlus,
307
+ lead_converted: lucideReact.ArrowRightLeft,
308
+ deal_created: lucideReact.Target,
309
+ stage_changed: lucideReact.MoveRight,
310
+ deal_won: lucideReact.Trophy,
311
+ deal_lost: lucideReact.XCircle,
312
+ quote_created: lucideReact.FilePlus2,
313
+ quote_sent: lucideReact.Send,
314
+ quote_approved: lucideReact.FileCheck2,
315
+ quote_rejected: lucideReact.FileX2,
316
+ lead_archived: lucideReact.Archive,
317
+ deal_archived: lucideReact.Archive,
318
+ quote_archived: lucideReact.Archive
296
319
  };
297
320
  function TabBar({ active, counts, onChange }) {
298
321
  const t2 = core.useTranslation();
299
- const tabs = [
300
- { id: "overview", label: t2("crm.dealSidebar.overview") },
301
- { id: "activity", label: t2("crm.dealSidebar.activity"), count: counts.activity },
302
- { id: "quotes", label: t2("crm.dealSidebar.quotes"), count: counts.quotes }
303
- ];
304
- return /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsxs(
305
- "button",
322
+ const label = (text, count, isActive) => /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
323
+ text,
324
+ count != null && count > 0 && /* @__PURE__ */ jsxRuntime.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 })
325
+ ] });
326
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 py-2 border-b shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(
327
+ ui.SegmentedControl,
306
328
  {
307
- onClick: () => onChange(tab.id),
308
- 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"}`,
309
- children: [
310
- tab.label,
311
- tab.count != null && tab.count > 0 && /* @__PURE__ */ jsxRuntime.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 })
329
+ value: active,
330
+ onChange,
331
+ options: [
332
+ { value: "overview", label: label(t2("crm.dealSidebar.overview"), void 0, active === "overview") },
333
+ { value: "activity", label: label(t2("crm.dealSidebar.activity"), counts.activity, active === "activity") },
334
+ { value: "quotes", label: label(t2("crm.dealSidebar.quotes"), counts.quotes, active === "quotes") }
312
335
  ]
313
- },
314
- tab.id
315
- )) });
336
+ }
337
+ ) });
316
338
  }
317
339
  function FormAnswers({ lead }) {
318
340
  const t2 = core.useTranslation();
@@ -400,18 +422,6 @@ function OverviewTab({ deal, lead, currency }) {
400
422
  deal.notes && deal.notes !== deal.title && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
401
423
  /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
402
424
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed", children: deal.notes })
403
- ] }),
404
- /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4 pt-3 border-t text-[10px] text-muted-foreground", children: [
405
- /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
406
- t2("crm.dealSidebar.created"),
407
- " ",
408
- deal.createdAt?.slice(0, 10)
409
- ] }),
410
- deal.updatedAt && /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
411
- t2("crm.dealSidebar.updated"),
412
- " ",
413
- deal.updatedAt?.slice(0, 10)
414
- ] })
415
425
  ] })
416
426
  ] });
417
427
  }
@@ -563,6 +573,12 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
563
573
  onClose();
564
574
  }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
565
575
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.dealNotFound") }) }) }),
576
+ deal && /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
577
+ t2("crm.dealSidebar.created"),
578
+ " ",
579
+ deal.createdAt?.slice(0, 10),
580
+ deal.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${deal.updatedAt.slice(0, 10)}` : ""
581
+ ] }),
566
582
  deal && lead && onViewLead && /* @__PURE__ */ jsxRuntime.jsx(ui.SheetFooter, { children: /* @__PURE__ */ jsxRuntime.jsxs(
567
583
  "button",
568
584
  {
@@ -597,7 +613,8 @@ function PipelineSkeleton() {
597
613
  ] }, i)) })
598
614
  ] }, col)) });
599
615
  }
600
- function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
616
+ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onDragEnd }) {
617
+ const t2 = core.useTranslation();
601
618
  return /* @__PURE__ */ jsxRuntime.jsxs(
602
619
  "div",
603
620
  {
@@ -605,11 +622,23 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
605
622
  onDragStart,
606
623
  onDragEnd,
607
624
  onClick,
608
- className: `rounded-lg border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
625
+ 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"}`,
609
626
  children: [
610
627
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between gap-2", children: [
611
628
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium truncate", children: deal.title }),
612
- saving && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" })
629
+ saving && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" }),
630
+ !saving && onArchive && /* @__PURE__ */ jsxRuntime.jsx(
631
+ "button",
632
+ {
633
+ onClick: (e) => {
634
+ e.stopPropagation();
635
+ onArchive();
636
+ },
637
+ title: t2("crm.pipeline.archive"),
638
+ 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",
639
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Archive, { className: "h-3 w-3" })
640
+ }
641
+ )
613
642
  ] }),
614
643
  deal.contactName && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground mt-0.5", children: deal.contactName }),
615
644
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between mt-2", children: [
@@ -623,7 +652,7 @@ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
623
652
  }
624
653
  );
625
654
  }
626
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
655
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
627
656
  const t2 = core.useTranslation();
628
657
  const isOver = dragOverStageId === stageId;
629
658
  const [hovered, setHovered] = React14.useState(false);
@@ -667,6 +696,7 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
667
696
  saving: savingDealIds.has(deal.id),
668
697
  currency,
669
698
  onClick: () => onDealClick?.(deal.id),
699
+ onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
670
700
  onDragStart: (e) => {
671
701
  e.dataTransfer.effectAllowed = "move";
672
702
  onDragStart(deal.id, stageId);
@@ -690,6 +720,8 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
690
720
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
691
721
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage);
692
722
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
723
+ const archiveDeal = useCrmStore((s) => s.archiveDeal);
724
+ const canArchive = useCanArchive();
693
725
  const [dragOverStageId, setDragOverStageId] = React14.useState(null);
694
726
  const [savingDealIds, setSavingDealIds] = React14.useState(/* @__PURE__ */ new Set());
695
727
  const [optimisticBoard, setOptimisticBoard] = React14.useState(null);
@@ -791,6 +823,9 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
791
823
  currency,
792
824
  dragOverStageId,
793
825
  onDealClick: handleDealClick,
826
+ onArchiveDeal: canArchive ? (id) => {
827
+ void archiveDeal(id);
828
+ } : void 0,
794
829
  onAddLead,
795
830
  onDragStart: handleDragStart,
796
831
  onDragEnd: handleDragEnd,
@@ -982,7 +1017,7 @@ var STATUS_COLORS = {
982
1017
  overdue: "bg-destructive-soft text-destructive-soft-foreground",
983
1018
  cancelled: "bg-muted text-muted-foreground"
984
1019
  };
985
- function useQuoteColumns(currency, onEditQuote) {
1020
+ function useQuoteColumns(currency, onEditQuote, onArchive) {
986
1021
  const t2 = core.useTranslation();
987
1022
  const cols = [
988
1023
  { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
@@ -1002,22 +1037,36 @@ function useQuoteColumns(currency, onEditQuote) {
1002
1037
  }
1003
1038
  }
1004
1039
  ];
1005
- if (onEditQuote) {
1040
+ if (onEditQuote || onArchive) {
1006
1041
  cols.push({
1007
1042
  id: "actions",
1008
1043
  header: "",
1009
- cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-right", children: /* @__PURE__ */ jsxRuntime.jsx(
1010
- "button",
1011
- {
1012
- onClick: (e) => {
1013
- e.stopPropagation();
1014
- onEditQuote(row.original.id);
1015
- },
1016
- className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1017
- title: "Edit quote",
1018
- children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { className: "h-3.5 w-3.5" })
1019
- }
1020
- ) })
1044
+ cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
1045
+ onEditQuote && /* @__PURE__ */ jsxRuntime.jsx(
1046
+ "button",
1047
+ {
1048
+ onClick: (e) => {
1049
+ e.stopPropagation();
1050
+ onEditQuote(row.original.id);
1051
+ },
1052
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1053
+ title: "Edit quote",
1054
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { className: "h-3.5 w-3.5" })
1055
+ }
1056
+ ),
1057
+ onArchive && /* @__PURE__ */ jsxRuntime.jsx(
1058
+ "button",
1059
+ {
1060
+ onClick: (e) => {
1061
+ e.stopPropagation();
1062
+ onArchive(row.original.id);
1063
+ },
1064
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
1065
+ title: t2("crm.quotes.archive"),
1066
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Archive, { className: "h-3.5 w-3.5" })
1067
+ }
1068
+ )
1069
+ ] })
1021
1070
  });
1022
1071
  }
1023
1072
  return cols;
@@ -1028,10 +1077,14 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1028
1077
  const quotes = useCrmStore((s) => s.quotes);
1029
1078
  const quotesLoading = useCrmStore((s) => s.quotesLoading);
1030
1079
  const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
1080
+ const archiveQuote = useCrmStore((s) => s.archiveQuote);
1081
+ const canArchive = useCanArchive();
1031
1082
  React14.useEffect(() => {
1032
1083
  fetchQuotes({});
1033
1084
  }, []);
1034
- const columns2 = useQuoteColumns(currency, onEditQuote);
1085
+ const columns2 = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
1086
+ void archiveQuote(id);
1087
+ } : void 0);
1035
1088
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
1036
1089
  /* @__PURE__ */ jsxRuntime.jsx(
1037
1090
  ui.SubpageHeader,
@@ -1729,7 +1782,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1729
1782
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap", children: quote.observations })
1730
1783
  ] })
1731
1784
  ] }),
1732
- quote.status === "approved" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
1785
+ ["approved", "invoiced", "paid", "partial", "overdue"].includes(quote.status) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
1733
1786
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1734
1787
  /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
1735
1788
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground", children: t2("crm.quoteDetail.invoiceCreated") })
@@ -1737,7 +1790,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1737
1790
  /* @__PURE__ */ jsxRuntime.jsxs(
1738
1791
  "a",
1739
1792
  {
1740
- href: `#/financial/receivables/detail/${quote.id}`,
1793
+ href: "#/financial/receivables/list",
1741
1794
  className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",
1742
1795
  children: [
1743
1796
  t2("crm.quoteDetail.viewInvoice"),
@@ -1819,6 +1872,9 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1819
1872
  const provider = useCrmProvider();
1820
1873
  const { currency } = useCrmConfig();
1821
1874
  const t2 = core.useTranslation();
1875
+ const archiveLead = useCrmStore((s) => s.archiveLead);
1876
+ const canArchive = useCanArchive();
1877
+ const [archiving, setArchiving] = React14.useState(false);
1822
1878
  const [lead, setLead] = React14.useState(null);
1823
1879
  const [deal, setDeal] = React14.useState(null);
1824
1880
  const [quotes, setQuotes] = React14.useState([]);
@@ -1882,18 +1938,37 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1882
1938
  lead.sourceName && /* @__PURE__ */ jsxRuntime.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 })
1883
1939
  ] })
1884
1940
  ] }),
1885
- onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxRuntime.jsxs(
1886
- "button",
1887
- {
1888
- onClick: () => onCreateQuote(leadId),
1889
- 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",
1890
- children: [
1891
- /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-3 w-3" }),
1892
- " ",
1893
- t2("crm.leadDetail.createQuote")
1894
- ]
1895
- }
1896
- )
1941
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 shrink-0", children: [
1942
+ canArchive && /* @__PURE__ */ jsxRuntime.jsxs(
1943
+ "button",
1944
+ {
1945
+ onClick: () => {
1946
+ setArchiving(true);
1947
+ archiveLead(leadId).then(onBack).catch(() => setArchiving(false));
1948
+ },
1949
+ disabled: archiving,
1950
+ title: t2("crm.leadDetail.archive"),
1951
+ 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",
1952
+ children: [
1953
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Archive, { className: "h-3 w-3" }),
1954
+ " ",
1955
+ t2("crm.leadDetail.archive")
1956
+ ]
1957
+ }
1958
+ ),
1959
+ onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxRuntime.jsxs(
1960
+ "button",
1961
+ {
1962
+ onClick: () => onCreateQuote(leadId),
1963
+ 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",
1964
+ children: [
1965
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-3 w-3" }),
1966
+ " ",
1967
+ t2("crm.leadDetail.createQuote")
1968
+ ]
1969
+ }
1970
+ )
1971
+ ] })
1897
1972
  ] }),
1898
1973
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-t" }),
1899
1974
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
@@ -1978,14 +2053,47 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1978
2053
  ] })
1979
2054
  ] });
1980
2055
  }
2056
+
2057
+ // src/types.ts
2058
+ var SYSTEM_ACTIVITY_TYPES = [
2059
+ "lead_created",
2060
+ "lead_converted",
2061
+ "lead_archived",
2062
+ "deal_created",
2063
+ "stage_changed",
2064
+ "deal_won",
2065
+ "deal_lost",
2066
+ "deal_archived",
2067
+ "quote_created",
2068
+ "quote_sent",
2069
+ "quote_approved",
2070
+ "quote_rejected",
2071
+ "quote_archived"
2072
+ ];
1981
2073
  var TYPE_CONFIG = {
1982
2074
  call: { icon: lucideReact.Phone, color: "bg-info/15 text-info dark:bg-info/20", label: "Call" },
1983
2075
  email: { icon: lucideReact.Mail, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Email" },
1984
2076
  meeting: { icon: lucideReact.Users, color: "bg-success-soft text-success-soft-foreground", label: "Meeting" },
1985
2077
  note: { icon: lucideReact.FileText, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Note" },
1986
2078
  task: { icon: lucideReact.CheckSquare, color: "bg-pink-100 text-pink-600 dark:bg-pink-500/20 dark:text-pink-400", label: "Task" },
1987
- whatsapp: { icon: lucideReact.MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" }
2079
+ whatsapp: { icon: lucideReact.MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" },
2080
+ // System timeline events (auto-logged by the data provider on every CRM write)
2081
+ lead_created: { icon: lucideReact.UserPlus, color: "bg-info/15 text-info dark:bg-info/20", label: "Lead created" },
2082
+ lead_converted: { icon: lucideReact.ArrowRightLeft, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Lead converted" },
2083
+ deal_created: { icon: lucideReact.Target, color: "bg-info/15 text-info dark:bg-info/20", label: "Deal created" },
2084
+ stage_changed: { icon: lucideReact.MoveRight, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Stage changed" },
2085
+ deal_won: { icon: lucideReact.Trophy, color: "bg-success/15 text-success dark:bg-success/20", label: "Deal won" },
2086
+ deal_lost: { icon: lucideReact.XCircle, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Deal lost" },
2087
+ quote_created: { icon: lucideReact.FilePlus2, color: "bg-info/15 text-info dark:bg-info/20", label: "Quote created" },
2088
+ quote_sent: { icon: lucideReact.Send, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Quote sent" },
2089
+ quote_approved: { icon: lucideReact.FileCheck2, color: "bg-success/15 text-success dark:bg-success/20", label: "Quote approved" },
2090
+ quote_rejected: { icon: lucideReact.FileX2, color: "bg-destructive/15 text-destructive dark:bg-destructive/20", label: "Quote rejected" },
2091
+ lead_archived: { icon: lucideReact.Archive, color: "bg-muted text-muted-foreground", label: "Lead archived" },
2092
+ deal_archived: { icon: lucideReact.Archive, color: "bg-muted text-muted-foreground", label: "Deal archived" },
2093
+ quote_archived: { icon: lucideReact.Archive, color: "bg-muted text-muted-foreground", label: "Quote archived" }
1988
2094
  };
2095
+ var SYSTEM_TYPES = new Set(SYSTEM_ACTIVITY_TYPES);
2096
+ var MANUAL_TYPES = Object.keys(TYPE_CONFIG).filter((t2) => !SYSTEM_TYPES.has(t2));
1989
2097
  function ActivitySkeleton() {
1990
2098
  return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: [1, 2, 3, 4, 5].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3 rounded-lg border bg-card shadow-sm p-4", children: [
1991
2099
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-9 w-9 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
@@ -2000,20 +2108,23 @@ function ActivitySkeleton() {
2000
2108
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse shrink-0" })
2001
2109
  ] }, i)) });
2002
2110
  }
2003
- function ActivityListView() {
2111
+ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2004
2112
  const t2 = core.useTranslation();
2113
+ const provider = useCrmProvider();
2114
+ const [selectedDealId, setSelectedDealId] = React14.useState(null);
2005
2115
  const activities = useCrmStore((s) => s.activities);
2006
2116
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
2007
2117
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
2008
2118
  const [typeFilter, setTypeFilter] = React14.useState(null);
2009
2119
  const [showCompleted, setShowCompleted] = React14.useState(null);
2120
+ const eventsFilter = typeFilter === "events";
2010
2121
  React14.useEffect(() => {
2011
2122
  fetchActivities({
2012
- activityType: typeFilter,
2013
- completed: showCompleted ?? void 0
2123
+ activityType: eventsFilter ? void 0 : typeFilter,
2124
+ completed: eventsFilter ? void 0 : showCompleted ?? void 0
2014
2125
  });
2015
2126
  }, [typeFilter, showCompleted]);
2016
- const filtered = activities;
2127
+ const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities;
2017
2128
  const pendingCount = activities.filter((a) => !a.completedAt).length;
2018
2129
  const overdueCount = activities.filter((a) => !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)).length;
2019
2130
  return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
@@ -2034,7 +2145,8 @@ function ActivityListView() {
2034
2145
  children: t2("crm.activities.all")
2035
2146
  }
2036
2147
  ),
2037
- Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
2148
+ MANUAL_TYPES.map((type) => {
2149
+ const cfg = TYPE_CONFIG[type];
2038
2150
  const Icon = cfg.icon;
2039
2151
  return /* @__PURE__ */ jsxRuntime.jsxs(
2040
2152
  "button",
@@ -2048,7 +2160,18 @@ function ActivityListView() {
2048
2160
  },
2049
2161
  type
2050
2162
  );
2051
- })
2163
+ }),
2164
+ /* @__PURE__ */ jsxRuntime.jsxs(
2165
+ "button",
2166
+ {
2167
+ onClick: () => setTypeFilter(eventsFilter ? null : "events"),
2168
+ 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"}`,
2169
+ children: [
2170
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Sparkles, { className: "h-3 w-3" }),
2171
+ t2("crm.activities.systemEvents")
2172
+ ]
2173
+ }
2174
+ )
2052
2175
  ] }),
2053
2176
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1" }),
2054
2177
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5", children: [
@@ -2085,17 +2208,26 @@ function ActivityListView() {
2085
2208
  ] }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: filtered.map((a) => {
2086
2209
  const cfg = TYPE_CONFIG[a.activityType] ?? { icon: lucideReact.FileText, color: "bg-muted text-muted-foreground", label: a.activityType };
2087
2210
  const Icon = cfg.icon;
2211
+ const isSystem = SYSTEM_TYPES.has(a.activityType);
2088
2212
  const isOverdue = !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2213
+ const openRecord = a.dealId ? () => setSelectedDealId(a.dealId) : a.leadId ? () => {
2214
+ void provider.getDealByLeadId(a.leadId).then((deal) => {
2215
+ if (deal) setSelectedDealId(deal.id);
2216
+ else onOpenLead?.(a.leadId);
2217
+ });
2218
+ } : void 0;
2089
2219
  return /* @__PURE__ */ jsxRuntime.jsxs(
2090
2220
  "div",
2091
2221
  {
2092
- className: `flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""}`,
2222
+ onClick: openRecord,
2223
+ role: openRecord ? "button" : void 0,
2224
+ 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" : ""}`,
2093
2225
  children: [
2094
2226
  /* @__PURE__ */ jsxRuntime.jsx("div", { className: `flex h-9 w-9 items-center justify-center rounded-lg shrink-0 ${cfg.color}`, children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-4 w-4" }) }),
2095
2227
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
2096
2228
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
2097
2229
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium truncate", children: a.title }),
2098
- a.completedAt && /* @__PURE__ */ jsxRuntime.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: [
2230
+ a.completedAt && !isSystem && /* @__PURE__ */ jsxRuntime.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: [
2099
2231
  /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-2.5 w-2.5" }),
2100
2232
  " ",
2101
2233
  t2("crm.activities.done")
@@ -2122,12 +2254,25 @@ function ActivityListView() {
2122
2254
  ] })
2123
2255
  ] })
2124
2256
  ] }),
2125
- /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] text-muted-foreground shrink-0 pt-1", children: new Date(a.createdAt).toLocaleDateString() })
2257
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "flex items-center gap-1.5 text-[10px] text-muted-foreground shrink-0 pt-1", children: [
2258
+ new Date(a.createdAt).toLocaleDateString(),
2259
+ openRecord && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ArrowRight, { className: "h-3 w-3 opacity-0 transition-opacity group-hover:opacity-60" })
2260
+ ] })
2126
2261
  ]
2127
2262
  },
2128
2263
  a.id
2129
2264
  );
2130
- }) })
2265
+ }) }),
2266
+ /* @__PURE__ */ jsxRuntime.jsx(
2267
+ DealSidebar,
2268
+ {
2269
+ dealId: selectedDealId ?? "",
2270
+ open: !!selectedDealId,
2271
+ onClose: () => setSelectedDealId(null),
2272
+ onViewLead: onOpenLead,
2273
+ onViewQuote: onOpenQuote
2274
+ }
2275
+ )
2131
2276
  ] });
2132
2277
  }
2133
2278
  function buildNav(config, view, navigate) {
@@ -2221,7 +2366,7 @@ function CrmPage({ config, provider, store, registries }) {
2221
2366
  return /* @__PURE__ */ jsxRuntime.jsx(QuoteFormView, { leadId: lid, onSaved: (id) => id ? navigate(`quotes-detail:${id}`) : navigate("quotes-list") });
2222
2367
  } },
2223
2368
  { id: "quotes-list", render: () => /* @__PURE__ */ jsxRuntime.jsx(QuoteListView, { onNew: () => navigate("quotes-new"), onEdit: (id) => navigate(`quotes-detail:${id}`), onEditQuote: (id) => navigate(`quotes-edit:${id}`) }) },
2224
- { id: "activities", render: () => /* @__PURE__ */ jsxRuntime.jsx(ActivityListView, {}) },
2369
+ { id: "activities", render: () => /* @__PURE__ */ jsxRuntime.jsx(ActivityListView, { onOpenLead: (id) => navigate(`leads-detail:${id}`), onOpenQuote: (id) => navigate(`quotes-detail:${id}`) }) },
2225
2370
  { id: "leads-detail", render: ({ id }) => /* @__PURE__ */ jsxRuntime.jsx(LeadDetailView, { leadId: id, onBack: () => navigate("leads-list"), onCreateQuote: (lid) => navigate("quotes-new", `/sales/quotes/new?leadId=${lid}`), onViewQuote: (qid) => navigate(`quotes-detail:${qid}`) }) },
2226
2371
  { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsxRuntime.jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
2227
2372
  window.location.hash = `/financial/receivables/detail/${invoiceId}`;
@@ -2464,6 +2609,7 @@ function deriveLeadStatus(stage) {
2464
2609
  return "qualified";
2465
2610
  }
2466
2611
  function deriveQuoteStatus(stage, current) {
2612
+ if (current === "archived") return current;
2467
2613
  if (stage.isWon) return "approved";
2468
2614
  if (stage.isLost) return "rejected";
2469
2615
  return current;
@@ -2489,7 +2635,7 @@ function paginate(items, page, pageSize) {
2489
2635
  function createStore(seedStages) {
2490
2636
  const tenantId = "mock-tenant";
2491
2637
  const pipelineId = uid();
2492
- const defaultStages = [
2638
+ const defaultStages = seedStages ?? [
2493
2639
  { name: "New", color: "#6366f1", probability: 10 },
2494
2640
  { name: "Contacted", color: "#3b82f6", probability: 25 },
2495
2641
  { name: "Qualified", color: "#f59e0b", probability: 50 },
@@ -2528,8 +2674,23 @@ function createStore(seedStages) {
2528
2674
  };
2529
2675
  }
2530
2676
  function createMockCrmProvider(options) {
2531
- const store = createStore();
2677
+ const store = createStore(options?.dealStages);
2532
2678
  const tenantId = "mock-tenant";
2679
+ function logEvent(input) {
2680
+ store.activities.push({
2681
+ id: uid(),
2682
+ dealId: input.dealId,
2683
+ leadId: input.leadId,
2684
+ contactId: input.contactId,
2685
+ contactName: input.contactName,
2686
+ activityType: input.activityType,
2687
+ title: input.title,
2688
+ description: input.description,
2689
+ completedAt: now(),
2690
+ tenantId,
2691
+ createdAt: now()
2692
+ });
2693
+ }
2533
2694
  function cascadeFromStage(deal, stage) {
2534
2695
  if (deal.leadId) {
2535
2696
  const lead = store.leads.find((l) => l.id === deal.leadId);
@@ -2554,7 +2715,7 @@ function createMockCrmProvider(options) {
2554
2715
  },
2555
2716
  // Leads
2556
2717
  async getLeads(query) {
2557
- let results = [...store.leads];
2718
+ let results = store.leads.filter((l) => l.isActive !== false);
2558
2719
  if (query.status) {
2559
2720
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2560
2721
  results = results.filter((l) => statuses.includes(l.status));
@@ -2588,6 +2749,7 @@ function createMockCrmProvider(options) {
2588
2749
  updatedAt: now()
2589
2750
  };
2590
2751
  store.leads.push(lead);
2752
+ logEvent({ activityType: "lead_created", title: lead.name, leadId: lead.id, contactName: lead.name });
2591
2753
  return lead;
2592
2754
  },
2593
2755
  async updateLead(id, data) {
@@ -2601,6 +2763,7 @@ function createMockCrmProvider(options) {
2601
2763
  if (!lead) throw new Error(`Lead ${leadId} not found`);
2602
2764
  lead.status = "converted";
2603
2765
  lead.updatedAt = now();
2766
+ logEvent({ activityType: "lead_converted", title: lead.name, leadId, contactName: lead.name });
2604
2767
  const deal = await provider.createDeal({ ...dealInput, leadId });
2605
2768
  return deal;
2606
2769
  },
@@ -2612,6 +2775,8 @@ function createMockCrmProvider(options) {
2612
2775
  if (query.status) {
2613
2776
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2614
2777
  results = results.filter((d) => statuses.includes(d.status));
2778
+ } else {
2779
+ results = results.filter((d) => d.status !== "archived");
2615
2780
  }
2616
2781
  if (query.search) {
2617
2782
  const s = query.search.toLowerCase();
@@ -2655,6 +2820,14 @@ function createMockCrmProvider(options) {
2655
2820
  updatedAt: now()
2656
2821
  };
2657
2822
  store.deals.push(deal);
2823
+ logEvent({
2824
+ activityType: "deal_created",
2825
+ title: deal.title,
2826
+ dealId: deal.id,
2827
+ leadId: deal.leadId,
2828
+ contactId: deal.contactId,
2829
+ contactName: deal.contactName
2830
+ });
2658
2831
  return deal;
2659
2832
  },
2660
2833
  async updateDeal(id, data) {
@@ -2676,8 +2849,31 @@ function createMockCrmProvider(options) {
2676
2849
  if (stage.isLost) deal.status = "lost";
2677
2850
  deal.updatedAt = now();
2678
2851
  cascadeFromStage(deal, stage);
2852
+ logEvent({
2853
+ activityType: stage.isWon ? "deal_won" : stage.isLost ? "deal_lost" : "stage_changed",
2854
+ title: deal.title || "Deal",
2855
+ description: stage.name,
2856
+ dealId: deal.id,
2857
+ contactName: deal.contactName
2858
+ });
2679
2859
  return deal;
2680
2860
  },
2861
+ async archiveDeal(dealId) {
2862
+ const deal = store.deals.find((d) => d.id === dealId);
2863
+ if (!deal) throw new Error(`Deal ${dealId} not found`);
2864
+ deal.status = "archived";
2865
+ deal.updatedAt = now();
2866
+ logEvent({ activityType: "deal_archived", title: deal.title || "Deal", dealId, contactName: deal.contactName });
2867
+ },
2868
+ async archiveLead(leadId) {
2869
+ const lead = store.leads.find((l) => l.id === leadId);
2870
+ if (!lead) throw new Error(`Lead ${leadId} not found`);
2871
+ lead.isActive = false;
2872
+ lead.updatedAt = now();
2873
+ const deal = store.deals.find((d) => d.leadId === leadId && d.status === "open");
2874
+ if (deal) await provider.archiveDeal(deal.id);
2875
+ logEvent({ activityType: "lead_archived", title: lead.name, leadId, contactName: lead.name });
2876
+ },
2681
2877
  // Activities
2682
2878
  async getActivities(query) {
2683
2879
  let results = [...store.activities];
@@ -2713,9 +2909,20 @@ function createMockCrmProvider(options) {
2713
2909
  activity.completedAt = now();
2714
2910
  return activity;
2715
2911
  },
2912
+ async getActivityTypes() {
2913
+ const seed = options?.activityTypes ?? [
2914
+ { value: "call", label: "Call", icon: "Phone" },
2915
+ { value: "email", label: "Email", icon: "Mail" },
2916
+ { value: "meeting", label: "Meeting", icon: "Users" },
2917
+ { value: "note", label: "Note", icon: "FileText" },
2918
+ { value: "task", label: "Task", icon: "CheckSquare" },
2919
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
2920
+ ];
2921
+ return seed.map((t2, i) => ({ id: `at-${i}`, name: t2.label, icon: t2.icon, isActive: true }));
2922
+ },
2716
2923
  // Quotes
2717
2924
  async getQuotes(query) {
2718
- let results = [...store.quotes];
2925
+ let results = store.quotes.filter((q) => q.status !== "archived" || query.status && (Array.isArray(query.status) ? query.status : [query.status]).includes("archived"));
2719
2926
  if (query.status) {
2720
2927
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
2721
2928
  results = results.filter((q) => statuses.includes(q.status));
@@ -2759,6 +2966,22 @@ function createMockCrmProvider(options) {
2759
2966
  updatedAt: now()
2760
2967
  };
2761
2968
  store.quotes.push(quote);
2969
+ if (quote.dealId && totalAmount > 0) {
2970
+ const deal = store.deals.find((d) => d.id === quote.dealId);
2971
+ if (deal) {
2972
+ deal.value = totalAmount;
2973
+ deal.updatedAt = now();
2974
+ }
2975
+ }
2976
+ logEvent({
2977
+ activityType: "quote_created",
2978
+ title: quote.quoteNumber ?? "Quote",
2979
+ description: quote.contactName,
2980
+ dealId: quote.dealId,
2981
+ leadId: quote.leadId,
2982
+ contactId: quote.contactId,
2983
+ contactName: quote.contactName
2984
+ });
2762
2985
  return quote;
2763
2986
  },
2764
2987
  async updateQuote(id, input) {
@@ -2782,6 +3005,13 @@ function createMockCrmProvider(options) {
2782
3005
  quote.items = items;
2783
3006
  quote.totalAmount = totalAmount;
2784
3007
  quote.updatedAt = now();
3008
+ if (quote.dealId && totalAmount > 0) {
3009
+ const deal = store.deals.find((d) => d.id === quote.dealId);
3010
+ if (deal) {
3011
+ deal.value = totalAmount;
3012
+ deal.updatedAt = now();
3013
+ }
3014
+ }
2785
3015
  return quote;
2786
3016
  },
2787
3017
  async sendQuote(id) {
@@ -2789,6 +3019,14 @@ function createMockCrmProvider(options) {
2789
3019
  if (!quote) throw new Error(`Quote ${id} not found`);
2790
3020
  quote.status = "sent";
2791
3021
  quote.updatedAt = now();
3022
+ logEvent({
3023
+ activityType: "quote_sent",
3024
+ title: quote.quoteNumber ?? "Quote",
3025
+ description: quote.contactName,
3026
+ dealId: quote.dealId,
3027
+ leadId: quote.leadId,
3028
+ contactName: quote.contactName
3029
+ });
2792
3030
  return quote;
2793
3031
  },
2794
3032
  async approveQuote(id) {
@@ -2812,6 +3050,14 @@ function createMockCrmProvider(options) {
2812
3050
  lead.metadata = { ...lead.metadata, convertedFromLead: true };
2813
3051
  }
2814
3052
  }
3053
+ logEvent({
3054
+ activityType: "quote_approved",
3055
+ title: quote.quoteNumber ?? "Quote",
3056
+ description: quote.contactName,
3057
+ dealId: quote.dealId,
3058
+ leadId: quote.leadId,
3059
+ contactName: quote.contactName
3060
+ });
2815
3061
  return quote;
2816
3062
  },
2817
3063
  async rejectQuote(id, reason) {
@@ -2829,6 +3075,14 @@ function createMockCrmProvider(options) {
2829
3075
  }
2830
3076
  }
2831
3077
  }
3078
+ logEvent({
3079
+ activityType: "quote_rejected",
3080
+ title: quote.quoteNumber ?? "Quote",
3081
+ description: reason,
3082
+ dealId: quote.dealId,
3083
+ leadId: quote.leadId,
3084
+ contactName: quote.contactName
3085
+ });
2832
3086
  return quote;
2833
3087
  },
2834
3088
  async expireQuote(id) {
@@ -2838,6 +3092,20 @@ function createMockCrmProvider(options) {
2838
3092
  quote.updatedAt = now();
2839
3093
  return quote;
2840
3094
  },
3095
+ async archiveQuote(id) {
3096
+ const quote = store.quotes.find((q) => q.id === id);
3097
+ if (!quote) throw new Error(`Quote ${id} not found`);
3098
+ quote.status = "archived";
3099
+ quote.updatedAt = now();
3100
+ logEvent({
3101
+ activityType: "quote_archived",
3102
+ title: quote.quoteNumber ?? "Quote",
3103
+ description: quote.contactName,
3104
+ dealId: quote.dealId,
3105
+ leadId: quote.leadId,
3106
+ contactName: quote.contactName
3107
+ });
3108
+ },
2841
3109
  // Cross-entity lookups
2842
3110
  async getQuotesByDealId(dealId) {
2843
3111
  return store.quotes.filter((q) => q.dealId === dealId);
@@ -2919,6 +3187,34 @@ async function mergePersonMetadata(personId, patch) {
2919
3187
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
2920
3188
  }
2921
3189
  function createSupabaseCrmProvider(options) {
3190
+ async function logEvent(input) {
3191
+ try {
3192
+ const { pub } = getClients();
3193
+ await pub.from(T.activities).insert({
3194
+ tenant_id: getTenantId(),
3195
+ deal_id: input.dealId ?? null,
3196
+ lead_id: input.leadId ?? null,
3197
+ contact_id: input.contactId ?? null,
3198
+ contact_name: input.contactName ?? null,
3199
+ activity_type: input.activityType,
3200
+ title: input.title,
3201
+ description: input.description ?? null,
3202
+ completed_at: (/* @__PURE__ */ new Date()).toISOString()
3203
+ });
3204
+ } catch {
3205
+ }
3206
+ }
3207
+ const typesSeeded = /* @__PURE__ */ new Set();
3208
+ async function ensureActivityTypes(tenantId) {
3209
+ const seed = options?.activityTypes;
3210
+ if (!seed?.length || typesSeeded.has(tenantId)) return;
3211
+ typesSeeded.add(tenantId);
3212
+ const { pub } = getClients();
3213
+ await pub.from(T.activityTypes).upsert(
3214
+ seed.map((t2) => ({ tenant_id: tenantId, name: t2.label, icon: t2.icon ?? null, is_active: true })),
3215
+ { onConflict: "tenant_id,name", ignoreDuplicates: true }
3216
+ );
3217
+ }
2922
3218
  const provider = {
2923
3219
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
2924
3220
  async getPipelines() {
@@ -2934,7 +3230,7 @@ function createSupabaseCrmProvider(options) {
2934
3230
  // --- Leads (via view — single query) ---
2935
3231
  async getLeads(query) {
2936
3232
  const { pub } = getClients();
2937
- let qb = pub.from("v_leads").select("*", { count: "exact" });
3233
+ let qb = pub.from("v_leads").select("*", { count: "exact" }).eq("is_active", true);
2938
3234
  if (query.search) qb = qb.ilike("name", `%${query.search}%`);
2939
3235
  if (query.status) {
2940
3236
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
@@ -3007,6 +3303,7 @@ function createSupabaseCrmProvider(options) {
3007
3303
  }).select().single();
3008
3304
  if (error) throw new Error(error.message);
3009
3305
  const p = snakeToCamel(data);
3306
+ await logEvent({ activityType: "lead_created", title: input.name, leadId: p.id, contactName: input.name });
3010
3307
  return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3011
3308
  },
3012
3309
  async updateLead(id, partial) {
@@ -3022,8 +3319,13 @@ function createSupabaseCrmProvider(options) {
3022
3319
  return await provider.getLeadById(id);
3023
3320
  },
3024
3321
  async convertLeadToDeal(leadId, dealInput) {
3025
- getClients();
3026
3322
  await mergePersonMetadata(leadId, { status: "converted" });
3323
+ await logEvent({
3324
+ activityType: "lead_converted",
3325
+ title: dealInput.contactName ?? dealInput.title,
3326
+ leadId,
3327
+ contactName: dealInput.contactName
3328
+ });
3027
3329
  return provider.createDeal({ ...dealInput, leadId });
3028
3330
  },
3029
3331
  // --- Deals (via view — single query with all joins) ---
@@ -3033,6 +3335,8 @@ function createSupabaseCrmProvider(options) {
3033
3335
  if (query.status) {
3034
3336
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3035
3337
  qb = qb.in("status", statuses);
3338
+ } else {
3339
+ qb = qb.neq("status", "archived");
3036
3340
  }
3037
3341
  if (query.search) qb = qb.ilike("title", `%${query.search}%`);
3038
3342
  if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
@@ -3094,7 +3398,7 @@ function createSupabaseCrmProvider(options) {
3094
3398
  async getDealsByStage(pipelineId) {
3095
3399
  const { pub } = getClients();
3096
3400
  const stages = await provider.getPipelineStages(pipelineId);
3097
- const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).neq("status", "lost");
3401
+ const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).not("status", "in", "(lost,archived)");
3098
3402
  const deals = (data ?? []).map((r) => ({
3099
3403
  id: r.id,
3100
3404
  title: r.title ?? "",
@@ -3145,6 +3449,14 @@ function createSupabaseCrmProvider(options) {
3145
3449
  expected_close_date: input.expectedCloseDate,
3146
3450
  lead_id: input.leadId
3147
3451
  });
3452
+ await logEvent({
3453
+ activityType: "deal_created",
3454
+ title: input.title,
3455
+ dealId: order.id,
3456
+ leadId: input.leadId,
3457
+ contactId: input.contactId,
3458
+ contactName: input.contactName
3459
+ });
3148
3460
  return {
3149
3461
  id: order.id,
3150
3462
  title: input.title,
@@ -3216,7 +3528,46 @@ function createSupabaseCrmProvider(options) {
3216
3528
  }
3217
3529
  }
3218
3530
  }
3219
- return await provider.getDealById(dealId);
3531
+ const moved = await provider.getDealById(dealId);
3532
+ if (stageRow) {
3533
+ await logEvent({
3534
+ activityType: stageRow.is_won ? "deal_won" : stageRow.is_lost ? "deal_lost" : "stage_changed",
3535
+ title: moved.title || "Deal",
3536
+ description: stageRow.name,
3537
+ dealId,
3538
+ contactName: moved.contactName
3539
+ });
3540
+ }
3541
+ return moved;
3542
+ },
3543
+ async archiveDeal(dealId) {
3544
+ const { core } = getClients();
3545
+ const deal = await provider.getDealById(dealId);
3546
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", dealId);
3547
+ if (error) throw new Error(error.message);
3548
+ await logEvent({
3549
+ activityType: "deal_archived",
3550
+ title: deal?.title || "Deal",
3551
+ dealId,
3552
+ contactName: deal?.contactName
3553
+ });
3554
+ },
3555
+ async archiveLead(leadId) {
3556
+ const { core } = getClients();
3557
+ const lead = await provider.getLeadById(leadId);
3558
+ const { error } = await core.from("people").update({ is_active: false }).eq("id", leadId);
3559
+ if (error) throw new Error(error.message);
3560
+ try {
3561
+ const deal = await provider.getDealByLeadId(leadId);
3562
+ if (deal && deal.status === "open") await provider.archiveDeal(deal.id);
3563
+ } catch {
3564
+ }
3565
+ await logEvent({
3566
+ activityType: "lead_archived",
3567
+ title: lead?.name ?? "Lead",
3568
+ leadId,
3569
+ contactName: lead?.name
3570
+ });
3220
3571
  },
3221
3572
  // --- Activities (public.plg_crm_activities) ---
3222
3573
  async getActivities(query) {
@@ -3256,6 +3607,14 @@ function createSupabaseCrmProvider(options) {
3256
3607
  if (error) throw new Error(error.message);
3257
3608
  return snakeToCamel(data);
3258
3609
  },
3610
+ async getActivityTypes() {
3611
+ const { pub } = getClients();
3612
+ const tenantId = getTenantId();
3613
+ if (!tenantId) return [];
3614
+ await ensureActivityTypes(tenantId);
3615
+ const { data } = await pub.from(T.activityTypes).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3616
+ return (data ?? []).map((r) => snakeToCamel(r));
3617
+ },
3259
3618
  // --- Quotes (public.orders kind='quote' + order_items) ---
3260
3619
  async getQuotes(query) {
3261
3620
  const { core } = getClients();
@@ -3263,6 +3622,8 @@ function createSupabaseCrmProvider(options) {
3263
3622
  if (query.status) {
3264
3623
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
3265
3624
  qb = qb.in("status", statuses);
3625
+ } else {
3626
+ qb = qb.neq("status", "archived");
3266
3627
  }
3267
3628
  if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`);
3268
3629
  const page = query.page ?? 1;
@@ -3365,6 +3726,18 @@ function createSupabaseCrmProvider(options) {
3365
3726
  );
3366
3727
  if (itemsError) throw new Error(itemsError.message);
3367
3728
  }
3729
+ if (input.dealId && totalAmount > 0) {
3730
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
3731
+ }
3732
+ await logEvent({
3733
+ activityType: "quote_created",
3734
+ title: order.reference_number ?? "Quote",
3735
+ description: input.contactName,
3736
+ dealId: input.dealId,
3737
+ leadId: input.leadId,
3738
+ contactId: input.contactId,
3739
+ contactName: input.contactName
3740
+ });
3368
3741
  return {
3369
3742
  id: order.id,
3370
3743
  quoteNumber: order.reference_number,
@@ -3408,6 +3781,9 @@ function createSupabaseCrmProvider(options) {
3408
3781
  );
3409
3782
  if (itemsError) throw new Error(itemsError.message);
3410
3783
  }
3784
+ if (input.dealId && totalAmount > 0) {
3785
+ await core.from("orders").update({ total: totalAmount }).eq("id", input.dealId);
3786
+ }
3411
3787
  return await provider.getQuoteById(id);
3412
3788
  },
3413
3789
  async sendQuote(id) {
@@ -3428,7 +3804,16 @@ function createSupabaseCrmProvider(options) {
3428
3804
  }
3429
3805
  } catch {
3430
3806
  }
3431
- return await provider.getQuoteById(id);
3807
+ const sent = await provider.getQuoteById(id);
3808
+ await logEvent({
3809
+ activityType: "quote_sent",
3810
+ title: sent.quoteNumber ?? "Quote",
3811
+ description: sent.contactName,
3812
+ dealId: sent.dealId,
3813
+ leadId: sent.leadId,
3814
+ contactName: sent.contactName
3815
+ });
3816
+ return sent;
3432
3817
  },
3433
3818
  async approveQuote(id) {
3434
3819
  const { core, pub } = getClients();
@@ -3472,7 +3857,16 @@ function createSupabaseCrmProvider(options) {
3472
3857
  }
3473
3858
  }
3474
3859
  }
3475
- return await provider.getQuoteById(id);
3860
+ const approved = await provider.getQuoteById(id);
3861
+ await logEvent({
3862
+ activityType: "quote_approved",
3863
+ title: approved.quoteNumber ?? "Quote",
3864
+ description: approved.contactName,
3865
+ dealId: approved.dealId,
3866
+ leadId: approved.leadId,
3867
+ contactName: approved.contactName
3868
+ });
3869
+ return approved;
3476
3870
  },
3477
3871
  async rejectQuote(id, reason) {
3478
3872
  const { core } = getClients();
@@ -3492,6 +3886,16 @@ function createSupabaseCrmProvider(options) {
3492
3886
  if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id);
3493
3887
  }
3494
3888
  }
3889
+ if (quote) {
3890
+ await logEvent({
3891
+ activityType: "quote_rejected",
3892
+ title: quote.quoteNumber ?? "Quote",
3893
+ description: reason,
3894
+ dealId: quote.dealId,
3895
+ leadId: quote.leadId,
3896
+ contactName: quote.contactName
3897
+ });
3898
+ }
3495
3899
  return quote;
3496
3900
  },
3497
3901
  async expireQuote(id) {
@@ -3499,6 +3903,20 @@ function createSupabaseCrmProvider(options) {
3499
3903
  await core.from("orders").update({ status: "expired" }).eq("id", id);
3500
3904
  return await provider.getQuoteById(id);
3501
3905
  },
3906
+ async archiveQuote(id) {
3907
+ const { core } = getClients();
3908
+ const quote = await provider.getQuoteById(id);
3909
+ const { error } = await core.from("orders").update({ status: "archived" }).eq("id", id);
3910
+ if (error) throw new Error(error.message);
3911
+ await logEvent({
3912
+ activityType: "quote_archived",
3913
+ title: quote?.quoteNumber ?? "Quote",
3914
+ description: quote?.contactName,
3915
+ dealId: quote?.dealId,
3916
+ leadId: quote?.leadId,
3917
+ contactName: quote?.contactName
3918
+ });
3919
+ },
3502
3920
  // Cross-entity lookups
3503
3921
  async getQuotesByDealId(dealId) {
3504
3922
  const { core } = getClients();
@@ -3574,6 +3992,7 @@ function createSupabaseCrmProvider(options) {
3574
3992
  return provider;
3575
3993
  }
3576
3994
  function createCrmStore(provider) {
3995
+ let lastActivitiesQuery = {};
3577
3996
  return vanilla.createStore((set, get) => ({
3578
3997
  pipelines: [],
3579
3998
  stages: [],
@@ -3635,12 +4054,20 @@ function createCrmStore(provider) {
3635
4054
  });
3636
4055
  },
3637
4056
  async fetchActivities(query) {
4057
+ lastActivitiesQuery = query;
3638
4058
  return saas.dedup("crm:activities:" + JSON.stringify(query), async () => {
3639
4059
  set({ activitiesLoading: true });
3640
4060
  const result = await provider.getActivities(query);
3641
4061
  set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false });
3642
4062
  });
3643
4063
  },
4064
+ async refreshActivities() {
4065
+ try {
4066
+ const result = await provider.getActivities(lastActivitiesQuery);
4067
+ set({ activities: result.data, activitiesTotal: result.total });
4068
+ } catch {
4069
+ }
4070
+ },
3644
4071
  async fetchQuotes(query) {
3645
4072
  return saas.dedup("crm:quotes:" + JSON.stringify(query), async () => {
3646
4073
  set({ quotesLoading: true });
@@ -3674,6 +4101,7 @@ function createCrmStore(provider) {
3674
4101
  }
3675
4102
  const summary = await provider.getSummary();
3676
4103
  set({ summary });
4104
+ void get().refreshActivities();
3677
4105
  ui.toast.success("Lead captured");
3678
4106
  return lead;
3679
4107
  } catch (err) {
@@ -3686,6 +4114,7 @@ function createCrmStore(provider) {
3686
4114
  const deal = await provider.createDeal(input);
3687
4115
  const [summary] = await Promise.all([provider.getSummary()]);
3688
4116
  set({ summary });
4117
+ void get().refreshActivities();
3689
4118
  ui.toast.success("Deal created");
3690
4119
  return deal;
3691
4120
  } catch (err) {
@@ -3776,6 +4205,7 @@ function createCrmStore(provider) {
3776
4205
  } catch {
3777
4206
  }
3778
4207
  }
4208
+ void get().refreshActivities();
3779
4209
  ui.toast.success("Quote created");
3780
4210
  return quote;
3781
4211
  } catch (err) {
@@ -3798,6 +4228,7 @@ function createCrmStore(provider) {
3798
4228
  try {
3799
4229
  const quote = await provider.sendQuote(id);
3800
4230
  set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
4231
+ void get().refreshActivities();
3801
4232
  ui.toast.success("Quote sent");
3802
4233
  return quote;
3803
4234
  } catch (err) {
@@ -3818,6 +4249,7 @@ function createCrmStore(provider) {
3818
4249
  ]);
3819
4250
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3820
4251
  }
4252
+ void get().refreshActivities();
3821
4253
  ui.toast.success("Quote approved \u2014 invoice created");
3822
4254
  return quote;
3823
4255
  } catch (err) {
@@ -3838,6 +4270,7 @@ function createCrmStore(provider) {
3838
4270
  ]);
3839
4271
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3840
4272
  }
4273
+ void get().refreshActivities();
3841
4274
  ui.toast.success("Quote rejected");
3842
4275
  return quote;
3843
4276
  } catch (err) {
@@ -3868,6 +4301,61 @@ function createCrmStore(provider) {
3868
4301
  ]);
3869
4302
  set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3870
4303
  }
4304
+ void get().refreshActivities();
4305
+ },
4306
+ async archiveDeal(dealId) {
4307
+ try {
4308
+ await provider.archiveDeal(dealId);
4309
+ const { pipelines } = get();
4310
+ if (pipelines.length > 0) {
4311
+ const [dealsByStage, summary] = await Promise.all([
4312
+ provider.getDealsByStage(pipelines[0].id),
4313
+ provider.getSummary()
4314
+ ]);
4315
+ set({ dealsByStage, summary });
4316
+ }
4317
+ void get().refreshActivities();
4318
+ ui.toast.success("Deal archived");
4319
+ } catch (err) {
4320
+ ui.toast.error("Failed to archive deal", { description: err?.message });
4321
+ throw err;
4322
+ }
4323
+ },
4324
+ async archiveLead(leadId) {
4325
+ try {
4326
+ await provider.archiveLead(leadId);
4327
+ const { pipelines } = get();
4328
+ const [leadsResult, summary, dealsByStage] = await Promise.all([
4329
+ provider.getLeads({}),
4330
+ provider.getSummary(),
4331
+ pipelines.length > 0 ? provider.getDealsByStage(pipelines[0].id) : Promise.resolve(null)
4332
+ ]);
4333
+ set({
4334
+ leads: leadsResult.data,
4335
+ leadsTotal: leadsResult.total,
4336
+ summary,
4337
+ ...dealsByStage ? { dealsByStage } : {}
4338
+ });
4339
+ void get().refreshActivities();
4340
+ ui.toast.success("Lead archived");
4341
+ } catch (err) {
4342
+ ui.toast.error("Failed to archive lead", { description: err?.message });
4343
+ throw err;
4344
+ }
4345
+ },
4346
+ async archiveQuote(quoteId) {
4347
+ try {
4348
+ await provider.archiveQuote(quoteId);
4349
+ set((state) => ({
4350
+ quotes: state.quotes.filter((q) => q.id !== quoteId),
4351
+ quotesTotal: Math.max(0, state.quotesTotal - 1)
4352
+ }));
4353
+ void get().refreshActivities();
4354
+ ui.toast.success("Quote archived");
4355
+ } catch (err) {
4356
+ ui.toast.error("Failed to archive quote", { description: err?.message });
4357
+ throw err;
4358
+ }
3871
4359
  }
3872
4360
  }));
3873
4361
  }
@@ -3930,10 +4418,19 @@ var activityTypeEntity = {
3930
4418
  defaultSort: "name",
3931
4419
  fields: [
3932
4420
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3933
- { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
4421
+ { key: "icon", label: "Icon", type: "text", showInTable: true },
4422
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
3934
4423
  ],
3935
4424
  data: { table: T.activityTypes, tenantScoped: true }
3936
4425
  };
4426
+ var DEFAULT_ACTIVITY_TYPES = [
4427
+ { value: "call", label: "Call", icon: "Phone" },
4428
+ { value: "email", label: "Email", icon: "Mail" },
4429
+ { value: "meeting", label: "Meeting", icon: "Users" },
4430
+ { value: "note", label: "Note", icon: "FileText" },
4431
+ { value: "task", label: "Task", icon: "CheckSquare" },
4432
+ { value: "whatsapp", label: "WhatsApp", icon: "MessageCircle" }
4433
+ ];
3937
4434
  var crmRegistries = [
3938
4435
  {
3939
4436
  id: "stages",
@@ -3983,17 +4480,25 @@ var crmRegistries = [
3983
4480
  icon: "MessageCircle",
3984
4481
  description: "Types of activities and interactions",
3985
4482
  display: "table",
3986
- readOnly: true,
4483
+ // Tenant-editable (the provider lazily seeds the app's set per tenant);
4484
+ // system timeline events (lead_created, stage_changed…) are product-defined
4485
+ // and never appear here.
3987
4486
  seedData: [
3988
- { id: "at-call", name: "Call", isActive: true },
3989
- { id: "at-email", name: "Email", isActive: true },
3990
- { id: "at-meeting", name: "Meeting", isActive: true },
3991
- { id: "at-note", name: "Note", isActive: true },
3992
- { id: "at-task", name: "Task", isActive: true },
3993
- { id: "at-whatsapp", name: "WhatsApp", isActive: true }
4487
+ ...DEFAULT_ACTIVITY_TYPES.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
3994
4488
  ]
3995
4489
  }
3996
4490
  ];
4491
+ function buildCrmRegistries(activityTypes) {
4492
+ if (!activityTypes?.length) return crmRegistries;
4493
+ return crmRegistries.map(
4494
+ (registry) => registry.id === "activity-types" ? {
4495
+ ...registry,
4496
+ seedData: [
4497
+ ...activityTypes.map((t2) => ({ id: `at-${t2.value}`, name: t2.label, icon: t2.icon, isActive: true }))
4498
+ ]
4499
+ } : registry
4500
+ );
4501
+ }
3997
4502
 
3998
4503
  // src/locales/en.ts
3999
4504
  var en = {
@@ -4007,6 +4512,7 @@ var en = {
4007
4512
  "crm.activities.overdueLabel": "Overdue",
4008
4513
  "crm.activities.pending": "pending",
4009
4514
  "crm.activities.pendingFilter": "Pending",
4515
+ "crm.activities.systemEvents": "Events",
4010
4516
  "crm.activities.title": "Activities",
4011
4517
  "crm.dashboard.activeDeals": "{{count}} active deals",
4012
4518
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -4053,6 +4559,7 @@ var en = {
4053
4559
  "crm.dealSidebar.value": "Value",
4054
4560
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
4055
4561
  "crm.leadDetail.assignedTo": "Assigned to",
4562
+ "crm.leadDetail.archive": "Archive",
4056
4563
  "crm.leadDetail.backToList": "Back to list",
4057
4564
  "crm.leadDetail.formAnswers": "Form answers",
4058
4565
  "crm.leadDetail.company": "Company",
@@ -4112,6 +4619,7 @@ var en = {
4112
4619
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
4113
4620
  "crm.page.settingsTitle": "Sales & CRM Settings",
4114
4621
  "crm.pipeline.dropHere": "Drop here",
4622
+ "crm.pipeline.archive": "Archive",
4115
4623
  "crm.pipeline.moveFailed": "Failed to move deal",
4116
4624
  "crm.pipeline.movedTo": "Moved to {{stage}}",
4117
4625
  "crm.pipeline.noDeals": "No deals",
@@ -4190,6 +4698,7 @@ var en = {
4190
4698
  "crm.quoteForm.unitPrice": "Unit Price",
4191
4699
  "crm.quoteForm.validUntil": "Valid Until",
4192
4700
  "crm.quotes.amount": "Amount",
4701
+ "crm.quotes.archive": "Archive",
4193
4702
  "crm.quotes.contact": "Contact",
4194
4703
  "crm.quotes.createFirst": "Create your first quote",
4195
4704
  "crm.quotes.date": "Date",
@@ -4301,6 +4810,7 @@ var ptBR = {
4301
4810
  "crm.activities.overdueLabel": "Atrasada",
4302
4811
  "crm.activities.pending": "pendente",
4303
4812
  "crm.activities.pendingFilter": "Pendentes",
4813
+ "crm.activities.systemEvents": "Eventos",
4304
4814
  "crm.activities.title": "Atividades",
4305
4815
  "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
4306
4816
  "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
@@ -4347,6 +4857,7 @@ var ptBR = {
4347
4857
  "crm.dealSidebar.value": "Valor",
4348
4858
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
4349
4859
  "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
4860
+ "crm.leadDetail.archive": "Arquivar",
4350
4861
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
4351
4862
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
4352
4863
  "crm.leadDetail.company": "Empresa",
@@ -4402,10 +4913,11 @@ var ptBR = {
4402
4913
  "crm.page.newLead": "Novo Lead",
4403
4914
  "crm.page.newLeadDesc": "Capturar um novo lead",
4404
4915
  "crm.page.newQuote": "Novo Or\xE7amento",
4405
- "crm.page.newQuoteDesc": "Enviar uma proposta",
4916
+ "crm.page.newQuoteDesc": "Enviar um or\xE7amento",
4406
4917
  "crm.page.settingsSubtitle": "Configure pipeline, gest\xE3o de leads e cadastros",
4407
4918
  "crm.page.settingsTitle": "Configura\xE7\xF5es de Vendas e CRM",
4408
4919
  "crm.pipeline.dropHere": "Solte aqui",
4920
+ "crm.pipeline.archive": "Arquivar",
4409
4921
  "crm.pipeline.moveFailed": "Falha ao mover neg\xF3cio",
4410
4922
  "crm.pipeline.movedTo": "Movido para {{stage}}",
4411
4923
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
@@ -4451,12 +4963,12 @@ var ptBR = {
4451
4963
  "crm.quoteForm.description": "Descri\xE7\xE3o",
4452
4964
  "crm.quoteForm.discount": "Desconto",
4453
4965
  "crm.quoteForm.done": "Conclu\xEDdo",
4454
- "crm.quoteForm.editSubtitle": "Atualizar esta proposta",
4966
+ "crm.quoteForm.editSubtitle": "Atualizar este or\xE7amento",
4455
4967
  "crm.quoteForm.editTitle": "Editar Or\xE7amento",
4456
4968
  "crm.quoteForm.itemCount": "{{count}} itens",
4457
4969
  "crm.quoteForm.itemDescriptionPlaceholder": "Descri\xE7\xE3o do item",
4458
4970
  "crm.quoteForm.loading": "Carregando...",
4459
- "crm.quoteForm.newSubtitle": "Criar uma proposta para seu cliente",
4971
+ "crm.quoteForm.newSubtitle": "Criar um or\xE7amento para seu cliente",
4460
4972
  "crm.quoteForm.newTitle": "Novo Or\xE7amento",
4461
4973
  "crm.quoteForm.noDescription": "Sem descri\xE7\xE3o",
4462
4974
  "crm.quoteForm.noItems": "Nenhum item adicionado",
@@ -4484,6 +4996,7 @@ var ptBR = {
4484
4996
  "crm.quoteForm.unitPrice": "Pre\xE7o Unit\xE1rio",
4485
4997
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
4486
4998
  "crm.quotes.amount": "Valor",
4999
+ "crm.quotes.archive": "Arquivar",
4487
5000
  "crm.quotes.contact": "Contato",
4488
5001
  "crm.quotes.createFirst": "Crie seu primeiro or\xE7amento",
4489
5002
  "crm.quotes.date": "Data",
@@ -4497,7 +5010,7 @@ var ptBR = {
4497
5010
  "crm.quickActions.newDeal": "Novo Neg\xF3cio",
4498
5011
  "crm.quickActions.newDealDesc": "Criar um neg\xF3cio no pipeline",
4499
5012
  "crm.quickActions.newQuote": "Novo Or\xE7amento",
4500
- "crm.quickActions.newQuoteDesc": "Enviar uma proposta",
5013
+ "crm.quickActions.newQuoteDesc": "Enviar um or\xE7amento",
4501
5014
  "crm.quickActions.logActivity": "Registrar Atividade",
4502
5015
  "crm.quickActions.logActivityDesc": "Registrar liga\xE7\xE3o, e-mail ou nota",
4503
5016
  "crm.settingsPage.title": "Configura\xE7\xF5es de Vendas e CRM",
@@ -4534,7 +5047,7 @@ var ptBR = {
4534
5047
  "crm.settings.weightedPipeline": "Valor ponderado do pipeline",
4535
5048
  "crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do est\xE1gio",
4536
5049
  "crm.settings.quotes": "Or\xE7amentos",
4537
- "crm.settings.quotesDesc": "Comportamento de or\xE7amentos e propostas",
5050
+ "crm.settings.quotesDesc": "Comportamento de or\xE7amentos",
4538
5051
  "crm.settings.autoNumberQuotes": "Numera\xE7\xE3o autom\xE1tica de or\xE7amentos",
4539
5052
  "crm.settings.autoNumberQuotesDesc": "Gerar automaticamente n\xFAmeros sequenciais de or\xE7amentos",
4540
5053
  "crm.settings.defaultValidity": "Validade padr\xE3o (30 dias)",
@@ -4627,12 +5140,14 @@ function resolveConfig(options) {
4627
5140
  function createCrmPlugin(options) {
4628
5141
  const config = resolveConfig(options);
4629
5142
  core.registerTranslations(crmLocales);
5143
+ const activityTypes = options?.activityTypes ?? DEFAULT_ACTIVITY_TYPES;
5144
+ const crmRegistries2 = buildCrmRegistries(activityTypes);
4630
5145
  const provider = options?.dataProvider ?? core.createSafeDataProvider(
4631
- () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
4632
- () => createMockCrmProvider()
5146
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion, activityTypes }),
5147
+ () => createMockCrmProvider({ activityTypes })
4633
5148
  );
4634
5149
  const store = createCrmStore(provider);
4635
- const PageComponent = () => React14__default.default.createElement(CrmPage, { config, provider, store, registries: crmRegistries });
5150
+ const PageComponent = () => React14__default.default.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
4636
5151
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
4637
5152
  return {
4638
5153
  id: "crm",
@@ -4661,6 +5176,86 @@ function createCrmPlugin(options) {
4661
5176
  { key: "deals", label: "Deals", table: "orders", kindFilter: "deal" },
4662
5177
  { key: "quotes", label: "Quotes", table: "orders", kindFilter: "quote" }
4663
5178
  ],
5179
+ // Read-models for the agent's data primitives (searchRecords/queryData).
5180
+ // Without these the assistant cannot see leads/deals/activities at all and
5181
+ // guesses wrong entities ("quem tá aguardando contato?" → invented filter
5182
+ // on Cliente). Keys are stable ASCII; fields are camelCase output shape.
5183
+ queryEntities: [
5184
+ {
5185
+ key: "crm:leads",
5186
+ writable: false,
5187
+ entity: {
5188
+ name: "Lead",
5189
+ namePlural: "Leads",
5190
+ icon: "UserPlus",
5191
+ permission: { feature: "crm.leads", action: "read" },
5192
+ fields: [
5193
+ { key: "name", label: "Name", type: "text", searchable: true },
5194
+ { key: "email", label: "Email", type: "text", searchable: true },
5195
+ { key: "phone", label: "Phone", type: "text", searchable: true },
5196
+ { key: "company", label: "Company", type: "text" },
5197
+ { key: "status", label: "Status (new=awaiting first contact, contacted, qualified, converted, lost)", type: "text" },
5198
+ { key: "sourceName", label: "Source", type: "text" },
5199
+ { key: "createdAt", label: "Created at", type: "text" }
5200
+ ],
5201
+ data: {
5202
+ table: "v_leads",
5203
+ tenantScoped: true,
5204
+ searchColumns: ["name", "email", "phone"]
5205
+ }
5206
+ }
5207
+ },
5208
+ {
5209
+ key: "crm:deals",
5210
+ writable: false,
5211
+ entity: {
5212
+ name: "Deal",
5213
+ namePlural: "Deals",
5214
+ icon: "Target",
5215
+ permission: { feature: "crm.pipeline", action: "read" },
5216
+ fields: [
5217
+ { key: "title", label: "Title", type: "text", searchable: true },
5218
+ { key: "value", label: "Value", type: "number" },
5219
+ { key: "status", label: "Status (open/won/lost)", type: "text" },
5220
+ { key: "stage", label: "Pipeline stage name", type: "text" },
5221
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5222
+ { key: "probability", label: "Probability %", type: "number" },
5223
+ { key: "expectedCloseDate", label: "Expected close", type: "text" },
5224
+ { key: "createdAt", label: "Created at", type: "text" }
5225
+ ],
5226
+ data: {
5227
+ table: "v_deals",
5228
+ tenantScoped: true,
5229
+ searchColumns: ["title", "contact_name"]
5230
+ }
5231
+ }
5232
+ },
5233
+ {
5234
+ key: "crm:activities",
5235
+ writable: false,
5236
+ entity: {
5237
+ name: "CRM activity",
5238
+ namePlural: "CRM activities",
5239
+ icon: "MessageCircle",
5240
+ permission: { feature: "sales", action: "read" },
5241
+ fields: [
5242
+ { key: "activityType", label: "Type (call/email/note\u2026 or system events: lead_created, deal_won, quote_approved\u2026)", type: "text" },
5243
+ { key: "title", label: "Title", type: "text", searchable: true },
5244
+ { key: "description", label: "Description", type: "text", searchable: true },
5245
+ { key: "contactName", label: "Contact", type: "text", searchable: true },
5246
+ { key: "dueDate", label: "Due date", type: "text" },
5247
+ { key: "completedAt", label: "Completed at", type: "text" },
5248
+ { key: "assignedToName", label: "Assigned to", type: "text" },
5249
+ { key: "createdAt", label: "Created at", type: "text" }
5250
+ ],
5251
+ data: {
5252
+ table: "plg_crm_activities",
5253
+ tenantScoped: true,
5254
+ searchColumns: ["title", "contact_name", "description"]
5255
+ }
5256
+ }
5257
+ }
5258
+ ],
4664
5259
  navigation: [
4665
5260
  {
4666
5261
  section: options?.navSection ?? "main",
@@ -4724,7 +5319,7 @@ function createCrmPlugin(options) {
4724
5319
  ]
4725
5320
  }
4726
5321
  ],
4727
- registries: crmRegistries,
5322
+ registries: crmRegistries2,
4728
5323
  settings: [
4729
5324
  {
4730
5325
  id: "crm",
@@ -4738,7 +5333,7 @@ function createCrmPlugin(options) {
4738
5333
  title: "Sales & CRM",
4739
5334
  subtitle: "Pipeline, lead management, and CRM properties",
4740
5335
  generalSettings: React14__default.default.createElement(CrmGeneralSettings),
4741
- registries: crmRegistries,
5336
+ registries: crmRegistries2,
4742
5337
  hostPluginId: "crm",
4743
5338
  routeBase: "/settings/crm"
4744
5339
  })