@fayz-ai/plugin-crm 0.9.4 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import React16, { useState, useEffect, useMemo, useRef } from 'react';
2
- import { registerTranslations, registerMessageDefaults, createSafeDataProvider, getSupabaseClientOptional, usePluginRuntimeOptional, useTranslation, useActiveTenantId, getActiveTenantId, loadMessageOverrides, resolveMessages } from '@fayz-ai/core';
3
- import { createPluginContext, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, useAccessOptional, invalidateLimit, useOrganizationStore } from '@fayz-ai/admin';
4
- import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, DashboardCanvas, PageToolbar, ToolbarButton, RangeControl, Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetBody, SheetFooter, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, ConfirmDialog, SegmentedControl, normalizePhone, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
1
+ import React17, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
2
+ import { tl, registerTranslations, registerMessageDefaults, createSafeDataProvider, getSupabaseClientOptional, usePluginRuntimeOptional, useTranslation, useActiveTenantId, exportCSV, getActiveTenantId, loadMessageOverrides, resolveMessages } from '@fayz-ai/core';
3
+ import { createPluginContext, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, PageActions, usePermissionOptional, useLimitGuard, RightRailPage, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, useAccessOptional, invalidateLimit, useOrganizationStore, getRailPage } from '@fayz-ai/admin';
4
+ import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, useIsWide, SubpageHeader, PageHeaderActions, ListView, ConfirmDialog, SheetBody, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SheetFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, DashboardCanvas, PageToolbar, ToolbarButton, RangeControl, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, normalizePhone, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
5
5
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
6
- import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, MoveRight, Target, ArrowRightLeft, UserPlus, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Tag, Plus, Zap, Paperclip, ImageOff, CircleAlert, CircleDashed, Loader2, DollarSign, User } 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, Settings, Download, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Tag, Zap, Paperclip, ImageOff, CircleAlert, CircleDashed, Loader2, DollarSign, User, Building2 } from 'lucide-react';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
9
9
 
@@ -576,51 +576,22 @@ function LeadAttachments({ attachments, variant = "full" }) {
576
576
  )) })
577
577
  ] });
578
578
  }
579
-
580
- // src/lib/relative-time.ts
581
- var MINUTE = 60;
582
- var HOUR = 60 * MINUTE;
583
- var DAY = 24 * HOUR;
584
- var WEEK = 7 * DAY;
585
- var MONTH = 30 * DAY;
586
- var YEAR = 365 * DAY;
587
- var STEPS2 = [
588
- ["year", YEAR],
589
- ["month", MONTH],
590
- ["week", WEEK],
591
- ["day", DAY],
592
- ["hour", HOUR],
593
- ["minute", MINUTE]
594
- ];
595
- function formatRelativeTime(iso, locale = "pt-BR", now2 = /* @__PURE__ */ new Date()) {
596
- if (!iso) return "";
597
- const then = new Date(iso);
598
- const at = then.getTime();
599
- if (Number.isNaN(at)) return "";
600
- const elapsed = Math.round((now2.getTime() - at) / 1e3);
601
- const abs = Math.abs(elapsed);
602
- if (abs < 45) {
603
- return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(0, "second");
604
- }
605
- const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "always" });
606
- for (const [unit, seconds] of STEPS2) {
607
- if (abs >= seconds) {
608
- return rtf.format(-Math.round(elapsed / seconds), unit);
609
- }
610
- }
611
- return rtf.format(0, "second");
612
- }
613
- function formatDateTime(iso, locale = "pt-BR") {
614
- if (!iso) return "";
615
- const at = new Date(iso);
616
- if (Number.isNaN(at.getTime())) return "";
617
- return at.toLocaleString(locale, {
618
- day: "2-digit",
619
- month: "2-digit",
620
- year: "numeric",
621
- hour: "2-digit",
622
- minute: "2-digit"
623
- });
579
+ function FormAnswers({ lead }) {
580
+ const t2 = useTranslation();
581
+ const entries = answerEntries(lead?.metadata?.fields);
582
+ const attachments = leadAttachments(lead?.metadata);
583
+ if (entries.length === 0 && attachments.length === 0) return null;
584
+ const formId = lead?.metadata?.formId;
585
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
586
+ entries.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
587
+ /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: formId ? `${t2("crm.leadDetail.formAnswers")} \xB7 ${formId}` : t2("crm.leadDetail.formAnswers") }),
588
+ /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: entries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 px-4 py-2.5", children: [
589
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground shrink-0 min-w-24", children: humanizeKey(key) }),
590
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-right flex-1 break-words", children: renderFieldValue(value) ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
591
+ ] }, key)) })
592
+ ] }),
593
+ /* @__PURE__ */ jsx(LeadAttachments, { attachments, variant: "compact" })
594
+ ] });
624
595
  }
625
596
  function automationKeyFor(activityType) {
626
597
  return `crm.${activityType}`;
@@ -661,24 +632,45 @@ function describe(hits) {
661
632
  return `${parts.join(" \xB7 ")} \u2014 clique para abrir a automa\xE7\xE3o`;
662
633
  }
663
634
  function AutomationBolt({ activityType, messages, className = "" }) {
635
+ const [open, setOpen] = useState(false);
636
+ const Detail = getRailPage("automations.detail");
664
637
  const hits = messages.filter((m) => m.event.name === automationKeyFor(activityType));
665
638
  if (hits.length === 0) return null;
666
639
  const target = hits.find((m) => m.enabled) ?? hits[0];
667
640
  const active = hits.some((m) => m.enabled);
668
- return /* @__PURE__ */ jsx(
669
- "button",
670
- {
671
- type: "button",
672
- onClick: (e) => {
673
- e.stopPropagation();
674
- adminNavigateTo(`/automations/${target.event.name}/${target.channel}`);
675
- },
676
- title: describe(hits),
677
- "aria-label": describe(hits),
678
- className: `inline-flex shrink-0 items-center justify-center rounded transition-colors ${active ? "text-primary hover:text-primary/70" : "text-muted-foreground/40 hover:text-muted-foreground"} ${className}`,
679
- children: /* @__PURE__ */ jsx(Zap, { className: `h-3.5 w-3.5 ${active ? "fill-current" : ""}` })
680
- }
681
- );
641
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
642
+ /* @__PURE__ */ jsx(
643
+ "button",
644
+ {
645
+ type: "button",
646
+ onClick: (e) => {
647
+ e.stopPropagation();
648
+ if (Detail) setOpen(true);
649
+ else adminNavigateTo(`/automations/${target.event.name}/${target.channel}`);
650
+ },
651
+ title: describe(hits),
652
+ "aria-label": describe(hits),
653
+ className: `inline-flex shrink-0 items-center justify-center rounded transition-colors ${active ? "text-primary hover:text-primary/70" : "text-muted-foreground/40 hover:text-muted-foreground"} ${className}`,
654
+ children: /* @__PURE__ */ jsx(Zap, { className: `h-3.5 w-3.5 ${active ? "fill-current" : ""}` })
655
+ }
656
+ ),
657
+ open && Detail && /* @__PURE__ */ jsx(
658
+ RightRailPage,
659
+ {
660
+ title: target.event.title ?? target.event.name,
661
+ open: true,
662
+ onClose: () => setOpen(false),
663
+ width: "max-w-2xl",
664
+ children: /* @__PURE__ */ jsx("div", { className: "min-h-0 flex-1 overflow-y-auto p-4", children: /* @__PURE__ */ jsx(
665
+ Detail,
666
+ {
667
+ params: { eventKey: target.event.name, channel: target.channel },
668
+ onClose: () => setOpen(false)
669
+ }
670
+ ) })
671
+ }
672
+ )
673
+ ] });
682
674
  }
683
675
  var TYPE_ICONS = {
684
676
  call: Phone,
@@ -702,42 +694,107 @@ var TYPE_ICONS = {
702
694
  deal_archived: Archive,
703
695
  quote_archived: Archive
704
696
  };
697
+ function ActivityTimeline({ activities, loading }) {
698
+ const t2 = useTranslation();
699
+ const messages = useActivityAutomations();
700
+ if (loading) {
701
+ return /* @__PURE__ */ jsx("div", { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
702
+ /* @__PURE__ */ jsx("div", { className: "h-8 w-8 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
703
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 space-y-1.5 pt-0.5", children: [
704
+ /* @__PURE__ */ jsx("div", { className: "h-3.5 w-2/3 rounded bg-muted/40 animate-pulse" }),
705
+ /* @__PURE__ */ jsx("div", { className: "h-2.5 w-1/3 rounded bg-muted/30 animate-pulse" })
706
+ ] })
707
+ ] }, i)) });
708
+ }
709
+ if (activities.length === 0) {
710
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [
711
+ /* @__PURE__ */ jsx("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-muted/30 mb-3", children: /* @__PURE__ */ jsx(Clock, { className: "h-5 w-5 text-muted-foreground/40" }) }),
712
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.noActivities") }),
713
+ /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground/60 mt-0.5", children: t2("crm.dealSidebar.activitiesAppear") })
714
+ ] });
715
+ }
716
+ return /* @__PURE__ */ jsx("div", { className: "space-y-1", children: activities.map((a) => {
717
+ const Icon = TYPE_ICONS[a.activityType] ?? FileText;
718
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/20 transition-colors", children: [
719
+ /* @__PURE__ */ jsx("div", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-muted shrink-0", children: /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 text-muted-foreground" }) }),
720
+ /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
721
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
722
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-medium truncate", children: a.title }),
723
+ a.completedAt && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 text-success shrink-0" }),
724
+ /* @__PURE__ */ jsx(AutomationBolt, { activityType: a.activityType, messages })
725
+ ] }),
726
+ a.description && /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground mt-0.5 line-clamp-2", children: a.description }),
727
+ /* @__PURE__ */ jsxs("p", { className: "text-[10px] text-muted-foreground/50 mt-1 capitalize", children: [
728
+ a.activityType,
729
+ " \xB7 ",
730
+ new Date(a.createdAt).toLocaleDateString()
731
+ ] })
732
+ ] })
733
+ ] }, a.id);
734
+ }) });
735
+ }
736
+
737
+ // src/lib/relative-time.ts
738
+ var MINUTE = 60;
739
+ var HOUR = 60 * MINUTE;
740
+ var DAY = 24 * HOUR;
741
+ var WEEK = 7 * DAY;
742
+ var MONTH = 30 * DAY;
743
+ var YEAR = 365 * DAY;
744
+ var STEPS2 = [
745
+ ["year", YEAR],
746
+ ["month", MONTH],
747
+ ["week", WEEK],
748
+ ["day", DAY],
749
+ ["hour", HOUR],
750
+ ["minute", MINUTE]
751
+ ];
752
+ function formatRelativeTime(iso, locale = "pt-BR", now2 = /* @__PURE__ */ new Date()) {
753
+ if (!iso) return "";
754
+ const then = new Date(iso);
755
+ const at = then.getTime();
756
+ if (Number.isNaN(at)) return "";
757
+ const elapsed = Math.round((now2.getTime() - at) / 1e3);
758
+ const abs = Math.abs(elapsed);
759
+ if (abs < 45) {
760
+ return new Intl.RelativeTimeFormat(locale, { numeric: "auto" }).format(0, "second");
761
+ }
762
+ const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "always" });
763
+ for (const [unit, seconds] of STEPS2) {
764
+ if (abs >= seconds) {
765
+ return rtf.format(-Math.round(elapsed / seconds), unit);
766
+ }
767
+ }
768
+ return rtf.format(0, "second");
769
+ }
770
+ function formatDateTime(iso, locale = "pt-BR") {
771
+ if (!iso) return "";
772
+ const at = new Date(iso);
773
+ if (Number.isNaN(at.getTime())) return "";
774
+ return at.toLocaleString(locale, {
775
+ day: "2-digit",
776
+ month: "2-digit",
777
+ year: "numeric",
778
+ hour: "2-digit",
779
+ minute: "2-digit"
780
+ });
781
+ }
705
782
  function TabBar({ active, counts, onChange }) {
706
783
  const t2 = useTranslation();
707
- const label2 = (text, count, isActive) => /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
708
- text,
709
- 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 })
710
- ] });
711
- return /* @__PURE__ */ jsx("div", { className: "px-5 py-2 border-b shrink-0", children: /* @__PURE__ */ jsx(
712
- SegmentedControl,
784
+ return /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b px-5 pt-1", children: /* @__PURE__ */ jsx(
785
+ HeaderTabs,
713
786
  {
787
+ className: "-mb-px",
714
788
  value: active,
715
789
  onChange,
716
- options: [
717
- { value: "overview", label: label2(t2("crm.dealSidebar.overview"), void 0, active === "overview") },
718
- { value: "activity", label: label2(t2("crm.dealSidebar.activity"), counts.activity, active === "activity") },
719
- { value: "quotes", label: label2(t2("crm.dealSidebar.quotes"), counts.quotes, active === "quotes") }
790
+ tabs: [
791
+ { value: "overview", label: t2("crm.dealSidebar.overview") },
792
+ { value: "activity", label: t2("crm.dealSidebar.activity"), count: counts.activity || void 0 },
793
+ { value: "quotes", label: t2("crm.dealSidebar.quotes"), count: counts.quotes || void 0 }
720
794
  ]
721
795
  }
722
796
  ) });
723
797
  }
724
- function FormAnswers({ lead }) {
725
- const t2 = useTranslation();
726
- const entries = answerEntries(lead?.metadata?.fields);
727
- const attachments = leadAttachments(lead?.metadata);
728
- if (entries.length === 0 && attachments.length === 0) return null;
729
- const formId = lead?.metadata?.formId;
730
- return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
731
- entries.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
732
- /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: formId ? `${t2("crm.leadDetail.formAnswers")} \xB7 ${formId}` : t2("crm.leadDetail.formAnswers") }),
733
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: entries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 px-4 py-2.5", children: [
734
- /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground shrink-0 min-w-24", children: humanizeKey(key) }),
735
- /* @__PURE__ */ jsx("span", { className: "text-xs text-right flex-1 break-words", children: renderFieldValue(value) ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
736
- ] }, key)) })
737
- ] }),
738
- /* @__PURE__ */ jsx(LeadAttachments, { attachments, variant: "compact" })
739
- ] });
740
- }
741
798
  function OverviewTab({ deal, lead, currency }) {
742
799
  const t2 = useTranslation();
743
800
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase();
@@ -837,45 +894,6 @@ function OverviewTab({ deal, lead, currency }) {
837
894
  ] })
838
895
  ] });
839
896
  }
840
- function ActivityTab({ activities, loading }) {
841
- const t2 = useTranslation();
842
- const messages = useActivityAutomations();
843
- if (loading) {
844
- return /* @__PURE__ */ jsx("div", { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
845
- /* @__PURE__ */ jsx("div", { className: "h-8 w-8 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
846
- /* @__PURE__ */ jsxs("div", { className: "flex-1 space-y-1.5 pt-0.5", children: [
847
- /* @__PURE__ */ jsx("div", { className: "h-3.5 w-2/3 rounded bg-muted/40 animate-pulse" }),
848
- /* @__PURE__ */ jsx("div", { className: "h-2.5 w-1/3 rounded bg-muted/30 animate-pulse" })
849
- ] })
850
- ] }, i)) });
851
- }
852
- if (activities.length === 0) {
853
- return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [
854
- /* @__PURE__ */ jsx("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-muted/30 mb-3", children: /* @__PURE__ */ jsx(Clock, { className: "h-5 w-5 text-muted-foreground/40" }) }),
855
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.noActivities") }),
856
- /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground/60 mt-0.5", children: t2("crm.dealSidebar.activitiesAppear") })
857
- ] });
858
- }
859
- return /* @__PURE__ */ jsx("div", { className: "space-y-1", children: activities.map((a, i) => {
860
- const Icon = TYPE_ICONS[a.activityType] ?? FileText;
861
- return /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/20 transition-colors", children: [
862
- /* @__PURE__ */ jsx("div", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-muted shrink-0", children: /* @__PURE__ */ jsx(Icon, { className: "h-3.5 w-3.5 text-muted-foreground" }) }),
863
- /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
864
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
865
- /* @__PURE__ */ jsx("p", { className: "text-xs font-medium truncate", children: a.title }),
866
- a.completedAt && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 text-success shrink-0" }),
867
- /* @__PURE__ */ jsx(AutomationBolt, { activityType: a.activityType, messages })
868
- ] }),
869
- a.description && /* @__PURE__ */ jsx("p", { className: "text-[11px] text-muted-foreground mt-0.5 line-clamp-2", children: a.description }),
870
- /* @__PURE__ */ jsxs("p", { className: "text-[10px] text-muted-foreground/50 mt-1 capitalize", children: [
871
- a.activityType,
872
- " \xB7 ",
873
- new Date(a.createdAt).toLocaleDateString()
874
- ] })
875
- ] })
876
- ] }, a.id);
877
- }) });
878
- }
879
897
  function QuotesTab({ quotes, loading, currency, onViewQuote, onQuoteUpdated }) {
880
898
  const t2 = useTranslation();
881
899
  if (loading) {
@@ -949,66 +967,71 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
949
967
  setQuotesLoading(false);
950
968
  });
951
969
  }, [dealId, open]);
952
- return /* @__PURE__ */ jsx(Sheet, { open, onOpenChange: (v) => {
953
- if (!v) onClose();
954
- }, children: /* @__PURE__ */ jsxs(SheetContent, { width: "max-w-md", children: [
955
- /* @__PURE__ */ jsx(SheetHeader, { children: loading ? /* @__PURE__ */ jsxs("div", { className: "space-y-1.5 pr-8", children: [
956
- /* @__PURE__ */ jsx("div", { className: "h-4 w-40 rounded bg-muted/40 animate-pulse" }),
957
- /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
958
- ] }) : /* @__PURE__ */ jsxs("div", { className: "pr-8", children: [
959
- /* @__PURE__ */ jsx(SheetTitle, { children: deal?.title ?? t2("crm.dealSidebar.deal") }),
960
- deal?.contactName && /* @__PURE__ */ jsx(SheetDescription, { children: deal.contactName })
961
- ] }) }),
962
- /* @__PURE__ */ jsx(
963
- TabBar,
970
+ return (
971
+ // No header of its own: the column heads the page, with the deal's name
972
+ // centred and the way back beside it. It used to print the title twice —
973
+ // once in the sheet header and again as the first line of the overview.
974
+ /* @__PURE__ */ jsxs(
975
+ RightRailPage,
964
976
  {
965
- active: activeTab,
966
- counts: { activity: activities.length, quotes: quotes.length },
967
- onChange: setActiveTab
968
- }
969
- ),
970
- /* @__PURE__ */ jsx(SheetBody, { children: loading ? /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
971
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
972
- /* @__PURE__ */ jsx("div", { className: "h-14 w-14 rounded-2xl bg-muted/40 animate-pulse" }),
973
- /* @__PURE__ */ jsxs("div", { className: "space-y-2 flex-1", children: [
974
- /* @__PURE__ */ jsx("div", { className: "h-4 w-32 rounded bg-muted/40 animate-pulse" }),
975
- /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
976
- ] })
977
- ] }),
978
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-3", children: [
979
- /* @__PURE__ */ jsx("div", { className: "h-3 w-20 rounded bg-muted/30 animate-pulse" }),
980
- /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/40 animate-pulse" })
981
- ] }, i)) })
982
- ] }) : deal ? /* @__PURE__ */ jsxs(Fragment, { children: [
983
- activeTab === "overview" && /* @__PURE__ */ jsx(OverviewTab, { deal, lead, currency }),
984
- activeTab === "activity" && /* @__PURE__ */ jsx(ActivityTab, { activities, loading: activitiesLoading }),
985
- activeTab === "quotes" && /* @__PURE__ */ jsx(QuotesTab, { quotes, loading: quotesLoading, currency, onViewQuote: (id) => {
986
- onViewQuote?.(id);
987
- onClose();
988
- }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
989
- ] }) : /* @__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") }) }) }),
990
- deal && /* @__PURE__ */ jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
991
- t2("crm.dealSidebar.created"),
992
- " ",
993
- deal.createdAt?.slice(0, 10),
994
- deal.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${deal.updatedAt.slice(0, 10)}` : ""
995
- ] }),
996
- deal && lead && onViewLead && /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsxs(
997
- "button",
998
- {
999
- onClick: () => {
1000
- onViewLead(lead.id);
1001
- onClose();
1002
- },
1003
- className: "flex-1 inline-flex items-center justify-center gap-2 rounded-lg border px-3 py-2.5 text-xs font-medium hover:bg-muted bg-card shadow-button active:shadow-button-inset transition-colors",
977
+ title: loading ? t2("crm.dealSidebar.deal") : deal?.title ?? t2("crm.dealSidebar.deal"),
978
+ open,
979
+ onClose,
980
+ width: "max-w-md",
1004
981
  children: [
1005
- t2("crm.dealSidebar.viewLeadProfile"),
1006
- " ",
1007
- /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
982
+ /* @__PURE__ */ jsx(
983
+ TabBar,
984
+ {
985
+ active: activeTab,
986
+ counts: { activity: activities.length, quotes: quotes.length },
987
+ onChange: setActiveTab
988
+ }
989
+ ),
990
+ /* @__PURE__ */ jsx(SheetBody, { children: loading ? /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
991
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
992
+ /* @__PURE__ */ jsx("div", { className: "h-14 w-14 rounded-2xl bg-muted/40 animate-pulse" }),
993
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2 flex-1", children: [
994
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-32 rounded bg-muted/40 animate-pulse" }),
995
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
996
+ ] })
997
+ ] }),
998
+ /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-3", children: [
999
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-20 rounded bg-muted/30 animate-pulse" }),
1000
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/40 animate-pulse" })
1001
+ ] }, i)) })
1002
+ ] }) : deal ? /* @__PURE__ */ jsxs(Fragment, { children: [
1003
+ activeTab === "overview" && /* @__PURE__ */ jsx(OverviewTab, { deal, lead, currency }),
1004
+ activeTab === "activity" && /* @__PURE__ */ jsx(ActivityTimeline, { activities, loading: activitiesLoading }),
1005
+ activeTab === "quotes" && /* @__PURE__ */ jsx(QuotesTab, { quotes, loading: quotesLoading, currency, onViewQuote: (id) => {
1006
+ onViewQuote?.(id);
1007
+ onClose();
1008
+ }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
1009
+ ] }) : /* @__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") }) }) }),
1010
+ deal && /* @__PURE__ */ jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
1011
+ t2("crm.dealSidebar.created"),
1012
+ " ",
1013
+ deal.createdAt?.slice(0, 10),
1014
+ deal.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${deal.updatedAt.slice(0, 10)}` : ""
1015
+ ] }),
1016
+ deal && lead && onViewLead && /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsxs(
1017
+ "button",
1018
+ {
1019
+ onClick: () => {
1020
+ onViewLead(lead.id);
1021
+ onClose();
1022
+ },
1023
+ className: "flex-1 inline-flex items-center justify-center gap-2 rounded-lg border px-3 py-2.5 text-xs font-medium hover:bg-muted bg-card shadow-button active:shadow-button-inset transition-colors",
1024
+ children: [
1025
+ t2("crm.dealSidebar.viewLeadProfile"),
1026
+ " ",
1027
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
1028
+ ]
1029
+ }
1030
+ ) })
1008
1031
  ]
1009
1032
  }
1010
- ) })
1011
- ] }) });
1033
+ )
1034
+ );
1012
1035
  }
1013
1036
  function periodToRange(period, customFrom, customTo) {
1014
1037
  if (period === "all") return {};
@@ -1168,7 +1191,7 @@ function PipelineSkeleton() {
1168
1191
  /* @__PURE__ */ jsx("div", { className: "h-3 w-16 rounded bg-muted/40 animate-pulse" }),
1169
1192
  /* @__PURE__ */ jsx("div", { className: "h-3 w-5 rounded bg-muted/30 animate-pulse" })
1170
1193
  ] }),
1171
- /* @__PURE__ */ jsx("div", { className: "space-y-2", children: Array.from({ length: col <= 2 ? 2 : 1 }).map((_, i) => /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card shadow-sm p-3 space-y-2", children: [
1194
+ /* @__PURE__ */ jsx("div", { className: "space-y-2", children: Array.from({ length: col <= 2 ? 2 : 1 }).map((_, i) => /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card shadow-sm p-3 space-y-2", children: [
1172
1195
  /* @__PURE__ */ jsx("div", { className: "h-4 w-3/4 rounded bg-muted/40 animate-pulse" }),
1173
1196
  /* @__PURE__ */ jsx("div", { className: "h-3 w-1/2 rounded bg-muted/30 animate-pulse" }),
1174
1197
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between pt-1", children: [
@@ -1187,7 +1210,7 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
1187
1210
  onDragStart,
1188
1211
  onDragEnd,
1189
1212
  onClick,
1190
- 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"}`,
1213
+ className: `group rounded-card border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
1191
1214
  children: [
1192
1215
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
1193
1216
  /* @__PURE__ */ jsx("p", { className: "text-sm font-medium truncate", children: deal.title }),
@@ -1309,6 +1332,7 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead, onOpenS
1309
1332
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
1310
1333
  const [optimisticBoard, setOptimisticBoard] = useState(null);
1311
1334
  const t2 = useTranslation();
1335
+ const isWide = useIsWide();
1312
1336
  const [selectedDealId, setSelectedDealId] = useState(null);
1313
1337
  const dragRef = useRef(null);
1314
1338
  const savingRef = useRef(savingDealIds);
@@ -1411,6 +1435,28 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead, onOpenS
1411
1435
  }
1412
1436
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1413
1437
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.pipeline.title"), subtitle: t2("crm.pipeline.subtitle") }),
1438
+ !isWide && /* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
1439
+ PageActions,
1440
+ {
1441
+ actions: [
1442
+ ...onAddLead ? [{
1443
+ id: "new-deal",
1444
+ label: t2("crm.quickActions.newDeal"),
1445
+ icon: Plus,
1446
+ intent: "primary",
1447
+ creates: true,
1448
+ onSelect: onAddLead
1449
+ }] : [],
1450
+ ...onOpenSettings ? [{
1451
+ id: "pipeline-stages",
1452
+ label: t2("crm.pipeline.setupStages"),
1453
+ icon: Settings,
1454
+ intent: "utility",
1455
+ onSelect: onOpenSettings
1456
+ }] : []
1457
+ ]
1458
+ }
1459
+ ) }),
1414
1460
  /* @__PURE__ */ jsx(
1415
1461
  BoardFilters,
1416
1462
  {
@@ -1480,13 +1526,25 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead, onOpenS
1480
1526
  )
1481
1527
  ] });
1482
1528
  }
1483
- var STATUS_OPTIONS = [
1484
- { value: "new", label: "New", color: "bg-info-soft text-info-soft-foreground" },
1485
- { value: "contacted", label: "Contacted", color: "bg-magic-soft text-magic-soft-foreground" },
1486
- { value: "qualified", label: "Qualified", color: "bg-success-soft text-success-soft-foreground" },
1487
- { value: "unqualified", label: "Unqualified", color: "bg-muted text-muted-foreground" },
1488
- { value: "converted", label: "Converted", color: "bg-warning-soft text-warning-soft-foreground" }
1529
+ var LEAD_STATUS_OPTIONS = [
1530
+ { value: "new", labelKey: "crm.leads.statusNew", color: "bg-info-soft text-info-soft-foreground" },
1531
+ { value: "contacted", labelKey: "crm.leads.statusContacted", color: "bg-magic-soft text-magic-soft-foreground" },
1532
+ { value: "qualified", labelKey: "crm.leads.statusQualified", color: "bg-success-soft text-success-soft-foreground" },
1533
+ { value: "unqualified", labelKey: "crm.leads.statusUnqualified", color: "bg-muted text-muted-foreground" },
1534
+ { value: "converted", labelKey: "crm.leads.statusConverted", color: "bg-warning-soft text-warning-soft-foreground" },
1535
+ { value: "lost", labelKey: "crm.leads.statusLost", color: "bg-destructive-soft text-destructive-soft-foreground" }
1489
1536
  ];
1537
+ function LeadStatusBadge({ status, className }) {
1538
+ const t2 = useTranslation();
1539
+ const opt = LEAD_STATUS_OPTIONS.find((o) => o.value === status);
1540
+ return /* @__PURE__ */ jsx(
1541
+ "span",
1542
+ {
1543
+ className: `inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${opt?.color ?? "bg-muted text-muted-foreground"} ${className ?? ""}`,
1544
+ children: opt ? t2(opt.labelKey) : status
1545
+ }
1546
+ );
1547
+ }
1490
1548
  var columns = [
1491
1549
  { accessorKey: "name", header: "Name", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: getValue() }) },
1492
1550
  {
@@ -1502,11 +1560,7 @@ var columns = [
1502
1560
  {
1503
1561
  accessorKey: "status",
1504
1562
  header: "Status",
1505
- cell: ({ getValue }) => {
1506
- const status = getValue();
1507
- const opt = STATUS_OPTIONS.find((o) => o.value === status);
1508
- return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${opt?.color ?? "bg-muted text-muted-foreground"}`, children: opt?.label ?? status });
1509
- }
1563
+ cell: ({ getValue }) => /* @__PURE__ */ jsx(LeadStatusBadge, { status: getValue() })
1510
1564
  },
1511
1565
  {
1512
1566
  // When the lead came in. The list is already sorted by it (provider orders
@@ -1527,17 +1581,123 @@ var columns = [
1527
1581
  }
1528
1582
  }
1529
1583
  ];
1584
+ function formAnswerColumns(leads) {
1585
+ const keys = [];
1586
+ for (const lead of leads) {
1587
+ for (const [key] of answerEntries(lead.metadata?.fields)) {
1588
+ if (!keys.includes(key)) keys.push(key);
1589
+ }
1590
+ }
1591
+ return keys.map((key) => ({
1592
+ key: `field:${key}`,
1593
+ label: humanizeKey(key),
1594
+ format: (_value, row) => {
1595
+ const fields = row.metadata?.fields;
1596
+ const value = fields?.[key];
1597
+ if (value === null || value === void 0 || value === "") return "";
1598
+ if (Array.isArray(value)) return value.join(", ");
1599
+ if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
1600
+ if (typeof value === "object") return JSON.stringify(value);
1601
+ return String(value);
1602
+ }
1603
+ }));
1604
+ }
1530
1605
  function LeadListView({ onNew, onEdit }) {
1531
1606
  const t2 = useTranslation();
1607
+ const can = usePermissionOptional();
1608
+ const provider = useCrmProvider();
1532
1609
  const leads = useCrmStore((s) => s.leads);
1533
1610
  const leadsLoading = useCrmStore((s) => s.leadsLoading);
1534
1611
  const fetchLeads = useCrmStore((s) => s.fetchLeads);
1612
+ const updateLead = useCrmStore((s) => s.updateLead);
1613
+ const refreshLeads = useCrmStore((s) => s.refreshLeads);
1535
1614
  const [search, setSearch] = useState("");
1536
1615
  const [statusFilter, setStatusFilter] = useState([]);
1616
+ const [archiveTarget, setArchiveTarget] = useState(null);
1617
+ const [bulkBusy, setBulkBusy] = useState(false);
1537
1618
  useEffect(() => {
1538
1619
  fetchLeads({ status: statusFilter.length > 0 ? statusFilter : void 0, search: search || void 0 });
1539
1620
  }, [statusFilter, search]);
1540
- const tags = useMemo(() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: o.label })), []);
1621
+ const tags = useMemo(() => LEAD_STATUS_OPTIONS.map((o) => ({ value: o.value, label: t2(o.labelKey) })), [t2]);
1622
+ const runBulk = useCallback(async (rows, write, labels) => {
1623
+ setBulkBusy(true);
1624
+ let done = 0;
1625
+ let failed = 0;
1626
+ for (const lead of rows) {
1627
+ try {
1628
+ await write(lead);
1629
+ done++;
1630
+ } catch (err) {
1631
+ failed++;
1632
+ console.warn("[crm] bulk lead write failed", lead.id, err);
1633
+ }
1634
+ }
1635
+ setBulkBusy(false);
1636
+ await refreshLeads();
1637
+ if (done > 0) toast.success(t2(labels.done, { count: String(done) }));
1638
+ if (failed > 0) toast.error(t2(labels.failed, { count: String(failed) }));
1639
+ }, [refreshLeads, t2]);
1640
+ const bulkActions = useMemo(() => {
1641
+ if (!can("sales", "edit")) return void 0;
1642
+ const statusActions = LEAD_STATUS_OPTIONS.filter((o) => o.value !== "converted" && o.value !== "lost").map((opt) => ({
1643
+ id: `status-${opt.value}`,
1644
+ label: t2("crm.leads.bulkSetStatus", { status: t2(opt.labelKey) }),
1645
+ // Os dois movimentos do dia a dia ficam à mão; o resto no menu, senão a
1646
+ // barra vira uma fileira de cinco botões quase iguais.
1647
+ overflow: opt.value !== "contacted" && opt.value !== "qualified",
1648
+ disabled: bulkBusy,
1649
+ onSelect: (rows) => {
1650
+ const targets = rows.filter((lead) => lead.status !== opt.value);
1651
+ if (targets.length === 0) {
1652
+ toast.error(t2("crm.leads.bulkStatusNone"));
1653
+ return;
1654
+ }
1655
+ void runBulk(targets, (lead) => updateLead(lead.id, { status: opt.value }), {
1656
+ done: "crm.leads.bulkStatusDone",
1657
+ failed: "crm.leads.bulkStatusFailed"
1658
+ });
1659
+ }
1660
+ }));
1661
+ return [
1662
+ ...statusActions,
1663
+ ...can("sales", "delete") ? [{
1664
+ id: "archive",
1665
+ label: t2("crm.leads.bulkArchive"),
1666
+ icon: Archive,
1667
+ destructive: true,
1668
+ overflow: true,
1669
+ disabled: bulkBusy,
1670
+ onSelect: (rows) => setArchiveTarget(rows)
1671
+ }] : []
1672
+ ];
1673
+ }, [can, bulkBusy, runBulk, updateLead, t2]);
1674
+ const exportRows = useCallback(() => {
1675
+ exportCSV(
1676
+ [
1677
+ { key: "createdAt", label: t2("crm.leads.receivedCol"), format: (v) => {
1678
+ const at = v ? new Date(String(v)) : null;
1679
+ return at && !Number.isNaN(at.getTime()) ? at.toLocaleString() : "";
1680
+ } },
1681
+ { key: "name", label: t2("crm.leads.name") },
1682
+ { key: "email", label: t2("crm.leadForm.email") },
1683
+ { key: "phone", label: t2("crm.leadForm.phone") },
1684
+ { key: "company", label: t2("crm.leadForm.company") },
1685
+ { key: "sourceName", label: t2("crm.leads.source") },
1686
+ { key: "status", label: t2("crm.leads.statusCol"), format: (v) => {
1687
+ const opt = LEAD_STATUS_OPTIONS.find((o) => o.value === v);
1688
+ return opt ? t2(opt.labelKey) : String(v ?? "");
1689
+ } },
1690
+ { key: "notes", label: t2("crm.leadDetail.notes") },
1691
+ // O que a landing page perguntou vira uma coluna POR PERGUNTA, com as
1692
+ // chaves descobertas nas linhas — cada campanha pergunta outra coisa, e
1693
+ // declarar as colunas aqui tornaria o próximo formulário invisível.
1694
+ ...formAnswerColumns(leads)
1695
+ ],
1696
+ leads,
1697
+ "leads"
1698
+ );
1699
+ toast.success(t2("crud.export.toastSuccess", { count: String(leads.length) }));
1700
+ }, [leads, t2]);
1541
1701
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1542
1702
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
1543
1703
  /* @__PURE__ */ jsx(
@@ -1555,12 +1715,36 @@ function LeadListView({ onNew, onEdit }) {
1555
1715
  onTagChange: (v) => setStatusFilter(v ? [v] : []),
1556
1716
  newLabel: t2("crm.leads.newLead"),
1557
1717
  onNew,
1718
+ onExport: leads.length > 0 ? exportRows : void 0,
1719
+ exportLabel: t2("crud.export.action"),
1720
+ bulkActions,
1558
1721
  onRowClick: (row) => onEdit?.(row.id),
1559
1722
  emptyIcon: UserPlus,
1560
1723
  emptyMessage: t2("crm.leads.noLeads"),
1561
1724
  emptyActionLabel: onNew ? t2("crm.leads.captureFirst") : void 0,
1562
1725
  onEmptyAction: onNew
1563
1726
  }
1727
+ ),
1728
+ /* @__PURE__ */ jsx(
1729
+ ConfirmDialog,
1730
+ {
1731
+ open: archiveTarget !== null,
1732
+ variant: "destructive",
1733
+ title: t2("crm.leads.bulkArchiveTitle", { count: String(archiveTarget?.length ?? 0) }),
1734
+ description: t2("crm.leads.bulkArchiveDesc"),
1735
+ confirmLabel: t2("crm.leads.bulkArchive"),
1736
+ cancelLabel: t2("crm.leads.bulkKeep"),
1737
+ loading: bulkBusy,
1738
+ onConfirm: () => {
1739
+ const rows = archiveTarget ?? [];
1740
+ setArchiveTarget(null);
1741
+ void runBulk(rows, (lead) => provider.archiveLead(lead.id), {
1742
+ done: "crm.leads.bulkArchiveDone",
1743
+ failed: "crm.leads.bulkArchiveFailed"
1744
+ });
1745
+ },
1746
+ onCancel: () => setArchiveTarget(null)
1747
+ }
1564
1748
  )
1565
1749
  ] });
1566
1750
  }
@@ -1568,17 +1752,27 @@ function LeadFormView({ onSaved }) {
1568
1752
  const t2 = useTranslation();
1569
1753
  const createLead = useCrmStore((s) => s.createLead);
1570
1754
  const guardLeads = useLimitGuard("leads");
1571
- const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
1572
- const pipelines = useCrmStore((s) => s.pipelines);
1573
- useEffect(() => {
1574
- if (pipelines.length === 0) fetchPipelines();
1575
- }, []);
1755
+ const resolveEntryPipeline = useCrmStore((s) => s.resolveEntryPipeline);
1576
1756
  const [name, setName] = useState("");
1577
1757
  const [email, setEmail] = useState("");
1578
1758
  const [phone, setPhone] = useState("");
1579
1759
  const [company, setCompany] = useState("");
1580
1760
  const [notes, setNotes] = useState("");
1581
1761
  const [saving, setSaving] = useState(false);
1762
+ const [stages, setStages] = useState([]);
1763
+ const [stageId, setStageId] = useState("");
1764
+ useEffect(() => {
1765
+ let cancelled = false;
1766
+ void resolveEntryPipeline().then(({ stages: entry }) => {
1767
+ if (cancelled) return;
1768
+ const open = entry.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order);
1769
+ setStages(open);
1770
+ setStageId((current) => current || open[0]?.id || "");
1771
+ });
1772
+ return () => {
1773
+ cancelled = true;
1774
+ };
1775
+ }, []);
1582
1776
  async function handleSave() {
1583
1777
  if (!name.trim()) {
1584
1778
  toast.error(t2("common.formIncomplete"));
@@ -1587,7 +1781,7 @@ function LeadFormView({ onSaved }) {
1587
1781
  if (await guardLeads() === "blocked") return;
1588
1782
  setSaving(true);
1589
1783
  try {
1590
- const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0 });
1784
+ const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0, stageId: stageId || void 0 });
1591
1785
  invalidateLimit("leads");
1592
1786
  invalidateLimit("deals");
1593
1787
  onSaved?.(lead.id);
@@ -1595,45 +1789,51 @@ function LeadFormView({ onSaved }) {
1595
1789
  setSaving(false);
1596
1790
  }
1597
1791
  }
1598
- const dirty = !!(name || email || phone || company || notes);
1599
- useSaveBar({
1600
- dirty,
1601
- saving,
1602
- onSave: () => {
1603
- void handleSave();
1604
- },
1605
- onDiscard: () => onSaved?.(),
1606
- saveLabel: t2("crm.leadForm.save")
1607
- });
1608
- return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
1609
- /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leadForm.title"), subtitle: t2("crm.leadForm.subtitle"), onBack: onSaved, parentLabel: t2("crm.leads.title") }),
1610
- /* @__PURE__ */ jsxs("div", { className: "rounded-lg border bg-card shadow-sm p-5 space-y-4", children: [
1611
- /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
1612
- /* @__PURE__ */ jsxs("div", { children: [
1613
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.name") }),
1614
- /* @__PURE__ */ jsx("input", { type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: t2("crm.leadForm.namePlaceholder"), autoFocus: true, className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1615
- ] }),
1616
- /* @__PURE__ */ jsxs("div", { children: [
1617
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.company") }),
1618
- /* @__PURE__ */ jsx("input", { type: "text", value: company, onChange: (e) => setCompany(e.target.value), placeholder: t2("crm.leadForm.companyPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1619
- ] })
1620
- ] }),
1621
- /* @__PURE__ */ jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
1622
- /* @__PURE__ */ jsxs("div", { children: [
1623
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.email") }),
1624
- /* @__PURE__ */ jsx("input", { type: "email", value: email, onChange: (e) => setEmail(e.target.value), placeholder: t2("crm.leadForm.emailPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1625
- ] }),
1626
- /* @__PURE__ */ jsxs("div", { children: [
1627
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.phone") }),
1628
- /* @__PURE__ */ jsx("input", { type: "tel", value: phone, onChange: (e) => setPhone(e.target.value), placeholder: t2("crm.leadForm.phonePlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1629
- ] })
1630
- ] }),
1631
- /* @__PURE__ */ jsxs("div", { children: [
1632
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
1633
- /* @__PURE__ */ jsx("textarea", { value: notes, onChange: (e) => setNotes(e.target.value), rows: 2, placeholder: t2("crm.leadForm.notesPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" })
1634
- ] })
1635
- ] })
1636
- ] });
1792
+ return (
1793
+ // Beside the list, not instead of it: a lead is entered while looking at
1794
+ // the ones already there, and the full-page form replaced exactly that.
1795
+ /* @__PURE__ */ jsxs(
1796
+ RightRailPage,
1797
+ {
1798
+ title: t2("crm.leadForm.title"),
1799
+ open: true,
1800
+ onClose: () => onSaved?.(),
1801
+ width: "max-w-md",
1802
+ children: [
1803
+ /* @__PURE__ */ jsxs(SheetBody, { className: "space-y-4", children: [
1804
+ /* @__PURE__ */ jsxs("div", { children: [
1805
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.name") }),
1806
+ /* @__PURE__ */ jsx("input", { type: "text", value: name, onChange: (e) => setName(e.target.value), placeholder: t2("crm.leadForm.namePlaceholder"), autoFocus: true, className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1807
+ ] }),
1808
+ /* @__PURE__ */ jsxs("div", { children: [
1809
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.company") }),
1810
+ /* @__PURE__ */ jsx("input", { type: "text", value: company, onChange: (e) => setCompany(e.target.value), placeholder: t2("crm.leadForm.companyPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1811
+ ] }),
1812
+ /* @__PURE__ */ jsxs("div", { children: [
1813
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.email") }),
1814
+ /* @__PURE__ */ jsx("input", { type: "email", value: email, onChange: (e) => setEmail(e.target.value), placeholder: t2("crm.leadForm.emailPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1815
+ ] }),
1816
+ /* @__PURE__ */ jsxs("div", { children: [
1817
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.phone") }),
1818
+ /* @__PURE__ */ jsx("input", { type: "tel", value: phone, onChange: (e) => setPhone(e.target.value), placeholder: t2("crm.leadForm.phonePlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1819
+ ] }),
1820
+ /* @__PURE__ */ jsxs("div", { children: [
1821
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
1822
+ /* @__PURE__ */ jsx("textarea", { value: notes, onChange: (e) => setNotes(e.target.value), rows: 2, placeholder: t2("crm.leadForm.notesPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" })
1823
+ ] }),
1824
+ stages.length > 1 && /* @__PURE__ */ jsxs("div", { children: [
1825
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.stage") }),
1826
+ /* @__PURE__ */ jsxs(Select, { value: stageId, onValueChange: setStageId, children: [
1827
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
1828
+ /* @__PURE__ */ jsx(SelectContent, { children: stages.map((s) => /* @__PURE__ */ jsx(SelectItem, { value: s.id, children: s.name }, s.id)) })
1829
+ ] })
1830
+ ] })
1831
+ ] }),
1832
+ /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsx(Button, { className: "flex-1", onClick: () => void handleSave(), disabled: saving || !name.trim(), children: saving ? t2("common.saving") : t2("crm.leadForm.save") }) })
1833
+ ]
1834
+ }
1835
+ )
1836
+ );
1637
1837
  }
1638
1838
  var STATUS_COLORS = {
1639
1839
  draft: "bg-muted text-muted-foreground",
@@ -1715,16 +1915,37 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1715
1915
  const columns2 = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
1716
1916
  void archiveQuote(id);
1717
1917
  } : void 0);
1918
+ const exportRows = useCallback(() => {
1919
+ exportCSV(
1920
+ [
1921
+ { key: "quoteNumber", label: "#" },
1922
+ { key: "quoteDate", label: t2("crm.quotes.date") },
1923
+ { key: "contactName", label: t2("crm.quotes.contact") },
1924
+ { key: "totalAmount", label: t2("crm.quotes.amount"), format: (v) => formatCurrency(Number(v) || 0, currency) },
1925
+ { key: "status", label: t2("crm.quotes.status") },
1926
+ { key: "validUntil", label: t2("crm.quoteForm.validUntil") }
1927
+ ],
1928
+ quotes,
1929
+ "orcamentos"
1930
+ );
1931
+ toast.success(t2("crud.export.toastSuccess", { count: String(quotes.length) }));
1932
+ }, [quotes, currency, t2]);
1718
1933
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1719
1934
  /* @__PURE__ */ jsx(
1720
1935
  SubpageHeader,
1721
1936
  {
1722
1937
  title: t2("crm.quotes.title"),
1723
- actions: onNew && /* @__PURE__ */ jsxs("button", { onClick: onNew, className: "inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors", children: [
1724
- /* @__PURE__ */ jsx("span", { className: "h-3.5 w-3.5 inline-flex items-center justify-center", children: "+" }),
1725
- " ",
1726
- t2("crm.quotes.newQuote")
1727
- ] })
1938
+ actions: (onNew || quotes.length > 0) && /* @__PURE__ */ jsx(
1939
+ PageActions,
1940
+ {
1941
+ actions: [
1942
+ ...onNew ? [{ id: "new-quote", label: t2("crm.quotes.newQuote"), icon: Plus, intent: "primary", onSelect: onNew }] : [],
1943
+ // 'utility': ícone só, ao lado do primário — o mesmo lugar que o
1944
+ // exportar ocupa em toda lista de CRUD.
1945
+ ...quotes.length > 0 ? [{ id: "export", label: t2("crud.export.action"), icon: Download, intent: "utility", onSelect: exportRows }] : []
1946
+ ]
1947
+ }
1948
+ )
1728
1949
  }
1729
1950
  ),
1730
1951
  /* @__PURE__ */ jsx(
@@ -1741,7 +1962,7 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1741
1962
  "button",
1742
1963
  {
1743
1964
  onClick: onNew,
1744
- className: "mt-3 inline-flex items-center gap-1.5 rounded-lg border border-primary bg-primary px-3 py-2 text-sm font-medium text-primary-foreground shadow-button-primary transition-colors hover:bg-primary/90 active:shadow-button-inset",
1965
+ className: "mt-3 inline-flex items-center gap-1.5 rounded-button border border-primary bg-primary px-3 py-2 text-sm font-medium text-primary-foreground shadow-button-primary transition-colors hover:bg-primary/90 active:shadow-button-inset",
1745
1966
  children: t2("crm.quotes.createFirst")
1746
1967
  }
1747
1968
  )
@@ -1890,7 +2111,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1890
2111
  observations,
1891
2112
  items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
1892
2113
  };
1893
- const snapshot = React16.useRef(null);
2114
+ const snapshot = React17.useRef(null);
1894
2115
  useEffect(() => {
1895
2116
  if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
1896
2117
  }, [loadingExisting]);
@@ -1904,7 +2125,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1904
2125
  onDiscard: () => onSaved?.(),
1905
2126
  saveLabel: isEdit ? t2("crm.quoteForm.saveChanges") : t2("crm.quoteForm.saveQuote")
1906
2127
  });
1907
- if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, {});
2128
+ if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t2("crm.quotes.title"), onBack: () => onSaved?.() });
1908
2129
  const money = (v) => formatCurrency(v, currency);
1909
2130
  const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
1910
2131
  /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
@@ -2098,7 +2319,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
2098
2319
  setRejecting(false);
2099
2320
  }
2100
2321
  }
2101
- if (loading) return /* @__PURE__ */ jsx(OrderDetailSkeleton, {});
2322
+ if (loading) return /* @__PURE__ */ jsx(OrderDetailSkeleton, { parentLabel: t2("crm.quotes.title"), onBack });
2102
2323
  if (!quote) {
2103
2324
  return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
2104
2325
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.quoteDetail.title"), onBack, parentLabel: t2("crm.quotes.title") }),
@@ -2135,7 +2356,7 @@ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
2135
2356
  type: "button",
2136
2357
  onClick: () => setSendMenuOpen((p) => !p),
2137
2358
  disabled: sending,
2138
- className: "inline-flex items-center gap-1.5 rounded-lg border border-primary bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-button-primary transition-colors hover:bg-primary/90 active:shadow-button-inset disabled:opacity-50",
2359
+ className: "inline-flex items-center gap-1.5 rounded-button border border-primary bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-button-primary transition-colors hover:bg-primary/90 active:shadow-button-inset disabled:opacity-50",
2139
2360
  children: [
2140
2361
  /* @__PURE__ */ jsx(Send, { className: "h-3 w-3" }),
2141
2362
  sending ? t2("crm.quoteDetail.sending") : t2("crm.quoteDetail.send"),
@@ -2351,7 +2572,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2351
2572
  /* @__PURE__ */ jsx("div", { className: "border-t" }),
2352
2573
  /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
2353
2574
  /* @__PURE__ */ jsx("div", { className: "h-4 w-36 rounded bg-muted/30 animate-pulse" }),
2354
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm p-5 space-y-3", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-4", children: [
2575
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm p-5 space-y-3", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-4", children: [
2355
2576
  /* @__PURE__ */ jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse" }),
2356
2577
  /* @__PURE__ */ jsx("div", { className: "col-span-2 h-3 w-24 rounded bg-muted/40 animate-pulse" })
2357
2578
  ] }, i)) })
@@ -2403,7 +2624,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2403
2624
  "button",
2404
2625
  {
2405
2626
  onClick: () => onCreateQuote(leadId),
2406
- 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",
2627
+ className: "inline-flex items-center gap-1.5 rounded-button 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",
2407
2628
  children: [
2408
2629
  /* @__PURE__ */ jsx(FileText, { className: "h-3 w-3" }),
2409
2630
  " ",
@@ -2416,7 +2637,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2416
2637
  /* @__PURE__ */ jsx("div", { className: "border-t" }),
2417
2638
  /* @__PURE__ */ jsxs("div", { children: [
2418
2639
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.contactInfo") }),
2419
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2640
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2420
2641
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.email"), value: lead.email ? /* @__PURE__ */ jsx("a", { href: `mailto:${lead.email}`, className: "text-primary hover:underline", children: lead.email }) : null }) }),
2421
2642
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(
2422
2643
  FieldRow,
@@ -2437,7 +2658,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2437
2658
  if (!fields.length && !utm.length && !attachments.length) return null;
2438
2659
  return /* @__PURE__ */ jsxs("div", { children: [
2439
2660
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.formAnswers") }),
2440
- /* @__PURE__ */ jsxs("div", { className: "rounded-xl border bg-card shadow-sm", children: [
2661
+ /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card shadow-sm", children: [
2441
2662
  /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: fields.map(([key, value]) => /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: humanizeKey2(key), value: renderFieldValue2(value) }) }, key)) }),
2442
2663
  attachments.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-t px-5 py-3", children: /* @__PURE__ */ jsx(LeadAttachments, { attachments }) }),
2443
2664
  utm.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1", children: utm.map(([key, value]) => /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
@@ -2451,7 +2672,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2451
2672
  })(),
2452
2673
  deal && /* @__PURE__ */ jsxs("div", { children: [
2453
2674
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.pipeline") }),
2454
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2675
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2455
2676
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.stage"), value: deal.stageName ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
2456
2677
  deal.stageColor && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: deal.stageColor } }),
2457
2678
  deal.stageName
@@ -2463,7 +2684,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2463
2684
  ] }),
2464
2685
  quotes.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
2465
2686
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.quotes") }),
2466
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm divide-y", children: quotes.map((q) => /* @__PURE__ */ jsxs(
2687
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm divide-y", children: quotes.map((q) => /* @__PURE__ */ jsxs(
2467
2688
  "div",
2468
2689
  {
2469
2690
  onClick: () => onViewQuote?.(q.id),
@@ -2487,7 +2708,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2487
2708
  ] }),
2488
2709
  /* @__PURE__ */ jsxs("div", { children: [
2489
2710
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.details") }),
2490
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2711
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
2491
2712
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.value"), value: lead.value != null && lead.value > 0 ? lead.value : null }) }),
2492
2713
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.assignedTo"), value: lead.assignedToName }) }),
2493
2714
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
@@ -2522,14 +2743,204 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
2522
2743
  ] }),
2523
2744
  lead.tags && lead.tags.length > 0 && /* @__PURE__ */ jsxs("div", { children: [
2524
2745
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.tags") }),
2525
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsx("div", { className: "flex gap-1.5 flex-wrap", children: lead.tags.map((tag) => /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) }) })
2746
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsx("div", { className: "flex gap-1.5 flex-wrap", children: lead.tags.map((tag) => /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) }) })
2526
2747
  ] }),
2527
2748
  lead.notes && /* @__PURE__ */ jsxs("div", { children: [
2528
2749
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.notes") }),
2529
- /* @__PURE__ */ jsx("div", { className: "rounded-xl border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-wrap", children: lead.notes }) })
2750
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-wrap", children: lead.notes }) })
2751
+ ] })
2752
+ ] });
2753
+ }
2754
+ function OverviewTab2({ lead, deal, currency }) {
2755
+ const t2 = useTranslation();
2756
+ const tagDefs = useCrmStore((s) => s.tagDefs);
2757
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
2758
+ useEffect(() => {
2759
+ fetchTagDefs();
2760
+ }, []);
2761
+ const initial = lead.name.charAt(0).toUpperCase();
2762
+ const value = lead.value ?? deal?.value;
2763
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
2764
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
2765
+ /* @__PURE__ */ jsx("div", { className: "flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary text-xl font-bold", children: initial }),
2766
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
2767
+ /* @__PURE__ */ jsx("p", { className: "text-base font-semibold truncate", children: lead.name }),
2768
+ (lead.email || lead.phone) && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground truncate", children: lead.email || lead.phone }),
2769
+ /* @__PURE__ */ jsxs("div", { className: "mt-1.5 flex flex-wrap items-center gap-1.5", children: [
2770
+ /* @__PURE__ */ jsx(LeadStatusBadge, { status: lead.status }),
2771
+ lead.sourceName && /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground", children: lead.sourceName })
2772
+ ] })
2773
+ ] })
2774
+ ] }),
2775
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border divide-y", children: [
2776
+ value !== void 0 && value > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
2777
+ /* @__PURE__ */ jsx(DollarSign, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
2778
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.value") }),
2779
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-bold", children: formatCurrency(value, currency) })
2780
+ ] }),
2781
+ lead.company && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
2782
+ /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
2783
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.leadSidebar.company") }),
2784
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-medium text-right", children: lead.company })
2785
+ ] }),
2786
+ deal?.stageName && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
2787
+ /* @__PURE__ */ jsx(Target, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
2788
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.stage") }),
2789
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-medium", children: deal.stageName })
2790
+ ] }),
2791
+ lead.assignedToName && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
2792
+ /* @__PURE__ */ jsx(User, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
2793
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.assignedTo") }),
2794
+ /* @__PURE__ */ jsx("span", { className: "text-xs font-medium", children: lead.assignedToName })
2795
+ ] }),
2796
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
2797
+ /* @__PURE__ */ jsx(Clock, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
2798
+ /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.created") }),
2799
+ /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-right", children: [
2800
+ formatDateTime(lead.createdAt, currency.locale),
2801
+ /* @__PURE__ */ jsxs("span", { className: "ml-1.5 text-muted-foreground", children: [
2802
+ "(",
2803
+ formatRelativeTime(lead.createdAt, currency.locale),
2804
+ ")"
2805
+ ] })
2806
+ ] })
2807
+ ] })
2808
+ ] }),
2809
+ (lead.email || lead.phone) && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2810
+ /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.contact") }),
2811
+ /* @__PURE__ */ jsxs("div", { className: "rounded-xl border divide-y", children: [
2812
+ lead.email && /* @__PURE__ */ jsxs("a", { href: `mailto:${lead.email}`, className: "flex items-center gap-3 px-4 py-2.5 text-xs text-primary hover:bg-muted/30 transition-colors", children: [
2813
+ /* @__PURE__ */ jsx(Mail, { className: "h-3.5 w-3.5 shrink-0" }),
2814
+ " ",
2815
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: lead.email })
2816
+ ] }),
2817
+ lead.phone && /* @__PURE__ */ jsxs(
2818
+ PhoneLink,
2819
+ {
2820
+ phone: lead.phone,
2821
+ className: "flex items-center gap-3 px-4 py-2.5 text-xs text-primary hover:bg-muted/30 transition-colors hover:no-underline",
2822
+ children: [
2823
+ /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5 shrink-0" }),
2824
+ /* @__PURE__ */ jsx("span", { children: normalizePhone(lead.phone).display })
2825
+ ]
2826
+ }
2827
+ )
2828
+ ] })
2829
+ ] }),
2830
+ /* @__PURE__ */ jsx(FormAnswers, { lead }),
2831
+ lead.tags && lead.tags.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2832
+ /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.tags") }),
2833
+ /* @__PURE__ */ jsx(TagChips, { tags: lead.tags, defs: tagDefs, size: "sm", className: "gap-1.5" })
2834
+ ] }),
2835
+ lead.notes && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2836
+ /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
2837
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed", children: lead.notes })
2530
2838
  ] })
2531
2839
  ] });
2532
2840
  }
2841
+ function LeadSidebar({ leadId, open, onClose, onViewDeal, onOpenLead }) {
2842
+ const t2 = useTranslation();
2843
+ const provider = useCrmProvider();
2844
+ const { currency } = useCrmConfig();
2845
+ const [lead, setLead] = useState(null);
2846
+ const [deal, setDeal] = useState(null);
2847
+ const [activities, setActivities] = useState([]);
2848
+ const [loading, setLoading] = useState(true);
2849
+ const [activitiesLoading, setActivitiesLoading] = useState(true);
2850
+ const [activeTab, setActiveTab] = useState("overview");
2851
+ useEffect(() => {
2852
+ if (!open || !leadId) return;
2853
+ setLoading(true);
2854
+ setActivitiesLoading(true);
2855
+ setActiveTab("overview");
2856
+ setLead(null);
2857
+ setDeal(null);
2858
+ setActivities([]);
2859
+ provider.getLeadById(leadId).then(async (l) => {
2860
+ setLead(l);
2861
+ if (l) setDeal(await provider.getDealByLeadId(leadId).catch(() => null));
2862
+ setLoading(false);
2863
+ });
2864
+ provider.getActivities({ leadId }).then((r) => {
2865
+ setActivities(r.data);
2866
+ setActivitiesLoading(false);
2867
+ });
2868
+ }, [leadId, open]);
2869
+ return /* @__PURE__ */ jsxs(
2870
+ RightRailPage,
2871
+ {
2872
+ title: loading ? t2("crm.leadSidebar.lead") : lead?.name ?? t2("crm.leadSidebar.lead"),
2873
+ open,
2874
+ onClose,
2875
+ width: "max-w-md",
2876
+ children: [
2877
+ /* @__PURE__ */ jsx("div", { className: "shrink-0 border-b px-5 pt-1", children: /* @__PURE__ */ jsx(
2878
+ HeaderTabs,
2879
+ {
2880
+ className: "-mb-px",
2881
+ value: activeTab,
2882
+ onChange: setActiveTab,
2883
+ tabs: [
2884
+ { value: "overview", label: t2("crm.dealSidebar.overview") },
2885
+ { value: "activity", label: t2("crm.dealSidebar.activity"), count: activities.length || void 0 }
2886
+ ]
2887
+ }
2888
+ ) }),
2889
+ /* @__PURE__ */ jsx(SheetBody, { children: loading ? /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
2890
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
2891
+ /* @__PURE__ */ jsx("div", { className: "h-14 w-14 rounded-2xl bg-muted/40 animate-pulse" }),
2892
+ /* @__PURE__ */ jsxs("div", { className: "space-y-2 flex-1", children: [
2893
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-32 rounded bg-muted/40 animate-pulse" }),
2894
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
2895
+ ] })
2896
+ ] }),
2897
+ /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between px-4 py-3", children: [
2898
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-20 rounded bg-muted/30 animate-pulse" }),
2899
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-24 rounded bg-muted/40 animate-pulse" })
2900
+ ] }, i)) })
2901
+ ] }) : lead ? /* @__PURE__ */ jsxs(Fragment, { children: [
2902
+ activeTab === "overview" && /* @__PURE__ */ jsx(OverviewTab2, { lead, deal, currency }),
2903
+ activeTab === "activity" && /* @__PURE__ */ jsx(ActivityTimeline, { activities, loading: activitiesLoading })
2904
+ ] }) : /* @__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.leadDetail.leadNotFound") }) }) }),
2905
+ lead && /* @__PURE__ */ jsxs("p", { className: "shrink-0 border-t border-border/40 px-5 py-1.5 text-[10px] text-muted-foreground/60", children: [
2906
+ t2("crm.dealSidebar.created"),
2907
+ " ",
2908
+ lead.createdAt?.slice(0, 10),
2909
+ lead.updatedAt ? ` \xB7 ${t2("crm.dealSidebar.updated")} ${lead.updatedAt.slice(0, 10)}` : ""
2910
+ ] }),
2911
+ lead && (deal || onOpenLead) && /* @__PURE__ */ jsxs(SheetFooter, { children: [
2912
+ deal && onViewDeal && /* @__PURE__ */ jsxs(
2913
+ "button",
2914
+ {
2915
+ onClick: () => onViewDeal(deal.id),
2916
+ className: "flex-1 inline-flex items-center justify-center gap-2 rounded-lg border px-3 py-2.5 text-xs font-medium hover:bg-muted bg-card shadow-button active:shadow-button-inset transition-colors",
2917
+ children: [
2918
+ t2("crm.leadSidebar.viewDeal"),
2919
+ " ",
2920
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
2921
+ ]
2922
+ }
2923
+ ),
2924
+ onOpenLead && /* @__PURE__ */ jsxs(
2925
+ "button",
2926
+ {
2927
+ onClick: () => {
2928
+ onOpenLead(lead.id);
2929
+ onClose();
2930
+ },
2931
+ className: "flex-1 inline-flex items-center justify-center gap-2 rounded-lg border px-3 py-2.5 text-xs font-medium hover:bg-muted bg-card shadow-button active:shadow-button-inset transition-colors",
2932
+ children: [
2933
+ t2("crm.leadSidebar.openFullProfile"),
2934
+ " ",
2935
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
2936
+ ]
2937
+ }
2938
+ )
2939
+ ] })
2940
+ ]
2941
+ }
2942
+ );
2943
+ }
2533
2944
 
2534
2945
  // src/types.ts
2535
2946
  var SYSTEM_ACTIVITY_TYPES = [
@@ -2572,7 +2983,7 @@ var TYPE_CONFIG = {
2572
2983
  var SYSTEM_TYPES = new Set(SYSTEM_ACTIVITY_TYPES);
2573
2984
  var MANUAL_TYPES = Object.keys(TYPE_CONFIG).filter((t2) => !SYSTEM_TYPES.has(t2));
2574
2985
  function ActivitySkeleton() {
2575
- 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: [
2986
+ 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-card border bg-card shadow-sm p-4", children: [
2576
2987
  /* @__PURE__ */ jsx("div", { className: "h-9 w-9 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
2577
2988
  /* @__PURE__ */ jsxs("div", { className: "flex-1 space-y-2 pt-0.5", children: [
2578
2989
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
@@ -2587,9 +2998,9 @@ function ActivitySkeleton() {
2587
2998
  }
2588
2999
  function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2589
3000
  const t2 = useTranslation();
2590
- const provider = useCrmProvider();
2591
3001
  const { currency } = useCrmConfig();
2592
3002
  const [selectedDealId, setSelectedDealId] = useState(null);
3003
+ const [selectedLeadId, setSelectedLeadId] = useState(null);
2593
3004
  const activities = useCrmStore((s) => s.activities);
2594
3005
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
2595
3006
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
@@ -2604,8 +3015,38 @@ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2604
3015
  }, [typeFilter, showCompleted]);
2605
3016
  const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities;
2606
3017
  const messages = useActivityAutomations();
3018
+ const exportRows = useCallback(() => {
3019
+ exportCSV(
3020
+ [
3021
+ { key: "createdAt", label: t2("crm.leads.receivedCol"), format: (v) => {
3022
+ const at = v ? new Date(String(v)) : null;
3023
+ return at && !Number.isNaN(at.getTime()) ? at.toLocaleString() : "";
3024
+ } },
3025
+ { key: "activityType", label: t2("crm.activities.typeCol"), format: (v) => TYPE_CONFIG[String(v)]?.label ?? String(v ?? "") },
3026
+ { key: "title", label: t2("crm.activities.titleCol") },
3027
+ { key: "description", label: t2("crm.leadDetail.notes") },
3028
+ { key: "contactName", label: t2("crm.quotes.contact") },
3029
+ { key: "dueDate", label: t2("crm.activities.dueCol") },
3030
+ { key: "completedAt", label: t2("crm.activities.done") }
3031
+ ],
3032
+ filtered,
3033
+ "atividades"
3034
+ );
3035
+ toast.success(t2("crud.export.toastSuccess", { count: String(filtered.length) }));
3036
+ }, [filtered, t2]);
2607
3037
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
2608
- /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.activities.title") }),
3038
+ /* @__PURE__ */ jsx(
3039
+ SubpageHeader,
3040
+ {
3041
+ title: t2("crm.activities.title"),
3042
+ actions: filtered.length > 0 && /* @__PURE__ */ jsx(
3043
+ PageActions,
3044
+ {
3045
+ actions: [{ id: "export", label: t2("crud.export.action"), icon: Download, intent: "utility", onSelect: exportRows }]
3046
+ }
3047
+ )
3048
+ }
3049
+ ),
2609
3050
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-3 sm:items-center", children: [
2610
3051
  /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 flex-wrap", children: [
2611
3052
  /* @__PURE__ */ jsx(
@@ -2681,18 +3122,19 @@ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2681
3122
  const Icon = cfg.icon;
2682
3123
  const isSystem = SYSTEM_TYPES.has(a.activityType);
2683
3124
  const isOverdue = !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2684
- const openRecord = a.dealId ? () => setSelectedDealId(a.dealId) : a.leadId ? () => {
2685
- void provider.getDealByLeadId(a.leadId).then((deal) => {
2686
- if (deal) setSelectedDealId(deal.id);
2687
- else onOpenLead?.(a.leadId);
2688
- });
3125
+ const openRecord = a.dealId ? () => {
3126
+ setSelectedLeadId(null);
3127
+ setSelectedDealId(a.dealId);
3128
+ } : a.leadId ? () => {
3129
+ setSelectedDealId(null);
3130
+ setSelectedLeadId(a.leadId);
2689
3131
  } : void 0;
2690
3132
  return /* @__PURE__ */ jsxs(
2691
3133
  "div",
2692
3134
  {
2693
3135
  onClick: openRecord,
2694
3136
  role: openRecord ? "button" : void 0,
2695
- 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" : ""}`,
3137
+ className: `group flex items-start gap-3 rounded-card border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""} ${openRecord ? "cursor-pointer hover:bg-muted/30" : ""}`,
2696
3138
  children: [
2697
3139
  /* @__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" }) }),
2698
3140
  /* @__PURE__ */ jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
@@ -2751,9 +3193,25 @@ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2751
3193
  dealId: selectedDealId ?? "",
2752
3194
  open: !!selectedDealId,
2753
3195
  onClose: () => setSelectedDealId(null),
2754
- onViewLead: onOpenLead,
3196
+ onViewLead: (id) => {
3197
+ setSelectedDealId(null);
3198
+ setSelectedLeadId(id);
3199
+ },
2755
3200
  onViewQuote: onOpenQuote
2756
3201
  }
3202
+ ),
3203
+ /* @__PURE__ */ jsx(
3204
+ LeadSidebar,
3205
+ {
3206
+ leadId: selectedLeadId ?? "",
3207
+ open: !!selectedLeadId,
3208
+ onClose: () => setSelectedLeadId(null),
3209
+ onViewDeal: (id) => {
3210
+ setSelectedLeadId(null);
3211
+ setSelectedDealId(id);
3212
+ },
3213
+ onOpenLead
3214
+ }
2757
3215
  )
2758
3216
  ] });
2759
3217
  }
@@ -2864,7 +3322,12 @@ function CrmPage({ config, provider, store, registries }) {
2864
3322
  const renderView = createViewRouter([
2865
3323
  { id: "pipeline", render: () => /* @__PURE__ */ jsx(PipelineView, { onViewLead: (id) => navigate(`leads-detail:${id}`), onViewQuote: (id) => navigate(`quotes-detail:${id}`), onAddLead: () => navigate("leads-new"), onOpenSettings: openStageSettings }) },
2866
3324
  { id: "leads-list", render: () => /* @__PURE__ */ jsx(LeadListView, { onNew: () => navigate("leads-new"), onEdit: (id) => navigate(`leads-detail:${id}`) }) },
2867
- { id: "leads-new", render: () => /* @__PURE__ */ jsx(LeadFormView, { onSaved: (id) => id ? navigate(`leads-detail:${id}`) : navigate("leads-list") }) },
3325
+ // The form lives in the right column, so the list it is added to stays on
3326
+ // screen behind it — rendered here, not replaced.
3327
+ { id: "leads-new", render: () => /* @__PURE__ */ jsxs(Fragment, { children: [
3328
+ /* @__PURE__ */ jsx(LeadListView, { onNew: () => navigate("leads-new"), onEdit: (id) => navigate(`leads-detail:${id}`) }),
3329
+ /* @__PURE__ */ jsx(LeadFormView, { onSaved: (id) => id ? navigate(`leads-detail:${id}`) : navigate("leads-list") })
3330
+ ] }) },
2868
3331
  { id: "quotes-new", render: () => {
2869
3332
  const hashParams = new URLSearchParams(window.location.hash.split("?")[1] ?? "");
2870
3333
  const lid = hashParams.get("leadId") ?? void 0;
@@ -2887,14 +3350,13 @@ function CrmPage({ config, provider, store, registries }) {
2887
3350
  nav,
2888
3351
  navVariant: config.moduleNav,
2889
3352
  showHeader: isSummary,
2890
- viewKey: view,
3353
+ viewKey: view === "leads-new" ? "leads-list" : view,
2891
3354
  direction,
2892
3355
  headerAction: /* @__PURE__ */ jsx(
2893
3356
  ModuleActionBar,
2894
3357
  {
2895
3358
  quickActions,
2896
- settingsPath: registries && registries.length > 0 ? "/settings/crm" : void 0,
2897
- settingsLabel: "CRM Settings"
3359
+ settingsPath: registries && registries.length > 0 ? "/settings/crm" : void 0
2898
3360
  }
2899
3361
  ),
2900
3362
  children: renderView(view)
@@ -3799,6 +4261,15 @@ function createSupabaseCrmProvider(options) {
3799
4261
  value: r.lead_value ? Number(r.lead_value) : void 0,
3800
4262
  tags: r.tags ?? [],
3801
4263
  notes: r.notes,
4264
+ // As respostas do formulário vinham só no getLeadById, embora o
4265
+ // select('*') já as trouxesse aqui: a lista tinha a informação na mão
4266
+ // e a jogava fora, então exportar os leads perdia justamente o que a
4267
+ // campanha perguntou.
4268
+ metadata: {
4269
+ formId: r.form_id ?? void 0,
4270
+ fields: r.custom_fields ?? {},
4271
+ utm: r.utm ?? {}
4272
+ },
3802
4273
  tenantId: r.tenant_id,
3803
4274
  createdAt: r.created_at,
3804
4275
  updatedAt: r.updated_at
@@ -4554,6 +5025,7 @@ function createSupabaseCrmProvider(options) {
4554
5025
  }
4555
5026
  function createCrmStore(provider) {
4556
5027
  let lastActivitiesQuery = {};
5028
+ let lastLeadsQuery = {};
4557
5029
  let lastBoard = null;
4558
5030
  return createStore$1((set, get) => ({
4559
5031
  pipelines: [],
@@ -4611,6 +5083,7 @@ function createCrmStore(provider) {
4611
5083
  });
4612
5084
  },
4613
5085
  async fetchLeads(query) {
5086
+ lastLeadsQuery = query;
4614
5087
  return dedup("crm:leads:" + JSON.stringify(query), async () => {
4615
5088
  set({ leadsLoading: true });
4616
5089
  const result = await provider.getLeads(query);
@@ -4661,25 +5134,33 @@ function createCrmStore(provider) {
4661
5134
  set({ quotes: result.data, quotesTotal: result.total, quotesLoading: false });
4662
5135
  });
4663
5136
  },
5137
+ async resolveEntryPipeline() {
5138
+ let { pipelines, stages } = get();
5139
+ if (pipelines.length === 0) {
5140
+ pipelines = await provider.getPipelines();
5141
+ stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
5142
+ set({ pipelines, stages });
5143
+ }
5144
+ const pipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
5145
+ if (!pipeline) return { pipeline: void 0, stages: [] };
5146
+ const own = pipeline.id === pipelines[0]?.id && stages.length > 0 ? stages : await provider.getPipelineStages(pipeline.id);
5147
+ return { pipeline, stages: own };
5148
+ },
4664
5149
  async createLead(input) {
4665
5150
  try {
4666
5151
  const lead = await provider.createLead(input);
4667
- let { pipelines, stages } = get();
4668
- if (pipelines.length === 0) {
4669
- pipelines = await provider.getPipelines();
4670
- stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
4671
- set({ pipelines, stages });
4672
- }
4673
- const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
4674
- const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0];
4675
- if (defaultPipeline && firstStage) {
5152
+ const { pipeline, stages: entryStages } = await get().resolveEntryPipeline();
5153
+ const open = entryStages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order);
5154
+ const chosen = input.stageId ? entryStages.find((s) => s.id === input.stageId) : void 0;
5155
+ const stage = chosen ?? open[0];
5156
+ if (pipeline && stage) {
4676
5157
  try {
4677
5158
  await provider.createDeal({
4678
5159
  leadId: lead.id,
4679
5160
  title: lead.name,
4680
5161
  value: input.value ?? 0,
4681
- pipelineId: defaultPipeline.id,
4682
- stageId: firstStage.id,
5162
+ pipelineId: pipeline.id,
5163
+ stageId: stage.id,
4683
5164
  contactName: lead.name
4684
5165
  });
4685
5166
  } catch {
@@ -4695,6 +5176,18 @@ function createCrmStore(provider) {
4695
5176
  throw err;
4696
5177
  }
4697
5178
  },
5179
+ async updateLead(id, data) {
5180
+ return provider.updateLead(id, data);
5181
+ },
5182
+ async refreshLeads() {
5183
+ const [leadsResult, summary] = await Promise.all([
5184
+ provider.getLeads(lastLeadsQuery),
5185
+ provider.getSummary(),
5186
+ get().refreshBoard()
5187
+ ]);
5188
+ set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary });
5189
+ void get().refreshActivities();
5190
+ },
4698
5191
  async createDeal(input) {
4699
5192
  try {
4700
5193
  const deal = await provider.createDeal(input);
@@ -4720,13 +5213,7 @@ function createCrmStore(provider) {
4720
5213
  },
4721
5214
  async createQuote(input) {
4722
5215
  try {
4723
- let { pipelines, stages } = get();
4724
- if (pipelines.length === 0) {
4725
- pipelines = await provider.getPipelines();
4726
- stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
4727
- set({ pipelines, stages });
4728
- }
4729
- const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
5216
+ const { pipeline: defaultPipeline, stages } = await get().resolveEntryPipeline();
4730
5217
  let leadId = input.leadId;
4731
5218
  let dealId = input.dealId;
4732
5219
  const contactId = input.contactId;
@@ -4890,7 +5377,7 @@ function createCrmStore(provider) {
4890
5377
  try {
4891
5378
  await provider.archiveLead(leadId);
4892
5379
  const [leadsResult, summary] = await Promise.all([
4893
- provider.getLeads({}),
5380
+ provider.getLeads(lastLeadsQuery),
4894
5381
  provider.getSummary(),
4895
5382
  get().refreshBoard()
4896
5383
  ]);
@@ -4918,6 +5405,275 @@ function createCrmStore(provider) {
4918
5405
  }
4919
5406
  }));
4920
5407
  }
5408
+ var LEADS = "plg_crm_rep_leads";
5409
+ var DEALS = "plg_crm_rep_deals";
5410
+ var CAT_LEADS = tl("Leads", "Leads");
5411
+ var CAT_DEALS = tl("Deals", "Neg\xF3cios");
5412
+ var LEAD_STATUS_LABELS = {
5413
+ new: tl("New", "Novo"),
5414
+ contacted: tl("Contacted", "Contatado"),
5415
+ qualified: tl("Qualified", "Qualificado"),
5416
+ unqualified: tl("Unqualified", "Desqualificado"),
5417
+ converted: tl("Converted", "Convertido"),
5418
+ lost: tl("Lost", "Perdido")
5419
+ };
5420
+ var DEAL_STATUS_LABELS = {
5421
+ open: tl("Open", "Aberto"),
5422
+ won: tl("Won", "Ganho"),
5423
+ lost: tl("Lost", "Perdido")
5424
+ };
5425
+ var leadStatusFilter = {
5426
+ key: "status",
5427
+ label: tl("Lead status", "Situa\xE7\xE3o do lead"),
5428
+ type: "multiselect",
5429
+ group: CAT_LEADS,
5430
+ options: [
5431
+ { label: tl("New", "Novo"), value: "new" },
5432
+ { label: tl("Contacted", "Contatado"), value: "contacted" },
5433
+ { label: tl("Qualified", "Qualificado"), value: "qualified" },
5434
+ { label: tl("Unqualified", "Desqualificado"), value: "unqualified" },
5435
+ { label: tl("Converted", "Convertido"), value: "converted" },
5436
+ { label: tl("Lost", "Perdido"), value: "lost" }
5437
+ ]
5438
+ };
5439
+ var dealStatusFilter = {
5440
+ key: "status",
5441
+ label: tl("Deal status", "Situa\xE7\xE3o do neg\xF3cio"),
5442
+ type: "multiselect",
5443
+ group: CAT_DEALS,
5444
+ options: [
5445
+ { label: tl("Open", "Aberto"), value: "open" },
5446
+ { label: tl("Won", "Ganho"), value: "won" },
5447
+ { label: tl("Lost", "Perdido"), value: "lost" }
5448
+ ]
5449
+ };
5450
+ function buildCrmAnalyticsCards() {
5451
+ const base = { domain: "crm", compare: true };
5452
+ return [
5453
+ // -----------------------------------------------------------------------
5454
+ // Leads
5455
+ // -----------------------------------------------------------------------
5456
+ {
5457
+ ...base,
5458
+ id: "crm.leads",
5459
+ name: tl("Leads", "Leads"),
5460
+ description: tl(
5461
+ "Leads that came in during the period.",
5462
+ "Leads que entraram no per\xEDodo."
5463
+ ),
5464
+ icon: "UserPlus",
5465
+ category: CAT_LEADS,
5466
+ grain: "lead",
5467
+ canonicalOwner: "public.v_leads",
5468
+ query: {
5469
+ source: { kind: "view", name: LEADS },
5470
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5471
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5472
+ filters: [leadStatusFilter]
5473
+ },
5474
+ viz: { type: "kpi", spark: true },
5475
+ dashboard: { span: 1, order: 20 }
5476
+ },
5477
+ {
5478
+ ...base,
5479
+ id: "crm.leads-by-source",
5480
+ name: tl("Leads by source", "Leads por origem"),
5481
+ description: tl(
5482
+ 'Where the enquiries came from \u2014 the answer to "is the campaign working".',
5483
+ 'De onde vieram os contatos \u2014 a resposta para "a campanha est\xE1 funcionando".'
5484
+ ),
5485
+ icon: "Share2",
5486
+ category: CAT_LEADS,
5487
+ grain: "lead",
5488
+ query: {
5489
+ source: { kind: "view", name: LEADS },
5490
+ dimensions: [{ key: "source_name", label: tl("Source", "Origem") }],
5491
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5492
+ filters: [leadStatusFilter],
5493
+ defaultSort: "leads",
5494
+ defaultSortDir: "desc"
5495
+ },
5496
+ viz: { type: "breakdown", limit: 8 },
5497
+ dashboard: { span: 1, order: 21 }
5498
+ },
5499
+ {
5500
+ ...base,
5501
+ id: "crm.leads-by-status",
5502
+ name: tl("Leads by status", "Leads por situa\xE7\xE3o"),
5503
+ description: tl(
5504
+ "How the period\u2019s enquiries are spread across the funnel.",
5505
+ "Como os contatos do per\xEDodo est\xE3o distribu\xEDdos no funil."
5506
+ ),
5507
+ icon: "Filter",
5508
+ category: CAT_LEADS,
5509
+ grain: "lead",
5510
+ query: {
5511
+ source: { kind: "view", name: LEADS },
5512
+ dimensions: [{ key: "status", label: tl("Status", "Situa\xE7\xE3o") }],
5513
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5514
+ defaultSort: "leads",
5515
+ defaultSortDir: "desc"
5516
+ },
5517
+ viz: { type: "donut" }
5518
+ },
5519
+ {
5520
+ // Converted over total, computed after aggregation: a ratio of sums, not
5521
+ // an average of per-row ratios, which would answer a different question.
5522
+ ...base,
5523
+ id: "crm.lead-conversion",
5524
+ name: tl("Lead conversion", "Convers\xE3o de leads"),
5525
+ description: tl(
5526
+ "Share of the period\u2019s leads that became a customer.",
5527
+ "Parte dos leads do per\xEDodo que virou cliente."
5528
+ ),
5529
+ icon: "TrendingUp",
5530
+ category: CAT_LEADS,
5531
+ grain: "lead",
5532
+ query: {
5533
+ source: { kind: "view", name: LEADS },
5534
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5535
+ measures: [
5536
+ { key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" },
5537
+ { key: "converted", label: tl("Converted", "Convertidos"), agg: "sum", column: "is_converted", format: "number" },
5538
+ {
5539
+ key: "conversion",
5540
+ label: tl("Conversion", "Convers\xE3o"),
5541
+ agg: "ratio",
5542
+ ratioOf: ["converted", "leads"],
5543
+ scale: 100,
5544
+ format: "percent"
5545
+ }
5546
+ ]
5547
+ },
5548
+ viz: { type: "kpi", measures: ["conversion"], spark: true }
5549
+ },
5550
+ {
5551
+ // The one the CRM never had: every lead, in a table, exportable. No
5552
+ // measures, so it is a plain select over the read model rather than an
5553
+ // aggregate — the rows themselves ARE the report.
5554
+ ...base,
5555
+ id: "crm.leads-list",
5556
+ name: tl("Lead list", "Lista de leads"),
5557
+ description: tl(
5558
+ "Every lead in the period with contact details, source and status \u2014 ready to export.",
5559
+ "Todo lead do per\xEDodo com contato, origem e situa\xE7\xE3o \u2014 pronto para exportar."
5560
+ ),
5561
+ icon: "Users",
5562
+ category: CAT_LEADS,
5563
+ grain: "lead",
5564
+ canonicalOwner: "public.v_leads",
5565
+ query: {
5566
+ source: { kind: "view", name: LEADS },
5567
+ filters: [leadStatusFilter],
5568
+ defaultSort: "created_at",
5569
+ defaultSortDir: "desc"
5570
+ },
5571
+ columns: [
5572
+ { key: "created_at", label: tl("Received", "Entrada"), type: "date", sortable: true },
5573
+ { key: "lead_name", label: tl("Name", "Nome"), type: "text", sortable: true },
5574
+ { key: "email", label: tl("E-mail", "E-mail"), type: "email" },
5575
+ { key: "phone", label: tl("Phone", "Telefone"), type: "text" },
5576
+ { key: "company", label: tl("Company", "Empresa"), type: "text" },
5577
+ { key: "source_name", label: tl("Source", "Origem"), type: "text" },
5578
+ { key: "status", label: tl("Status", "Situa\xE7\xE3o"), type: "text", valueMap: LEAD_STATUS_LABELS },
5579
+ // O que a landing page perguntou — estilo, perfil, "tem WhatsApp?".
5580
+ // Uma coluna na tela (as perguntas mudam a cada campanha, e declarar
5581
+ // uma coluna por pergunta tornaria o PRÓXIMO formulário invisível) e,
5582
+ // na planilha, uma coluna por pergunta: é `expand` quem faz isso, com
5583
+ // as chaves descobertas nas linhas exportadas.
5584
+ {
5585
+ key: "custom_fields",
5586
+ label: tl("Form answers", "Dados do formul\xE1rio"),
5587
+ type: "text",
5588
+ expand: true,
5589
+ sortable: false
5590
+ },
5591
+ // Export-only: useful in the spreadsheet, noise in a table already
5592
+ // carrying seven columns.
5593
+ { key: "utm_source", label: tl("UTM source", "UTM origem"), type: "text", visible: false },
5594
+ { key: "utm_campaign", label: tl("UTM campaign", "UTM campanha"), type: "text", visible: false },
5595
+ { key: "lead_value", label: tl("Value", "Valor"), type: "currency", visible: false }
5596
+ ],
5597
+ viz: { type: "table" }
5598
+ },
5599
+ // -----------------------------------------------------------------------
5600
+ // Deals
5601
+ // -----------------------------------------------------------------------
5602
+ {
5603
+ ...base,
5604
+ id: "crm.deals-won",
5605
+ name: tl("Won deals", "Neg\xF3cios ganhos"),
5606
+ description: tl(
5607
+ "Value of the deals closed as won in the period.",
5608
+ "Valor dos neg\xF3cios fechados como ganhos no per\xEDodo."
5609
+ ),
5610
+ icon: "Trophy",
5611
+ category: CAT_DEALS,
5612
+ grain: "deal",
5613
+ canonicalOwner: "public.v_deals",
5614
+ query: {
5615
+ source: { kind: "view", name: DEALS },
5616
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5617
+ measures: [{ key: "won_value", label: tl("Won", "Ganho"), agg: "sum", format: "currency" }]
5618
+ },
5619
+ viz: { type: "kpi", spark: true }
5620
+ },
5621
+ {
5622
+ ...base,
5623
+ id: "crm.deals-by-stage",
5624
+ name: tl("Pipeline by stage", "Funil por etapa"),
5625
+ description: tl(
5626
+ "What is sitting in each stage of the board, and what it is worth.",
5627
+ "O que est\xE1 parado em cada etapa do quadro, e quanto vale."
5628
+ ),
5629
+ icon: "Columns3",
5630
+ category: CAT_DEALS,
5631
+ grain: "deal",
5632
+ query: {
5633
+ source: { kind: "view", name: DEALS },
5634
+ dimensions: [{ key: "stage_name", label: tl("Stage", "Etapa") }],
5635
+ measures: [
5636
+ { key: "deals", label: tl("Deals", "Neg\xF3cios"), agg: "count", format: "number" },
5637
+ { key: "value", label: tl("Value", "Valor"), agg: "sum", format: "currency" }
5638
+ ],
5639
+ filters: [dealStatusFilter],
5640
+ defaultSort: "value",
5641
+ defaultSortDir: "desc"
5642
+ },
5643
+ viz: { type: "bar", measures: ["value"] }
5644
+ },
5645
+ {
5646
+ ...base,
5647
+ id: "crm.deals-list",
5648
+ name: tl("Deal list", "Lista de neg\xF3cios"),
5649
+ description: tl(
5650
+ "Every deal in the period with its stage, value and owner \u2014 ready to export.",
5651
+ "Todo neg\xF3cio do per\xEDodo com etapa, valor e respons\xE1vel \u2014 pronto para exportar."
5652
+ ),
5653
+ icon: "Handshake",
5654
+ category: CAT_DEALS,
5655
+ grain: "deal",
5656
+ canonicalOwner: "public.v_deals",
5657
+ query: {
5658
+ source: { kind: "view", name: DEALS },
5659
+ filters: [dealStatusFilter],
5660
+ defaultSort: "created_at",
5661
+ defaultSortDir: "desc"
5662
+ },
5663
+ columns: [
5664
+ { key: "created_at", label: tl("Opened", "Aberto em"), type: "date", sortable: true },
5665
+ { key: "title", label: tl("Deal", "Neg\xF3cio"), type: "text" },
5666
+ { key: "contact_name", label: tl("Contact", "Contato"), type: "text" },
5667
+ { key: "stage_name", label: tl("Stage", "Etapa"), type: "text" },
5668
+ { key: "status", label: tl("Status", "Situa\xE7\xE3o"), type: "text", valueMap: DEAL_STATUS_LABELS },
5669
+ { key: "value", label: tl("Value", "Valor"), type: "currency", sortable: true, aggregate: "sum" },
5670
+ { key: "expected_close_date", label: tl("Expected close", "Previs\xE3o"), type: "date", visible: false },
5671
+ { key: "lost_reason", label: tl("Lost reason", "Motivo da perda"), type: "text", visible: false }
5672
+ ],
5673
+ viz: { type: "table" }
5674
+ }
5675
+ ];
5676
+ }
4921
5677
 
4922
5678
  // src/data/registries.ts
4923
5679
  var leadSourceEntity = {
@@ -5081,6 +5837,9 @@ var en = {
5081
5837
  "crm.activities.pending": "pending",
5082
5838
  "crm.activities.pendingFilter": "Pending",
5083
5839
  "crm.activities.systemEvents": "Events",
5840
+ "crm.activities.typeCol": "Type",
5841
+ "crm.activities.titleCol": "Title",
5842
+ "crm.activities.dueCol": "Due",
5084
5843
  "crm.activities.title": "Activities",
5085
5844
  "crm.dashboard.activeDeals": "{{count}} active deals",
5086
5845
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -5164,15 +5923,37 @@ var en = {
5164
5923
  "crm.leadForm.notesPlaceholder": "Additional notes...",
5165
5924
  "crm.leadForm.phone": "Phone",
5166
5925
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
5926
+ "crm.leadForm.stage": "Stage",
5167
5927
  "crm.leadForm.save": "Save",
5168
5928
  "crm.leadForm.saving": "Saving...",
5169
5929
  "crm.leadForm.subtitle": "Capture a new lead",
5170
5930
  "crm.leadForm.title": "New Lead",
5931
+ "crm.leadSidebar.company": "Company",
5932
+ "crm.leadSidebar.lead": "Lead",
5933
+ "crm.leadSidebar.openFullProfile": "Open full profile",
5934
+ "crm.leadSidebar.viewDeal": "View deal",
5935
+ "crm.leads.statusLost": "Lost",
5936
+ "crm.leads.bulkArchive": "Archive",
5937
+ "crm.leads.bulkArchiveDesc": "They leave the list and the pipeline board. This cannot be undone from here.",
5938
+ "crm.leads.bulkArchiveDone": "{{count}} lead(s) archived",
5939
+ "crm.leads.bulkArchiveFailed": "{{count}} lead(s) could not be archived",
5940
+ "crm.leads.bulkArchiveTitle": "Archive {{count}} lead(s)?",
5941
+ "crm.leads.bulkKeep": "Keep",
5942
+ "crm.leads.bulkSetStatus": "Mark as {{status}}",
5943
+ "crm.leads.bulkStatusDone": "{{count}} lead(s) updated",
5944
+ "crm.leads.bulkStatusFailed": "{{count}} lead(s) could not be updated",
5945
+ "crm.leads.bulkStatusNone": "The selected leads already have this status.",
5946
+ "crm.leads.statusContacted": "Contacted",
5947
+ "crm.leads.statusConverted": "Converted",
5948
+ "crm.leads.statusNew": "New",
5949
+ "crm.leads.statusQualified": "Qualified",
5950
+ "crm.leads.statusUnqualified": "Unqualified",
5171
5951
  "crm.leads.captureFirst": "Capture your first lead",
5172
5952
  "crm.leads.contactCol": "Contact",
5173
5953
  "crm.leads.name": "Name",
5174
5954
  "crm.leads.newLead": "New Lead",
5175
5955
  "crm.leads.noLeads": "No leads yet",
5956
+ "crm.leads.receivedCol": "Received",
5176
5957
  "crm.leads.searchPlaceholder": "Search leads...",
5177
5958
  "crm.leads.source": "Source",
5178
5959
  "crm.leads.statusCol": "Status",
@@ -5393,6 +6174,9 @@ var ptBR = {
5393
6174
  "crm.activities.pending": "pendente",
5394
6175
  "crm.activities.pendingFilter": "Pendentes",
5395
6176
  "crm.activities.systemEvents": "Eventos",
6177
+ "crm.activities.typeCol": "Tipo",
6178
+ "crm.activities.titleCol": "T\xEDtulo",
6179
+ "crm.activities.dueCol": "Vencimento",
5396
6180
  "crm.activities.title": "Atividades",
5397
6181
  "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
5398
6182
  "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
@@ -5476,15 +6260,37 @@ var ptBR = {
5476
6260
  "crm.leadForm.notesPlaceholder": "Observa\xE7\xF5es adicionais...",
5477
6261
  "crm.leadForm.phone": "Telefone",
5478
6262
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
6263
+ "crm.leadForm.stage": "Etapa",
5479
6264
  "crm.leadForm.save": "Salvar",
5480
6265
  "crm.leadForm.saving": "Salvando...",
5481
6266
  "crm.leadForm.subtitle": "Capturar um novo lead",
5482
6267
  "crm.leadForm.title": "Novo Lead",
6268
+ "crm.leadSidebar.company": "Empresa",
6269
+ "crm.leadSidebar.lead": "Lead",
6270
+ "crm.leadSidebar.openFullProfile": "Abrir ficha completa",
6271
+ "crm.leadSidebar.viewDeal": "Ver neg\xF3cio",
6272
+ "crm.leads.statusLost": "Perdido",
6273
+ "crm.leads.bulkArchive": "Arquivar",
6274
+ "crm.leads.bulkArchiveDesc": "Eles saem da lista e do quadro do funil. N\xE3o d\xE1 para desfazer por aqui.",
6275
+ "crm.leads.bulkArchiveDone": "{{count}} lead(s) arquivado(s)",
6276
+ "crm.leads.bulkArchiveFailed": "{{count}} lead(s) n\xE3o puderam ser arquivados",
6277
+ "crm.leads.bulkArchiveTitle": "Arquivar {{count}} lead(s)?",
6278
+ "crm.leads.bulkKeep": "Manter",
6279
+ "crm.leads.bulkSetStatus": "Marcar como {{status}}",
6280
+ "crm.leads.bulkStatusDone": "{{count}} lead(s) atualizado(s)",
6281
+ "crm.leads.bulkStatusFailed": "{{count}} lead(s) n\xE3o puderam ser atualizados",
6282
+ "crm.leads.bulkStatusNone": "Os leads selecionados j\xE1 est\xE3o nesse status.",
6283
+ "crm.leads.statusContacted": "Contatado",
6284
+ "crm.leads.statusConverted": "Convertido",
6285
+ "crm.leads.statusNew": "Novo",
6286
+ "crm.leads.statusQualified": "Qualificado",
6287
+ "crm.leads.statusUnqualified": "Desqualificado",
5483
6288
  "crm.leads.captureFirst": "Capture seu primeiro lead",
5484
6289
  "crm.leads.contactCol": "Contato",
5485
6290
  "crm.leads.name": "Nome",
5486
6291
  "crm.leads.newLead": "Novo Lead",
5487
6292
  "crm.leads.noLeads": "Nenhum lead ainda",
6293
+ "crm.leads.receivedCol": "Entrada",
5488
6294
  "crm.leads.searchPlaceholder": "Buscar leads...",
5489
6295
  "crm.leads.source": "Origem",
5490
6296
  "crm.leads.statusCol": "Status",
@@ -5772,10 +6578,11 @@ function createCrmPlugin(options) {
5772
6578
  () => createMockCrmProvider({ activityTypes })
5773
6579
  );
5774
6580
  const store = createCrmStore(provider);
5775
- const PageComponent = () => React16.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
6581
+ const PageComponent = () => React17.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
5776
6582
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
5777
6583
  return {
5778
6584
  id: "crm",
6585
+ defaultAgentRole: "growth",
5779
6586
  name: config.labels.pageTitle,
5780
6587
  icon: "Filter",
5781
6588
  version: "1.0.0",
@@ -5785,12 +6592,23 @@ function createCrmPlugin(options) {
5785
6592
  // saas/admin Panel world, not the ecommerce storefront.
5786
6593
  scaffolds: ["saas"],
5787
6594
  defaultEnabled: true,
6595
+ // The parts a plan can permit separately (#281, ADR 0025). A contact list
6596
+ // is table stakes; a pipeline that automates itself is not.
6597
+ facets: [
6598
+ { id: "contacts", label: "Contatos e leads", description: "Cadastro, tags e hist\xF3rico.", includedWithPlugin: true },
6599
+ { id: "pipeline", label: "Funil de vendas", description: "Board de neg\xF3cios, etapas e previs\xE3o." },
6600
+ { id: "automation", label: "Automa\xE7\xF5es de funil", description: "Regras que movem o card e disparam a pr\xF3xima a\xE7\xE3o." }
6601
+ ],
5788
6602
  dependencies: [],
5789
6603
  // Os FATOS do funil. Vão no manifesto (e não num registro à parte) para que
5790
6604
  // o runtime só os exponha enquanto o CRM está ATIVO — automações, webhooks
5791
6605
  // e auditoria leem todos daqui. Sem esta linha os textos existiam mas não
5792
6606
  // tinham evento a que se ligar, e a lista de automações saía vazia.
5793
6607
  events: buildCrmDomainEvents(),
6608
+ // Leads e negócios em /analytics: o mesmo card é bloco do painel, linha da
6609
+ // lista de relatórios e o relatório inteiro — que é onde alguém finalmente
6610
+ // exporta os leads para uma planilha. Read models na migration 017.
6611
+ analyticsCards: options?.analyticsCards === false ? [] : buildCrmAnalyticsCards(),
5794
6612
  declaredFeatures: [
5795
6613
  { id: "sales", label: config.labels.pageTitle, group: config.labels.pageTitle },
5796
6614
  { id: "crm.leads", label: config.labels.leads, group: config.labels.pageTitle },
@@ -6036,13 +6854,12 @@ function createCrmPlugin(options) {
6036
6854
  label: "Sales & CRM",
6037
6855
  icon: "Filter",
6038
6856
  component: (() => {
6039
- const Tab = () => React16.createElement(
6857
+ const Tab = () => React17.createElement(
6040
6858
  CrmContextProvider,
6041
6859
  { config, provider, store },
6042
- React16.createElement(PluginSettingsPanel, {
6860
+ React17.createElement(PluginSettingsPanel, {
6043
6861
  title: "Sales & CRM",
6044
- subtitle: "Pipeline, lead management, and CRM properties",
6045
- generalSettings: React16.createElement(CrmGeneralSettings),
6862
+ generalSettings: React17.createElement(CrmGeneralSettings),
6046
6863
  registries: crmRegistries2,
6047
6864
  hostPluginId: "crm",
6048
6865
  routeBase: "/settings/crm"