@fayz-ai/plugin-crm 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/CrmContext.d.ts +32 -0
  2. package/dist/CrmContext.d.ts.map +1 -0
  3. package/dist/CrmPage.d.ts +13 -0
  4. package/dist/CrmPage.d.ts.map +1 -0
  5. package/dist/cascade.d.ts +13 -0
  6. package/dist/cascade.d.ts.map +1 -0
  7. package/dist/components/CrmGeneralSettings.d.ts +3 -0
  8. package/dist/components/CrmGeneralSettings.d.ts.map +1 -0
  9. package/dist/components/CrmOnboarding.d.ts +5 -0
  10. package/dist/components/CrmOnboarding.d.ts.map +1 -0
  11. package/dist/components/PipelineSettings.d.ts +3 -0
  12. package/dist/components/PipelineSettings.d.ts.map +1 -0
  13. package/dist/components/QuoteStatusDropdown.d.ts +8 -0
  14. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -0
  15. package/dist/data/index.d.ts +3 -0
  16. package/dist/data/index.d.ts.map +1 -0
  17. package/dist/data/mock.d.ts +9 -0
  18. package/dist/data/mock.d.ts.map +1 -0
  19. package/dist/data/supabase.d.ts +9 -0
  20. package/dist/data/supabase.d.ts.map +1 -0
  21. package/dist/data/types.d.ts +32 -0
  22. package/dist/data/types.d.ts.map +1 -0
  23. package/dist/index.cjs +4601 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.ts +72 -0
  26. package/dist/index.d.ts.map +1 -0
  27. package/dist/index.js +4595 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/lib/tenant.d.ts +3 -0
  30. package/dist/lib/tenant.d.ts.map +1 -0
  31. package/dist/locales/en.d.ts +2 -0
  32. package/dist/locales/en.d.ts.map +1 -0
  33. package/dist/locales/index.d.ts +2 -0
  34. package/dist/locales/index.d.ts.map +1 -0
  35. package/dist/locales/pt-BR.d.ts +2 -0
  36. package/dist/locales/pt-BR.d.ts.map +1 -0
  37. package/dist/registries.d.ts +3 -0
  38. package/dist/registries.d.ts.map +1 -0
  39. package/dist/schema/index.d.ts +1036 -0
  40. package/dist/schema/index.d.ts.map +1 -0
  41. package/dist/store.d.ts +43 -0
  42. package/dist/store.d.ts.map +1 -0
  43. package/dist/types.d.ts +238 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/views/ActivityListView.d.ts +3 -0
  46. package/dist/views/ActivityListView.d.ts.map +1 -0
  47. package/dist/views/DashboardView.d.ts +9 -0
  48. package/dist/views/DashboardView.d.ts.map +1 -0
  49. package/dist/views/DealSidebar.d.ts +9 -0
  50. package/dist/views/DealSidebar.d.ts.map +1 -0
  51. package/dist/views/LeadDetailView.d.ts +8 -0
  52. package/dist/views/LeadDetailView.d.ts.map +1 -0
  53. package/dist/views/LeadFormView.d.ts +5 -0
  54. package/dist/views/LeadFormView.d.ts.map +1 -0
  55. package/dist/views/LeadListView.d.ts +6 -0
  56. package/dist/views/LeadListView.d.ts.map +1 -0
  57. package/dist/views/PipelineView.d.ts +8 -0
  58. package/dist/views/PipelineView.d.ts.map +1 -0
  59. package/dist/views/QuoteDetailView.d.ts +8 -0
  60. package/dist/views/QuoteDetailView.d.ts.map +1 -0
  61. package/dist/views/QuoteFormView.d.ts +7 -0
  62. package/dist/views/QuoteFormView.d.ts.map +1 -0
  63. package/dist/views/QuoteListView.d.ts +7 -0
  64. package/dist/views/QuoteListView.d.ts.map +1 -0
  65. package/dist/views/dashboardWidgets.d.ts +11 -0
  66. package/dist/views/dashboardWidgets.d.ts.map +1 -0
  67. package/package.json +55 -0
  68. package/src/CrmContext.tsx +30 -0
  69. package/src/CrmPage.tsx +152 -0
  70. package/src/README.md +97 -0
  71. package/src/cascade.ts +24 -0
  72. package/src/components/CrmGeneralSettings.tsx +36 -0
  73. package/src/components/CrmOnboarding.tsx +52 -0
  74. package/src/components/PipelineSettings.tsx +45 -0
  75. package/src/components/QuoteStatusDropdown.tsx +214 -0
  76. package/src/data/index.ts +2 -0
  77. package/src/data/mock.ts +426 -0
  78. package/src/data/supabase.ts +634 -0
  79. package/src/data/types.ts +50 -0
  80. package/src/index.ts +240 -0
  81. package/src/lib/tenant.ts +4 -0
  82. package/src/locales/en.ts +292 -0
  83. package/src/locales/index.ts +7 -0
  84. package/src/locales/pt-BR.ts +292 -0
  85. package/src/migrations/001_crm_base.sql +73 -0
  86. package/src/migrations/002_activities.sql +33 -0
  87. package/src/migrations/003_crm_views_rls.sql +61 -0
  88. package/src/migrations/004_seed_default_pipeline.sql +31 -0
  89. package/src/registries.ts +88 -0
  90. package/src/schema/index.ts +102 -0
  91. package/src/store.ts +375 -0
  92. package/src/types.ts +280 -0
  93. package/src/views/ActivityListView.tsx +183 -0
  94. package/src/views/DashboardView.tsx +12 -0
  95. package/src/views/DealSidebar.tsx +414 -0
  96. package/src/views/LeadDetailView.tsx +264 -0
  97. package/src/views/LeadFormView.tsx +56 -0
  98. package/src/views/LeadListView.tsx +81 -0
  99. package/src/views/PipelineView.tsx +299 -0
  100. package/src/views/QuoteDetailView.tsx +408 -0
  101. package/src/views/QuoteFormView.tsx +489 -0
  102. package/src/views/QuoteListView.tsx +101 -0
  103. package/src/views/dashboardWidgets.tsx +248 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,4601 @@
1
+ 'use strict';
2
+
3
+ var React15 = require('react');
4
+ var core = require('@fayz-ai/core');
5
+ var ui = require('@fayz-ai/ui');
6
+ var saas = require('@fayz-ai/saas');
7
+ var jsxRuntime = require('react/jsx-runtime');
8
+ var lucideReact = require('lucide-react');
9
+ var reactDom = require('react-dom');
10
+ var vanilla = require('zustand/vanilla');
11
+
12
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
13
+
14
+ var React15__default = /*#__PURE__*/_interopDefault(React15);
15
+
16
+ // src/index.ts
17
+ var ctx = saas.createPluginContext("CrmPage");
18
+ var CrmContextProvider = ctx.ContextProvider;
19
+ var useCrmConfig = ctx.useConfig;
20
+ var useCrmProvider = ctx.useProvider;
21
+ var useCrmStore = ctx.useStore;
22
+ function CrmGeneralSettings() {
23
+ const t2 = core.useTranslation();
24
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
25
+ /* @__PURE__ */ jsxRuntime.jsxs(saas.SettingsGroup, { title: t2("crm.settings.leadManagement"), description: t2("crm.settings.leadManagementDesc"), children: [
26
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.autoAssign"), description: t2("crm.settings.autoAssignDesc"), checked: false, onChange: () => {
27
+ } }),
28
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.requireSource"), description: t2("crm.settings.requireSourceDesc"), checked: true, onChange: () => {
29
+ } }),
30
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.leadScoring"), description: t2("crm.settings.leadScoringDesc"), checked: false, onChange: () => {
31
+ } }),
32
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.duplicateDetection"), description: t2("crm.settings.duplicateDetectionDesc"), checked: true, onChange: () => {
33
+ } })
34
+ ] }),
35
+ /* @__PURE__ */ jsxRuntime.jsxs(saas.SettingsGroup, { title: t2("crm.settings.deals"), description: t2("crm.settings.dealsDesc"), children: [
36
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.autoCreateDeal"), description: t2("crm.settings.autoCreateDealDesc"), checked: true, onChange: () => {
37
+ } }),
38
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.requireCloseDate"), description: t2("crm.settings.requireCloseDateDesc"), checked: false, onChange: () => {
39
+ } }),
40
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.rottingDeals"), description: t2("crm.settings.rottingDealsDesc"), checked: true, onChange: () => {
41
+ } }),
42
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.weightedPipeline"), description: t2("crm.settings.weightedPipelineDesc"), checked: true, onChange: () => {
43
+ } })
44
+ ] }),
45
+ /* @__PURE__ */ jsxRuntime.jsxs(saas.SettingsGroup, { title: t2("crm.settings.quotes"), description: t2("crm.settings.quotesDesc"), children: [
46
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.autoNumberQuotes"), description: t2("crm.settings.autoNumberQuotesDesc"), checked: true, onChange: () => {
47
+ } }),
48
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.defaultValidity"), description: t2("crm.settings.defaultValidityDesc"), checked: true, onChange: () => {
49
+ } }),
50
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.requireApproval"), description: t2("crm.settings.requireApprovalDesc"), checked: false, onChange: () => {
51
+ } })
52
+ ] }),
53
+ /* @__PURE__ */ jsxRuntime.jsxs(saas.SettingsGroup, { title: t2("crm.settings.notifications"), description: t2("crm.settings.notificationsDesc"), children: [
54
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.overdueAlerts"), description: t2("crm.settings.overdueAlertsDesc"), checked: true, onChange: () => {
55
+ } }),
56
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.stageChangeAlerts"), description: t2("crm.settings.stageChangeAlertsDesc"), checked: false, onChange: () => {
57
+ } }),
58
+ /* @__PURE__ */ jsxRuntime.jsx(saas.ToggleRow, { label: t2("crm.settings.newLeadNotif"), description: t2("crm.settings.newLeadNotifDesc"), checked: true, onChange: () => {
59
+ } })
60
+ ] })
61
+ ] });
62
+ }
63
+ function PipelineSettings() {
64
+ const t2 = core.useTranslation();
65
+ const stages = useCrmStore((s) => s.stages);
66
+ useCrmStore((s) => s.pipelines);
67
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
68
+ React15.useEffect(() => {
69
+ fetchPipelines();
70
+ }, []);
71
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
72
+ /* @__PURE__ */ jsxRuntime.jsx(saas.SettingsGroup, { title: t2("crm.pipelineSettings.title"), description: t2("crm.pipelineSettings.description"), children: stages.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: "py-6 text-center text-sm text-muted-foreground", children: t2("common.loading") }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-0", children: stages.map((stage, i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 py-3", children: [
73
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground w-5 shrink-0", children: i + 1 }),
74
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-3 rounded-full shrink-0", style: { backgroundColor: stage.color } }),
75
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
76
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium", children: stage.name }),
77
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-[10px] text-muted-foreground", children: [
78
+ t2("crm.pipelineSettings.probability"),
79
+ ": ",
80
+ stage.probability,
81
+ "%",
82
+ stage.isWon && ` \u2014 ${t2("crm.pipelineSettings.winStage")}`,
83
+ stage.isLost && ` \u2014 ${t2("crm.pipelineSettings.lossStage")}`
84
+ ] })
85
+ ] }),
86
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-muted-foreground", children: [
87
+ stage.probability,
88
+ "%"
89
+ ] })
90
+ ] }, stage.id)) }) }),
91
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground px-1", children: t2("crm.pipelineSettings.customizationNote") })
92
+ ] });
93
+ }
94
+ var STEPS = [
95
+ { id: "welcome", icon: lucideReact.Filter, titleKey: "crm.onboarding.welcome", descKey: "crm.onboarding.description" },
96
+ { id: "sources", icon: lucideReact.Globe, titleKey: "crm.onboarding.sources.title", descKey: "crm.onboarding.sources.description" },
97
+ { id: "pipeline", icon: lucideReact.Target, titleKey: "crm.onboarding.pipeline.title", descKey: "crm.onboarding.pipeline.description" }
98
+ ];
99
+ function CrmOnboarding({ onComplete }) {
100
+ const t2 = core.useTranslation();
101
+ const [step, setStep] = React15.useState(0);
102
+ const current = STEPS[step];
103
+ const isLast = step === STEPS.length - 1;
104
+ const Icon = current.icon;
105
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-center py-12", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-full max-w-lg", children: [
106
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-1 mb-8", children: STEPS.map((_, i) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: `h-1 flex-1 rounded-full transition-colors ${i <= step ? "bg-primary" : "bg-muted"}` }, i)) }),
107
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-card border bg-card p-8 text-center space-y-6 shadow-sm", children: [
108
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-center", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-16 w-16 items-center justify-center rounded-2xl bg-primary/10", children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-8 w-8 text-primary" }) }) }),
109
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
110
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-xl font-bold", children: t2(current.titleKey) }),
111
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground mt-2 max-w-sm mx-auto", children: t2(current.descKey) })
112
+ ] }),
113
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-3 pt-2", children: [
114
+ step > 0 && /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { variant: "outline", size: "lg", onClick: () => setStep(step - 1), children: t2("common.back") }),
115
+ isLast ? /* @__PURE__ */ jsxRuntime.jsxs(ui.Button, { variant: "default", size: "lg", onClick: onComplete, children: [
116
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-4 w-4" }),
117
+ " ",
118
+ t2("crm.onboarding.startSelling")
119
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs(ui.Button, { variant: "default", size: "lg", onClick: () => setStep(step + 1), children: [
120
+ step === 0 ? t2("crm.onboarding.getStarted") : t2("crm.onboarding.next"),
121
+ " ",
122
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronRight, { className: "h-4 w-4" })
123
+ ] })
124
+ ] }),
125
+ step === 0 && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onComplete, className: "text-xs text-muted-foreground hover:text-foreground transition-colors", children: t2("crm.onboarding.skip") })
126
+ ] })
127
+ ] }) });
128
+ }
129
+ function DashboardView() {
130
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.DashboardCanvas, { surface: "plugin-home", domain: "crm", showHeader: false, className: "space-y-6" });
131
+ }
132
+ var STATUS_CONFIG = {
133
+ draft: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: lucideReact.CircleDashed, label: "Draft" },
134
+ sent: { bg: "bg-info-soft text-info-soft-foreground", dot: "bg-info", icon: lucideReact.Send, label: "Sent" },
135
+ approved: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: lucideReact.CircleCheckBig, label: "Approved" },
136
+ rejected: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: lucideReact.Ban, label: "Rejected" },
137
+ expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: lucideReact.CircleAlert, label: "Expired" }
138
+ };
139
+ var TRANSITIONS = {
140
+ draft: ["sent", "expired"],
141
+ sent: ["approved", "rejected", "expired"],
142
+ approved: [],
143
+ rejected: [],
144
+ expired: []
145
+ };
146
+ function RejectModal({ onConfirm, onCancel }) {
147
+ const [reason, setReason] = React15.useState("");
148
+ return reactDom.createPortal(
149
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "fixed inset-0 z-[60] flex items-center justify-center bg-black/50", onClick: onCancel, children: /* @__PURE__ */ jsxRuntime.jsxs(
150
+ "div",
151
+ {
152
+ className: "w-full max-w-sm rounded-modal border bg-card shadow-lg mx-4 p-5",
153
+ onClick: (e) => e.stopPropagation(),
154
+ style: { animation: "saas-sheet-fade-in 150ms ease-out" },
155
+ children: [
156
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mb-3", children: [
157
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: "Reject Quote" }),
158
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground mt-0.5", children: "Provide a reason for the rejection." })
159
+ ] }),
160
+ /* @__PURE__ */ jsxRuntime.jsx(
161
+ "textarea",
162
+ {
163
+ value: reason,
164
+ onChange: (e) => setReason(e.target.value),
165
+ rows: 3,
166
+ placeholder: "Reason for rejection...",
167
+ autoFocus: true,
168
+ className: "w-full rounded-input border border-input bg-card px-3 py-2 text-sm shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] focus:outline-none focus:ring-2 focus:ring-ring resize-none"
169
+ }
170
+ ),
171
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-end gap-2 mt-3", children: [
172
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { variant: "outline", size: "sm", onClick: onCancel, children: "Cancel" }),
173
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { variant: "destructive", size: "sm", onClick: () => onConfirm(reason), disabled: !reason.trim(), children: "Reject Quote" })
174
+ ] })
175
+ ]
176
+ }
177
+ ) }),
178
+ document.body
179
+ );
180
+ }
181
+ function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
182
+ const sendQuote = useCrmStore((s) => s.sendQuote);
183
+ const approveQuote = useCrmStore((s) => s.approveQuote);
184
+ const rejectQuote = useCrmStore((s) => s.rejectQuote);
185
+ const expireQuote = useCrmStore((s) => s.expireQuote);
186
+ const [loading, setLoading] = React15.useState(false);
187
+ const [showApprove, setShowApprove] = React15.useState(false);
188
+ const [showReject, setShowReject] = React15.useState(false);
189
+ const config = STATUS_CONFIG[quote.status] ?? STATUS_CONFIG.draft;
190
+ const StatusIcon = config.icon;
191
+ const transitions = TRANSITIONS[quote.status] ?? [];
192
+ async function handleTransition(target) {
193
+ if (loading) return;
194
+ setLoading(true);
195
+ try {
196
+ let updated;
197
+ switch (target) {
198
+ case "sent":
199
+ updated = await sendQuote(quote.id);
200
+ break;
201
+ case "approved":
202
+ setShowApprove(true);
203
+ setLoading(false);
204
+ return;
205
+ case "expired":
206
+ updated = await expireQuote(quote.id);
207
+ break;
208
+ default:
209
+ setLoading(false);
210
+ return;
211
+ }
212
+ onStatusChange?.(updated);
213
+ } catch {
214
+ } finally {
215
+ setLoading(false);
216
+ }
217
+ }
218
+ async function handleReject(reason) {
219
+ setShowReject(false);
220
+ setLoading(true);
221
+ try {
222
+ const updated = await rejectQuote(quote.id, reason);
223
+ onStatusChange?.(updated);
224
+ } catch {
225
+ } finally {
226
+ setLoading(false);
227
+ }
228
+ }
229
+ const isSmall = size === "sm";
230
+ if (transitions.length === 0) {
231
+ return /* @__PURE__ */ jsxRuntime.jsxs("span", { className: `inline-flex items-center gap-1 rounded-full font-medium capitalize ${config.bg} ${isSmall ? "px-1.5 py-0.5 text-[9px]" : "px-2.5 py-1 text-[11px]"}`, children: [
232
+ !isSmall && /* @__PURE__ */ jsxRuntime.jsx(StatusIcon, { className: "h-3 w-3" }),
233
+ config.label
234
+ ] });
235
+ }
236
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
237
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.Dropdown, { children: [
238
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs(
239
+ "button",
240
+ {
241
+ onClick: (e) => e.stopPropagation(),
242
+ disabled: loading,
243
+ className: `inline-flex items-center gap-1 rounded-full font-medium capitalize transition-all ${config.bg} ${isSmall ? "px-1.5 py-0.5 text-[9px]" : "px-2.5 py-1 text-[11px]"} hover:ring-2 hover:ring-primary/20 focus:outline-none focus:ring-2 focus:ring-ring`,
244
+ children: [
245
+ !isSmall && /* @__PURE__ */ jsxRuntime.jsx(StatusIcon, { className: "h-3 w-3" }),
246
+ config.label,
247
+ loading ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: `animate-spin ${isSmall ? "h-2.5 w-2.5" : "h-3 w-3"}` }) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronDown, { className: `opacity-50 ${isSmall ? "h-2.5 w-2.5" : "h-3 w-3"}` })
248
+ ]
249
+ }
250
+ ) }),
251
+ /* @__PURE__ */ jsxRuntime.jsxs(ui.DropdownContent, { align: "end", sideOffset: 4, onClick: (e) => e.stopPropagation(), children: [
252
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownLabel, { children: "Change status" }),
253
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DropdownSeparator, {}),
254
+ transitions.map((target) => {
255
+ const t2 = STATUS_CONFIG[target];
256
+ const TargetIcon = t2.icon;
257
+ return /* @__PURE__ */ jsxRuntime.jsxs(
258
+ ui.DropdownItem,
259
+ {
260
+ onClick: () => target === "rejected" ? setShowReject(true) : handleTransition(target),
261
+ className: "gap-2.5",
262
+ children: [
263
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: `h-2 w-2 rounded-full shrink-0 ${t2.dot}` }),
264
+ /* @__PURE__ */ jsxRuntime.jsx(TargetIcon, { className: "h-3.5 w-3.5 shrink-0" }),
265
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: t2.label })
266
+ ]
267
+ },
268
+ target
269
+ );
270
+ })
271
+ ] })
272
+ ] }),
273
+ /* @__PURE__ */ jsxRuntime.jsx(
274
+ ui.ConfirmDialog,
275
+ {
276
+ open: showApprove,
277
+ variant: "success",
278
+ title: "Approve this quote?",
279
+ description: "This will create an invoice and convert the lead to a client. This action cannot be undone.",
280
+ confirmLabel: "Approve",
281
+ cancelLabel: "Cancel",
282
+ loading,
283
+ onConfirm: async () => {
284
+ setLoading(true);
285
+ try {
286
+ const updated = await approveQuote(quote.id);
287
+ setShowApprove(false);
288
+ onStatusChange?.(updated);
289
+ } catch {
290
+ } finally {
291
+ setLoading(false);
292
+ }
293
+ },
294
+ onCancel: () => setShowApprove(false)
295
+ }
296
+ ),
297
+ showReject && /* @__PURE__ */ jsxRuntime.jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
298
+ ] });
299
+ }
300
+ var TYPE_ICONS = {
301
+ call: lucideReact.Phone,
302
+ email: lucideReact.Mail,
303
+ meeting: lucideReact.Users,
304
+ note: lucideReact.FileText,
305
+ task: lucideReact.CheckSquare,
306
+ whatsapp: lucideReact.MessageCircle
307
+ };
308
+ function TabBar({ active, counts, onChange }) {
309
+ const t2 = core.useTranslation();
310
+ const tabs = [
311
+ { id: "overview", label: t2("crm.dealSidebar.overview") },
312
+ { id: "activity", label: t2("crm.dealSidebar.activity"), count: counts.activity },
313
+ { id: "quotes", label: t2("crm.dealSidebar.quotes"), count: counts.quotes }
314
+ ];
315
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center gap-0.5 px-5 py-2 border-b shrink-0 bg-muted/20", children: tabs.map((tab) => /* @__PURE__ */ jsxRuntime.jsxs(
316
+ "button",
317
+ {
318
+ onClick: () => onChange(tab.id),
319
+ className: `relative px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${active === tab.id ? "bg-card text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground"}`,
320
+ children: [
321
+ tab.label,
322
+ tab.count != null && tab.count > 0 && /* @__PURE__ */ jsxRuntime.jsx("span", { className: `ml-1 inline-flex items-center justify-center min-w-[16px] h-4 rounded-full px-1 text-[10px] font-semibold ${active === tab.id ? "bg-primary/10 text-primary" : "bg-muted text-muted-foreground"}`, children: tab.count })
323
+ ]
324
+ },
325
+ tab.id
326
+ )) });
327
+ }
328
+ function OverviewTab({ deal, lead, currency }) {
329
+ const t2 = core.useTranslation();
330
+ const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase();
331
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
332
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3.5", children: [
333
+ /* @__PURE__ */ jsxRuntime.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 }),
334
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-0 flex-1", children: [
335
+ /* @__PURE__ */ jsxRuntime.jsx(
336
+ saas.PersonLink,
337
+ {
338
+ personId: lead?.id ?? deal.contactId,
339
+ name: lead?.name ?? deal.contactName ?? deal.title,
340
+ size: "default",
341
+ className: "text-base"
342
+ }
343
+ ),
344
+ lead && (lead.email || lead.phone) && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground truncate", children: lead.email || lead.phone }),
345
+ lead?.company && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[11px] text-muted-foreground", children: lead.company })
346
+ ] })
347
+ ] }),
348
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-xl border divide-y", children: [
349
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
350
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.DollarSign, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
351
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.value") }),
352
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-bold", children: saas.formatCurrency(deal.value, currency) })
353
+ ] }),
354
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
355
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Target, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
356
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.probability") }),
357
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-sm font-semibold", children: [
358
+ deal.probability,
359
+ "%"
360
+ ] })
361
+ ] }),
362
+ deal.stageName && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
363
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-4 flex items-center justify-center shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2.5 w-2.5 rounded-full", style: { backgroundColor: deal.stageColor } }) }),
364
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.stage") }),
365
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-medium", children: deal.stageName })
366
+ ] }),
367
+ deal.expectedCloseDate && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
368
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Calendar, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
369
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.expectedClose") }),
370
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs font-medium", children: deal.expectedCloseDate })
371
+ ] }),
372
+ deal.assignedToName && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 px-4 py-3", children: [
373
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.User, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
374
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground flex-1", children: t2("crm.dealSidebar.assignedTo") }),
375
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs font-medium", children: deal.assignedToName })
376
+ ] })
377
+ ] }),
378
+ lead && (lead.email || lead.phone) && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
379
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.contact") }),
380
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-xl border divide-y", children: [
381
+ lead.email && /* @__PURE__ */ jsxRuntime.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: [
382
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Mail, { className: "h-3.5 w-3.5 shrink-0" }),
383
+ " ",
384
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "truncate", children: lead.email })
385
+ ] }),
386
+ lead.phone && /* @__PURE__ */ jsxRuntime.jsxs("a", { href: `tel:${lead.phone}`, className: "flex items-center gap-3 px-4 py-2.5 text-xs text-primary hover:bg-muted/30 transition-colors", children: [
387
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Phone, { className: "h-3.5 w-3.5 shrink-0" }),
388
+ " ",
389
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: lead.phone })
390
+ ] })
391
+ ] })
392
+ ] }),
393
+ deal.tags && deal.tags.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
394
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.tags") }),
395
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-1.5 flex-wrap", children: deal.tags.map((tag) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) })
396
+ ] }),
397
+ deal.notes && deal.notes !== deal.title && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
398
+ /* @__PURE__ */ jsxRuntime.jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
399
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap leading-relaxed", children: deal.notes })
400
+ ] }),
401
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-4 pt-3 border-t text-[10px] text-muted-foreground", children: [
402
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
403
+ t2("crm.dealSidebar.created"),
404
+ " ",
405
+ deal.createdAt?.slice(0, 10)
406
+ ] }),
407
+ deal.updatedAt && /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
408
+ t2("crm.dealSidebar.updated"),
409
+ " ",
410
+ deal.updatedAt?.slice(0, 10)
411
+ ] })
412
+ ] })
413
+ ] });
414
+ }
415
+ function ActivityTab({ activities, loading }) {
416
+ const t2 = core.useTranslation();
417
+ if (loading) {
418
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
419
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-8 w-8 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
420
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 space-y-1.5 pt-0.5", children: [
421
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3.5 w-2/3 rounded bg-muted/40 animate-pulse" }),
422
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2.5 w-1/3 rounded bg-muted/30 animate-pulse" })
423
+ ] })
424
+ ] }, i)) });
425
+ }
426
+ if (activities.length === 0) {
427
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [
428
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-muted/30 mb-3", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Clock, { className: "h-5 w-5 text-muted-foreground/40" }) }),
429
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.noActivities") }),
430
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground/60 mt-0.5", children: t2("crm.dealSidebar.activitiesAppear") })
431
+ ] });
432
+ }
433
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-1", children: activities.map((a, i) => {
434
+ const Icon = TYPE_ICONS[a.activityType] ?? lucideReact.FileText;
435
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3 rounded-lg px-2 py-2.5 hover:bg-muted/20 transition-colors", children: [
436
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-8 w-8 items-center justify-center rounded-lg bg-muted shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-3.5 w-3.5 text-muted-foreground" }) }),
437
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
438
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
439
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium truncate", children: a.title }),
440
+ a.completedAt && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-3 w-3 text-success shrink-0" })
441
+ ] }),
442
+ a.description && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[11px] text-muted-foreground mt-0.5 line-clamp-2", children: a.description }),
443
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-[10px] text-muted-foreground/50 mt-1 capitalize", children: [
444
+ a.activityType,
445
+ " \xB7 ",
446
+ new Date(a.createdAt).toLocaleDateString()
447
+ ] })
448
+ ] })
449
+ ] }, a.id);
450
+ }) });
451
+ }
452
+ function QuotesTab({ quotes, loading, currency, onViewQuote, onQuoteUpdated }) {
453
+ const t2 = core.useTranslation();
454
+ if (loading) {
455
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: [1, 2].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-xl border p-4 space-y-2.5", children: [
456
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3.5 w-20 rounded bg-muted/40 animate-pulse" }),
457
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-28 rounded bg-muted/30 animate-pulse" })
458
+ ] }, i)) });
459
+ }
460
+ if (quotes.length === 0) {
461
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: [
462
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-muted/30 mb-3", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-5 w-5 text-muted-foreground/40" }) }),
463
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.noQuotes") }),
464
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground/60 mt-0.5", children: t2("crm.dealSidebar.quotesAppear") })
465
+ ] });
466
+ }
467
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: quotes.map((q) => /* @__PURE__ */ jsxRuntime.jsxs(
468
+ "button",
469
+ {
470
+ onClick: () => onViewQuote?.(q.id),
471
+ className: "w-full text-left rounded-xl border p-4 hover:bg-muted/20 hover:shadow-sm transition-all group",
472
+ children: [
473
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", onClick: (e) => e.stopPropagation(), children: [
474
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-semibold", children: q.quoteNumber }),
475
+ /* @__PURE__ */ jsxRuntime.jsx(QuoteStatusDropdown, { quote: q, size: "sm", onStatusChange: onQuoteUpdated })
476
+ ] }),
477
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between mt-2", children: [
478
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[11px] text-muted-foreground", children: q.quoteDate }),
479
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-bold", children: saas.formatCurrency(q.totalAmount, currency) })
480
+ ] }),
481
+ q.contactName && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground mt-1.5 truncate", children: q.contactName })
482
+ ]
483
+ },
484
+ q.id
485
+ )) });
486
+ }
487
+ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
488
+ const t2 = core.useTranslation();
489
+ const provider = useCrmProvider();
490
+ const { currency } = useCrmConfig();
491
+ const [deal, setDeal] = React15.useState(null);
492
+ const [lead, setLead] = React15.useState(null);
493
+ const [activities, setActivities] = React15.useState([]);
494
+ const [quotes, setQuotes] = React15.useState([]);
495
+ const [loading, setLoading] = React15.useState(true);
496
+ const [activitiesLoading, setActivitiesLoading] = React15.useState(true);
497
+ const [quotesLoading, setQuotesLoading] = React15.useState(true);
498
+ const [activeTab, setActiveTab] = React15.useState("overview");
499
+ React15.useEffect(() => {
500
+ if (!open) return;
501
+ setLoading(true);
502
+ setActivitiesLoading(true);
503
+ setQuotesLoading(true);
504
+ setActiveTab("overview");
505
+ setLead(null);
506
+ setActivities([]);
507
+ setQuotes([]);
508
+ provider.getDealById(dealId).then(async (d) => {
509
+ setDeal(d);
510
+ if (d?.leadId) {
511
+ const l = await provider.getLeadById(d.leadId);
512
+ setLead(l);
513
+ }
514
+ setLoading(false);
515
+ });
516
+ provider.getActivities({ dealId }).then((r) => {
517
+ setActivities(r.data);
518
+ setActivitiesLoading(false);
519
+ });
520
+ provider.getQuotesByDealId(dealId).then((q) => {
521
+ setQuotes(q);
522
+ setQuotesLoading(false);
523
+ });
524
+ }, [dealId, open]);
525
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.Sheet, { open, onOpenChange: (v) => {
526
+ if (!v) onClose();
527
+ }, children: /* @__PURE__ */ jsxRuntime.jsxs(ui.SheetContent, { width: "max-w-md", children: [
528
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SheetHeader, { children: loading ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5 pr-8", children: [
529
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-40 rounded bg-muted/40 animate-pulse" }),
530
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
531
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "pr-8", children: [
532
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SheetTitle, { children: deal?.title ?? t2("crm.dealSidebar.deal") }),
533
+ deal?.contactName && /* @__PURE__ */ jsxRuntime.jsx(ui.SheetDescription, { children: deal.contactName })
534
+ ] }) }),
535
+ /* @__PURE__ */ jsxRuntime.jsx(
536
+ TabBar,
537
+ {
538
+ active: activeTab,
539
+ counts: { activity: activities.length, quotes: quotes.length },
540
+ onChange: setActiveTab
541
+ }
542
+ ),
543
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SheetBody, { children: loading ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
544
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3.5", children: [
545
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-14 w-14 rounded-2xl bg-muted/40 animate-pulse" }),
546
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2 flex-1", children: [
547
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-32 rounded bg-muted/40 animate-pulse" }),
548
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-24 rounded bg-muted/30 animate-pulse" })
549
+ ] })
550
+ ] }),
551
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border divide-y", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between px-4 py-3", children: [
552
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-20 rounded bg-muted/30 animate-pulse" }),
553
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-24 rounded bg-muted/40 animate-pulse" })
554
+ ] }, i)) })
555
+ ] }) : deal ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
556
+ activeTab === "overview" && /* @__PURE__ */ jsxRuntime.jsx(OverviewTab, { deal, lead, currency }),
557
+ activeTab === "activity" && /* @__PURE__ */ jsxRuntime.jsx(ActivityTab, { activities, loading: activitiesLoading }),
558
+ activeTab === "quotes" && /* @__PURE__ */ jsxRuntime.jsx(QuotesTab, { quotes, loading: quotesLoading, currency, onViewQuote: (id) => {
559
+ onViewQuote?.(id);
560
+ onClose();
561
+ }, onQuoteUpdated: (updated) => setQuotes(quotes.map((q) => q.id === updated.id ? updated : q)) })
562
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex flex-col items-center justify-center py-12 text-center", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.dealSidebar.dealNotFound") }) }) }),
563
+ deal && lead && onViewLead && /* @__PURE__ */ jsxRuntime.jsx(ui.SheetFooter, { children: /* @__PURE__ */ jsxRuntime.jsxs(
564
+ "button",
565
+ {
566
+ onClick: () => {
567
+ onViewLead(lead.id);
568
+ onClose();
569
+ },
570
+ 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",
571
+ children: [
572
+ t2("crm.dealSidebar.viewLeadProfile"),
573
+ " ",
574
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ArrowRight, { className: "h-3 w-3" })
575
+ ]
576
+ }
577
+ ) })
578
+ ] }) });
579
+ }
580
+ function PipelineSkeleton() {
581
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: [1, 2, 3, 4, 5].map((col) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-[240px] max-w-[280px] flex-shrink-0", children: [
582
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 mb-2 px-1", children: [
583
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full bg-muted/40 animate-pulse" }),
584
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/40 animate-pulse" }),
585
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-5 rounded bg-muted/30 animate-pulse" })
586
+ ] }),
587
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: Array.from({ length: col <= 2 ? 2 : 1 }).map((_, i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-lg border bg-card shadow-sm p-3 space-y-2", children: [
588
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-3/4 rounded bg-muted/40 animate-pulse" }),
589
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-1/2 rounded bg-muted/30 animate-pulse" }),
590
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between pt-1", children: [
591
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/40 animate-pulse" }),
592
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-8 rounded bg-muted/30 animate-pulse" })
593
+ ] })
594
+ ] }, i)) })
595
+ ] }, col)) });
596
+ }
597
+ function DealCard({ deal, saving, currency, onClick, onDragStart, onDragEnd }) {
598
+ return /* @__PURE__ */ jsxRuntime.jsxs(
599
+ "div",
600
+ {
601
+ draggable: !saving,
602
+ onDragStart,
603
+ onDragEnd,
604
+ onClick,
605
+ className: `rounded-lg border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
606
+ children: [
607
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between gap-2", children: [
608
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium truncate", children: deal.title }),
609
+ saving && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" })
610
+ ] }),
611
+ deal.contactName && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground mt-0.5", children: deal.contactName }),
612
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between mt-2", children: [
613
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs font-semibold", children: saas.formatCurrency(deal.value, currency) }),
614
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-[10px] text-muted-foreground", children: [
615
+ deal.probability,
616
+ "%"
617
+ ] })
618
+ ] })
619
+ ]
620
+ }
621
+ );
622
+ }
623
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
624
+ const t2 = core.useTranslation();
625
+ const isOver = dragOverStageId === stageId;
626
+ const [hovered, setHovered] = React15.useState(false);
627
+ return /* @__PURE__ */ jsxRuntime.jsxs(
628
+ "div",
629
+ {
630
+ className: "min-w-[240px] max-w-[280px] flex-shrink-0 flex flex-col",
631
+ onMouseEnter: () => setHovered(true),
632
+ onMouseLeave: () => setHovered(false),
633
+ children: [
634
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 mb-2 px-1", children: [
635
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-2 rounded-full shrink-0", style: { backgroundColor: stageColor } }),
636
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs font-semibold", children: stageName }),
637
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-[10px] text-muted-foreground", children: [
638
+ "(",
639
+ deals.length,
640
+ ")"
641
+ ] }),
642
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1" }),
643
+ onAddLead && /* @__PURE__ */ jsxRuntime.jsx(
644
+ "button",
645
+ {
646
+ onClick: onAddLead,
647
+ className: `flex h-5 w-5 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground transition-all ${hovered ? "opacity-100" : "opacity-0"}`,
648
+ title: "Add lead",
649
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Plus, { className: "h-3.5 w-3.5" })
650
+ }
651
+ )
652
+ ] }),
653
+ /* @__PURE__ */ jsxRuntime.jsx(
654
+ "div",
655
+ {
656
+ onDragOver,
657
+ onDragLeave,
658
+ onDrop,
659
+ className: `flex-1 space-y-2 rounded-lg p-1 transition-colors min-h-[80px] ${isOver ? "bg-primary/5 ring-2 ring-primary/20 ring-inset" : ""}`,
660
+ children: deals.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx("div", { className: `rounded-lg border border-dashed p-4 text-center text-xs text-muted-foreground ${isOver ? "border-primary/30" : ""}`, children: isOver ? t2("crm.pipeline.dropHere") : t2("crm.pipeline.noDeals") }) : deals.map((deal) => /* @__PURE__ */ jsxRuntime.jsx(
661
+ DealCard,
662
+ {
663
+ deal,
664
+ saving: savingDealIds.has(deal.id),
665
+ currency,
666
+ onClick: () => onDealClick?.(deal.id),
667
+ onDragStart: (e) => {
668
+ e.dataTransfer.effectAllowed = "move";
669
+ onDragStart(deal.id, stageId);
670
+ },
671
+ onDragEnd
672
+ },
673
+ deal.id
674
+ ))
675
+ }
676
+ )
677
+ ]
678
+ }
679
+ );
680
+ }
681
+ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
682
+ const { currency } = useCrmConfig();
683
+ const pipelines = useCrmStore((s) => s.pipelines);
684
+ const stages = useCrmStore((s) => s.stages);
685
+ const dealsByStage = useCrmStore((s) => s.dealsByStage);
686
+ const dealsLoading = useCrmStore((s) => s.dealsLoading);
687
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
688
+ const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage);
689
+ const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
690
+ const [dragOverStageId, setDragOverStageId] = React15.useState(null);
691
+ const [savingDealIds, setSavingDealIds] = React15.useState(/* @__PURE__ */ new Set());
692
+ const [optimisticBoard, setOptimisticBoard] = React15.useState(null);
693
+ const t2 = core.useTranslation();
694
+ const [selectedDealId, setSelectedDealId] = React15.useState(null);
695
+ const dragRef = React15.useRef(null);
696
+ React15.useEffect(() => {
697
+ fetchPipelines();
698
+ }, []);
699
+ React15.useEffect(() => {
700
+ if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id);
701
+ }, [pipelines]);
702
+ React15.useEffect(() => {
703
+ if (savingDealIds.size === 0) setOptimisticBoard(null);
704
+ }, [dealsByStage, savingDealIds]);
705
+ const visibleStages = stages.filter((s) => !s.isLost);
706
+ const displayBoard = optimisticBoard ?? dealsByStage;
707
+ function handleDragStart(dealId, fromStageId) {
708
+ dragRef.current = { dealId, fromStageId };
709
+ }
710
+ function handleDragEnd() {
711
+ dragRef.current = null;
712
+ setDragOverStageId(null);
713
+ }
714
+ function handleDragOver(stageId, e) {
715
+ e.preventDefault();
716
+ e.dataTransfer.dropEffect = "move";
717
+ if (dragOverStageId !== stageId) setDragOverStageId(stageId);
718
+ }
719
+ function handleDrop(toStageId) {
720
+ const drag = dragRef.current;
721
+ if (!drag) return;
722
+ dragRef.current = null;
723
+ setDragOverStageId(null);
724
+ if (drag.fromStageId === toStageId) return;
725
+ const { dealId, fromStageId } = drag;
726
+ const targetStage = stages.find((s) => s.id === toStageId);
727
+ const currentBoard = optimisticBoard ?? dealsByStage;
728
+ const nextBoard = new Map(currentBoard);
729
+ const fromDeals = [...nextBoard.get(fromStageId) ?? []];
730
+ const movedDeal = fromDeals.find((d) => d.id === dealId);
731
+ if (!movedDeal) return;
732
+ const updatedDeal = {
733
+ ...movedDeal,
734
+ stageId: toStageId,
735
+ stageName: targetStage?.name,
736
+ stageColor: targetStage?.color,
737
+ probability: targetStage?.probability ?? movedDeal.probability
738
+ };
739
+ nextBoard.set(fromStageId, fromDeals.filter((d) => d.id !== dealId));
740
+ nextBoard.set(toStageId, [...nextBoard.get(toStageId) ?? [], updatedDeal]);
741
+ setOptimisticBoard(nextBoard);
742
+ setSavingDealIds((prev) => new Set(prev).add(dealId));
743
+ moveDealToStage(dealId, toStageId).then(() => {
744
+ ui.toast.success(t2("crm.pipeline.movedTo", { stage: targetStage?.name ?? "stage" }));
745
+ }).catch(() => {
746
+ setOptimisticBoard(null);
747
+ ui.toast.error(t2("crm.pipeline.moveFailed"));
748
+ }).finally(() => {
749
+ setSavingDealIds((prev) => {
750
+ const next = new Set(prev);
751
+ next.delete(dealId);
752
+ return next;
753
+ });
754
+ });
755
+ }
756
+ function handleDealClick(dealId) {
757
+ setSelectedDealId(dealId);
758
+ onDealClick?.(dealId);
759
+ }
760
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
761
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: t2("crm.pipeline.title"), subtitle: t2("crm.pipeline.subtitle") }),
762
+ dealsLoading && dealsByStage.size === 0 ? /* @__PURE__ */ jsxRuntime.jsx(PipelineSkeleton, {}) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: visibleStages.map((stage) => {
763
+ const deals = displayBoard.get(stage.id) ?? [];
764
+ return /* @__PURE__ */ jsxRuntime.jsx(
765
+ StageColumn,
766
+ {
767
+ stageId: stage.id,
768
+ stageName: stage.name,
769
+ stageColor: stage.color,
770
+ deals,
771
+ savingDealIds,
772
+ currency,
773
+ dragOverStageId,
774
+ onDealClick: handleDealClick,
775
+ onAddLead,
776
+ onDragStart: handleDragStart,
777
+ onDragEnd: handleDragEnd,
778
+ onDragOver: (e) => handleDragOver(stage.id, e),
779
+ onDragLeave: () => {
780
+ if (dragOverStageId === stage.id) setDragOverStageId(null);
781
+ },
782
+ onDrop: () => handleDrop(stage.id)
783
+ },
784
+ stage.id
785
+ );
786
+ }) }),
787
+ /* @__PURE__ */ jsxRuntime.jsx(
788
+ DealSidebar,
789
+ {
790
+ dealId: selectedDealId ?? "",
791
+ open: !!selectedDealId,
792
+ onClose: () => setSelectedDealId(null),
793
+ onViewLead,
794
+ onViewQuote
795
+ }
796
+ )
797
+ ] });
798
+ }
799
+ var STATUS_OPTIONS = [
800
+ { value: "new", label: "New", color: "bg-info-soft text-info-soft-foreground" },
801
+ { value: "contacted", label: "Contacted", color: "bg-magic-soft text-magic-soft-foreground" },
802
+ { value: "qualified", label: "Qualified", color: "bg-success-soft text-success-soft-foreground" },
803
+ { value: "unqualified", label: "Unqualified", color: "bg-muted text-muted-foreground" },
804
+ { value: "converted", label: "Converted", color: "bg-warning-soft text-warning-soft-foreground" }
805
+ ];
806
+ var columns = [
807
+ { accessorKey: "name", header: "Name", cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: getValue() }) },
808
+ {
809
+ id: "contact",
810
+ header: "Contact",
811
+ cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-xs", children: row.original.email || row.original.phone || "\u2014" })
812
+ },
813
+ {
814
+ accessorKey: "sourceName",
815
+ header: "Source",
816
+ cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-xs", children: getValue() || "\u2014" })
817
+ },
818
+ {
819
+ accessorKey: "status",
820
+ header: "Status",
821
+ cell: ({ getValue }) => {
822
+ const status = getValue();
823
+ const opt = STATUS_OPTIONS.find((o) => o.value === status);
824
+ return /* @__PURE__ */ jsxRuntime.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 });
825
+ }
826
+ }
827
+ ];
828
+ function LeadListView({ onNew, onEdit }) {
829
+ const t2 = core.useTranslation();
830
+ const leads = useCrmStore((s) => s.leads);
831
+ const leadsLoading = useCrmStore((s) => s.leadsLoading);
832
+ const fetchLeads = useCrmStore((s) => s.fetchLeads);
833
+ const [search, setSearch] = React15.useState("");
834
+ const [statusFilter, setStatusFilter] = React15.useState([]);
835
+ React15.useEffect(() => {
836
+ fetchLeads({ status: statusFilter.length > 0 ? statusFilter : void 0, search: search || void 0 });
837
+ }, [statusFilter, search]);
838
+ const tags = React15.useMemo(() => STATUS_OPTIONS.map((o) => ({ value: o.value, label: o.label })), []);
839
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
840
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: t2("crm.leads.title"), subtitle: `${leads.length} leads` }),
841
+ /* @__PURE__ */ jsxRuntime.jsx(
842
+ ui.ListView,
843
+ {
844
+ columns,
845
+ data: leads,
846
+ loading: leadsLoading,
847
+ searchPlaceholder: t2("crm.leads.searchPlaceholder"),
848
+ search,
849
+ onSearchChange: setSearch,
850
+ searchDebounce: 0,
851
+ tags,
852
+ activeTag: statusFilter.length === 1 ? statusFilter[0] : void 0,
853
+ onTagChange: (v) => setStatusFilter(v ? [v] : []),
854
+ newLabel: t2("crm.leads.newLead"),
855
+ onNew,
856
+ onRowClick: (row) => onEdit?.(row.id),
857
+ emptyIcon: lucideReact.UserPlus,
858
+ emptyMessage: t2("crm.leads.noLeads"),
859
+ emptyActionLabel: onNew ? t2("crm.leads.captureFirst") : void 0,
860
+ onEmptyAction: onNew
861
+ }
862
+ )
863
+ ] });
864
+ }
865
+ function LeadFormView({ onSaved }) {
866
+ const t2 = core.useTranslation();
867
+ const createLead = useCrmStore((s) => s.createLead);
868
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
869
+ const pipelines = useCrmStore((s) => s.pipelines);
870
+ React15.useEffect(() => {
871
+ if (pipelines.length === 0) fetchPipelines();
872
+ }, []);
873
+ const [name, setName] = React15.useState("");
874
+ const [email, setEmail] = React15.useState("");
875
+ const [phone, setPhone] = React15.useState("");
876
+ const [company, setCompany] = React15.useState("");
877
+ const [notes, setNotes] = React15.useState("");
878
+ const [saving, setSaving] = React15.useState(false);
879
+ async function handleSave() {
880
+ if (!name.trim()) {
881
+ ui.toast.error(t2("common.formIncomplete"));
882
+ return;
883
+ }
884
+ setSaving(true);
885
+ try {
886
+ const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0 });
887
+ onSaved?.(lead.id);
888
+ } finally {
889
+ setSaving(false);
890
+ }
891
+ }
892
+ const dirty = !!(name || email || phone || company || notes);
893
+ ui.useSaveBar({
894
+ dirty,
895
+ saving,
896
+ onSave: () => {
897
+ void handleSave();
898
+ },
899
+ onDiscard: () => onSaved?.(),
900
+ saveLabel: t2("crm.leadForm.save")
901
+ });
902
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
903
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: t2("crm.leadForm.title"), subtitle: t2("crm.leadForm.subtitle"), onBack: onSaved, parentLabel: t2("crm.leads.title") }),
904
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-lg border bg-card shadow-sm p-5 space-y-4", children: [
905
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
906
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
907
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.name") }),
908
+ /* @__PURE__ */ jsxRuntime.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" })
909
+ ] }),
910
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
911
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.company") }),
912
+ /* @__PURE__ */ jsxRuntime.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" })
913
+ ] })
914
+ ] }),
915
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-4 sm:grid-cols-2", children: [
916
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
917
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.email") }),
918
+ /* @__PURE__ */ jsxRuntime.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" })
919
+ ] }),
920
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
921
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.phone") }),
922
+ /* @__PURE__ */ jsxRuntime.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" })
923
+ ] })
924
+ ] }),
925
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
926
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
927
+ /* @__PURE__ */ jsxRuntime.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" })
928
+ ] })
929
+ ] })
930
+ ] });
931
+ }
932
+ var STATUS_COLORS = {
933
+ draft: "bg-muted text-muted-foreground",
934
+ sent: "bg-info-soft text-info-soft-foreground",
935
+ approved: "bg-success-soft text-success-soft-foreground",
936
+ rejected: "bg-destructive-soft text-destructive-soft-foreground",
937
+ expired: "bg-warning-soft text-warning-soft-foreground",
938
+ invoiced: "bg-warning-soft text-warning-soft-foreground",
939
+ paid: "bg-success-soft text-success-soft-foreground",
940
+ partial: "bg-warning-soft text-warning-soft-foreground",
941
+ overdue: "bg-destructive-soft text-destructive-soft-foreground",
942
+ cancelled: "bg-muted text-muted-foreground"
943
+ };
944
+ function useQuoteColumns(currency, onEditQuote) {
945
+ const t2 = core.useTranslation();
946
+ const cols = [
947
+ { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
948
+ { accessorKey: "contactName", header: t2("crm.quotes.contact"), cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: getValue() || "\u2014" }) },
949
+ { accessorKey: "quoteDate", header: t2("crm.quotes.date"), cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
950
+ {
951
+ accessorKey: "totalAmount",
952
+ header: t2("crm.quotes.amount"),
953
+ cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: saas.formatCurrency(getValue(), currency) })
954
+ },
955
+ {
956
+ accessorKey: "status",
957
+ header: t2("crm.quotes.status"),
958
+ cell: ({ getValue }) => {
959
+ const status = getValue();
960
+ return /* @__PURE__ */ jsxRuntime.jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium capitalize ${STATUS_COLORS[status] ?? "bg-muted text-muted-foreground"}`, children: status });
961
+ }
962
+ }
963
+ ];
964
+ if (onEditQuote) {
965
+ cols.push({
966
+ id: "actions",
967
+ header: "",
968
+ cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("div", { className: "text-right", children: /* @__PURE__ */ jsxRuntime.jsx(
969
+ "button",
970
+ {
971
+ onClick: (e) => {
972
+ e.stopPropagation();
973
+ onEditQuote(row.original.id);
974
+ },
975
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
976
+ title: "Edit quote",
977
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { className: "h-3.5 w-3.5" })
978
+ }
979
+ ) })
980
+ });
981
+ }
982
+ return cols;
983
+ }
984
+ function QuoteListView({ onNew, onEdit, onEditQuote }) {
985
+ const t2 = core.useTranslation();
986
+ const { currency } = useCrmConfig();
987
+ const quotes = useCrmStore((s) => s.quotes);
988
+ const quotesLoading = useCrmStore((s) => s.quotesLoading);
989
+ const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
990
+ React15.useEffect(() => {
991
+ fetchQuotes({});
992
+ }, []);
993
+ const columns2 = useQuoteColumns(currency, onEditQuote);
994
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
995
+ /* @__PURE__ */ jsxRuntime.jsx(
996
+ ui.SubpageHeader,
997
+ {
998
+ title: t2("crm.quotes.title"),
999
+ subtitle: t2("crm.quotes.quotesCount", { count: String(quotes.length) }),
1000
+ actions: onNew && /* @__PURE__ */ jsxRuntime.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: [
1001
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "h-3.5 w-3.5 inline-flex items-center justify-center", children: "+" }),
1002
+ " ",
1003
+ t2("crm.quotes.newQuote")
1004
+ ] })
1005
+ }
1006
+ ),
1007
+ quotesLoading ? /* @__PURE__ */ jsxRuntime.jsx(ui.DataTable, { columns: columns2, data: [], loading: true }) : quotes.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center rounded-lg border-2 border-dashed border-muted", children: [
1008
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-8 w-8 text-muted-foreground/30 mb-2" }),
1009
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.quotes.noQuotes") }),
1010
+ onNew && /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onNew, className: "text-xs text-primary hover:underline mt-1", children: t2("crm.quotes.createFirst") })
1011
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(
1012
+ ui.DataTable,
1013
+ {
1014
+ columns: columns2,
1015
+ data: quotes,
1016
+ onRowClick: (row) => onEdit?.(row.id)
1017
+ }
1018
+ )
1019
+ ] });
1020
+ }
1021
+ var STATUSES = [
1022
+ { value: "draft", labelKey: "crm.quoteForm.statusDraft", color: "bg-primary text-primary-foreground" },
1023
+ { value: "sent", labelKey: "crm.quoteForm.statusSent", color: "bg-info-soft text-info-soft-foreground border border-info/30 dark:border-info/30" },
1024
+ { value: "approved", labelKey: "crm.quoteForm.statusApproved", color: "bg-success-soft text-success-soft-foreground border border-success/30 dark:border-success/30" },
1025
+ { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
1026
+ { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
1027
+ ];
1028
+ var fid = 1;
1029
+ function nextId() {
1030
+ return `qi${fid++}`;
1031
+ }
1032
+ function QuoteItemRow({ item, index, itemTypes, currency, expanded, onToggle, onUpdate, onRemove, showDiscount, onShowDiscount, onHideDiscount, entityLookups }) {
1033
+ const t2 = core.useTranslation();
1034
+ const total = item.quantity * item.unitPrice - item.discount;
1035
+ const kindLabel = itemTypes.find((ty) => ty.value === item.itemKind)?.label ?? item.itemKind;
1036
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "border-b last:border-0", children: [
1037
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 px-4 py-3 cursor-pointer hover:bg-muted/30 transition-colors group", onClick: onToggle, children: [
1038
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronDown, { className: `h-3 w-3 text-muted-foreground shrink-0 transition-transform ${expanded ? "rotate-0" : "-rotate-90"}` }),
1039
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-[10px] font-medium text-muted-foreground w-5 shrink-0", children: [
1040
+ index + 1,
1041
+ "."
1042
+ ] }),
1043
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded px-1.5 py-0.5 text-[9px] font-medium bg-muted text-muted-foreground shrink-0", children: kindLabel }),
1044
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm truncate flex-1 min-w-0", children: item.description || /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground italic", children: t2("crm.quoteForm.noDescription") }) }),
1045
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-muted-foreground shrink-0", children: [
1046
+ item.quantity,
1047
+ " x ",
1048
+ saas.formatCurrency(item.unitPrice, currency)
1049
+ ] }),
1050
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-semibold shrink-0 min-w-[80px] text-right", children: saas.formatCurrency(total, currency) }),
1051
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: (e) => {
1052
+ e.stopPropagation();
1053
+ onRemove();
1054
+ }, className: "p-1 text-muted-foreground opacity-0 group-hover:opacity-100 hover:text-destructive transition-all shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Trash2, { className: "h-3 w-3" }) })
1055
+ ] }),
1056
+ expanded && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "px-4 pb-4 pt-1 ml-8 space-y-3 bg-muted/10", children: [
1057
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-1.5", children: itemTypes.map((t3) => /* @__PURE__ */ jsxRuntime.jsx(
1058
+ "button",
1059
+ {
1060
+ onClick: () => onUpdate({ itemKind: t3.value }),
1061
+ className: `rounded-full px-2.5 py-1 text-[10px] font-medium transition-colors ${item.itemKind === t3.value ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground hover:bg-muted/80"}`,
1062
+ children: t3.label
1063
+ },
1064
+ t3.value
1065
+ )) }),
1066
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-3 grid-cols-12", children: [
1067
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-6 sm:col-span-7", children: entityLookups[item.itemKind] ? /* @__PURE__ */ jsxRuntime.jsx(
1068
+ ui.SearchSelect,
1069
+ {
1070
+ label: "Item",
1071
+ value: item._id,
1072
+ displayValue: item.description,
1073
+ loadOnOpen: true,
1074
+ onChange: (id, opt) => {
1075
+ onUpdate({
1076
+ description: opt?.label ?? "",
1077
+ unitPrice: opt?.data?.price ?? item.unitPrice
1078
+ });
1079
+ },
1080
+ onSearch: async (q) => {
1081
+ const results = await entityLookups[item.itemKind].search(q);
1082
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
1083
+ },
1084
+ placeholder: `Search ${itemTypes.find((t3) => t3.value === item.itemKind)?.label?.toLowerCase() ?? "item"}...`,
1085
+ renderOption: (opt) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-0 flex-1", children: [
1086
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm truncate", children: opt.label }),
1087
+ opt.subtitle && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: opt.subtitle })
1088
+ ] })
1089
+ }
1090
+ ) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1091
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-[10px] font-medium text-muted-foreground", children: t2("crm.quoteForm.description") }),
1092
+ /* @__PURE__ */ jsxRuntime.jsx("input", { type: "text", value: item.description, onChange: (e) => onUpdate({ description: e.target.value }), placeholder: t2("crm.quoteForm.itemDescriptionPlaceholder"), autoFocus: true, className: "w-full mt-0.5 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-2.5 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring" })
1093
+ ] }) }),
1094
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "col-span-2 sm:col-span-1", children: [
1095
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-[10px] font-medium text-muted-foreground", children: t2("crm.quoteForm.qty") }),
1096
+ /* @__PURE__ */ jsxRuntime.jsx("input", { type: "number", min: 1, value: item.quantity, onChange: (e) => onUpdate({ quantity: Number(e.target.value) || 1 }), className: "w-full mt-0.5 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-2 py-1.5 text-sm text-center focus:outline-none focus:ring-2 focus:ring-ring" })
1097
+ ] }),
1098
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-4", children: /* @__PURE__ */ jsxRuntime.jsx(ui.CurrencyInput, { label: t2("crm.quoteForm.unitPrice"), value: item.unitPrice, onChange: (v) => onUpdate({ unitPrice: v }), symbol: currency.symbol, locale: currency.locale, currencyCode: currency.code }) })
1099
+ ] }),
1100
+ !showDiscount ? /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: onShowDiscount, className: "inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors", children: [
1101
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Plus, { className: "h-3 w-3" }),
1102
+ " ",
1103
+ t2("crm.quoteForm.discount")
1104
+ ] }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-3 grid-cols-12 items-end", children: [
1105
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-4", children: /* @__PURE__ */ jsxRuntime.jsx(ui.CurrencyInput, { label: t2("crm.quoteForm.discount"), value: item.discount, onChange: (v) => onUpdate({ discount: v }), symbol: currency.symbol, locale: currency.locale, currencyCode: currency.code }) }),
1106
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-1", children: /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => {
1107
+ onUpdate({ discount: 0 });
1108
+ onHideDiscount();
1109
+ }, className: "mb-2 p-1 text-muted-foreground hover:text-destructive transition-colors", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-3.5 w-3.5" }) }) })
1110
+ ] }),
1111
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex justify-end pt-1", children: /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: onToggle, className: "inline-flex items-center gap-1 rounded-md px-2.5 py-1 text-[11px] text-muted-foreground hover:text-foreground hover:bg-muted/50 transition-colors", children: [
1112
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-3 w-3" }),
1113
+ " ",
1114
+ t2("crm.quoteForm.done")
1115
+ ] }) })
1116
+ ] })
1117
+ ] });
1118
+ }
1119
+ function AddItemStep({ itemTypes, onSelect, onCancel }) {
1120
+ const t2 = core.useTranslation();
1121
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "border-b px-4 py-3 bg-primary/5 animate-in fade-in-0 slide-in-from-top-1", children: [
1122
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium text-muted-foreground mb-2", children: t2("crm.quoteForm.selectItemType") }),
1123
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-2 flex-wrap", children: [
1124
+ itemTypes.map((t3) => /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => onSelect(t3.value), className: "inline-flex items-center gap-1.5 rounded-lg border-2 border-transparent bg-card px-4 py-2 text-sm font-medium shadow-sm hover:border-primary hover:shadow-md transition-all", children: t3.label }, t3.value)),
1125
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onCancel, className: "inline-flex items-center rounded-lg px-3 py-2 text-xs text-muted-foreground hover:text-foreground transition-colors", children: t2("crm.quoteForm.cancel") })
1126
+ ] })
1127
+ ] });
1128
+ }
1129
+ function QuoteFormView({ quoteId, leadId, onSaved }) {
1130
+ const t2 = core.useTranslation();
1131
+ const config = useCrmConfig();
1132
+ const provider = useCrmProvider();
1133
+ const { currency, itemTypes } = config;
1134
+ const createQuote = useCrmStore((s) => s.createQuote);
1135
+ const updateQuote = useCrmStore((s) => s.updateQuote);
1136
+ const isEdit = !!quoteId;
1137
+ const [loadingExisting, setLoadingExisting] = React15.useState(isEdit || !!leadId);
1138
+ const [linkedLeadId, setLinkedLeadId] = React15.useState(leadId ?? "");
1139
+ const [linkedDealId, setLinkedDealId] = React15.useState("");
1140
+ const [contactName, setContactName] = React15.useState("");
1141
+ const [contactId, setContactId] = React15.useState("");
1142
+ const [quoteDate, setQuoteDate] = React15.useState((/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
1143
+ const [validUntil, setValidUntil] = React15.useState(() => {
1144
+ const d = /* @__PURE__ */ new Date();
1145
+ d.setDate(d.getDate() + 30);
1146
+ return d.toISOString().slice(0, 10);
1147
+ });
1148
+ const [currentStatus, setCurrentStatus] = React15.useState("draft");
1149
+ const [paymentConditions, setPaymentConditions] = React15.useState("");
1150
+ const [observations, setObservations] = React15.useState("");
1151
+ const [items, setItems] = React15.useState([]);
1152
+ const [expandedItemId, setExpandedItemId] = React15.useState(null);
1153
+ const [discountVisible, setDiscountVisible] = React15.useState(/* @__PURE__ */ new Set());
1154
+ const [addingItem, setAddingItem] = React15.useState(false);
1155
+ const [saving, setSaving] = React15.useState(false);
1156
+ React15.useEffect(() => {
1157
+ if (!quoteId) return;
1158
+ provider.getQuoteById(quoteId).then((q) => {
1159
+ if (q) {
1160
+ setContactName(q.contactName ?? "");
1161
+ setContactId(q.contactId ?? "");
1162
+ setLinkedLeadId(q.leadId ?? "");
1163
+ setLinkedDealId(q.dealId ?? "");
1164
+ setQuoteDate(q.quoteDate);
1165
+ setValidUntil(q.validUntil);
1166
+ setCurrentStatus(q.status);
1167
+ setPaymentConditions(q.paymentConditions ?? "");
1168
+ setObservations(q.observations ?? "");
1169
+ setItems(q.items.map((it) => ({
1170
+ _id: nextId(),
1171
+ itemKind: it.itemKind,
1172
+ description: it.description,
1173
+ quantity: it.quantity,
1174
+ unitPrice: it.unitPrice,
1175
+ discount: it.discount
1176
+ })));
1177
+ setDiscountVisible(new Set(q.items.filter((it) => it.discount > 0).map((_, i) => `qi${fid - q.items.length + i}`)));
1178
+ }
1179
+ setLoadingExisting(false);
1180
+ });
1181
+ }, [quoteId]);
1182
+ React15.useEffect(() => {
1183
+ if (!leadId || quoteId) return;
1184
+ provider.getLeadById(leadId).then(async (lead) => {
1185
+ if (lead) {
1186
+ setContactName(lead.name);
1187
+ setContactId(lead.id);
1188
+ setLinkedLeadId(lead.id);
1189
+ const deal = await provider.getDealByLeadId(lead.id);
1190
+ if (deal) setLinkedDealId(deal.id);
1191
+ }
1192
+ setLoadingExisting(false);
1193
+ });
1194
+ }, [leadId]);
1195
+ const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0);
1196
+ function addItemOfKind(kind) {
1197
+ const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
1198
+ setItems([...items, newItem]);
1199
+ setExpandedItemId(newItem._id);
1200
+ setAddingItem(false);
1201
+ }
1202
+ function updateItem(id, data) {
1203
+ setItems(items.map((it) => it._id === id ? { ...it, ...data } : it));
1204
+ }
1205
+ function removeItem(id) {
1206
+ setItems(items.filter((it) => it._id !== id));
1207
+ if (expandedItemId === id) setExpandedItemId(null);
1208
+ }
1209
+ async function handleSave() {
1210
+ if (items.length === 0) {
1211
+ ui.toast.error(t2("crm.quoteForm.errNoItems"));
1212
+ return;
1213
+ }
1214
+ setSaving(true);
1215
+ try {
1216
+ const input = {
1217
+ contactId: contactId || void 0,
1218
+ contactName: contactName || void 0,
1219
+ leadId: linkedLeadId || void 0,
1220
+ dealId: linkedDealId || void 0,
1221
+ quoteDate,
1222
+ validUntil,
1223
+ paymentConditions: paymentConditions || void 0,
1224
+ observations: observations || void 0,
1225
+ items: items.map((it) => ({
1226
+ itemKind: it.itemKind,
1227
+ description: it.description,
1228
+ quantity: it.quantity,
1229
+ unitPrice: it.unitPrice,
1230
+ discount: it.discount,
1231
+ totalAmount: it.quantity * it.unitPrice - it.discount
1232
+ }))
1233
+ };
1234
+ if (isEdit) {
1235
+ await updateQuote(quoteId, input);
1236
+ onSaved?.(quoteId);
1237
+ } else {
1238
+ const created = await createQuote(input);
1239
+ onSaved?.(created?.id);
1240
+ }
1241
+ } finally {
1242
+ setSaving(false);
1243
+ }
1244
+ }
1245
+ const currentFields = {
1246
+ contactId,
1247
+ contactName,
1248
+ linkedLeadId,
1249
+ linkedDealId,
1250
+ quoteDate,
1251
+ validUntil,
1252
+ currentStatus,
1253
+ paymentConditions,
1254
+ observations,
1255
+ items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
1256
+ };
1257
+ const snapshot = React15__default.default.useRef(null);
1258
+ React15.useEffect(() => {
1259
+ if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
1260
+ }, [loadingExisting]);
1261
+ const dirty = snapshot.current !== null && JSON.stringify(currentFields) !== snapshot.current;
1262
+ ui.useSaveBar({
1263
+ dirty,
1264
+ saving,
1265
+ onSave: () => {
1266
+ void handleSave();
1267
+ },
1268
+ onDiscard: () => onSaved?.(),
1269
+ saveLabel: isEdit ? t2("crm.quoteForm.saveChanges") : t2("crm.quoteForm.saveQuote")
1270
+ });
1271
+ if (loadingExisting) {
1272
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
1273
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: "", onBack: onSaved, parentLabel: t2("crm.quotes.title") }),
1274
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-4 lg:grid-cols-3", children: [
1275
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-lg border bg-card shadow-sm p-5 space-y-4", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1.5", children: [
1276
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse" }),
1277
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-9 w-full rounded-lg bg-muted/20 animate-pulse" })
1278
+ ] }, i)) }),
1279
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "lg:col-span-2 rounded-lg border bg-card shadow-sm p-5 space-y-3", children: [
1280
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-24 rounded bg-muted/30 animate-pulse" }),
1281
+ [1, 2].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 py-2", children: [
1282
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-4 rounded bg-muted/30 animate-pulse" }),
1283
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 flex-1 rounded bg-muted/20 animate-pulse" }),
1284
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-20 rounded bg-muted/30 animate-pulse" })
1285
+ ] }, i))
1286
+ ] })
1287
+ ] })
1288
+ ] });
1289
+ }
1290
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
1291
+ /* @__PURE__ */ jsxRuntime.jsx(
1292
+ ui.SubpageHeader,
1293
+ {
1294
+ title: isEdit ? t2("crm.quoteForm.editTitle") : t2("crm.quoteForm.newTitle"),
1295
+ subtitle: isEdit ? t2("crm.quoteForm.editSubtitle") : t2("crm.quoteForm.newSubtitle"),
1296
+ onBack: () => onSaved?.(),
1297
+ parentLabel: t2("crm.quotes.title")
1298
+ }
1299
+ ),
1300
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-2", children: STATUSES.map((s) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: `inline-flex items-center rounded-full px-3 py-1 text-xs font-medium ${s.value === currentStatus ? s.color : "bg-muted/30 text-muted-foreground/50"}`, children: t2(s.labelKey) }, s.value)) }),
1301
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid gap-4 lg:grid-cols-3", children: [
1302
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-lg border bg-card shadow-sm p-5 space-y-4", children: [
1303
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: t2("crm.quoteForm.quoteDetails") }),
1304
+ /* @__PURE__ */ jsxRuntime.jsx(
1305
+ ui.SearchSelect,
1306
+ {
1307
+ value: contactId,
1308
+ displayValue: contactName,
1309
+ onChange: (id, opt) => {
1310
+ setContactId(id);
1311
+ setContactName(opt?.label ?? "");
1312
+ },
1313
+ onSearch: async (q) => {
1314
+ if (!config.contactLookup) return [];
1315
+ const results = await config.contactLookup.search(q);
1316
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
1317
+ },
1318
+ label: t2("crm.quoteForm.client"),
1319
+ required: true,
1320
+ placeholder: t2("crm.quoteForm.searchClient"),
1321
+ allowCreate: true,
1322
+ createLabel: t2("crm.quoteForm.addAsLead"),
1323
+ onCreate: async (name) => {
1324
+ const lead = await provider.createLead({ name });
1325
+ setContactId(lead.id);
1326
+ setContactName(lead.name);
1327
+ }
1328
+ }
1329
+ ),
1330
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1331
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.quoteDate") }),
1332
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DatePicker, { value: quoteDate, onChange: setQuoteDate, className: "mt-1" })
1333
+ ] }),
1334
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1335
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.validUntil") }),
1336
+ /* @__PURE__ */ jsxRuntime.jsx(ui.DatePicker, { value: validUntil, onChange: setValidUntil, className: "mt-1" })
1337
+ ] }),
1338
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1339
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.paymentConditions") }),
1340
+ /* @__PURE__ */ jsxRuntime.jsx("textarea", { value: paymentConditions, onChange: (e) => setPaymentConditions(e.target.value), rows: 2, placeholder: t2("crm.quoteForm.paymentConditionsPlaceholder"), 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" })
1341
+ ] }),
1342
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1343
+ /* @__PURE__ */ jsxRuntime.jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.notes") }),
1344
+ /* @__PURE__ */ jsxRuntime.jsx("textarea", { value: observations, onChange: (e) => setObservations(e.target.value), rows: 2, placeholder: t2("crm.quoteForm.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" })
1345
+ ] })
1346
+ ] }),
1347
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "lg:col-span-2 rounded-lg border bg-card shadow-sm overflow-hidden flex flex-col", children: [
1348
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between px-4 py-3 border-b", children: [
1349
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: t2("crm.quoteForm.quoteItems") }),
1350
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { onClick: () => setAddingItem(true), 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", children: [
1351
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Plus, { className: "h-3 w-3" }),
1352
+ " ",
1353
+ t2("crm.quoteForm.addItem")
1354
+ ] })
1355
+ ] }),
1356
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1", children: [
1357
+ addingItem && /* @__PURE__ */ jsxRuntime.jsx(AddItemStep, { itemTypes, onSelect: addItemOfKind, onCancel: () => setAddingItem(false) }),
1358
+ items.length === 0 && !addingItem ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "py-12 text-center", children: [
1359
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.quoteForm.noItems") }),
1360
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: () => setAddingItem(true), className: "text-xs text-primary hover:underline mt-1", children: t2("crm.quoteForm.addFirstItem") })
1361
+ ] }) : items.map((item, i) => /* @__PURE__ */ jsxRuntime.jsx(
1362
+ QuoteItemRow,
1363
+ {
1364
+ item,
1365
+ index: i,
1366
+ itemTypes,
1367
+ currency,
1368
+ expanded: expandedItemId === item._id,
1369
+ onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
1370
+ onUpdate: (data) => updateItem(item._id, data),
1371
+ onRemove: () => removeItem(item._id),
1372
+ showDiscount: discountVisible.has(item._id) || item.discount > 0,
1373
+ onShowDiscount: () => setDiscountVisible((prev) => new Set(prev).add(item._id)),
1374
+ onHideDiscount: () => setDiscountVisible((prev) => {
1375
+ const next = new Set(prev);
1376
+ next.delete(item._id);
1377
+ return next;
1378
+ }),
1379
+ entityLookups: config.entityLookups
1380
+ },
1381
+ item._id
1382
+ ))
1383
+ ] }),
1384
+ items.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "px-4 py-3 border-t bg-muted/20 flex justify-between items-center mt-auto", children: [
1385
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: t2("crm.quoteForm.itemCount", { count: String(items.length) }) }),
1386
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "text-right", children: [
1387
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-xs text-muted-foreground", children: [
1388
+ t2("crm.quoteForm.total"),
1389
+ ": "
1390
+ ] }),
1391
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-lg font-bold", children: saas.formatCurrency(totalAmount, currency) })
1392
+ ] })
1393
+ ] })
1394
+ ] })
1395
+ ] })
1396
+ ] });
1397
+ }
1398
+ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
1399
+ const t2 = core.useTranslation();
1400
+ const { currency } = useCrmConfig();
1401
+ const provider = useCrmProvider();
1402
+ const sendQuote = useCrmStore((s) => s.sendQuote);
1403
+ const approveQuote = useCrmStore((s) => s.approveQuote);
1404
+ const rejectQuote = useCrmStore((s) => s.rejectQuote);
1405
+ const [quote, setQuote] = React15.useState(null);
1406
+ const [loading, setLoading] = React15.useState(true);
1407
+ const [sendMenuOpen, setSendMenuOpen] = React15.useState(false);
1408
+ const [sending, setSending] = React15.useState(false);
1409
+ const [approving, setApproving] = React15.useState(false);
1410
+ const [rejectOpen, setRejectOpen] = React15.useState(false);
1411
+ const [rejectReason, setRejectReason] = React15.useState("");
1412
+ const [rejecting, setRejecting] = React15.useState(false);
1413
+ const sendMenuRef = React15.useRef(null);
1414
+ React15.useEffect(() => {
1415
+ setLoading(true);
1416
+ provider.getQuoteById(quoteId).then((q) => {
1417
+ setQuote(q);
1418
+ setLoading(false);
1419
+ });
1420
+ }, [quoteId]);
1421
+ React15.useEffect(() => {
1422
+ if (!sendMenuOpen) return;
1423
+ const h = (e) => {
1424
+ if (sendMenuRef.current && !sendMenuRef.current.contains(e.target)) setSendMenuOpen(false);
1425
+ };
1426
+ document.addEventListener("mousedown", h);
1427
+ return () => document.removeEventListener("mousedown", h);
1428
+ }, [sendMenuOpen]);
1429
+ async function handleSend(channel) {
1430
+ setSending(true);
1431
+ setSendMenuOpen(false);
1432
+ try {
1433
+ const updated = await sendQuote(quoteId);
1434
+ setQuote(updated);
1435
+ } finally {
1436
+ setSending(false);
1437
+ }
1438
+ }
1439
+ async function handleApprove() {
1440
+ setApproving(true);
1441
+ try {
1442
+ const updated = await approveQuote(quoteId);
1443
+ setQuote(updated);
1444
+ if (onInvoiceCreated) {
1445
+ onInvoiceCreated(quoteId);
1446
+ }
1447
+ } finally {
1448
+ setApproving(false);
1449
+ }
1450
+ }
1451
+ async function handleReject() {
1452
+ if (!rejectReason.trim()) return;
1453
+ setRejecting(true);
1454
+ try {
1455
+ const updated = await rejectQuote(quoteId, rejectReason.trim());
1456
+ setQuote(updated);
1457
+ setRejectOpen(false);
1458
+ setRejectReason("");
1459
+ } finally {
1460
+ setRejecting(false);
1461
+ }
1462
+ }
1463
+ if (loading) {
1464
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
1465
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: "", onBack, parentLabel: t2("crm.quotes.title") }),
1466
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-xl border bg-card shadow-sm overflow-hidden", children: [
1467
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-1 bg-muted animate-pulse" }),
1468
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "p-5 pb-4", children: [
1469
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start justify-between", children: [
1470
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
1471
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-10 w-10 rounded-lg bg-muted/40 animate-pulse" }),
1472
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
1473
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-20 rounded bg-muted/40 animate-pulse" }),
1474
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-6 w-32 rounded bg-muted/40 animate-pulse" })
1475
+ ] })
1476
+ ] }),
1477
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-6 w-20 rounded-full bg-muted/40 animate-pulse" })
1478
+ ] }),
1479
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "grid grid-cols-2 sm:grid-cols-4 gap-3 mt-4 pt-4 border-t", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1480
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3.5 w-3.5 rounded bg-muted/30 animate-pulse" }),
1481
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-1", children: [
1482
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2 w-10 rounded bg-muted/30 animate-pulse" }),
1483
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/40 animate-pulse" })
1484
+ ] })
1485
+ ] }, i)) })
1486
+ ] })
1487
+ ] })
1488
+ ] });
1489
+ }
1490
+ if (!quote) {
1491
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
1492
+ /* @__PURE__ */ jsxRuntime.jsx(ui.SubpageHeader, { title: t2("crm.quoteDetail.title"), onBack, parentLabel: t2("crm.quotes.title") }),
1493
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center rounded-lg border-2 border-dashed border-muted", children: [
1494
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-8 w-8 text-muted-foreground/30 mb-2" }),
1495
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.quoteDetail.notFound") }),
1496
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onBack, className: "text-xs text-primary hover:underline mt-1", children: t2("crm.quoteDetail.backToList") })
1497
+ ] })
1498
+ ] });
1499
+ }
1500
+ const subtotal = quote.items.reduce((sum, it) => sum + it.quantity * it.unitPrice, 0);
1501
+ const totalDiscount = quote.items.reduce((sum, it) => sum + it.discount, 0);
1502
+ const itemColumns = [
1503
+ {
1504
+ id: "index",
1505
+ header: "#",
1506
+ cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: row.index + 1 })
1507
+ },
1508
+ {
1509
+ accessorKey: "description",
1510
+ header: t2("crm.quoteDetail.description"),
1511
+ cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1512
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded px-1.5 py-0.5 text-[9px] font-medium bg-muted text-muted-foreground capitalize", children: row.original.itemKind }),
1513
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "truncate", children: row.original.description || "\u2014" })
1514
+ ] })
1515
+ },
1516
+ {
1517
+ accessorKey: "quantity",
1518
+ header: () => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right", children: t2("crm.quoteDetail.qty") }),
1519
+ cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right text-xs tabular-nums", children: getValue() })
1520
+ },
1521
+ {
1522
+ accessorKey: "unitPrice",
1523
+ header: () => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right", children: t2("crm.quoteDetail.unitPrice") }),
1524
+ cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right text-xs tabular-nums", children: saas.formatCurrency(getValue(), currency) })
1525
+ },
1526
+ {
1527
+ accessorKey: "totalAmount",
1528
+ header: () => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right", children: t2("crm.quoteDetail.total") }),
1529
+ cell: ({ getValue }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "block text-right font-medium tabular-nums", children: saas.formatCurrency(getValue(), currency) })
1530
+ }
1531
+ ];
1532
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-5", children: [
1533
+ /* @__PURE__ */ jsxRuntime.jsx(
1534
+ ui.SubpageHeader,
1535
+ {
1536
+ title: `#${quote.quoteNumber}`,
1537
+ onBack,
1538
+ parentLabel: t2("crm.quotes.title"),
1539
+ actions: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-1.5", children: [
1540
+ quote.status === "draft" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", ref: sendMenuRef, children: [
1541
+ /* @__PURE__ */ jsxRuntime.jsxs(
1542
+ "button",
1543
+ {
1544
+ type: "button",
1545
+ onClick: () => setSendMenuOpen((p) => !p),
1546
+ disabled: sending,
1547
+ 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 disabled:opacity-50",
1548
+ children: [
1549
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Send, { className: "h-3 w-3" }),
1550
+ sending ? t2("crm.quoteDetail.sending") : t2("crm.quoteDetail.send"),
1551
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ChevronDown, { className: "h-3 w-3 opacity-60" })
1552
+ ]
1553
+ }
1554
+ ),
1555
+ sendMenuOpen && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "absolute right-0 top-full mt-1 w-48 rounded-lg border bg-card shadow-lg z-20 py-1 animate-in fade-in zoom-in-95 duration-100", children: [
1556
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", onClick: () => handleSend(), className: "flex w-full items-center gap-2 px-3 py-2 text-xs hover:bg-muted/50 transition-colors", children: [
1557
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Printer, { className: "h-3.5 w-3.5 text-muted-foreground" }),
1558
+ " ",
1559
+ t2("crm.quoteDetail.sendPrint")
1560
+ ] }),
1561
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", onClick: () => handleSend(), className: "flex w-full items-center gap-2 px-3 py-2 text-xs hover:bg-muted/50 transition-colors", children: [
1562
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Mail, { className: "h-3.5 w-3.5 text-muted-foreground" }),
1563
+ " ",
1564
+ t2("crm.quoteDetail.sendEmail")
1565
+ ] }),
1566
+ /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", onClick: () => handleSend(), className: "flex w-full items-center gap-2 px-3 py-2 text-xs hover:bg-muted/50 transition-colors", children: [
1567
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.MessageCircle, { className: "h-3.5 w-3.5 text-muted-foreground" }),
1568
+ " ",
1569
+ t2("crm.quoteDetail.sendWhatsApp")
1570
+ ] })
1571
+ ] })
1572
+ ] }),
1573
+ quote.status === "sent" && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1574
+ /* @__PURE__ */ jsxRuntime.jsxs(
1575
+ ui.Button,
1576
+ {
1577
+ type: "button",
1578
+ variant: "default",
1579
+ size: "sm",
1580
+ onClick: handleApprove,
1581
+ disabled: approving,
1582
+ className: "bg-success text-success-foreground hover:bg-success/90 border-success",
1583
+ children: [
1584
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-3.5 w-3.5" }),
1585
+ approving ? t2("crm.quoteDetail.approving") : t2("crm.quoteDetail.approve")
1586
+ ]
1587
+ }
1588
+ ),
1589
+ /* @__PURE__ */ jsxRuntime.jsxs(
1590
+ ui.Button,
1591
+ {
1592
+ type: "button",
1593
+ variant: "outline",
1594
+ size: "sm",
1595
+ onClick: () => setRejectOpen(true),
1596
+ className: "border-destructive/30 text-destructive hover:bg-destructive/10",
1597
+ children: [
1598
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-3.5 w-3.5" }),
1599
+ t2("crm.quoteDetail.reject")
1600
+ ]
1601
+ }
1602
+ )
1603
+ ] }),
1604
+ onEdit && quote.status !== "approved" && quote.status !== "rejected" && quote.status !== "expired" && /* @__PURE__ */ jsxRuntime.jsxs("button", { type: "button", onClick: onEdit, className: "inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium hover:bg-muted bg-card shadow-button active:shadow-button-inset transition-colors", children: [
1605
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Pencil, { className: "h-3 w-3" }),
1606
+ " ",
1607
+ t2("crm.quoteDetail.edit")
1608
+ ] })
1609
+ ] })
1610
+ }
1611
+ ),
1612
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "rounded-xl border bg-card shadow-sm overflow-hidden", children: [
1613
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-1 bg-primary" }),
1614
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "p-5 pb-4", children: [
1615
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start justify-between gap-4", children: [
1616
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
1617
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-lg bg-primary/10 shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-5 w-5 text-primary" }) }),
1618
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1619
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium text-muted-foreground uppercase tracking-wider", children: t2("crm.quoteDetail.quoteNumber", { number: quote.quoteNumber }) }),
1620
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xl font-bold mt-0.5", children: saas.formatCurrency(quote.totalAmount, currency) })
1621
+ ] })
1622
+ ] }),
1623
+ /* @__PURE__ */ jsxRuntime.jsx(QuoteStatusDropdown, { quote, onStatusChange: (q) => setQuote(q) })
1624
+ ] }),
1625
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-2 sm:grid-cols-4 gap-3 mt-4 pt-4 border-t", children: [
1626
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1627
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.User, { className: "h-3.5 w-3.5 text-muted-foreground shrink-0" }),
1628
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-0", children: [
1629
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: t2("crm.quoteDetail.client") }),
1630
+ quote.contactName ? /* @__PURE__ */ jsxRuntime.jsx(saas.PersonLink, { personId: quote.contactId ?? quote.leadId, name: quote.contactName, size: "sm" }) : /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium truncate", children: "\u2014" })
1631
+ ] })
1632
+ ] }),
1633
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1634
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Calendar, { className: "h-3.5 w-3.5 text-muted-foreground shrink-0" }),
1635
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1636
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: t2("crm.quoteDetail.date") }),
1637
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium", children: quote.quoteDate })
1638
+ ] })
1639
+ ] }),
1640
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1641
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Calendar, { className: "h-3.5 w-3.5 text-muted-foreground shrink-0" }),
1642
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1643
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: t2("crm.quoteDetail.validUntil") }),
1644
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium", children: quote.validUntil })
1645
+ ] })
1646
+ ] }),
1647
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1648
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Hash, { className: "h-3.5 w-3.5 text-muted-foreground shrink-0" }),
1649
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1650
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: t2("crm.quoteDetail.items") }),
1651
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs font-medium", children: quote.items.length })
1652
+ ] })
1653
+ ] })
1654
+ ] })
1655
+ ] }),
1656
+ quote.items.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1657
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 pt-3 pb-1.5", children: /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.quoteDetail.items") }) }),
1658
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5", children: /* @__PURE__ */ jsxRuntime.jsx(ui.DataTable, { columns: itemColumns, data: quote.items, variant: "flat", compact: true }) }),
1659
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 py-3 mt-1 border-t bg-muted/10", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-end gap-0.5", children: [
1660
+ totalDiscount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1661
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-6 text-xs", children: [
1662
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground", children: t2("crm.quoteDetail.subtotal") }),
1663
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "tabular-nums w-24 text-right", children: saas.formatCurrency(subtotal, currency) })
1664
+ ] }),
1665
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-6 text-xs text-success", children: [
1666
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: t2("crm.quoteDetail.discount") }),
1667
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "tabular-nums w-24 text-right", children: [
1668
+ "-",
1669
+ saas.formatCurrency(totalDiscount, currency)
1670
+ ] })
1671
+ ] })
1672
+ ] }),
1673
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-6 text-sm font-bold pt-1", children: [
1674
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: t2("crm.quoteDetail.total") }),
1675
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "tabular-nums w-24 text-right", children: saas.formatCurrency(quote.totalAmount, currency) })
1676
+ ] })
1677
+ ] }) })
1678
+ ] }),
1679
+ quote.paymentConditions && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "px-5 py-3 border-t", children: [
1680
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1", children: t2("crm.quoteDetail.paymentConditions") }),
1681
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: quote.paymentConditions })
1682
+ ] }),
1683
+ quote.observations && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "px-5 py-3 border-t", children: [
1684
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1", children: t2("crm.quoteDetail.notes") }),
1685
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground whitespace-pre-wrap", children: quote.observations })
1686
+ ] })
1687
+ ] }),
1688
+ quote.status === "approved" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
1689
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1690
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
1691
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground", children: t2("crm.quoteDetail.invoiceCreated") })
1692
+ ] }),
1693
+ /* @__PURE__ */ jsxRuntime.jsxs(
1694
+ "a",
1695
+ {
1696
+ href: `#/financial/receivables/detail/${quote.id}`,
1697
+ className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",
1698
+ children: [
1699
+ t2("crm.quoteDetail.viewInvoice"),
1700
+ " ",
1701
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ArrowRight, { className: "h-3 w-3" })
1702
+ ]
1703
+ }
1704
+ )
1705
+ ] }),
1706
+ quote.status === "rejected" && quote.rejectionReason && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-2.5", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1707
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Ban, { className: "h-3.5 w-3.5 text-destructive" }),
1708
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground", children: [
1709
+ t2("crm.quoteDetail.rejectionReason"),
1710
+ ": ",
1711
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium text-foreground", children: quote.rejectionReason })
1712
+ ] })
1713
+ ] }) }),
1714
+ rejectOpen && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/50", onClick: () => setRejectOpen(false), children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "w-full max-w-sm rounded-modal border bg-card shadow-lg mx-4 p-5", onClick: (e) => e.stopPropagation(), children: [
1715
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 mb-3", children: [
1716
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-10 w-10 items-center justify-center rounded-full bg-destructive/10 shrink-0", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.X, { className: "h-5 w-5 text-destructive" }) }),
1717
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1718
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold", children: t2("crm.quoteDetail.reject") }),
1719
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.quoteDetail.rejectDescription") })
1720
+ ] })
1721
+ ] }),
1722
+ /* @__PURE__ */ jsxRuntime.jsx(
1723
+ "textarea",
1724
+ {
1725
+ value: rejectReason,
1726
+ onChange: (e) => setRejectReason(e.target.value),
1727
+ placeholder: t2("crm.quoteDetail.rejectReasonPlaceholder"),
1728
+ className: "w-full rounded-input border border-input bg-card px-3 py-2 text-sm shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] resize-none h-20 focus:outline-none focus:ring-2 focus:ring-ring",
1729
+ autoFocus: true
1730
+ }
1731
+ ),
1732
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-end gap-2 mt-3", children: [
1733
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Button, { type: "button", variant: "outline", size: "sm", onClick: () => setRejectOpen(false), children: t2("common.cancel") }),
1734
+ /* @__PURE__ */ jsxRuntime.jsx(
1735
+ ui.Button,
1736
+ {
1737
+ type: "button",
1738
+ variant: "destructive",
1739
+ size: "sm",
1740
+ onClick: handleReject,
1741
+ disabled: rejecting || !rejectReason.trim(),
1742
+ children: rejecting ? t2("crm.quoteDetail.rejecting") : t2("crm.quoteDetail.confirmReject")
1743
+ }
1744
+ )
1745
+ ] })
1746
+ ] }) })
1747
+ ] });
1748
+ }
1749
+ var STATUS_COLORS2 = {
1750
+ new: "bg-info-soft text-info-soft-foreground",
1751
+ contacted: "bg-magic-soft text-magic-soft-foreground",
1752
+ qualified: "bg-success-soft text-success-soft-foreground",
1753
+ unqualified: "bg-muted text-muted-foreground",
1754
+ converted: "bg-warning-soft text-warning-soft-foreground",
1755
+ lost: "bg-destructive-soft text-destructive-soft-foreground"
1756
+ };
1757
+ function FieldRow({ label, value }) {
1758
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-3 gap-4 py-3", children: [
1759
+ /* @__PURE__ */ jsxRuntime.jsx("dt", { className: "text-sm font-medium text-muted-foreground", children: label }),
1760
+ /* @__PURE__ */ jsxRuntime.jsx("dd", { className: "col-span-2 text-sm text-foreground", children: value ?? /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
1761
+ ] });
1762
+ }
1763
+ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote }) {
1764
+ const provider = useCrmProvider();
1765
+ const { currency } = useCrmConfig();
1766
+ const t2 = core.useTranslation();
1767
+ const [lead, setLead] = React15.useState(null);
1768
+ const [deal, setDeal] = React15.useState(null);
1769
+ const [quotes, setQuotes] = React15.useState([]);
1770
+ const [loading, setLoading] = React15.useState(true);
1771
+ React15.useEffect(() => {
1772
+ setLoading(true);
1773
+ provider.getLeadById(leadId).then(async (l) => {
1774
+ setLead(l);
1775
+ if (l) {
1776
+ const d = await provider.getDealByLeadId(leadId);
1777
+ setDeal(d);
1778
+ if (d) {
1779
+ const q = await provider.getQuotesByDealId(d.id);
1780
+ setQuotes(q);
1781
+ }
1782
+ }
1783
+ setLoading(false);
1784
+ });
1785
+ }, [leadId]);
1786
+ if (loading) {
1787
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
1788
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Breadcrumb, { parent: t2("crm.leads.title"), current: t2("crm.leadDetail.loading"), onBack }),
1789
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-5", children: [
1790
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-20 w-20 shrink-0 rounded-2xl bg-muted/40 animate-pulse" }),
1791
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 space-y-2 pt-1", children: [
1792
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-6 w-40 rounded bg-muted/40 animate-pulse" }),
1793
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-28 rounded bg-muted/30 animate-pulse" }),
1794
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-5 w-16 rounded-full bg-muted/30 animate-pulse" })
1795
+ ] })
1796
+ ] }),
1797
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-t" }),
1798
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
1799
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-36 rounded bg-muted/30 animate-pulse" }),
1800
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm p-5 space-y-3", children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "grid grid-cols-3 gap-4", children: [
1801
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse" }),
1802
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "col-span-2 h-3 w-24 rounded bg-muted/40 animate-pulse" })
1803
+ ] }, i)) })
1804
+ ] })
1805
+ ] });
1806
+ }
1807
+ if (!lead) {
1808
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
1809
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Breadcrumb, { parent: t2("crm.leads.title"), current: t2("crm.leadDetail.notFound"), onBack }),
1810
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-12 text-center rounded-lg border-2 border-dashed border-muted", children: [
1811
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.UserPlus, { className: "h-8 w-8 text-muted-foreground/30 mb-2" }),
1812
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.leadDetail.leadNotFound") }),
1813
+ /* @__PURE__ */ jsxRuntime.jsx("button", { onClick: onBack, className: "text-xs text-primary hover:underline mt-1", children: t2("crm.leadDetail.backToList") })
1814
+ ] })
1815
+ ] });
1816
+ }
1817
+ const initial = lead.name.charAt(0).toUpperCase();
1818
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6", children: [
1819
+ /* @__PURE__ */ jsxRuntime.jsx(ui.Breadcrumb, { parent: t2("crm.leads.title"), current: lead.name, onBack }),
1820
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-5", children: [
1821
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-20 w-20 shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary text-2xl font-bold shadow-sm", children: initial }),
1822
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0", children: [
1823
+ /* @__PURE__ */ jsxRuntime.jsx("h1", { className: "text-2xl font-bold text-foreground truncate", children: lead.name }),
1824
+ (lead.email || lead.phone) && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground mt-0.5", children: lead.email || lead.phone }),
1825
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2 mt-2", children: [
1826
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: `inline-flex items-center rounded-full px-2.5 py-0.5 text-[10px] font-medium capitalize ${STATUS_COLORS2[lead.status] ?? "bg-muted text-muted-foreground"}`, children: lead.status }),
1827
+ lead.sourceName && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: lead.sourceName })
1828
+ ] })
1829
+ ] }),
1830
+ onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxRuntime.jsxs(
1831
+ "button",
1832
+ {
1833
+ onClick: () => onCreateQuote(leadId),
1834
+ className: "inline-flex items-center gap-1.5 rounded-lg bg-primary border border-primary px-3 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors shrink-0",
1835
+ children: [
1836
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-3 w-3" }),
1837
+ " ",
1838
+ t2("crm.leadDetail.createQuote")
1839
+ ]
1840
+ }
1841
+ )
1842
+ ] }),
1843
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-t" }),
1844
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1845
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.contactInfo") }),
1846
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxRuntime.jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
1847
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.email"), value: lead.email ? /* @__PURE__ */ jsxRuntime.jsx("a", { href: `mailto:${lead.email}`, className: "text-primary hover:underline", children: lead.email }) : null }) }),
1848
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.phone"), value: lead.phone ? /* @__PURE__ */ jsxRuntime.jsx("a", { href: `tel:${lead.phone}`, className: "text-primary hover:underline", children: lead.phone }) : null }) }),
1849
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.company"), value: lead.company }) }),
1850
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.source"), value: lead.sourceName }) })
1851
+ ] }) })
1852
+ ] }),
1853
+ deal && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1854
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.pipeline") }),
1855
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxRuntime.jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
1856
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.stage"), value: deal.stageName ? /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
1857
+ deal.stageColor && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: deal.stageColor } }),
1858
+ deal.stageName
1859
+ ] }) : null }) }),
1860
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.dealValue"), value: deal.value > 0 ? saas.formatCurrency(deal.value, currency) : null }) }),
1861
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.probability"), value: `${deal.probability}%` }) }),
1862
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.dealStatus"), value: deal.status }) })
1863
+ ] }) })
1864
+ ] }),
1865
+ quotes.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1866
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.quotes") }),
1867
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm divide-y", children: quotes.map((q) => /* @__PURE__ */ jsxRuntime.jsxs(
1868
+ "div",
1869
+ {
1870
+ onClick: () => onViewQuote?.(q.id),
1871
+ className: "flex items-center justify-between px-5 py-3 hover:bg-muted/20 transition-colors cursor-pointer",
1872
+ children: [
1873
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 min-w-0", children: [
1874
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.FileText, { className: "h-4 w-4 text-muted-foreground shrink-0" }),
1875
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "min-w-0", children: [
1876
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium", children: q.quoteNumber }),
1877
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground", children: q.quoteDate })
1878
+ ] })
1879
+ ] }),
1880
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 shrink-0", onClick: (e) => e.stopPropagation(), children: [
1881
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm font-semibold", children: saas.formatCurrency(q.totalAmount, currency) }),
1882
+ /* @__PURE__ */ jsxRuntime.jsx(QuoteStatusDropdown, { quote: q, size: "sm", onStatusChange: (updated) => setQuotes(quotes.map((existing) => existing.id === updated.id ? updated : existing)) })
1883
+ ] })
1884
+ ]
1885
+ },
1886
+ q.id
1887
+ )) })
1888
+ ] }),
1889
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1890
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.details") }),
1891
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm", children: /* @__PURE__ */ jsxRuntime.jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
1892
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.value"), value: lead.value != null && lead.value > 0 ? lead.value : null }) }),
1893
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.assignedTo"), value: lead.assignedToName }) }),
1894
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.created"), value: lead.createdAt?.slice(0, 10) }) }),
1895
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsxRuntime.jsx(FieldRow, { label: t2("crm.leadDetail.updated"), value: lead.updatedAt?.slice(0, 10) }) })
1896
+ ] }) })
1897
+ ] }),
1898
+ lead.tags && lead.tags.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1899
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.tags") }),
1900
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex gap-1.5 flex-wrap", children: lead.tags.map((tag) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) }) })
1901
+ ] }),
1902
+ lead.notes && /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
1903
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.notes") }),
1904
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "rounded-xl border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-wrap", children: lead.notes }) })
1905
+ ] })
1906
+ ] });
1907
+ }
1908
+ var TYPE_CONFIG = {
1909
+ call: { icon: lucideReact.Phone, color: "bg-info/15 text-info dark:bg-info/20", label: "Call" },
1910
+ email: { icon: lucideReact.Mail, color: "bg-magic/15 text-magic dark:bg-magic/20", label: "Email" },
1911
+ meeting: { icon: lucideReact.Users, color: "bg-success-soft text-success-soft-foreground", label: "Meeting" },
1912
+ note: { icon: lucideReact.FileText, color: "bg-warning/15 text-warning dark:bg-warning/20", label: "Note" },
1913
+ task: { icon: lucideReact.CheckSquare, color: "bg-pink-100 text-pink-600 dark:bg-pink-500/20 dark:text-pink-400", label: "Task" },
1914
+ whatsapp: { icon: lucideReact.MessageCircle, color: "bg-success/15 text-success dark:bg-success/20", label: "WhatsApp" }
1915
+ };
1916
+ function ActivitySkeleton() {
1917
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: [1, 2, 3, 4, 5].map((i) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3 rounded-lg border bg-card shadow-sm p-4", children: [
1918
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-9 w-9 rounded-lg bg-muted/40 animate-pulse shrink-0" }),
1919
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 space-y-2 pt-0.5", children: [
1920
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
1921
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3.5 w-32 rounded bg-muted/40 animate-pulse" }),
1922
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-4 w-12 rounded-full bg-muted/30 animate-pulse" })
1923
+ ] }),
1924
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-48 rounded bg-muted/30 animate-pulse" }),
1925
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-2.5 w-24 rounded bg-muted/20 animate-pulse" })
1926
+ ] }),
1927
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "h-3 w-16 rounded bg-muted/30 animate-pulse shrink-0" })
1928
+ ] }, i)) });
1929
+ }
1930
+ function ActivityListView() {
1931
+ const t2 = core.useTranslation();
1932
+ const activities = useCrmStore((s) => s.activities);
1933
+ const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
1934
+ const fetchActivities = useCrmStore((s) => s.fetchActivities);
1935
+ const [typeFilter, setTypeFilter] = React15.useState(null);
1936
+ const [showCompleted, setShowCompleted] = React15.useState(null);
1937
+ React15.useEffect(() => {
1938
+ fetchActivities({
1939
+ activityType: typeFilter,
1940
+ completed: showCompleted ?? void 0
1941
+ });
1942
+ }, [typeFilter, showCompleted]);
1943
+ const filtered = activities;
1944
+ const pendingCount = activities.filter((a) => !a.completedAt).length;
1945
+ const overdueCount = activities.filter((a) => !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10)).length;
1946
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
1947
+ /* @__PURE__ */ jsxRuntime.jsx(
1948
+ ui.SubpageHeader,
1949
+ {
1950
+ title: t2("crm.activities.title"),
1951
+ subtitle: `${activities.length} ${t2("crm.activities.title").toLowerCase()}${pendingCount > 0 ? ` \xB7 ${pendingCount} ${t2("crm.activities.pending")}` : ""}${overdueCount > 0 ? ` \xB7 ${overdueCount} ${t2("crm.activities.overdue")}` : ""}`
1952
+ }
1953
+ ),
1954
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col sm:flex-row gap-3 sm:items-center", children: [
1955
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5 flex-wrap", children: [
1956
+ /* @__PURE__ */ jsxRuntime.jsx(
1957
+ "button",
1958
+ {
1959
+ onClick: () => setTypeFilter(null),
1960
+ className: `rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${typeFilter === null ? "bg-primary text-primary-foreground" : "bg-muted/50 text-muted-foreground hover:bg-muted"}`,
1961
+ children: t2("crm.activities.all")
1962
+ }
1963
+ ),
1964
+ Object.entries(TYPE_CONFIG).map(([type, cfg]) => {
1965
+ const Icon = cfg.icon;
1966
+ return /* @__PURE__ */ jsxRuntime.jsxs(
1967
+ "button",
1968
+ {
1969
+ onClick: () => setTypeFilter(typeFilter === type ? null : type),
1970
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${typeFilter === type ? cfg.color : "bg-muted/50 text-muted-foreground hover:bg-muted"}`,
1971
+ children: [
1972
+ /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-3 w-3" }),
1973
+ cfg.label
1974
+ ]
1975
+ },
1976
+ type
1977
+ );
1978
+ })
1979
+ ] }),
1980
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex-1" }),
1981
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex gap-1.5", children: [
1982
+ /* @__PURE__ */ jsxRuntime.jsxs(
1983
+ "button",
1984
+ {
1985
+ onClick: () => setShowCompleted(showCompleted === false ? null : false),
1986
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${showCompleted === false ? "bg-warning-soft text-warning-soft-foreground" : "bg-muted/50 text-muted-foreground hover:bg-muted"}`,
1987
+ children: [
1988
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Clock, { className: "h-3 w-3" }),
1989
+ " ",
1990
+ t2("crm.activities.pendingFilter")
1991
+ ]
1992
+ }
1993
+ ),
1994
+ /* @__PURE__ */ jsxRuntime.jsxs(
1995
+ "button",
1996
+ {
1997
+ onClick: () => setShowCompleted(showCompleted === true ? null : true),
1998
+ className: `inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-xs font-medium transition-colors ${showCompleted === true ? "bg-success-soft text-success-soft-foreground" : "bg-muted/50 text-muted-foreground hover:bg-muted"}`,
1999
+ children: [
2000
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-3 w-3" }),
2001
+ " ",
2002
+ t2("crm.activities.completedFilter")
2003
+ ]
2004
+ }
2005
+ )
2006
+ ] })
2007
+ ] }),
2008
+ activitiesLoading ? /* @__PURE__ */ jsxRuntime.jsx(ActivitySkeleton, {}) : filtered.length === 0 ? /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center justify-center py-16 text-center rounded-lg border-2 border-dashed border-muted", children: [
2009
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex h-12 w-12 items-center justify-center rounded-2xl bg-muted/30 mb-3", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Calendar, { className: "h-5 w-5 text-muted-foreground/40" }) }),
2010
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: typeFilter ? t2("crm.activities.noActivitiesOfType", { type: TYPE_CONFIG[typeFilter]?.label ?? typeFilter }) : t2("crm.activities.noActivities") }),
2011
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-[10px] text-muted-foreground/60 mt-0.5", children: t2("crm.activities.activitiesLogged") })
2012
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-2", children: filtered.map((a) => {
2013
+ const cfg = TYPE_CONFIG[a.activityType] ?? { icon: lucideReact.FileText, color: "bg-muted text-muted-foreground", label: a.activityType };
2014
+ const Icon = cfg.icon;
2015
+ const isOverdue = !a.completedAt && a.dueDate && a.dueDate < (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2016
+ return /* @__PURE__ */ jsxRuntime.jsxs(
2017
+ "div",
2018
+ {
2019
+ className: `flex items-start gap-3 rounded-lg border bg-card p-4 transition-colors ${isOverdue ? "border-destructive/30 dark:border-destructive/20" : ""}`,
2020
+ children: [
2021
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: `flex h-9 w-9 items-center justify-center rounded-lg shrink-0 ${cfg.color}`, children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "h-4 w-4" }) }),
2022
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex-1 min-w-0 pt-0.5", children: [
2023
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
2024
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium truncate", children: a.title }),
2025
+ a.completedAt && /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-0.5 rounded-full bg-success/15 px-1.5 py-0.5 text-[9px] font-medium text-success dark:bg-success/20", children: [
2026
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Check, { className: "h-2.5 w-2.5" }),
2027
+ " ",
2028
+ t2("crm.activities.done")
2029
+ ] }),
2030
+ isOverdue && /* @__PURE__ */ jsxRuntime.jsx("span", { className: "inline-flex items-center gap-0.5 rounded-full bg-destructive/15 px-1.5 py-0.5 text-[9px] font-medium text-destructive dark:bg-destructive/20", children: t2("crm.activities.overdueLabel") })
2031
+ ] }),
2032
+ a.description && /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground mt-0.5 line-clamp-2", children: a.description }),
2033
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-3 mt-1.5 text-[10px] text-muted-foreground/60", children: [
2034
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "capitalize", children: cfg.label }),
2035
+ a.dueDate && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2036
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xB7" }),
2037
+ /* @__PURE__ */ jsxRuntime.jsxs("span", { className: isOverdue ? "text-destructive font-medium" : "", children: [
2038
+ "Due ",
2039
+ a.dueDate
2040
+ ] })
2041
+ ] }),
2042
+ a.assignedToName && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2043
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xB7" }),
2044
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: a.assignedToName })
2045
+ ] }),
2046
+ a.contactName && /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2047
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: "\xB7" }),
2048
+ /* @__PURE__ */ jsxRuntime.jsx("span", { children: a.contactName })
2049
+ ] })
2050
+ ] })
2051
+ ] }),
2052
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] text-muted-foreground shrink-0 pt-1", children: new Date(a.createdAt).toLocaleDateString() })
2053
+ ]
2054
+ },
2055
+ a.id
2056
+ );
2057
+ }) })
2058
+ ] });
2059
+ }
2060
+ function buildNav(config, view, navigate) {
2061
+ const items = [
2062
+ { id: "dashboard", label: config.labels.dashboard, icon: "BarChart3", active: view === "dashboard", onClick: () => navigate("dashboard") }
2063
+ ];
2064
+ if (config.modules.pipeline) {
2065
+ items.push({ id: "pipeline", label: config.labels.pipeline, icon: "Filter", active: view === "pipeline", onClick: () => navigate("pipeline") });
2066
+ }
2067
+ items.push({
2068
+ id: "leads",
2069
+ label: config.labels.leads,
2070
+ icon: "UserPlus",
2071
+ children: [
2072
+ { id: "leads-new", label: config.labels.leadsNew, active: view === "leads-new", onClick: () => navigate("leads-new") },
2073
+ { id: "leads-list", label: config.labels.leadsList, active: view === "leads-list" || view.startsWith("leads-detail:"), onClick: () => navigate("leads-list") }
2074
+ ]
2075
+ });
2076
+ if (config.modules.quotes) {
2077
+ items.push({
2078
+ id: "quotes",
2079
+ label: config.labels.quotes,
2080
+ icon: "FileText",
2081
+ children: [
2082
+ { id: "quotes-new", label: config.labels.quotesNew, active: view === "quotes-new", onClick: () => navigate("quotes-new") },
2083
+ { id: "quotes-list", label: config.labels.quotesList, active: view === "quotes-list" || view.startsWith("quotes-detail:") || view.startsWith("quotes-edit:"), onClick: () => navigate("quotes-list") }
2084
+ ]
2085
+ });
2086
+ }
2087
+ if (config.modules.activities) {
2088
+ items.push({ id: "activities", label: config.labels.activities, icon: "MessageCircle", active: view === "activities", onClick: () => navigate("activities") });
2089
+ }
2090
+ return items;
2091
+ }
2092
+ function CrmPage({ config, provider, store, registries }) {
2093
+ const { view, direction, navigate } = saas.useModuleNavigation("/sales", {
2094
+ dashboard: 0,
2095
+ pipeline: 0,
2096
+ "leads-list": 0,
2097
+ "leads-new": 1,
2098
+ "leads-detail": 1,
2099
+ "quotes-list": 0,
2100
+ "quotes-new": 1,
2101
+ "quotes-detail": 1,
2102
+ "quotes-edit": 2,
2103
+ activities: 0,
2104
+ settings: 1
2105
+ }, "dashboard");
2106
+ const [onboardingComplete, setOnboardingComplete] = React15.useState(() => {
2107
+ try {
2108
+ return localStorage.getItem("saas-core:crm-onboarded") === "true";
2109
+ } catch {
2110
+ return false;
2111
+ }
2112
+ });
2113
+ const isSettings = view === "settings";
2114
+ const isSummary = view === "dashboard";
2115
+ const nav = buildNav(config, view, navigate);
2116
+ const t2 = core.useTranslation();
2117
+ const quickActions = React15.useMemo(() => [
2118
+ { id: "new-lead", label: t2("crm.quickActions.newLead"), icon: "UserPlus", description: t2("crm.quickActions.newLeadDesc"), action: () => navigate("leads-new") },
2119
+ { id: "new-deal", label: t2("crm.quickActions.newDeal"), icon: "Target", description: t2("crm.quickActions.newDealDesc"), action: () => navigate("pipeline") },
2120
+ ...config.modules.quotes ? [{ id: "new-quote", label: t2("crm.quickActions.newQuote"), icon: "FileText", description: t2("crm.quickActions.newQuoteDesc"), action: () => navigate("quotes-new") }] : [],
2121
+ ...config.modules.activities ? [{ id: "log-activity", label: t2("crm.quickActions.logActivity"), icon: "MessageCircle", description: t2("crm.quickActions.logActivityDesc"), action: () => navigate("activities") }] : []
2122
+ ], [config.modules]);
2123
+ if (!onboardingComplete) {
2124
+ return /* @__PURE__ */ jsxRuntime.jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsxRuntime.jsx(CrmOnboarding, { onComplete: () => {
2125
+ setOnboardingComplete(true);
2126
+ try {
2127
+ localStorage.setItem("saas-core:crm-onboarded", "true");
2128
+ } catch {
2129
+ }
2130
+ } }) });
2131
+ }
2132
+ if (isSettings && registries && registries.length > 0) {
2133
+ return /* @__PURE__ */ jsxRuntime.jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsxRuntime.jsx(ui.PageTransition, { transitionKey: "settings", direction, children: /* @__PURE__ */ jsxRuntime.jsxs("div", { style: { padding: "24px", display: "flex", flexDirection: "column", gap: "20px" }, children: [
2134
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
2135
+ /* @__PURE__ */ jsxRuntime.jsx("h1", { style: { fontSize: "20px", fontWeight: 600, margin: 0 }, children: t2("crm.settingsPage.title") }),
2136
+ /* @__PURE__ */ jsxRuntime.jsx("p", { style: { color: "var(--muted-foreground, #6b7280)", margin: "4px 0 0", fontSize: "14px" }, children: t2("crm.settingsPage.subtitle") })
2137
+ ] }),
2138
+ /* @__PURE__ */ jsxRuntime.jsx(CrmGeneralSettings, {}),
2139
+ /* @__PURE__ */ jsxRuntime.jsx(PipelineSettings, {})
2140
+ ] }) }) });
2141
+ }
2142
+ const renderView = saas.createViewRouter([
2143
+ { id: "pipeline", render: () => /* @__PURE__ */ jsxRuntime.jsx(PipelineView, { onViewLead: (id) => navigate(`leads-detail:${id}`), onViewQuote: (id) => navigate(`quotes-detail:${id}`), onAddLead: () => navigate("leads-new") }) },
2144
+ { id: "leads-list", render: () => /* @__PURE__ */ jsxRuntime.jsx(LeadListView, { onNew: () => navigate("leads-new"), onEdit: (id) => navigate(`leads-detail:${id}`) }) },
2145
+ { id: "leads-new", render: () => /* @__PURE__ */ jsxRuntime.jsx(LeadFormView, { onSaved: (id) => id ? navigate(`leads-detail:${id}`) : navigate("leads-list") }) },
2146
+ { id: "quotes-new", render: () => {
2147
+ const hashParams = new URLSearchParams(window.location.hash.split("?")[1] ?? "");
2148
+ const lid = hashParams.get("leadId") ?? void 0;
2149
+ return /* @__PURE__ */ jsxRuntime.jsx(QuoteFormView, { leadId: lid, onSaved: (id) => id ? navigate(`quotes-detail:${id}`) : navigate("quotes-list") });
2150
+ } },
2151
+ { id: "quotes-list", render: () => /* @__PURE__ */ jsxRuntime.jsx(QuoteListView, { onNew: () => navigate("quotes-new"), onEdit: (id) => navigate(`quotes-detail:${id}`), onEditQuote: (id) => navigate(`quotes-edit:${id}`) }) },
2152
+ { id: "activities", render: () => /* @__PURE__ */ jsxRuntime.jsx(ActivityListView, {}) },
2153
+ { id: "leads-detail", render: ({ id }) => /* @__PURE__ */ jsxRuntime.jsx(LeadDetailView, { leadId: id, onBack: () => navigate("leads-list"), onCreateQuote: (lid) => navigate("quotes-new", `/sales/quotes/new?leadId=${lid}`), onViewQuote: (qid) => navigate(`quotes-detail:${qid}`) }) },
2154
+ { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsxRuntime.jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
2155
+ window.location.hash = `/financial/receivables/detail/${invoiceId}`;
2156
+ } }) },
2157
+ { id: "quotes-edit", render: ({ id }) => /* @__PURE__ */ jsxRuntime.jsx(QuoteFormView, { quoteId: id, onSaved: () => navigate(`quotes-detail:${id}`) }) },
2158
+ { id: "dashboard", render: () => /* @__PURE__ */ jsxRuntime.jsx(DashboardView, {}) }
2159
+ ], "dashboard");
2160
+ return /* @__PURE__ */ jsxRuntime.jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsxRuntime.jsx(
2161
+ ui.ModulePage,
2162
+ {
2163
+ title: config.labels.pageTitle,
2164
+ subtitle: config.labels.pageSubtitle,
2165
+ nav,
2166
+ showHeader: isSummary,
2167
+ viewKey: view,
2168
+ direction,
2169
+ headerAction: /* @__PURE__ */ jsxRuntime.jsx(
2170
+ saas.ModuleActionBar,
2171
+ {
2172
+ quickActions,
2173
+ settingsPath: registries && registries.length > 0 ? "/settings/crm" : void 0,
2174
+ settingsLabel: "CRM Settings"
2175
+ }
2176
+ ),
2177
+ children: renderView(view)
2178
+ }
2179
+ ) });
2180
+ }
2181
+ function useEnsureSummary() {
2182
+ const fetchSummary = useCrmStore((s) => s.fetchSummary);
2183
+ React15.useEffect(() => {
2184
+ void fetchSummary();
2185
+ }, []);
2186
+ }
2187
+ function useEnsureFunnel() {
2188
+ const pipelines = useCrmStore((s) => s.pipelines);
2189
+ const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
2190
+ const fetchFunnel = useCrmStore((s) => s.fetchFunnel);
2191
+ React15.useEffect(() => {
2192
+ void fetchPipelines();
2193
+ }, []);
2194
+ React15.useEffect(() => {
2195
+ if (pipelines.length > 0) void fetchFunnel(pipelines[0].id);
2196
+ }, [pipelines]);
2197
+ }
2198
+ function StatusDot({ status, palette }) {
2199
+ return /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
2200
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: `h-1.5 w-1.5 rounded-full ${palette[status] ?? "bg-muted-foreground/40"}` }),
2201
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs capitalize text-muted-foreground", children: status })
2202
+ ] });
2203
+ }
2204
+ function TotalLeadsKpi() {
2205
+ const t2 = core.useTranslation();
2206
+ const summary = useCrmStore((s) => s.summary);
2207
+ useEnsureSummary();
2208
+ return /* @__PURE__ */ jsxRuntime.jsx(
2209
+ ui.KpiCard,
2210
+ {
2211
+ label: t2("crm.dashboard.totalLeads"),
2212
+ icon: "Users",
2213
+ value: String(summary?.totalLeads ?? 0),
2214
+ sub: t2("crm.dashboard.newThisMonth", { count: String(summary?.newLeadsThisMonth ?? 0) })
2215
+ }
2216
+ );
2217
+ }
2218
+ function OpenPipelineKpi() {
2219
+ const t2 = core.useTranslation();
2220
+ const { currency } = useCrmConfig();
2221
+ const summary = useCrmStore((s) => s.summary);
2222
+ useEnsureSummary();
2223
+ return /* @__PURE__ */ jsxRuntime.jsx(
2224
+ ui.KpiCard,
2225
+ {
2226
+ label: t2("crm.dashboard.openPipeline"),
2227
+ icon: "Target",
2228
+ value: saas.formatCurrency(summary?.openDealsValue ?? 0, currency),
2229
+ sub: t2("crm.dashboard.activeDeals", { count: String(summary?.totalDeals ?? 0) })
2230
+ }
2231
+ );
2232
+ }
2233
+ function ConversionRateKpi() {
2234
+ const t2 = core.useTranslation();
2235
+ const summary = useCrmStore((s) => s.summary);
2236
+ useEnsureSummary();
2237
+ return /* @__PURE__ */ jsxRuntime.jsx(
2238
+ ui.KpiCard,
2239
+ {
2240
+ label: t2("crm.dashboard.conversionRate"),
2241
+ icon: "TrendingUp",
2242
+ value: `${(summary?.conversionRate ?? 0).toFixed(1)}%`,
2243
+ sub: t2("crm.dashboard.leadToDeal")
2244
+ }
2245
+ );
2246
+ }
2247
+ function PendingTasksKpi() {
2248
+ const t2 = core.useTranslation();
2249
+ const summary = useCrmStore((s) => s.summary);
2250
+ useEnsureSummary();
2251
+ return /* @__PURE__ */ jsxRuntime.jsx(
2252
+ ui.KpiCard,
2253
+ {
2254
+ label: t2("crm.dashboard.pendingTasks"),
2255
+ icon: summary?.overdueActivities ? "AlertTriangle" : "Clock",
2256
+ value: String(summary?.pendingActivities ?? 0),
2257
+ sub: t2("crm.dashboard.overdueCount", { count: String(summary?.overdueActivities ?? 0) })
2258
+ }
2259
+ );
2260
+ }
2261
+ function SalesFunnelChart() {
2262
+ const t2 = core.useTranslation();
2263
+ const funnel = useCrmStore((s) => s.funnel);
2264
+ useEnsureFunnel();
2265
+ const data = funnel.map((s) => ({ name: s.stageName, deals: s.dealCount }));
2266
+ return /* @__PURE__ */ jsxRuntime.jsx(
2267
+ ui.ChartWidget,
2268
+ {
2269
+ type: "bar",
2270
+ title: t2("crm.dashboard.pipelineOverview"),
2271
+ icon: "BarChart3",
2272
+ categoryKey: "name",
2273
+ data,
2274
+ series: [{ dataKey: "deals" }]
2275
+ }
2276
+ );
2277
+ }
2278
+ function PipelineValueChart() {
2279
+ const t2 = core.useTranslation();
2280
+ const funnel = useCrmStore((s) => s.funnel);
2281
+ useEnsureFunnel();
2282
+ const data = funnel.map((s) => ({ name: s.stageName, value: s.totalValue }));
2283
+ return /* @__PURE__ */ jsxRuntime.jsx(
2284
+ ui.ChartWidget,
2285
+ {
2286
+ type: "bar",
2287
+ title: t2("crm.dashboard.pipelineValue"),
2288
+ icon: "Target",
2289
+ categoryKey: "name",
2290
+ data,
2291
+ series: [{ dataKey: "value", label: t2("crm.dashboard.pipelineValue"), color: "hsl(var(--magic))" }]
2292
+ }
2293
+ );
2294
+ }
2295
+ function PerformancePanel() {
2296
+ const t2 = core.useTranslation();
2297
+ const { currency } = useCrmConfig();
2298
+ const summary = useCrmStore((s) => s.summary);
2299
+ useEnsureSummary();
2300
+ const rows = [
2301
+ { label: t2("crm.dashboard.dealsWon"), value: String(summary?.wonDealsThisMonth ?? 0) },
2302
+ { label: t2("crm.dashboard.revenueWon"), value: saas.formatCurrency(summary?.wonDealsValueThisMonth ?? 0, currency), accent: true },
2303
+ { label: t2("crm.dashboard.avgDealValue"), value: saas.formatCurrency(summary?.averageDealValue ?? 0, currency) },
2304
+ { label: t2("crm.dashboard.conversionRateLabel"), value: `${(summary?.conversionRate ?? 0).toFixed(1)}%` }
2305
+ ];
2306
+ return /* @__PURE__ */ jsxRuntime.jsxs(ui.Card, { children: [
2307
+ /* @__PURE__ */ jsxRuntime.jsx(ui.CardHeader, { children: /* @__PURE__ */ jsxRuntime.jsxs(ui.CardTitle, { className: "flex items-center gap-2", children: [
2308
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-warning", children: "\u2605" }),
2309
+ t2("crm.dashboard.performance")
2310
+ ] }) }),
2311
+ /* @__PURE__ */ jsxRuntime.jsx(ui.CardContent, { className: "space-y-3", children: rows.map((r) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
2312
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm text-muted-foreground", children: r.label }),
2313
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: `text-sm font-semibold ${r.accent ? "text-success" : ""}`, children: r.value })
2314
+ ] }, r.label)) })
2315
+ ] });
2316
+ }
2317
+ var LEAD_STATUS = {
2318
+ new: "bg-info",
2319
+ contacted: "bg-magic",
2320
+ qualified: "bg-success",
2321
+ converted: "bg-warning",
2322
+ lost: "bg-destructive"
2323
+ };
2324
+ var QUOTE_STATUS = {
2325
+ draft: "bg-muted-foreground",
2326
+ sent: "bg-info",
2327
+ approved: "bg-success",
2328
+ rejected: "bg-destructive",
2329
+ expired: "bg-warning"
2330
+ };
2331
+ function RecentLeadsTable() {
2332
+ const t2 = core.useTranslation();
2333
+ const leads = useCrmStore((s) => s.leads);
2334
+ const fetchLeads = useCrmStore((s) => s.fetchLeads);
2335
+ React15.useEffect(() => {
2336
+ void fetchLeads({ pageSize: 5 });
2337
+ }, []);
2338
+ const columns2 = [
2339
+ { accessorKey: "name", header: t2("crm.dashboard.recentLeads"), cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: row.original.name }) },
2340
+ { id: "contact", header: "", cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: row.original.email || row.original.phone || row.original.sourceName || "\u2014" }) },
2341
+ { accessorKey: "status", header: "", cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx(StatusDot, { status: row.original.status, palette: LEAD_STATUS }) }
2342
+ ];
2343
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.TableWidget, { title: t2("crm.dashboard.recentLeads"), icon: "Users", columns: columns2, data: leads.slice(0, 5), emptyMessage: t2("crm.dashboard.noLeadsYet") });
2344
+ }
2345
+ function RecentQuotesTable() {
2346
+ const t2 = core.useTranslation();
2347
+ const { currency } = useCrmConfig();
2348
+ const quotes = useCrmStore((s) => s.quotes);
2349
+ const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
2350
+ React15.useEffect(() => {
2351
+ void fetchQuotes({ pageSize: 5 });
2352
+ }, []);
2353
+ const columns2 = [
2354
+ { accessorKey: "quoteNumber", header: t2("crm.dashboard.recentQuotes"), cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-medium", children: row.original.quoteNumber }) },
2355
+ { id: "contact", header: "", cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-xs text-muted-foreground", children: row.original.contactName || "\u2014" }) },
2356
+ { accessorKey: "status", header: "", cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx(StatusDot, { status: row.original.status, palette: QUOTE_STATUS }) },
2357
+ { accessorKey: "totalAmount", header: "", cell: ({ row }) => /* @__PURE__ */ jsxRuntime.jsx("span", { className: "font-semibold", children: saas.formatCurrency(row.original.totalAmount, currency) }) }
2358
+ ];
2359
+ return /* @__PURE__ */ jsxRuntime.jsx(ui.TableWidget, { title: t2("crm.dashboard.recentQuotes"), icon: "FileText", columns: columns2, data: quotes.slice(0, 5), emptyMessage: t2("crm.dashboard.noQuotesYet") });
2360
+ }
2361
+ function createCrmDashboardWidgets(ctx2) {
2362
+ const withCtx = (Inner) => {
2363
+ const Wrapped = () => /* @__PURE__ */ jsxRuntime.jsx(CrmContextProvider, { config: ctx2.config, provider: ctx2.provider, store: ctx2.store, children: /* @__PURE__ */ jsxRuntime.jsx(Inner, {}) });
2364
+ Wrapped.displayName = `CrmWidget(${Inner.displayName ?? Inner.name})`;
2365
+ return Wrapped;
2366
+ };
2367
+ return [
2368
+ // Open pipeline is CRM's headline KPI — visible on the global home by
2369
+ // default. The rest are hidden on the home (defaultVisible:false) but show
2370
+ // on the CRM plugin-home and can be added to the home via Customize.
2371
+ ui.defineKpiWidget({ id: "crm.kpi.open-pipeline", title: "crm.dashboard.openPipeline", domain: "crm", defaultOrder: 1, component: withCtx(OpenPipelineKpi) }),
2372
+ ui.defineKpiWidget({ id: "crm.kpi.total-leads", title: "crm.dashboard.totalLeads", domain: "crm", defaultOrder: 0, defaultVisible: false, component: withCtx(TotalLeadsKpi) }),
2373
+ ui.defineKpiWidget({ id: "crm.kpi.conversion-rate", title: "crm.dashboard.conversionRate", domain: "crm", defaultOrder: 2, defaultVisible: false, component: withCtx(ConversionRateKpi) }),
2374
+ ui.defineKpiWidget({ id: "crm.kpi.pending-tasks", title: "crm.dashboard.pendingTasks", domain: "crm", defaultOrder: 3, defaultVisible: false, component: withCtx(PendingTasksKpi) }),
2375
+ // Charts/tables are richer — default them to the CRM plugin-home only, so
2376
+ // the global app home stays a clean cross-domain KPI overview. Users can
2377
+ // still surface them via the Customize menu / app layout.
2378
+ ui.defineChartWidget({ id: "crm.chart.funnel", title: "crm.dashboard.pipelineOverview", domain: "crm", span: 2, defaultOrder: 10, surfaces: ["plugin-home"], component: withCtx(SalesFunnelChart) }),
2379
+ ui.defineCustomWidget({ id: "crm.panel.performance", title: "crm.dashboard.performance", domain: "crm", span: 2, defaultOrder: 11, surfaces: ["plugin-home"], component: withCtx(PerformancePanel) }),
2380
+ ui.defineChartWidget({ id: "crm.chart.pipeline-value", title: "crm.dashboard.pipelineValue", domain: "crm", span: 4, defaultOrder: 12, surfaces: ["plugin-home"], component: withCtx(PipelineValueChart) }),
2381
+ ui.defineTableWidget({ id: "crm.table.recent-leads", title: "crm.dashboard.recentLeads", domain: "crm", span: 2, defaultOrder: 20, surfaces: ["plugin-home"], component: withCtx(RecentLeadsTable) }),
2382
+ ui.defineTableWidget({ id: "crm.table.recent-quotes", title: "crm.dashboard.recentQuotes", domain: "crm", span: 2, defaultOrder: 21, surfaces: ["plugin-home"], component: withCtx(RecentQuotesTable) })
2383
+ ];
2384
+ }
2385
+
2386
+ // src/cascade.ts
2387
+ function deriveLeadStatus(stage) {
2388
+ if (stage.isWon) return "converted";
2389
+ if (stage.isLost) return "lost";
2390
+ if (stage.probability <= 10) return "new";
2391
+ if (stage.probability <= 25) return "contacted";
2392
+ return "qualified";
2393
+ }
2394
+ function deriveQuoteStatus(stage, current) {
2395
+ if (stage.isWon) return "approved";
2396
+ if (stage.isLost) return "rejected";
2397
+ return current;
2398
+ }
2399
+
2400
+ // src/data/mock.ts
2401
+ var nextId2 = 1;
2402
+ function uid() {
2403
+ return String(nextId2++);
2404
+ }
2405
+ function now() {
2406
+ return (/* @__PURE__ */ new Date()).toISOString();
2407
+ }
2408
+ function today() {
2409
+ return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2410
+ }
2411
+ function paginate(items, page, pageSize) {
2412
+ const p = page ?? 1;
2413
+ const ps = pageSize ?? 50;
2414
+ const start = (p - 1) * ps;
2415
+ return { data: items.slice(start, start + ps), total: items.length };
2416
+ }
2417
+ function createStore(seedStages) {
2418
+ const tenantId = "mock-tenant";
2419
+ const pipelineId = uid();
2420
+ const defaultStages = [
2421
+ { name: "New", color: "#6366f1", probability: 10 },
2422
+ { name: "Contacted", color: "#3b82f6", probability: 25 },
2423
+ { name: "Qualified", color: "#f59e0b", probability: 50 },
2424
+ { name: "Proposal", color: "#f97316", probability: 75 },
2425
+ { name: "Negotiation", color: "#8b5cf6", probability: 90 },
2426
+ { name: "Won", color: "#22c55e", probability: 100 },
2427
+ { name: "Lost", color: "#ef4444", probability: 0 }
2428
+ ];
2429
+ const stages = defaultStages.map((s, i) => ({
2430
+ id: uid(),
2431
+ pipelineId,
2432
+ name: s.name,
2433
+ order: i,
2434
+ color: s.color,
2435
+ probability: s.probability,
2436
+ isWon: s.name === "Won",
2437
+ isLost: s.name === "Lost",
2438
+ tenantId,
2439
+ createdAt: now()
2440
+ }));
2441
+ return {
2442
+ pipelines: [{
2443
+ id: pipelineId,
2444
+ name: "Sales Pipeline",
2445
+ isDefault: true,
2446
+ isActive: true,
2447
+ tenantId,
2448
+ createdAt: now(),
2449
+ updatedAt: now()
2450
+ }],
2451
+ stages,
2452
+ leads: [],
2453
+ deals: [],
2454
+ activities: [],
2455
+ quotes: []
2456
+ };
2457
+ }
2458
+ function createMockCrmProvider(options) {
2459
+ const store = createStore();
2460
+ const tenantId = "mock-tenant";
2461
+ function cascadeFromStage(deal, stage) {
2462
+ if (deal.leadId) {
2463
+ const lead = store.leads.find((l) => l.id === deal.leadId);
2464
+ if (lead) {
2465
+ lead.status = deriveLeadStatus(stage);
2466
+ lead.updatedAt = now();
2467
+ }
2468
+ }
2469
+ for (const q of store.quotes) {
2470
+ if (q.dealId === deal.id) {
2471
+ q.status = deriveQuoteStatus(stage, q.status);
2472
+ q.updatedAt = now();
2473
+ }
2474
+ }
2475
+ }
2476
+ const provider = {
2477
+ async getPipelines() {
2478
+ return store.pipelines;
2479
+ },
2480
+ async getPipelineStages(pipelineId) {
2481
+ return store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
2482
+ },
2483
+ // Leads
2484
+ async getLeads(query) {
2485
+ let results = [...store.leads];
2486
+ if (query.status) {
2487
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
2488
+ results = results.filter((l) => statuses.includes(l.status));
2489
+ }
2490
+ if (query.sourceId) results = results.filter((l) => l.sourceId === query.sourceId);
2491
+ if (query.search) {
2492
+ const s = query.search.toLowerCase();
2493
+ results = results.filter((l) => l.name.toLowerCase().includes(s) || l.email?.toLowerCase().includes(s) || l.company?.toLowerCase().includes(s));
2494
+ }
2495
+ results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2496
+ return paginate(results, query.page, query.pageSize);
2497
+ },
2498
+ async getLeadById(id) {
2499
+ return store.leads.find((l) => l.id === id) ?? null;
2500
+ },
2501
+ async createLead(input) {
2502
+ const lead = {
2503
+ id: uid(),
2504
+ name: input.name,
2505
+ email: input.email,
2506
+ phone: input.phone,
2507
+ company: input.company,
2508
+ sourceId: input.sourceId,
2509
+ status: "new",
2510
+ assignedToId: input.assignedToId,
2511
+ value: input.value,
2512
+ tags: input.tags ?? [],
2513
+ notes: input.notes,
2514
+ tenantId,
2515
+ createdAt: now(),
2516
+ updatedAt: now()
2517
+ };
2518
+ store.leads.push(lead);
2519
+ return lead;
2520
+ },
2521
+ async updateLead(id, data) {
2522
+ const lead = store.leads.find((l) => l.id === id);
2523
+ if (!lead) throw new Error(`Lead ${id} not found`);
2524
+ Object.assign(lead, data, { updatedAt: now() });
2525
+ return lead;
2526
+ },
2527
+ async convertLeadToDeal(leadId, dealInput) {
2528
+ const lead = store.leads.find((l) => l.id === leadId);
2529
+ if (!lead) throw new Error(`Lead ${leadId} not found`);
2530
+ lead.status = "converted";
2531
+ lead.updatedAt = now();
2532
+ const deal = await provider.createDeal({ ...dealInput, leadId });
2533
+ return deal;
2534
+ },
2535
+ // Deals
2536
+ async getDeals(query) {
2537
+ let results = [...store.deals];
2538
+ if (query.pipelineId) results = results.filter((d) => d.pipelineId === query.pipelineId);
2539
+ if (query.stageId) results = results.filter((d) => d.stageId === query.stageId);
2540
+ if (query.status) {
2541
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
2542
+ results = results.filter((d) => statuses.includes(d.status));
2543
+ }
2544
+ if (query.search) {
2545
+ const s = query.search.toLowerCase();
2546
+ results = results.filter((d) => d.title.toLowerCase().includes(s) || d.contactName?.toLowerCase().includes(s));
2547
+ }
2548
+ results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2549
+ return paginate(results, query.page, query.pageSize);
2550
+ },
2551
+ async getDealById(id) {
2552
+ return store.deals.find((d) => d.id === id) ?? null;
2553
+ },
2554
+ async getDealsByStage(pipelineId) {
2555
+ const stages = store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
2556
+ const map = /* @__PURE__ */ new Map();
2557
+ for (const stage of stages) {
2558
+ map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open"));
2559
+ }
2560
+ return map;
2561
+ },
2562
+ async createDeal(input) {
2563
+ const stage = store.stages.find((s) => s.id === input.stageId);
2564
+ const deal = {
2565
+ id: uid(),
2566
+ leadId: input.leadId,
2567
+ title: input.title,
2568
+ value: input.value,
2569
+ pipelineId: input.pipelineId,
2570
+ stageId: input.stageId,
2571
+ stageName: stage?.name,
2572
+ stageColor: stage?.color,
2573
+ probability: stage?.probability ?? 0,
2574
+ expectedCloseDate: input.expectedCloseDate,
2575
+ assignedToId: input.assignedToId,
2576
+ contactId: input.contactId,
2577
+ contactName: input.contactName,
2578
+ status: "open",
2579
+ tags: input.tags ?? [],
2580
+ notes: input.notes,
2581
+ tenantId,
2582
+ createdAt: now(),
2583
+ updatedAt: now()
2584
+ };
2585
+ store.deals.push(deal);
2586
+ return deal;
2587
+ },
2588
+ async updateDeal(id, data) {
2589
+ const deal = store.deals.find((d) => d.id === id);
2590
+ if (!deal) throw new Error(`Deal ${id} not found`);
2591
+ Object.assign(deal, data, { updatedAt: now() });
2592
+ return deal;
2593
+ },
2594
+ async moveDealToStage(dealId, stageId) {
2595
+ const deal = store.deals.find((d) => d.id === dealId);
2596
+ if (!deal) throw new Error(`Deal ${dealId} not found`);
2597
+ const stage = store.stages.find((s) => s.id === stageId);
2598
+ if (!stage) throw new Error(`Stage ${stageId} not found`);
2599
+ deal.stageId = stageId;
2600
+ deal.stageName = stage.name;
2601
+ deal.stageColor = stage.color;
2602
+ deal.probability = stage.probability ?? 0;
2603
+ if (stage.isWon) deal.status = "won";
2604
+ if (stage.isLost) deal.status = "lost";
2605
+ deal.updatedAt = now();
2606
+ cascadeFromStage(deal, stage);
2607
+ return deal;
2608
+ },
2609
+ // Activities
2610
+ async getActivities(query) {
2611
+ let results = [...store.activities];
2612
+ if (query.dealId) results = results.filter((a) => a.dealId === query.dealId);
2613
+ if (query.leadId) results = results.filter((a) => a.leadId === query.leadId);
2614
+ if (query.activityType) results = results.filter((a) => a.activityType === query.activityType);
2615
+ if (query.completed !== void 0) {
2616
+ results = query.completed ? results.filter((a) => a.completedAt) : results.filter((a) => !a.completedAt);
2617
+ }
2618
+ results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2619
+ return paginate(results, query.page, query.pageSize);
2620
+ },
2621
+ async createActivity(input) {
2622
+ const activity = {
2623
+ id: uid(),
2624
+ dealId: input.dealId,
2625
+ leadId: input.leadId,
2626
+ contactId: input.contactId,
2627
+ activityType: input.activityType,
2628
+ title: input.title,
2629
+ description: input.description,
2630
+ dueDate: input.dueDate,
2631
+ assignedToId: input.assignedToId,
2632
+ tenantId,
2633
+ createdAt: now()
2634
+ };
2635
+ store.activities.push(activity);
2636
+ return activity;
2637
+ },
2638
+ async completeActivity(id) {
2639
+ const activity = store.activities.find((a) => a.id === id);
2640
+ if (!activity) throw new Error(`Activity ${id} not found`);
2641
+ activity.completedAt = now();
2642
+ return activity;
2643
+ },
2644
+ // Quotes
2645
+ async getQuotes(query) {
2646
+ let results = [...store.quotes];
2647
+ if (query.status) {
2648
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
2649
+ results = results.filter((q) => statuses.includes(q.status));
2650
+ }
2651
+ if (query.contactId) results = results.filter((q) => q.contactId === query.contactId);
2652
+ if (query.search) {
2653
+ const s = query.search.toLowerCase();
2654
+ results = results.filter((q) => q.quoteNumber.includes(s) || q.contactName?.toLowerCase().includes(s));
2655
+ }
2656
+ results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
2657
+ return paginate(results, query.page, query.pageSize);
2658
+ },
2659
+ async getQuoteById(id) {
2660
+ return store.quotes.find((q) => q.id === id) ?? null;
2661
+ },
2662
+ async createQuote(input) {
2663
+ const quoteId = uid();
2664
+ const items = input.items.map((item) => ({
2665
+ id: uid(),
2666
+ quoteId,
2667
+ ...item,
2668
+ createdAt: now()
2669
+ }));
2670
+ const totalAmount = items.reduce((sum, i) => sum + i.totalAmount, 0);
2671
+ const quote = {
2672
+ id: quoteId,
2673
+ dealId: input.dealId,
2674
+ leadId: input.leadId,
2675
+ contactId: input.contactId,
2676
+ contactName: input.contactName,
2677
+ quoteNumber: `Q-${String(store.quotes.length + 1).padStart(4, "0")}`,
2678
+ quoteDate: input.quoteDate,
2679
+ validUntil: input.validUntil,
2680
+ status: "draft",
2681
+ totalAmount,
2682
+ observations: input.observations,
2683
+ paymentConditions: input.paymentConditions,
2684
+ items,
2685
+ tenantId,
2686
+ createdAt: now(),
2687
+ updatedAt: now()
2688
+ };
2689
+ store.quotes.push(quote);
2690
+ return quote;
2691
+ },
2692
+ async updateQuote(id, input) {
2693
+ const quote = store.quotes.find((q) => q.id === id);
2694
+ if (!quote) throw new Error(`Quote ${id} not found`);
2695
+ const items = input.items.map((item) => ({
2696
+ id: uid(),
2697
+ quoteId: id,
2698
+ ...item,
2699
+ createdAt: now()
2700
+ }));
2701
+ const totalAmount = items.reduce((sum, i) => sum + i.totalAmount, 0);
2702
+ quote.contactId = input.contactId;
2703
+ quote.contactName = input.contactName;
2704
+ quote.dealId = input.dealId;
2705
+ quote.leadId = input.leadId;
2706
+ quote.quoteDate = input.quoteDate;
2707
+ quote.validUntil = input.validUntil;
2708
+ quote.observations = input.observations;
2709
+ quote.paymentConditions = input.paymentConditions;
2710
+ quote.items = items;
2711
+ quote.totalAmount = totalAmount;
2712
+ quote.updatedAt = now();
2713
+ return quote;
2714
+ },
2715
+ async sendQuote(id) {
2716
+ const quote = store.quotes.find((q) => q.id === id);
2717
+ if (!quote) throw new Error(`Quote ${id} not found`);
2718
+ quote.status = "sent";
2719
+ quote.updatedAt = now();
2720
+ return quote;
2721
+ },
2722
+ async approveQuote(id) {
2723
+ const quote = store.quotes.find((q) => q.id === id);
2724
+ if (!quote) throw new Error(`Quote ${id} not found`);
2725
+ quote.status = "approved";
2726
+ quote.updatedAt = now();
2727
+ if (quote.dealId) {
2728
+ const deal = store.deals.find((d) => d.id === quote.dealId);
2729
+ if (deal) {
2730
+ const wonStage = store.stages.find((s) => s.pipelineId === deal.pipelineId && s.isWon);
2731
+ if (wonStage) {
2732
+ await provider.moveDealToStage(deal.id, wonStage.id);
2733
+ }
2734
+ }
2735
+ }
2736
+ quote.convertedInvoiceId = uid();
2737
+ if (quote.leadId) {
2738
+ const lead = store.leads.find((l) => l.id === quote.leadId);
2739
+ if (lead) {
2740
+ lead.metadata = { ...lead.metadata, convertedFromLead: true };
2741
+ }
2742
+ }
2743
+ return quote;
2744
+ },
2745
+ async rejectQuote(id, reason) {
2746
+ const quote = store.quotes.find((q) => q.id === id);
2747
+ if (!quote) throw new Error(`Quote ${id} not found`);
2748
+ quote.status = "rejected";
2749
+ quote.rejectionReason = reason;
2750
+ quote.updatedAt = now();
2751
+ if (quote.dealId) {
2752
+ const deal = store.deals.find((d) => d.id === quote.dealId);
2753
+ if (deal) {
2754
+ const lostStage = store.stages.find((s) => s.pipelineId === deal.pipelineId && s.isLost);
2755
+ if (lostStage) {
2756
+ await provider.moveDealToStage(deal.id, lostStage.id);
2757
+ }
2758
+ }
2759
+ }
2760
+ return quote;
2761
+ },
2762
+ async expireQuote(id) {
2763
+ const quote = store.quotes.find((q) => q.id === id);
2764
+ if (!quote) throw new Error(`Quote ${id} not found`);
2765
+ quote.status = "expired";
2766
+ quote.updatedAt = now();
2767
+ return quote;
2768
+ },
2769
+ // Cross-entity lookups
2770
+ async getQuotesByDealId(dealId) {
2771
+ return store.quotes.filter((q) => q.dealId === dealId);
2772
+ },
2773
+ async getDealByLeadId(leadId) {
2774
+ return store.deals.find((d) => d.leadId === leadId) ?? null;
2775
+ },
2776
+ // Summary
2777
+ async getSummary() {
2778
+ const monthStart = today().slice(0, 7) + "-01";
2779
+ const monthLeads = store.leads.filter((l) => l.createdAt >= monthStart);
2780
+ const wonDeals = store.deals.filter((d) => d.status === "won");
2781
+ const wonThisMonth = wonDeals.filter((d) => d.updatedAt >= monthStart);
2782
+ const openDeals = store.deals.filter((d) => d.status === "open");
2783
+ const totalConverted = store.leads.filter((l) => l.status === "converted").length;
2784
+ const pendingActivities = store.activities.filter((a) => !a.completedAt);
2785
+ const overdueActivities = pendingActivities.filter((a) => a.dueDate && a.dueDate < today());
2786
+ return {
2787
+ totalLeads: store.leads.length,
2788
+ newLeadsThisMonth: monthLeads.length,
2789
+ totalDeals: store.deals.length,
2790
+ openDealsValue: openDeals.reduce((s, d) => s + d.value, 0),
2791
+ wonDealsThisMonth: wonThisMonth.length,
2792
+ wonDealsValueThisMonth: wonThisMonth.reduce((s, d) => s + d.value, 0),
2793
+ conversionRate: store.leads.length > 0 ? totalConverted / store.leads.length * 100 : 0,
2794
+ averageDealValue: wonDeals.length > 0 ? wonDeals.reduce((s, d) => s + d.value, 0) / wonDeals.length : 0,
2795
+ pendingActivities: pendingActivities.length,
2796
+ overdueActivities: overdueActivities.length
2797
+ };
2798
+ },
2799
+ async getFunnel(pipelineId) {
2800
+ const stages = store.stages.filter((s) => s.pipelineId === pipelineId && !s.isLost).sort((a, b) => a.order - b.order);
2801
+ return stages.map((stage) => {
2802
+ const deals = store.deals.filter((d) => d.stageId === stage.id);
2803
+ return {
2804
+ stageId: stage.id,
2805
+ stageName: stage.name,
2806
+ stageColor: stage.color,
2807
+ dealCount: deals.length,
2808
+ totalValue: deals.reduce((s, d) => s + d.value, 0)
2809
+ };
2810
+ });
2811
+ }
2812
+ };
2813
+ return provider;
2814
+ }
2815
+
2816
+ // src/data/supabase.ts
2817
+ function getTenantId() {
2818
+ return core.getActiveTenantId();
2819
+ }
2820
+ function snakeToCamel(obj) {
2821
+ const result = {};
2822
+ for (const [key, value] of Object.entries(obj)) {
2823
+ result[key.replace(/_([a-z])/g, (_, c) => c.toUpperCase())] = value;
2824
+ }
2825
+ return result;
2826
+ }
2827
+ function getClients() {
2828
+ const supabase = core.getSupabaseClientOptional();
2829
+ if (!supabase) throw new Error("Supabase not initialized");
2830
+ return { core: supabase.schema("saas_core"), pub: supabase };
2831
+ }
2832
+ function createSupabaseCrmProvider(options) {
2833
+ const provider = {
2834
+ // --- Pipelines (public.pipelines + pipeline_stages) ---
2835
+ async getPipelines() {
2836
+ const { pub } = getClients();
2837
+ const { data } = await pub.from("pipelines").select("*").eq("is_active", true).order("name");
2838
+ return (data ?? []).map((r) => snakeToCamel(r));
2839
+ },
2840
+ async getPipelineStages(pipelineId) {
2841
+ const { pub } = getClients();
2842
+ const { data } = await pub.from("pipeline_stages").select("*").eq("pipeline_id", pipelineId).order("order");
2843
+ return (data ?? []).map((r) => snakeToCamel(r));
2844
+ },
2845
+ // --- Leads (via view — single query) ---
2846
+ async getLeads(query) {
2847
+ const { pub } = getClients();
2848
+ let qb = pub.from("v_leads").select("*", { count: "exact" });
2849
+ if (query.search) qb = qb.ilike("name", `%${query.search}%`);
2850
+ if (query.status) {
2851
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
2852
+ qb = qb.in("lead_status", statuses);
2853
+ }
2854
+ const page = query.page ?? 1;
2855
+ const pageSize = query.pageSize ?? 50;
2856
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
2857
+ const { data, count } = await qb;
2858
+ return {
2859
+ data: (data ?? []).map((r) => ({
2860
+ id: r.id,
2861
+ name: r.name,
2862
+ email: r.email,
2863
+ phone: r.phone,
2864
+ company: r.company,
2865
+ sourceId: r.source_id,
2866
+ sourceName: r.source_name,
2867
+ status: r.lead_status ?? "new",
2868
+ assignedToId: r.assigned_to_id,
2869
+ value: r.lead_value ? Number(r.lead_value) : void 0,
2870
+ tags: r.tags ?? [],
2871
+ notes: r.notes,
2872
+ tenantId: r.tenant_id,
2873
+ createdAt: r.created_at,
2874
+ updatedAt: r.updated_at
2875
+ })),
2876
+ total: count ?? 0
2877
+ };
2878
+ },
2879
+ async getLeadById(id) {
2880
+ const { pub } = getClients();
2881
+ const { data: r } = await pub.from("v_leads").select("*").eq("id", id).maybeSingle();
2882
+ if (!r) return null;
2883
+ return {
2884
+ id: r.id,
2885
+ name: r.name,
2886
+ email: r.email,
2887
+ phone: r.phone,
2888
+ company: r.company,
2889
+ status: r.lead_status ?? "new",
2890
+ tags: r.tags ?? [],
2891
+ notes: r.notes,
2892
+ tenantId: r.tenant_id,
2893
+ createdAt: r.created_at,
2894
+ updatedAt: r.updated_at
2895
+ };
2896
+ },
2897
+ async createLead(input) {
2898
+ const { core } = getClients();
2899
+ const tenantId = getTenantId();
2900
+ const { data, error } = await core.from("persons").insert({
2901
+ tenant_id: tenantId,
2902
+ kind: "lead",
2903
+ name: input.name,
2904
+ email: input.email,
2905
+ phone: input.phone,
2906
+ notes: input.notes,
2907
+ tags: input.tags ?? [],
2908
+ is_active: true,
2909
+ metadata: { company: input.company, sourceId: input.sourceId, status: "new", value: input.value }
2910
+ }).select().single();
2911
+ if (error) throw new Error(error.message);
2912
+ const p = snakeToCamel(data);
2913
+ return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
2914
+ },
2915
+ async updateLead(id, partial) {
2916
+ const { core } = getClients();
2917
+ const row = {};
2918
+ if (partial.name) row.name = partial.name;
2919
+ if (partial.email !== void 0) row.email = partial.email;
2920
+ if (partial.phone !== void 0) row.phone = partial.phone;
2921
+ if (partial.notes !== void 0) row.notes = partial.notes;
2922
+ if (partial.status) row.metadata = { status: partial.status };
2923
+ const { data, error } = await core.from("persons").update(row).eq("id", id).select().single();
2924
+ if (error) throw new Error(error.message);
2925
+ return await provider.getLeadById(id);
2926
+ },
2927
+ async convertLeadToDeal(leadId, dealInput) {
2928
+ const { core } = getClients();
2929
+ await core.from("persons").update({ metadata: { status: "converted" } }).eq("id", leadId);
2930
+ return provider.createDeal({ ...dealInput, leadId });
2931
+ },
2932
+ // --- Deals (via view — single query with all joins) ---
2933
+ async getDeals(query) {
2934
+ const { pub } = getClients();
2935
+ let qb = pub.from("v_deals").select("*", { count: "exact" });
2936
+ if (query.status) {
2937
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
2938
+ qb = qb.in("status", statuses);
2939
+ }
2940
+ if (query.search) qb = qb.ilike("title", `%${query.search}%`);
2941
+ if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
2942
+ if (query.stageId) qb = qb.eq("stage_id", query.stageId);
2943
+ const page = query.page ?? 1;
2944
+ const pageSize = query.pageSize ?? 50;
2945
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
2946
+ const { data, count } = await qb;
2947
+ const deals = (data ?? []).map((r) => ({
2948
+ id: r.id,
2949
+ leadId: r.lead_id,
2950
+ title: r.title ?? "Untitled Deal",
2951
+ value: r.value ?? 0,
2952
+ pipelineId: r.pipeline_id ?? "",
2953
+ stageId: r.stage_id ?? "",
2954
+ stageName: r.stage_name,
2955
+ stageColor: r.stage_color,
2956
+ probability: r.probability ?? 0,
2957
+ expectedCloseDate: r.expected_close_date,
2958
+ assignedToId: r.assigned_to_id,
2959
+ contactId: r.contact_id,
2960
+ contactName: r.contact_name,
2961
+ status: r.status ?? "open",
2962
+ lostReason: r.lost_reason,
2963
+ tags: r.tags ?? [],
2964
+ notes: r.title,
2965
+ tenantId: r.tenant_id,
2966
+ createdAt: r.created_at,
2967
+ updatedAt: r.updated_at
2968
+ }));
2969
+ return { data: deals, total: count ?? 0 };
2970
+ },
2971
+ async getDealById(id) {
2972
+ const { pub } = getClients();
2973
+ const { data: r } = await pub.from("v_deals").select("*").eq("id", id).maybeSingle();
2974
+ if (!r) return null;
2975
+ return {
2976
+ id: r.id,
2977
+ title: r.title ?? "",
2978
+ value: r.value ?? 0,
2979
+ pipelineId: r.pipeline_id ?? "",
2980
+ stageId: r.stage_id ?? "",
2981
+ stageName: r.stage_name,
2982
+ stageColor: r.stage_color,
2983
+ probability: r.probability ?? 0,
2984
+ status: r.status ?? "open",
2985
+ contactName: r.contact_name,
2986
+ tags: r.tags ?? [],
2987
+ tenantId: r.tenant_id,
2988
+ createdAt: r.created_at,
2989
+ updatedAt: r.updated_at
2990
+ };
2991
+ },
2992
+ async getDealsByStage(pipelineId) {
2993
+ const { pub } = getClients();
2994
+ const stages = await provider.getPipelineStages(pipelineId);
2995
+ const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).neq("status", "lost");
2996
+ const deals = (data ?? []).map((r) => ({
2997
+ id: r.id,
2998
+ title: r.title ?? "",
2999
+ value: r.value ?? 0,
3000
+ pipelineId: r.pipeline_id,
3001
+ stageId: r.stage_id,
3002
+ stageName: r.stage_name,
3003
+ stageColor: r.stage_color,
3004
+ probability: r.probability ?? 0,
3005
+ status: r.status ?? "open",
3006
+ contactName: r.contact_name,
3007
+ tags: r.tags ?? [],
3008
+ tenantId: r.tenant_id,
3009
+ createdAt: r.created_at,
3010
+ updatedAt: r.updated_at
3011
+ }));
3012
+ const map = /* @__PURE__ */ new Map();
3013
+ for (const stage of stages) map.set(stage.id, []);
3014
+ for (const deal of deals) {
3015
+ const arr = map.get(deal.stageId);
3016
+ if (arr) arr.push(deal);
3017
+ }
3018
+ return map;
3019
+ },
3020
+ async createDeal(input) {
3021
+ const { core, pub } = getClients();
3022
+ const tenantId = getTenantId();
3023
+ const { data: order, error } = await core.from("orders").insert({
3024
+ tenant_id: tenantId,
3025
+ kind: "deal",
3026
+ status: "open",
3027
+ total: input.value,
3028
+ party_id: input.contactId,
3029
+ assignee_id: input.assignedToId,
3030
+ notes: input.title,
3031
+ tags: input.tags ?? [],
3032
+ currency: "BRL",
3033
+ metadata: { contactName: input.contactName }
3034
+ }).select().single();
3035
+ if (error) throw new Error(error.message);
3036
+ await pub.from("deal_extensions").insert({
3037
+ order_id: order.id,
3038
+ tenant_id: tenantId,
3039
+ pipeline_id: input.pipelineId,
3040
+ stage_id: input.stageId,
3041
+ probability: 0,
3042
+ expected_close_date: input.expectedCloseDate,
3043
+ lead_id: input.leadId
3044
+ });
3045
+ return {
3046
+ id: order.id,
3047
+ title: input.title,
3048
+ value: input.value,
3049
+ pipelineId: input.pipelineId,
3050
+ stageId: input.stageId,
3051
+ status: "open",
3052
+ probability: 0,
3053
+ tags: input.tags ?? [],
3054
+ contactName: input.contactName,
3055
+ tenantId,
3056
+ createdAt: order.created_at,
3057
+ updatedAt: order.updated_at
3058
+ };
3059
+ },
3060
+ async updateDeal(id, partial) {
3061
+ const { core, pub } = getClients();
3062
+ if (partial.title || partial.value || partial.status) {
3063
+ const row = {};
3064
+ if (partial.title) row.notes = partial.title;
3065
+ if (partial.value) row.total = partial.value;
3066
+ if (partial.status) row.status = partial.status;
3067
+ await core.from("orders").update(row).eq("id", id);
3068
+ }
3069
+ if (partial.stageId || partial.probability != null || partial.expectedCloseDate) {
3070
+ const row = {};
3071
+ if (partial.stageId) row.stage_id = partial.stageId;
3072
+ if (partial.probability != null) row.probability = partial.probability;
3073
+ if (partial.expectedCloseDate) row.expected_close_date = partial.expectedCloseDate;
3074
+ await pub.from("deal_extensions").update(row).eq("order_id", id);
3075
+ }
3076
+ return await provider.getDealById(id);
3077
+ },
3078
+ async moveDealToStage(dealId, stageId) {
3079
+ const { core, pub } = getClients();
3080
+ const { data: stageRow } = await pub.from("pipeline_stages").select("*").eq("id", stageId).single();
3081
+ await pub.from("deal_extensions").update({
3082
+ stage_id: stageId,
3083
+ probability: stageRow?.probability ?? 0
3084
+ }).eq("order_id", dealId);
3085
+ if (stageRow?.is_won) await core.from("orders").update({ status: "won" }).eq("id", dealId);
3086
+ if (stageRow?.is_lost) await core.from("orders").update({ status: "lost" }).eq("id", dealId);
3087
+ if (stageRow) {
3088
+ const typedStage = {
3089
+ id: stageRow.id,
3090
+ pipelineId: stageRow.pipeline_id,
3091
+ name: stageRow.name,
3092
+ order: stageRow.order,
3093
+ color: stageRow.color,
3094
+ probability: stageRow.probability,
3095
+ isWon: stageRow.is_won,
3096
+ isLost: stageRow.is_lost,
3097
+ tenantId: stageRow.tenant_id,
3098
+ createdAt: stageRow.created_at
3099
+ };
3100
+ const { data: ext } = await pub.from("deal_extensions").select("lead_id").eq("order_id", dealId).single();
3101
+ if (ext?.lead_id) {
3102
+ const newLeadStatus = deriveLeadStatus(typedStage);
3103
+ await core.from("persons").update({ metadata: { status: newLeadStatus } }).eq("id", ext.lead_id);
3104
+ }
3105
+ const { data: quotes } = await core.from("orders").select("id, status").eq("kind", "quote");
3106
+ for (const q of quotes ?? []) {
3107
+ const meta = q.metadata;
3108
+ if (meta?.dealId === dealId) {
3109
+ const newStatus = deriveQuoteStatus(typedStage, q.status);
3110
+ if (newStatus !== q.status) {
3111
+ await core.from("orders").update({ status: newStatus }).eq("id", q.id);
3112
+ }
3113
+ }
3114
+ }
3115
+ }
3116
+ return await provider.getDealById(dealId);
3117
+ },
3118
+ // --- Activities (public.crm_activities) ---
3119
+ async getActivities(query) {
3120
+ const { pub } = getClients();
3121
+ let qb = pub.from("crm_activities").select("*", { count: "exact" });
3122
+ if (query.dealId) qb = qb.eq("deal_id", query.dealId);
3123
+ if (query.leadId) qb = qb.eq("lead_id", query.leadId);
3124
+ if (query.activityType) qb = qb.eq("activity_type", query.activityType);
3125
+ if (query.completed === true) qb = qb.not("completed_at", "is", null);
3126
+ if (query.completed === false) qb = qb.is("completed_at", null);
3127
+ const page = query.page ?? 1;
3128
+ const pageSize = query.pageSize ?? 50;
3129
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
3130
+ const { data, count } = await qb;
3131
+ return { data: (data ?? []).map((r) => snakeToCamel(r)), total: count ?? 0 };
3132
+ },
3133
+ async createActivity(input) {
3134
+ const { pub } = getClients();
3135
+ const tenantId = getTenantId();
3136
+ const { data, error } = await pub.from("crm_activities").insert({
3137
+ tenant_id: tenantId,
3138
+ deal_id: input.dealId,
3139
+ lead_id: input.leadId,
3140
+ contact_id: input.contactId,
3141
+ activity_type: input.activityType,
3142
+ title: input.title,
3143
+ description: input.description,
3144
+ due_date: input.dueDate,
3145
+ assigned_to_id: input.assignedToId
3146
+ }).select().single();
3147
+ if (error) throw new Error(error.message);
3148
+ return snakeToCamel(data);
3149
+ },
3150
+ async completeActivity(id) {
3151
+ const { pub } = getClients();
3152
+ const { data, error } = await pub.from("crm_activities").update({ completed_at: (/* @__PURE__ */ new Date()).toISOString() }).eq("id", id).select().single();
3153
+ if (error) throw new Error(error.message);
3154
+ return snakeToCamel(data);
3155
+ },
3156
+ // --- Quotes (saas_core.orders kind='quote' + order_items) ---
3157
+ async getQuotes(query) {
3158
+ const { core } = getClients();
3159
+ let qb = core.from("orders").select("*", { count: "exact" }).eq("kind", "quote");
3160
+ if (query.status) {
3161
+ const statuses = Array.isArray(query.status) ? query.status : [query.status];
3162
+ qb = qb.in("status", statuses);
3163
+ }
3164
+ if (query.search) qb = qb.or(`reference_number.ilike.%${query.search}%,notes.ilike.%${query.search}%`);
3165
+ const page = query.page ?? 1;
3166
+ const pageSize = query.pageSize ?? 50;
3167
+ qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
3168
+ const { data, count } = await qb;
3169
+ const quotes = (data ?? []).map((r) => {
3170
+ const stage = r.stage;
3171
+ const financialStages = ["invoiced", "paid", "partial", "overdue"];
3172
+ const displayStatus = stage && financialStages.includes(stage) ? stage : r.status ?? "draft";
3173
+ return {
3174
+ id: r.id,
3175
+ quoteNumber: r.metadata?.quoteNumber ?? r.reference_number ?? "",
3176
+ quoteDate: r.created_at?.slice(0, 10) ?? "",
3177
+ validUntil: r.due_at?.slice(0, 10) ?? "",
3178
+ status: displayStatus,
3179
+ totalAmount: r.total ?? 0,
3180
+ contactId: r.party_id,
3181
+ contactName: r.metadata?.contactName,
3182
+ observations: r.notes,
3183
+ dealId: r.metadata?.dealId,
3184
+ leadId: r.metadata?.leadId,
3185
+ convertedInvoiceId: r.metadata?.convertedInvoiceId,
3186
+ items: [],
3187
+ tenantId: r.tenant_id,
3188
+ createdAt: r.created_at,
3189
+ updatedAt: r.updated_at
3190
+ };
3191
+ });
3192
+ return { data: quotes, total: count ?? 0 };
3193
+ },
3194
+ async getQuoteById(id) {
3195
+ const { core } = getClients();
3196
+ const { data: order } = await core.from("orders").select("*").eq("id", id).eq("kind", "quote").maybeSingle();
3197
+ if (!order) return null;
3198
+ const { data: items } = await core.from("order_items").select("*").eq("order_id", id).order("sort_order");
3199
+ const stage = order.stage;
3200
+ const financialStages = ["invoiced", "paid", "partial", "overdue"];
3201
+ const displayStatus = stage && financialStages.includes(stage) ? stage : order.status ?? "draft";
3202
+ return {
3203
+ id: order.id,
3204
+ quoteNumber: order.metadata?.quoteNumber ?? order.reference_number ?? "",
3205
+ quoteDate: order.created_at?.slice(0, 10) ?? "",
3206
+ validUntil: order.due_at?.slice(0, 10) ?? "",
3207
+ status: displayStatus,
3208
+ totalAmount: order.total ?? 0,
3209
+ contactId: order.party_id,
3210
+ contactName: order.metadata?.contactName,
3211
+ observations: order.notes,
3212
+ dealId: order.metadata?.dealId,
3213
+ leadId: order.metadata?.leadId,
3214
+ convertedInvoiceId: order.metadata?.convertedInvoiceId,
3215
+ items: (items ?? []).map((i) => ({
3216
+ id: i.id,
3217
+ quoteId: id,
3218
+ itemKind: i.metadata?.itemKind ?? "other",
3219
+ description: i.name ?? "",
3220
+ quantity: i.quantity ?? 1,
3221
+ unitPrice: i.unit_price ?? 0,
3222
+ discount: i.discount ?? 0,
3223
+ totalAmount: i.total ?? 0,
3224
+ createdAt: i.created_at
3225
+ })),
3226
+ tenantId: order.tenant_id,
3227
+ createdAt: order.created_at,
3228
+ updatedAt: order.updated_at
3229
+ };
3230
+ },
3231
+ async createQuote(input) {
3232
+ const { core } = getClients();
3233
+ const tenantId = getTenantId();
3234
+ const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0);
3235
+ const { count } = await core.from("orders").select("*", { count: "exact", head: true }).eq("kind", "quote");
3236
+ const nextNum = (count ?? 0) + 1;
3237
+ const { data: order, error } = await core.from("orders").insert({
3238
+ tenant_id: tenantId,
3239
+ kind: "quote",
3240
+ status: "draft",
3241
+ reference_number: `Q-${String(nextNum).padStart(4, "0")}`,
3242
+ total: totalAmount,
3243
+ party_id: input.contactId,
3244
+ due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
3245
+ notes: input.observations,
3246
+ currency: "BRL",
3247
+ metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId }
3248
+ }).select().single();
3249
+ if (error) throw new Error(error.message);
3250
+ if (input.items.length > 0) {
3251
+ const { error: itemsError } = await core.from("order_items").insert(
3252
+ input.items.map((item, i) => ({
3253
+ order_id: order.id,
3254
+ name: item.description,
3255
+ quantity: item.quantity,
3256
+ unit_price: item.unitPrice,
3257
+ discount: item.discount,
3258
+ total: item.totalAmount,
3259
+ sort_order: i,
3260
+ metadata: { itemKind: item.itemKind }
3261
+ }))
3262
+ );
3263
+ if (itemsError) throw new Error(itemsError.message);
3264
+ }
3265
+ return {
3266
+ id: order.id,
3267
+ quoteNumber: order.reference_number,
3268
+ quoteDate: order.created_at?.slice(0, 10),
3269
+ validUntil: input.validUntil,
3270
+ status: "draft",
3271
+ totalAmount,
3272
+ contactName: input.contactName,
3273
+ dealId: input.dealId,
3274
+ leadId: input.leadId,
3275
+ items: [],
3276
+ tenantId,
3277
+ createdAt: order.created_at,
3278
+ updatedAt: order.updated_at
3279
+ };
3280
+ },
3281
+ async updateQuote(id, input) {
3282
+ const { core } = getClients();
3283
+ const totalAmount = input.items.reduce((sum, i) => sum + i.totalAmount, 0);
3284
+ const { error } = await core.from("orders").update({
3285
+ total: totalAmount,
3286
+ party_id: input.contactId,
3287
+ due_at: input.validUntil ? new Date(input.validUntil).toISOString() : null,
3288
+ notes: input.observations,
3289
+ metadata: { contactName: input.contactName, paymentConditions: input.paymentConditions, dealId: input.dealId, leadId: input.leadId }
3290
+ }).eq("id", id);
3291
+ if (error) throw new Error(error.message);
3292
+ await core.from("order_items").delete().eq("order_id", id);
3293
+ if (input.items.length > 0) {
3294
+ const { error: itemsError } = await core.from("order_items").insert(
3295
+ input.items.map((item, i) => ({
3296
+ order_id: id,
3297
+ name: item.description,
3298
+ quantity: item.quantity,
3299
+ unit_price: item.unitPrice,
3300
+ discount: item.discount,
3301
+ total: item.totalAmount,
3302
+ sort_order: i,
3303
+ metadata: { itemKind: item.itemKind }
3304
+ }))
3305
+ );
3306
+ if (itemsError) throw new Error(itemsError.message);
3307
+ }
3308
+ return await provider.getQuoteById(id);
3309
+ },
3310
+ async sendQuote(id) {
3311
+ const { core } = getClients();
3312
+ await core.from("orders").update({ status: "sent" }).eq("id", id);
3313
+ try {
3314
+ const quote = await provider.getQuoteById(id);
3315
+ if (quote?.dealId) {
3316
+ const deal = await provider.getDealById(quote.dealId);
3317
+ if (deal) {
3318
+ const stages = await provider.getPipelineStages(deal.pipelineId);
3319
+ const negotiationStage = stages.find((s) => s.name === "Negotiation") ?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0];
3320
+ const currentStage = stages.find((s) => s.id === deal.stageId);
3321
+ if (negotiationStage && currentStage && negotiationStage.order > currentStage.order) {
3322
+ await provider.moveDealToStage(deal.id, negotiationStage.id);
3323
+ }
3324
+ }
3325
+ }
3326
+ } catch {
3327
+ }
3328
+ return await provider.getQuoteById(id);
3329
+ },
3330
+ async approveQuote(id) {
3331
+ const { core, pub } = getClients();
3332
+ getTenantId();
3333
+ const quote = await provider.getQuoteById(id);
3334
+ if (!quote) throw new Error("Quote not found");
3335
+ const { error: promoteErr } = await pub.rpc("fn_invoice_from_order", {
3336
+ p_order_id: id,
3337
+ p_due_date: quote.validUntil ?? null,
3338
+ p_status: "approved"
3339
+ });
3340
+ if (promoteErr) throw new Error(promoteErr.message);
3341
+ if (quote.dealId) {
3342
+ try {
3343
+ const deal = await provider.getDealById(quote.dealId);
3344
+ if (deal) {
3345
+ const stages = await provider.getPipelineStages(deal.pipelineId);
3346
+ const wonStage = stages.find((s) => s.isWon);
3347
+ if (wonStage) await provider.moveDealToStage(deal.id, wonStage.id);
3348
+ }
3349
+ } catch {
3350
+ }
3351
+ }
3352
+ const personToConvert = quote.leadId ?? quote.contactId;
3353
+ if (personToConvert) {
3354
+ const clientKind = options?.clientConversion?.archetypeKind ?? "client";
3355
+ const { data: person } = await core.from("persons").select("kind, name, email, phone, tenant_id, metadata").eq("id", personToConvert).single();
3356
+ const personKind = person?.kind;
3357
+ if (person && (personKind === "lead" || personKind === "contact")) {
3358
+ const personMeta = person?.metadata ?? {};
3359
+ await core.from("persons").update({
3360
+ kind: clientKind,
3361
+ metadata: { ...personMeta, convertedFromLead: true }
3362
+ }).eq("id", personToConvert);
3363
+ if (options?.clientConversion) {
3364
+ const { extensionTable, fkColumn } = options.clientConversion;
3365
+ await pub.from(extensionTable).upsert({
3366
+ [fkColumn]: personToConvert,
3367
+ tenant_id: person.tenant_id
3368
+ }, { onConflict: fkColumn });
3369
+ }
3370
+ }
3371
+ }
3372
+ return await provider.getQuoteById(id);
3373
+ },
3374
+ async rejectQuote(id, reason) {
3375
+ const { core } = getClients();
3376
+ const { data: existing } = await core.from("orders").select("metadata").eq("id", id).single();
3377
+ const existingMeta = existing?.metadata ?? {};
3378
+ const { error } = await core.from("orders").update({
3379
+ status: "rejected",
3380
+ metadata: { ...existingMeta, rejectionReason: reason }
3381
+ }).eq("id", id);
3382
+ if (error) throw new Error(error.message);
3383
+ const quote = await provider.getQuoteById(id);
3384
+ if (quote?.dealId) {
3385
+ const deal = await provider.getDealById(quote.dealId);
3386
+ if (deal) {
3387
+ const stages = await provider.getPipelineStages(deal.pipelineId);
3388
+ const lostStage = stages.find((s) => s.isLost);
3389
+ if (lostStage) await provider.moveDealToStage(deal.id, lostStage.id);
3390
+ }
3391
+ }
3392
+ return quote;
3393
+ },
3394
+ async expireQuote(id) {
3395
+ const { core } = getClients();
3396
+ await core.from("orders").update({ status: "expired" }).eq("id", id);
3397
+ return await provider.getQuoteById(id);
3398
+ },
3399
+ // Cross-entity lookups
3400
+ async getQuotesByDealId(dealId) {
3401
+ const { core } = getClients();
3402
+ const { data } = await core.from("orders").select("*").eq("kind", "quote");
3403
+ return (data ?? []).filter((r) => r.metadata?.dealId === dealId).map((r) => ({
3404
+ id: r.id,
3405
+ quoteNumber: r.reference_number ?? "",
3406
+ quoteDate: r.created_at?.slice(0, 10) ?? "",
3407
+ validUntil: r.due_at?.slice(0, 10) ?? "",
3408
+ status: r.status ?? "draft",
3409
+ totalAmount: r.total ?? 0,
3410
+ contactId: r.party_id,
3411
+ contactName: r.metadata?.contactName,
3412
+ dealId: r.metadata?.dealId,
3413
+ leadId: r.metadata?.leadId,
3414
+ convertedInvoiceId: r.metadata?.convertedInvoiceId,
3415
+ items: [],
3416
+ tenantId: r.tenant_id,
3417
+ createdAt: r.created_at,
3418
+ updatedAt: r.updated_at
3419
+ }));
3420
+ },
3421
+ async getDealByLeadId(leadId) {
3422
+ const { pub } = getClients();
3423
+ const { data } = await pub.from("deal_extensions").select("order_id").eq("lead_id", leadId).limit(1);
3424
+ if (!data || data.length === 0) return null;
3425
+ return provider.getDealById(data[0].order_id);
3426
+ },
3427
+ // --- Summary ---
3428
+ async getSummary() {
3429
+ const { core, pub } = getClients();
3430
+ const monthStart = (/* @__PURE__ */ new Date()).toISOString().slice(0, 7) + "-01";
3431
+ const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
3432
+ const { count: totalLeads } = await core.from("persons").select("*", { count: "exact", head: true }).eq("kind", "lead");
3433
+ const { count: newLeads } = await core.from("persons").select("*", { count: "exact", head: true }).eq("kind", "lead").gte("created_at", monthStart);
3434
+ const { data: deals } = await core.from("orders").select("status, total, updated_at").eq("kind", "deal");
3435
+ const allDeals = deals ?? [];
3436
+ const openDeals = allDeals.filter((d) => d.status === "open");
3437
+ const wonDeals = allDeals.filter((d) => d.status === "won");
3438
+ const wonThisMonth = wonDeals.filter((d) => d.updated_at >= monthStart);
3439
+ const convertedLeads = allDeals.length;
3440
+ const { count: pendingActs } = await pub.from("crm_activities").select("*", { count: "exact", head: true }).is("completed_at", null);
3441
+ const { count: overdueActs } = await pub.from("crm_activities").select("*", { count: "exact", head: true }).is("completed_at", null).lt("due_date", today2);
3442
+ return {
3443
+ totalLeads: totalLeads ?? 0,
3444
+ newLeadsThisMonth: newLeads ?? 0,
3445
+ totalDeals: allDeals.length,
3446
+ openDealsValue: openDeals.reduce((s, d) => s + (d.total ?? 0), 0),
3447
+ wonDealsThisMonth: wonThisMonth.length,
3448
+ wonDealsValueThisMonth: wonThisMonth.reduce((s, d) => s + (d.total ?? 0), 0),
3449
+ conversionRate: (totalLeads ?? 0) > 0 ? convertedLeads / (totalLeads ?? 1) * 100 : 0,
3450
+ averageDealValue: wonDeals.length > 0 ? wonDeals.reduce((s, d) => s + (d.total ?? 0), 0) / wonDeals.length : 0,
3451
+ pendingActivities: pendingActs ?? 0,
3452
+ overdueActivities: overdueActs ?? 0
3453
+ };
3454
+ },
3455
+ async getFunnel(pipelineId) {
3456
+ getClients();
3457
+ const stages = await provider.getPipelineStages(pipelineId);
3458
+ const deals = await provider.getDeals({ status: "open" });
3459
+ return stages.filter((s) => !s.isLost).map((stage) => {
3460
+ const stageDeals = deals.data.filter((d) => d.stageId === stage.id);
3461
+ return {
3462
+ stageId: stage.id,
3463
+ stageName: stage.name,
3464
+ stageColor: stage.color,
3465
+ dealCount: stageDeals.length,
3466
+ totalValue: stageDeals.reduce((s, d) => s + d.value, 0)
3467
+ };
3468
+ });
3469
+ }
3470
+ };
3471
+ return provider;
3472
+ }
3473
+ function createCrmStore(provider) {
3474
+ return vanilla.createStore((set, get) => ({
3475
+ pipelines: [],
3476
+ stages: [],
3477
+ leads: [],
3478
+ leadsTotal: 0,
3479
+ leadsLoading: false,
3480
+ deals: [],
3481
+ dealsTotal: 0,
3482
+ dealsLoading: false,
3483
+ dealsByStage: /* @__PURE__ */ new Map(),
3484
+ activities: [],
3485
+ activitiesTotal: 0,
3486
+ activitiesLoading: false,
3487
+ quotes: [],
3488
+ quotesTotal: 0,
3489
+ quotesLoading: false,
3490
+ summary: null,
3491
+ summaryLoading: false,
3492
+ funnel: [],
3493
+ async fetchPipelines() {
3494
+ return saas.dedup("crm:pipelines", async () => {
3495
+ const pipelines = await provider.getPipelines();
3496
+ const stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
3497
+ set({ pipelines, stages });
3498
+ });
3499
+ },
3500
+ async fetchSummary() {
3501
+ return saas.dedup("crm:summary", async () => {
3502
+ set({ summaryLoading: true });
3503
+ const summary = await provider.getSummary();
3504
+ set({ summary, summaryLoading: false });
3505
+ });
3506
+ },
3507
+ async fetchFunnel(pipelineId) {
3508
+ return saas.dedup("crm:funnel:" + pipelineId, async () => {
3509
+ const funnel = await provider.getFunnel(pipelineId);
3510
+ set({ funnel });
3511
+ });
3512
+ },
3513
+ async fetchLeads(query) {
3514
+ return saas.dedup("crm:leads:" + JSON.stringify(query), async () => {
3515
+ set({ leadsLoading: true });
3516
+ const result = await provider.getLeads(query);
3517
+ set({ leads: result.data, leadsTotal: result.total, leadsLoading: false });
3518
+ });
3519
+ },
3520
+ async fetchDeals(query) {
3521
+ return saas.dedup("crm:deals:" + JSON.stringify(query), async () => {
3522
+ set({ dealsLoading: true });
3523
+ const result = await provider.getDeals(query);
3524
+ set({ deals: result.data, dealsTotal: result.total, dealsLoading: false });
3525
+ });
3526
+ },
3527
+ async fetchDealsByStage(pipelineId) {
3528
+ return saas.dedup("crm:dealsByStage:" + pipelineId, async () => {
3529
+ set({ dealsLoading: true });
3530
+ const dealsByStage = await provider.getDealsByStage(pipelineId);
3531
+ set({ dealsByStage, dealsLoading: false });
3532
+ });
3533
+ },
3534
+ async fetchActivities(query) {
3535
+ return saas.dedup("crm:activities:" + JSON.stringify(query), async () => {
3536
+ set({ activitiesLoading: true });
3537
+ const result = await provider.getActivities(query);
3538
+ set({ activities: result.data, activitiesTotal: result.total, activitiesLoading: false });
3539
+ });
3540
+ },
3541
+ async fetchQuotes(query) {
3542
+ return saas.dedup("crm:quotes:" + JSON.stringify(query), async () => {
3543
+ set({ quotesLoading: true });
3544
+ const result = await provider.getQuotes(query);
3545
+ set({ quotes: result.data, quotesTotal: result.total, quotesLoading: false });
3546
+ });
3547
+ },
3548
+ async createLead(input) {
3549
+ try {
3550
+ const lead = await provider.createLead(input);
3551
+ let { pipelines, stages } = get();
3552
+ if (pipelines.length === 0) {
3553
+ pipelines = await provider.getPipelines();
3554
+ stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
3555
+ set({ pipelines, stages });
3556
+ }
3557
+ const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
3558
+ const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0];
3559
+ if (defaultPipeline && firstStage) {
3560
+ try {
3561
+ await provider.createDeal({
3562
+ leadId: lead.id,
3563
+ title: lead.name,
3564
+ value: input.value ?? 0,
3565
+ pipelineId: defaultPipeline.id,
3566
+ stageId: firstStage.id,
3567
+ contactName: lead.name
3568
+ });
3569
+ } catch {
3570
+ }
3571
+ }
3572
+ const summary = await provider.getSummary();
3573
+ set({ summary });
3574
+ ui.toast.success("Lead captured");
3575
+ return lead;
3576
+ } catch (err) {
3577
+ ui.toast.error("Failed to create lead", { description: err?.message });
3578
+ throw err;
3579
+ }
3580
+ },
3581
+ async createDeal(input) {
3582
+ try {
3583
+ const deal = await provider.createDeal(input);
3584
+ const [summary] = await Promise.all([provider.getSummary()]);
3585
+ set({ summary });
3586
+ ui.toast.success("Deal created");
3587
+ return deal;
3588
+ } catch (err) {
3589
+ ui.toast.error("Failed to create deal", { description: err?.message });
3590
+ throw err;
3591
+ }
3592
+ },
3593
+ async createActivity(input) {
3594
+ try {
3595
+ const activity = await provider.createActivity(input);
3596
+ ui.toast.success("Activity logged");
3597
+ return activity;
3598
+ } catch (err) {
3599
+ ui.toast.error("Failed to log activity", { description: err?.message });
3600
+ throw err;
3601
+ }
3602
+ },
3603
+ async createQuote(input) {
3604
+ try {
3605
+ let { pipelines, stages } = get();
3606
+ if (pipelines.length === 0) {
3607
+ pipelines = await provider.getPipelines();
3608
+ stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
3609
+ set({ pipelines, stages });
3610
+ }
3611
+ const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
3612
+ let leadId = input.leadId;
3613
+ let dealId = input.dealId;
3614
+ const contactId = input.contactId;
3615
+ const contactName = input.contactName;
3616
+ if (!leadId && contactId) {
3617
+ try {
3618
+ const lead = await provider.getLeadById(contactId);
3619
+ if (lead) leadId = lead.id;
3620
+ } catch {
3621
+ }
3622
+ }
3623
+ if (!leadId && contactName) {
3624
+ try {
3625
+ const lead = await provider.createLead({ name: contactName });
3626
+ leadId = lead.id;
3627
+ if (!contactId) input = { ...input, contactId: lead.id };
3628
+ } catch {
3629
+ }
3630
+ }
3631
+ if (leadId && !dealId) {
3632
+ try {
3633
+ const existingDeal = await provider.getDealByLeadId(leadId);
3634
+ if (existingDeal) {
3635
+ dealId = existingDeal.id;
3636
+ } else if (defaultPipeline) {
3637
+ const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0];
3638
+ if (firstStage) {
3639
+ const deal = await provider.createDeal({
3640
+ leadId,
3641
+ title: contactName ?? "Deal",
3642
+ value: input.items?.reduce((s, i) => s + (i.totalAmount ?? 0), 0) ?? 0,
3643
+ pipelineId: defaultPipeline.id,
3644
+ stageId: firstStage.id,
3645
+ contactName: contactName ?? ""
3646
+ });
3647
+ dealId = deal.id;
3648
+ }
3649
+ }
3650
+ } catch {
3651
+ }
3652
+ }
3653
+ const enrichedInput = { ...input, leadId, dealId };
3654
+ const quote = await provider.createQuote(enrichedInput);
3655
+ if (dealId && defaultPipeline) {
3656
+ try {
3657
+ const deal = await provider.getDealById(dealId);
3658
+ if (deal && deal.status === "open") {
3659
+ const currentStage = stages.find((s) => s.id === deal.stageId);
3660
+ const proposalStage = stages.find((s) => s.name === "Proposal") ?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0];
3661
+ if (proposalStage && currentStage && proposalStage.order > currentStage.order) {
3662
+ await provider.moveDealToStage(dealId, proposalStage.id);
3663
+ }
3664
+ }
3665
+ } catch {
3666
+ }
3667
+ }
3668
+ set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }));
3669
+ if (defaultPipeline) {
3670
+ try {
3671
+ const dealsByStage = await provider.getDealsByStage(defaultPipeline.id);
3672
+ set({ dealsByStage });
3673
+ } catch {
3674
+ }
3675
+ }
3676
+ ui.toast.success("Quote created");
3677
+ return quote;
3678
+ } catch (err) {
3679
+ ui.toast.error("Failed to create quote", { description: err?.message });
3680
+ throw err;
3681
+ }
3682
+ },
3683
+ async updateQuote(id, input) {
3684
+ try {
3685
+ const quote = await provider.updateQuote(id, input);
3686
+ set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
3687
+ ui.toast.success("Quote updated");
3688
+ return quote;
3689
+ } catch (err) {
3690
+ ui.toast.error("Failed to update quote", { description: err?.message });
3691
+ throw err;
3692
+ }
3693
+ },
3694
+ async sendQuote(id) {
3695
+ try {
3696
+ const quote = await provider.sendQuote(id);
3697
+ set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
3698
+ ui.toast.success("Quote sent");
3699
+ return quote;
3700
+ } catch (err) {
3701
+ ui.toast.error("Failed to send quote", { description: err?.message });
3702
+ throw err;
3703
+ }
3704
+ },
3705
+ async approveQuote(id) {
3706
+ try {
3707
+ const quote = await provider.approveQuote(id);
3708
+ const { pipelines } = get();
3709
+ if (pipelines.length > 0) {
3710
+ const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3711
+ provider.getDealsByStage(pipelines[0].id),
3712
+ provider.getSummary(),
3713
+ provider.getLeads({}),
3714
+ provider.getQuotes({})
3715
+ ]);
3716
+ set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3717
+ }
3718
+ ui.toast.success("Quote approved \u2014 invoice created");
3719
+ return quote;
3720
+ } catch (err) {
3721
+ ui.toast.error("Failed to approve quote", { description: err?.message });
3722
+ throw err;
3723
+ }
3724
+ },
3725
+ async rejectQuote(id, reason) {
3726
+ try {
3727
+ const quote = await provider.rejectQuote(id, reason);
3728
+ const { pipelines } = get();
3729
+ if (pipelines.length > 0) {
3730
+ const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3731
+ provider.getDealsByStage(pipelines[0].id),
3732
+ provider.getSummary(),
3733
+ provider.getLeads({}),
3734
+ provider.getQuotes({})
3735
+ ]);
3736
+ set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3737
+ }
3738
+ ui.toast.success("Quote rejected");
3739
+ return quote;
3740
+ } catch (err) {
3741
+ ui.toast.error("Failed to reject quote", { description: err?.message });
3742
+ throw err;
3743
+ }
3744
+ },
3745
+ async expireQuote(id) {
3746
+ try {
3747
+ const quote = await provider.expireQuote(id);
3748
+ set((state) => ({ quotes: state.quotes.map((q) => q.id === id ? quote : q) }));
3749
+ ui.toast.success("Quote expired");
3750
+ return quote;
3751
+ } catch (err) {
3752
+ ui.toast.error("Failed to expire quote", { description: err?.message });
3753
+ throw err;
3754
+ }
3755
+ },
3756
+ async moveDealToStage(dealId, stageId) {
3757
+ await provider.moveDealToStage(dealId, stageId);
3758
+ const { pipelines } = get();
3759
+ if (pipelines.length > 0) {
3760
+ const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
3761
+ provider.getDealsByStage(pipelines[0].id),
3762
+ provider.getSummary(),
3763
+ provider.getLeads({}),
3764
+ provider.getQuotes({})
3765
+ ]);
3766
+ set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
3767
+ }
3768
+ }
3769
+ }));
3770
+ }
3771
+
3772
+ // src/registries.ts
3773
+ var leadSourceEntity = {
3774
+ name: "Lead Source",
3775
+ namePlural: "Lead Sources",
3776
+ icon: "Globe",
3777
+ displayField: "name",
3778
+ defaultSort: "name",
3779
+ fields: [
3780
+ { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3781
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3782
+ ],
3783
+ data: { table: "lead_sources", tenantScoped: true }
3784
+ };
3785
+ var tagEntity = {
3786
+ name: "Tag",
3787
+ namePlural: "Tags",
3788
+ icon: "Tag",
3789
+ displayField: "name",
3790
+ defaultSort: "name",
3791
+ fields: [
3792
+ { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3793
+ { key: "color", label: "Color", type: "text", showInTable: true, defaultValue: "#6366f1" },
3794
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3795
+ ],
3796
+ data: { table: "crm_tags", tenantScoped: true }
3797
+ };
3798
+ var activityTypeEntity = {
3799
+ name: "Activity Type",
3800
+ namePlural: "Activity Types",
3801
+ icon: "MessageCircle",
3802
+ displayField: "name",
3803
+ defaultSort: "name",
3804
+ fields: [
3805
+ { key: "name", label: "Name", type: "text", required: true, showInTable: true },
3806
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
3807
+ ],
3808
+ data: { table: "crm_activity_types", tenantScoped: true }
3809
+ };
3810
+ var crmRegistries = [
3811
+ {
3812
+ id: "lead-sources",
3813
+ entity: leadSourceEntity,
3814
+ icon: "Globe",
3815
+ description: "Where your leads come from",
3816
+ display: "table",
3817
+ seedData: [
3818
+ { id: "src-instagram", name: "Instagram", isActive: true },
3819
+ { id: "src-whatsapp", name: "WhatsApp", isActive: true },
3820
+ { id: "src-referral", name: "Referral", isActive: true },
3821
+ { id: "src-google", name: "Google", isActive: true },
3822
+ { id: "src-website", name: "Website", isActive: true },
3823
+ { id: "src-walkin", name: "Walk-in", isActive: true }
3824
+ ]
3825
+ },
3826
+ {
3827
+ id: "tags",
3828
+ entity: tagEntity,
3829
+ icon: "Tag",
3830
+ description: "Tags for organizing leads and deals",
3831
+ display: "table",
3832
+ seedData: [
3833
+ { id: "tag-vip", name: "VIP", color: "#f59e0b", isActive: true },
3834
+ { id: "tag-hot", name: "Hot Lead", color: "#ef4444", isActive: true },
3835
+ { id: "tag-followup", name: "Follow-up", color: "#3b82f6", isActive: true }
3836
+ ]
3837
+ },
3838
+ {
3839
+ id: "activity-types",
3840
+ entity: activityTypeEntity,
3841
+ icon: "MessageCircle",
3842
+ description: "Types of activities and interactions",
3843
+ display: "table",
3844
+ readOnly: true,
3845
+ seedData: [
3846
+ { id: "at-call", name: "Call", isActive: true },
3847
+ { id: "at-email", name: "Email", isActive: true },
3848
+ { id: "at-meeting", name: "Meeting", isActive: true },
3849
+ { id: "at-note", name: "Note", isActive: true },
3850
+ { id: "at-task", name: "Task", isActive: true },
3851
+ { id: "at-whatsapp", name: "WhatsApp", isActive: true }
3852
+ ]
3853
+ }
3854
+ ];
3855
+
3856
+ // src/locales/en.ts
3857
+ var en = {
3858
+ "crm.activities.activitiesLogged": "Activities are logged from lead and deal interactions",
3859
+ "crm.activities.all": "All",
3860
+ "crm.activities.completedFilter": "Completed",
3861
+ "crm.activities.done": "Done",
3862
+ "crm.activities.noActivities": "No activities",
3863
+ "crm.activities.noActivitiesOfType": 'No activities of type "{{type}}"',
3864
+ "crm.activities.overdue": "overdue",
3865
+ "crm.activities.overdueLabel": "Overdue",
3866
+ "crm.activities.pending": "pending",
3867
+ "crm.activities.pendingFilter": "Pending",
3868
+ "crm.activities.title": "Activities",
3869
+ "crm.dashboard.activeDeals": "{{count}} active deals",
3870
+ "crm.dashboard.avgDealValue": "Avg deal value",
3871
+ "crm.dashboard.leadsCount": "{{count}} leads",
3872
+ "crm.dashboard.quotesCount": "{{count}} quotes",
3873
+ "crm.dashboard.conversionRate": "Conversion Rate",
3874
+ "crm.dashboard.conversionRateLabel": "Conversion rate",
3875
+ "crm.dashboard.createFirstLead": "Create your first lead to see the funnel",
3876
+ "crm.dashboard.dealsWon": "Deals won this month",
3877
+ "crm.dashboard.leadToDeal": "Lead to deal",
3878
+ "crm.dashboard.newThisMonth": "{{count}} new this month",
3879
+ "crm.dashboard.noLeadsYet": "No leads yet. Capture your first lead to get started.",
3880
+ "crm.dashboard.noPipelineData": "No pipeline data yet",
3881
+ "crm.dashboard.noQuotesYet": "No quotes yet.",
3882
+ "crm.dashboard.openPipeline": "Open Pipeline",
3883
+ "crm.dashboard.overdueCount": "{{count}} overdue",
3884
+ "crm.dashboard.pendingTasks": "Pending Tasks",
3885
+ "crm.dashboard.performance": "Performance",
3886
+ "crm.dashboard.pipelineOverview": "Pipeline Overview",
3887
+ "crm.dashboard.pipelineValue": "Pipeline Value",
3888
+ "crm.dashboard.recentLeads": "Recent Leads",
3889
+ "crm.dashboard.recentQuotes": "Recent Quotes",
3890
+ "crm.dashboard.revenueWon": "Revenue won",
3891
+ "crm.dashboard.totalDeals": "{{count}} total deals",
3892
+ "crm.dashboard.totalLeads": "Total Leads",
3893
+ "crm.dealSidebar.activitiesAppear": "Activities will appear here as they are logged",
3894
+ "crm.dealSidebar.activity": "Activity",
3895
+ "crm.dealSidebar.assignedTo": "Assigned to",
3896
+ "crm.dealSidebar.contact": "Contact",
3897
+ "crm.dealSidebar.created": "Created",
3898
+ "crm.dealSidebar.deal": "Deal",
3899
+ "crm.dealSidebar.dealNotFound": "Deal not found",
3900
+ "crm.dealSidebar.expectedClose": "Expected close",
3901
+ "crm.dealSidebar.noActivities": "No activities yet",
3902
+ "crm.dealSidebar.noQuotes": "No quotes linked",
3903
+ "crm.dealSidebar.notes": "Notes",
3904
+ "crm.dealSidebar.overview": "Overview",
3905
+ "crm.dealSidebar.probability": "Probability",
3906
+ "crm.dealSidebar.quotes": "Quotes",
3907
+ "crm.dealSidebar.quotesAppear": "Quotes created for this lead will appear here",
3908
+ "crm.dealSidebar.stage": "Stage",
3909
+ "crm.dealSidebar.tags": "Tags",
3910
+ "crm.dealSidebar.updated": "Updated",
3911
+ "crm.dealSidebar.value": "Value",
3912
+ "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
3913
+ "crm.leadDetail.assignedTo": "Assigned to",
3914
+ "crm.leadDetail.backToList": "Back to list",
3915
+ "crm.leadDetail.company": "Company",
3916
+ "crm.leadDetail.contactInfo": "Contact Information",
3917
+ "crm.leadDetail.createQuote": "Create Quote",
3918
+ "crm.leadDetail.created": "Created",
3919
+ "crm.leadDetail.dealStatus": "Deal status",
3920
+ "crm.leadDetail.dealValue": "Deal value",
3921
+ "crm.leadDetail.details": "Details",
3922
+ "crm.leadDetail.email": "Email",
3923
+ "crm.leadDetail.leadNotFound": "Lead not found",
3924
+ "crm.leadDetail.leads": "Leads",
3925
+ "crm.leadDetail.loading": "Loading...",
3926
+ "crm.leadDetail.notFound": "Not found",
3927
+ "crm.leadDetail.notes": "Notes",
3928
+ "crm.leadDetail.phone": "Phone",
3929
+ "crm.leadDetail.pipeline": "Pipeline",
3930
+ "crm.leadDetail.probability": "Probability",
3931
+ "crm.leadDetail.quotes": "Quotes",
3932
+ "crm.leadDetail.source": "Source",
3933
+ "crm.leadDetail.stage": "Stage",
3934
+ "crm.leadDetail.tags": "Tags",
3935
+ "crm.leadDetail.updated": "Updated",
3936
+ "crm.leadDetail.value": "Value",
3937
+ "crm.leadForm.cancel": "Cancel",
3938
+ "crm.leadForm.company": "Company",
3939
+ "crm.leadForm.companyPlaceholder": "Company name",
3940
+ "crm.leadForm.email": "Email",
3941
+ "crm.leadForm.emailPlaceholder": "email@example.com",
3942
+ "crm.leadForm.name": "Name *",
3943
+ "crm.leadForm.namePlaceholder": "Contact name",
3944
+ "crm.leadForm.notes": "Notes",
3945
+ "crm.leadForm.notesPlaceholder": "Additional notes...",
3946
+ "crm.leadForm.phone": "Phone",
3947
+ "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
3948
+ "crm.leadForm.save": "Save",
3949
+ "crm.leadForm.saving": "Saving...",
3950
+ "crm.leadForm.subtitle": "Capture a new lead",
3951
+ "crm.leadForm.title": "New Lead",
3952
+ "crm.leads.captureFirst": "Capture your first lead",
3953
+ "crm.leads.contactCol": "Contact",
3954
+ "crm.leads.name": "Name",
3955
+ "crm.leads.newLead": "New Lead",
3956
+ "crm.leads.noLeads": "No leads yet",
3957
+ "crm.leads.searchPlaceholder": "Search leads...",
3958
+ "crm.leads.source": "Source",
3959
+ "crm.leads.statusCol": "Status",
3960
+ "crm.leads.title": "Leads",
3961
+ "crm.page.logActivity": "Log Activity",
3962
+ "crm.page.logActivityDesc": "Record a call, email, or note",
3963
+ "crm.page.newDeal": "New Deal",
3964
+ "crm.page.newDealDesc": "Create a deal from pipeline",
3965
+ "crm.page.newLead": "New Lead",
3966
+ "crm.page.newLeadDesc": "Capture a new lead",
3967
+ "crm.page.newQuote": "New Quote",
3968
+ "crm.page.newQuoteDesc": "Send a proposal",
3969
+ "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
3970
+ "crm.page.settingsTitle": "Sales & CRM Settings",
3971
+ "crm.pipeline.dropHere": "Drop here",
3972
+ "crm.pipeline.moveFailed": "Failed to move deal",
3973
+ "crm.pipeline.movedTo": "Moved to {{stage}}",
3974
+ "crm.pipeline.noDeals": "No deals",
3975
+ "crm.pipeline.subtitle": "Drag deals between stages",
3976
+ "crm.pipeline.title": "Pipeline",
3977
+ "crm.quoteDetail.backToList": "Back to list",
3978
+ "crm.quoteDetail.client": "Client",
3979
+ "crm.quoteDetail.date": "Date",
3980
+ "crm.quoteDetail.description": "Description",
3981
+ "crm.quoteDetail.discount": "Discount",
3982
+ "crm.quoteDetail.edit": "Edit",
3983
+ "crm.quoteDetail.send": "Send",
3984
+ "crm.quoteDetail.sending": "Sending...",
3985
+ "crm.quoteDetail.sendPrint": "Print",
3986
+ "crm.quoteDetail.sendEmail": "Send by E-mail",
3987
+ "crm.quoteDetail.sendWhatsApp": "Send by WhatsApp",
3988
+ "crm.quoteDetail.approve": "Approve",
3989
+ "crm.quoteDetail.approving": "Approving...",
3990
+ "crm.quoteDetail.reject": "Reject",
3991
+ "crm.quoteDetail.rejecting": "Rejecting...",
3992
+ "crm.quoteDetail.confirmReject": "Confirm Rejection",
3993
+ "crm.quoteDetail.rejectDescription": "Provide a reason for rejecting this quote.",
3994
+ "crm.quoteDetail.rejectReasonPlaceholder": "Reason for rejection...",
3995
+ "crm.quoteDetail.invoiceCreated": "Invoice created from this quote",
3996
+ "crm.quoteDetail.items": "Items",
3997
+ "crm.quoteDetail.loading": "Loading...",
3998
+ "crm.quoteDetail.notFound": "Quote not found",
3999
+ "crm.quoteDetail.notes": "Notes",
4000
+ "crm.quoteDetail.paymentConditions": "Payment Conditions",
4001
+ "crm.quoteDetail.qty": "Qty",
4002
+ "crm.quoteDetail.quoteNumber": "Quote {{number}}",
4003
+ "crm.quoteDetail.rejectionReason": "Rejection reason",
4004
+ "crm.quoteDetail.subtotal": "Subtotal",
4005
+ "crm.quoteDetail.title": "Quotes",
4006
+ "crm.quoteDetail.total": "Total",
4007
+ "crm.quoteDetail.unitPrice": "Unit Price",
4008
+ "crm.quoteDetail.validUntil": "Valid Until",
4009
+ "crm.quoteDetail.viewInvoice": "View Invoice",
4010
+ "crm.quoteForm.addFirstItem": "Add your first item",
4011
+ "crm.quoteForm.addItem": "Add Item",
4012
+ "crm.quoteForm.cancel": "Cancel",
4013
+ "crm.quoteForm.client": "Client",
4014
+ "crm.quoteForm.description": "Description",
4015
+ "crm.quoteForm.discount": "Discount",
4016
+ "crm.quoteForm.done": "Done",
4017
+ "crm.quoteForm.editSubtitle": "Update this proposal",
4018
+ "crm.quoteForm.editTitle": "Edit Quote",
4019
+ "crm.quoteForm.itemCount": "{{count}} items",
4020
+ "crm.quoteForm.itemDescriptionPlaceholder": "Item description",
4021
+ "crm.quoteForm.loading": "Loading...",
4022
+ "crm.quoteForm.newSubtitle": "Create a proposal for your client",
4023
+ "crm.quoteForm.newTitle": "New Quote",
4024
+ "crm.quoteForm.noDescription": "No description",
4025
+ "crm.quoteForm.noItems": "No items added",
4026
+ "crm.quoteForm.errNoItems": "Add at least one item before saving.",
4027
+ "crm.quoteForm.notes": "Notes",
4028
+ "crm.quoteForm.notesPlaceholder": "Internal observations...",
4029
+ "crm.quoteForm.paymentConditions": "Payment Conditions",
4030
+ "crm.quoteForm.paymentConditionsPlaceholder": "e.g. 50% upfront, 50% on delivery",
4031
+ "crm.quoteForm.qty": "Qty",
4032
+ "crm.quoteForm.quoteDate": "Quote Date",
4033
+ "crm.quoteForm.quoteDetails": "Quote Details",
4034
+ "crm.quoteForm.quoteItems": "Quote Items",
4035
+ "crm.quoteForm.saveChanges": "Save Changes",
4036
+ "crm.quoteForm.saveQuote": "Save Quote",
4037
+ "crm.quoteForm.saving": "Saving...",
4038
+ "crm.quoteForm.searchClient": "Search client...",
4039
+ "crm.quoteForm.addAsLead": "Add as lead",
4040
+ "crm.quoteForm.selectItemType": "Select item type:",
4041
+ "crm.quoteForm.statusApproved": "Approved",
4042
+ "crm.quoteForm.statusDraft": "Draft",
4043
+ "crm.quoteForm.statusExpired": "Expired",
4044
+ "crm.quoteForm.statusRejected": "Rejected",
4045
+ "crm.quoteForm.statusSent": "Sent",
4046
+ "crm.quoteForm.total": "Total",
4047
+ "crm.quoteForm.unitPrice": "Unit Price",
4048
+ "crm.quoteForm.validUntil": "Valid Until",
4049
+ "crm.quotes.amount": "Amount",
4050
+ "crm.quotes.contact": "Contact",
4051
+ "crm.quotes.createFirst": "Create your first quote",
4052
+ "crm.quotes.date": "Date",
4053
+ "crm.quotes.newQuote": "New Quote",
4054
+ "crm.quotes.noQuotes": "No quotes yet",
4055
+ "crm.quotes.quotesCount": "{{count}} quotes",
4056
+ "crm.quotes.status": "Status",
4057
+ "crm.quotes.title": "Quotes",
4058
+ "crm.quickActions.newLead": "New Lead",
4059
+ "crm.quickActions.newLeadDesc": "Capture a new lead",
4060
+ "crm.quickActions.newDeal": "New Deal",
4061
+ "crm.quickActions.newDealDesc": "Create a deal from pipeline",
4062
+ "crm.quickActions.newQuote": "New Quote",
4063
+ "crm.quickActions.newQuoteDesc": "Send a proposal",
4064
+ "crm.quickActions.logActivity": "Log Activity",
4065
+ "crm.quickActions.logActivityDesc": "Record a call, email, or note",
4066
+ "crm.settingsPage.title": "Sales & CRM Settings",
4067
+ "crm.settingsPage.subtitle": "Configure pipeline, lead management, and registries",
4068
+ "crm.settingsPage.pipeline": "Pipeline",
4069
+ "crm.onboarding.welcome": "Welcome to Sales & CRM",
4070
+ "crm.onboarding.description": "Track leads, manage your sales pipeline, and close more deals.",
4071
+ "crm.onboarding.sources.title": "Lead Sources",
4072
+ "crm.onboarding.sources.description": "Default sources (Instagram, WhatsApp, Google, etc.) are ready. Customize them in Settings.",
4073
+ "crm.onboarding.pipeline.title": "Sales Pipeline",
4074
+ "crm.onboarding.pipeline.description": "Your default pipeline with 7 stages is set up. Customize stages and probabilities anytime.",
4075
+ "crm.onboarding.startSelling": "Start selling",
4076
+ "crm.onboarding.getStarted": "Get Started",
4077
+ "crm.onboarding.next": "Next",
4078
+ "crm.onboarding.skip": "Skip setup",
4079
+ "crm.settings.leadManagement": "Lead Management",
4080
+ "crm.settings.leadManagementDesc": "How leads are captured and handled",
4081
+ "crm.settings.autoAssign": "Auto-assign leads",
4082
+ "crm.settings.autoAssignDesc": "Automatically assign new leads to available team members",
4083
+ "crm.settings.requireSource": "Require lead source",
4084
+ "crm.settings.requireSourceDesc": "Make source selection mandatory when capturing leads",
4085
+ "crm.settings.leadScoring": "Lead scoring",
4086
+ "crm.settings.leadScoringDesc": "Automatically score leads based on engagement signals",
4087
+ "crm.settings.duplicateDetection": "Duplicate detection",
4088
+ "crm.settings.duplicateDetectionDesc": "Warn when a lead with the same email or phone already exists",
4089
+ "crm.settings.deals": "Deals",
4090
+ "crm.settings.dealsDesc": "Deal pipeline behavior",
4091
+ "crm.settings.autoCreateDeal": "Auto-create deal on conversion",
4092
+ "crm.settings.autoCreateDealDesc": "Create a deal automatically when a lead is qualified",
4093
+ "crm.settings.requireCloseDate": "Require expected close date",
4094
+ "crm.settings.requireCloseDateDesc": "Make expected close date mandatory on deals",
4095
+ "crm.settings.rottingDeals": "Rotting deals warning",
4096
+ "crm.settings.rottingDealsDesc": "Highlight deals that haven't been updated in X days",
4097
+ "crm.settings.weightedPipeline": "Weighted pipeline value",
4098
+ "crm.settings.weightedPipelineDesc": "Calculate pipeline value using stage probability",
4099
+ "crm.settings.quotes": "Quotes",
4100
+ "crm.settings.quotesDesc": "Quote and proposal behavior",
4101
+ "crm.settings.autoNumberQuotes": "Auto-number quotes",
4102
+ "crm.settings.autoNumberQuotesDesc": "Automatically generate sequential quote numbers",
4103
+ "crm.settings.defaultValidity": "Default validity (30 days)",
4104
+ "crm.settings.defaultValidityDesc": "New quotes expire after 30 days by default",
4105
+ "crm.settings.requireApproval": "Require approval",
4106
+ "crm.settings.requireApprovalDesc": "Quotes need manager approval before sending",
4107
+ "crm.settings.notifications": "Notifications",
4108
+ "crm.settings.notificationsDesc": "Alerts and reminders",
4109
+ "crm.settings.overdueAlerts": "Overdue activity alerts",
4110
+ "crm.settings.overdueAlertsDesc": "Notify when activities pass their due date",
4111
+ "crm.settings.stageChangeAlerts": "Deal stage change alerts",
4112
+ "crm.settings.stageChangeAlertsDesc": "Notify when deals move to a new stage",
4113
+ "crm.settings.newLeadNotif": "New lead notification",
4114
+ "crm.settings.newLeadNotifDesc": "Alert team when a new lead is captured",
4115
+ "crm.pipelineSettings.title": "Pipeline Stages",
4116
+ "crm.pipelineSettings.description": "Define stages that deals move through. Drag to reorder.",
4117
+ "crm.pipelineSettings.probability": "Probability",
4118
+ "crm.pipelineSettings.winStage": "Win stage",
4119
+ "crm.pipelineSettings.lossStage": "Loss stage",
4120
+ "crm.pipelineSettings.customizationNote": "Pipeline stage customization (add, remove, reorder, edit colors and probabilities) will be available when connected to the database.",
4121
+ "crm.title": "CRM",
4122
+ "crm.deals.title": "Deals",
4123
+ "crm.deals.create": "New Deal",
4124
+ "crm.deals.value": "Value",
4125
+ "crm.deals.stage": "Stage",
4126
+ "crm.deals.probability": "Probability",
4127
+ "crm.deals.expectedClose": "Expected Close",
4128
+ "crm.deals.empty": "No deals yet",
4129
+ "crm.leads.create": "New Lead",
4130
+ "crm.leads.status": "Status",
4131
+ "crm.leads.convertToDeal": "Convert to Deal",
4132
+ "crm.contacts.title": "Contacts",
4133
+ "crm.contacts.create": "New Contact",
4134
+ "crm.quotes.create": "New Quote",
4135
+ "crm.quotes.edit": "Edit Quote",
4136
+ "crm.quotes.items": "Items",
4137
+ "crm.quotes.addItem": "Add Item",
4138
+ "crm.quotes.subtotal": "Subtotal",
4139
+ "crm.quotes.discount": "Discount",
4140
+ "crm.quotes.total": "Total",
4141
+ "crm.quotes.save": "Save Quote",
4142
+ "crm.quotes.saving": "Saving...",
4143
+ "crm.quotes.send": "Send Quote",
4144
+ "crm.quotes.loading": "Loading...",
4145
+ "crm.settings.title": "CRM Settings",
4146
+ "crm.settings.pipeline": "Pipeline Stages"
4147
+ };
4148
+
4149
+ // src/locales/pt-BR.ts
4150
+ var ptBR = {
4151
+ "crm.activities.activitiesLogged": "Atividades s\xE3o registradas a partir de intera\xE7\xF5es com leads e neg\xF3cios",
4152
+ "crm.activities.all": "Todas",
4153
+ "crm.activities.completedFilter": "Conclu\xEDdas",
4154
+ "crm.activities.done": "Conclu\xEDdo",
4155
+ "crm.activities.noActivities": "Nenhuma atividade",
4156
+ "crm.activities.noActivitiesOfType": 'Nenhuma atividade do tipo "{{type}}"',
4157
+ "crm.activities.overdue": "atrasada",
4158
+ "crm.activities.overdueLabel": "Atrasada",
4159
+ "crm.activities.pending": "pendente",
4160
+ "crm.activities.pendingFilter": "Pendentes",
4161
+ "crm.activities.title": "Atividades",
4162
+ "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
4163
+ "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
4164
+ "crm.dashboard.leadsCount": "{{count}} leads",
4165
+ "crm.dashboard.quotesCount": "{{count}} or\xE7amentos",
4166
+ "crm.dashboard.conversionRate": "Taxa de Convers\xE3o",
4167
+ "crm.dashboard.conversionRateLabel": "Taxa de convers\xE3o",
4168
+ "crm.dashboard.createFirstLead": "Crie seu primeiro lead para ver o funil",
4169
+ "crm.dashboard.dealsWon": "Neg\xF3cios fechados neste m\xEAs",
4170
+ "crm.dashboard.leadToDeal": "Lead para neg\xF3cio",
4171
+ "crm.dashboard.newThisMonth": "{{count}} novos neste m\xEAs",
4172
+ "crm.dashboard.noLeadsYet": "Nenhum lead ainda. Capture seu primeiro lead para come\xE7ar.",
4173
+ "crm.dashboard.noPipelineData": "Nenhum dado de pipeline ainda",
4174
+ "crm.dashboard.noQuotesYet": "Nenhum or\xE7amento ainda.",
4175
+ "crm.dashboard.openPipeline": "Pipeline Aberto",
4176
+ "crm.dashboard.overdueCount": "{{count}} atrasados",
4177
+ "crm.dashboard.pendingTasks": "Tarefas Pendentes",
4178
+ "crm.dashboard.performance": "Desempenho",
4179
+ "crm.dashboard.pipelineOverview": "Vis\xE3o Geral do Pipeline",
4180
+ "crm.dashboard.pipelineValue": "Valor do Pipeline",
4181
+ "crm.dashboard.recentLeads": "Leads Recentes",
4182
+ "crm.dashboard.recentQuotes": "Or\xE7amentos Recentes",
4183
+ "crm.dashboard.revenueWon": "Receita ganha",
4184
+ "crm.dashboard.totalDeals": "{{count}} neg\xF3cios no total",
4185
+ "crm.dashboard.totalLeads": "Total de Leads",
4186
+ "crm.dealSidebar.activitiesAppear": "As atividades aparecer\xE3o aqui conforme forem registradas",
4187
+ "crm.dealSidebar.activity": "Atividade",
4188
+ "crm.dealSidebar.assignedTo": "Atribu\xEDdo a",
4189
+ "crm.dealSidebar.contact": "Contato",
4190
+ "crm.dealSidebar.created": "Criado",
4191
+ "crm.dealSidebar.deal": "Neg\xF3cio",
4192
+ "crm.dealSidebar.dealNotFound": "Neg\xF3cio n\xE3o encontrado",
4193
+ "crm.dealSidebar.expectedClose": "Fechamento previsto",
4194
+ "crm.dealSidebar.noActivities": "Nenhuma atividade ainda",
4195
+ "crm.dealSidebar.noQuotes": "Nenhum or\xE7amento vinculado",
4196
+ "crm.dealSidebar.notes": "Observa\xE7\xF5es",
4197
+ "crm.dealSidebar.overview": "Vis\xE3o Geral",
4198
+ "crm.dealSidebar.probability": "Probabilidade",
4199
+ "crm.dealSidebar.quotes": "Or\xE7amentos",
4200
+ "crm.dealSidebar.quotesAppear": "Or\xE7amentos criados para este lead aparecer\xE3o aqui",
4201
+ "crm.dealSidebar.stage": "Etapa",
4202
+ "crm.dealSidebar.tags": "Tags",
4203
+ "crm.dealSidebar.updated": "Atualizado",
4204
+ "crm.dealSidebar.value": "Valor",
4205
+ "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
4206
+ "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
4207
+ "crm.leadDetail.backToList": "Voltar \xE0 lista",
4208
+ "crm.leadDetail.company": "Empresa",
4209
+ "crm.leadDetail.contactInfo": "Informa\xE7\xF5es de Contato",
4210
+ "crm.leadDetail.createQuote": "Criar Or\xE7amento",
4211
+ "crm.leadDetail.created": "Criado",
4212
+ "crm.leadDetail.dealStatus": "Status do neg\xF3cio",
4213
+ "crm.leadDetail.dealValue": "Valor do neg\xF3cio",
4214
+ "crm.leadDetail.details": "Detalhes",
4215
+ "crm.leadDetail.email": "E-mail",
4216
+ "crm.leadDetail.leadNotFound": "Lead n\xE3o encontrado",
4217
+ "crm.leadDetail.leads": "Leads",
4218
+ "crm.leadDetail.loading": "Carregando...",
4219
+ "crm.leadDetail.notFound": "N\xE3o encontrado",
4220
+ "crm.leadDetail.notes": "Observa\xE7\xF5es",
4221
+ "crm.leadDetail.phone": "Telefone",
4222
+ "crm.leadDetail.pipeline": "Pipeline",
4223
+ "crm.leadDetail.probability": "Probabilidade",
4224
+ "crm.leadDetail.quotes": "Or\xE7amentos",
4225
+ "crm.leadDetail.source": "Origem",
4226
+ "crm.leadDetail.stage": "Etapa",
4227
+ "crm.leadDetail.tags": "Tags",
4228
+ "crm.leadDetail.updated": "Atualizado",
4229
+ "crm.leadDetail.value": "Valor",
4230
+ "crm.leadForm.cancel": "Cancelar",
4231
+ "crm.leadForm.company": "Empresa",
4232
+ "crm.leadForm.companyPlaceholder": "Nome da empresa",
4233
+ "crm.leadForm.email": "E-mail",
4234
+ "crm.leadForm.emailPlaceholder": "email@exemplo.com",
4235
+ "crm.leadForm.name": "Nome *",
4236
+ "crm.leadForm.namePlaceholder": "Nome do contato",
4237
+ "crm.leadForm.notes": "Observa\xE7\xF5es",
4238
+ "crm.leadForm.notesPlaceholder": "Observa\xE7\xF5es adicionais...",
4239
+ "crm.leadForm.phone": "Telefone",
4240
+ "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
4241
+ "crm.leadForm.save": "Salvar",
4242
+ "crm.leadForm.saving": "Salvando...",
4243
+ "crm.leadForm.subtitle": "Capturar um novo lead",
4244
+ "crm.leadForm.title": "Novo Lead",
4245
+ "crm.leads.captureFirst": "Capture seu primeiro lead",
4246
+ "crm.leads.contactCol": "Contato",
4247
+ "crm.leads.name": "Nome",
4248
+ "crm.leads.newLead": "Novo Lead",
4249
+ "crm.leads.noLeads": "Nenhum lead ainda",
4250
+ "crm.leads.searchPlaceholder": "Buscar leads...",
4251
+ "crm.leads.source": "Origem",
4252
+ "crm.leads.statusCol": "Status",
4253
+ "crm.leads.title": "Leads",
4254
+ "crm.page.logActivity": "Registrar Atividade",
4255
+ "crm.page.logActivityDesc": "Registrar uma liga\xE7\xE3o, e-mail ou nota",
4256
+ "crm.page.newDeal": "Novo Neg\xF3cio",
4257
+ "crm.page.newDealDesc": "Criar um neg\xF3cio a partir do pipeline",
4258
+ "crm.page.newLead": "Novo Lead",
4259
+ "crm.page.newLeadDesc": "Capturar um novo lead",
4260
+ "crm.page.newQuote": "Novo Or\xE7amento",
4261
+ "crm.page.newQuoteDesc": "Enviar uma proposta",
4262
+ "crm.page.settingsSubtitle": "Configure pipeline, gest\xE3o de leads e cadastros",
4263
+ "crm.page.settingsTitle": "Configura\xE7\xF5es de Vendas e CRM",
4264
+ "crm.pipeline.dropHere": "Solte aqui",
4265
+ "crm.pipeline.moveFailed": "Falha ao mover neg\xF3cio",
4266
+ "crm.pipeline.movedTo": "Movido para {{stage}}",
4267
+ "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
4268
+ "crm.pipeline.subtitle": "Arraste neg\xF3cios entre etapas",
4269
+ "crm.pipeline.title": "Pipeline",
4270
+ "crm.quoteDetail.backToList": "Voltar \xE0 lista",
4271
+ "crm.quoteDetail.client": "Cliente",
4272
+ "crm.quoteDetail.date": "Data",
4273
+ "crm.quoteDetail.description": "Descri\xE7\xE3o",
4274
+ "crm.quoteDetail.discount": "Desconto",
4275
+ "crm.quoteDetail.edit": "Editar",
4276
+ "crm.quoteDetail.send": "Enviar",
4277
+ "crm.quoteDetail.sending": "Enviando...",
4278
+ "crm.quoteDetail.sendPrint": "Imprimir",
4279
+ "crm.quoteDetail.sendEmail": "Enviar por E-mail",
4280
+ "crm.quoteDetail.sendWhatsApp": "Enviar por WhatsApp",
4281
+ "crm.quoteDetail.approve": "Aprovar",
4282
+ "crm.quoteDetail.approving": "Aprovando...",
4283
+ "crm.quoteDetail.reject": "Rejeitar",
4284
+ "crm.quoteDetail.rejecting": "Rejeitando...",
4285
+ "crm.quoteDetail.confirmReject": "Confirmar Rejei\xE7\xE3o",
4286
+ "crm.quoteDetail.rejectDescription": "Informe o motivo da rejei\xE7\xE3o deste or\xE7amento.",
4287
+ "crm.quoteDetail.rejectReasonPlaceholder": "Motivo da rejei\xE7\xE3o...",
4288
+ "crm.quoteDetail.invoiceCreated": "Fatura criada a partir deste or\xE7amento",
4289
+ "crm.quoteDetail.items": "Itens",
4290
+ "crm.quoteDetail.loading": "Carregando...",
4291
+ "crm.quoteDetail.notFound": "Or\xE7amento n\xE3o encontrado",
4292
+ "crm.quoteDetail.notes": "Observa\xE7\xF5es",
4293
+ "crm.quoteDetail.paymentConditions": "Condi\xE7\xF5es de Pagamento",
4294
+ "crm.quoteDetail.qty": "Qtd",
4295
+ "crm.quoteDetail.quoteNumber": "Or\xE7amento {{number}}",
4296
+ "crm.quoteDetail.rejectionReason": "Motivo da rejei\xE7\xE3o",
4297
+ "crm.quoteDetail.subtotal": "Subtotal",
4298
+ "crm.quoteDetail.title": "Or\xE7amentos",
4299
+ "crm.quoteDetail.total": "Total",
4300
+ "crm.quoteDetail.unitPrice": "Pre\xE7o Unit\xE1rio",
4301
+ "crm.quoteDetail.validUntil": "V\xE1lido At\xE9",
4302
+ "crm.quoteDetail.viewInvoice": "Ver Fatura",
4303
+ "crm.quoteForm.addFirstItem": "Adicione seu primeiro item",
4304
+ "crm.quoteForm.addItem": "Adicionar Item",
4305
+ "crm.quoteForm.cancel": "Cancelar",
4306
+ "crm.quoteForm.client": "Cliente",
4307
+ "crm.quoteForm.description": "Descri\xE7\xE3o",
4308
+ "crm.quoteForm.discount": "Desconto",
4309
+ "crm.quoteForm.done": "Conclu\xEDdo",
4310
+ "crm.quoteForm.editSubtitle": "Atualizar esta proposta",
4311
+ "crm.quoteForm.editTitle": "Editar Or\xE7amento",
4312
+ "crm.quoteForm.itemCount": "{{count}} itens",
4313
+ "crm.quoteForm.itemDescriptionPlaceholder": "Descri\xE7\xE3o do item",
4314
+ "crm.quoteForm.loading": "Carregando...",
4315
+ "crm.quoteForm.newSubtitle": "Criar uma proposta para seu cliente",
4316
+ "crm.quoteForm.newTitle": "Novo Or\xE7amento",
4317
+ "crm.quoteForm.noDescription": "Sem descri\xE7\xE3o",
4318
+ "crm.quoteForm.noItems": "Nenhum item adicionado",
4319
+ "crm.quoteForm.errNoItems": "Adicione pelo menos um item antes de salvar.",
4320
+ "crm.quoteForm.notes": "Observa\xE7\xF5es",
4321
+ "crm.quoteForm.notesPlaceholder": "Observa\xE7\xF5es internas...",
4322
+ "crm.quoteForm.paymentConditions": "Condi\xE7\xF5es de Pagamento",
4323
+ "crm.quoteForm.paymentConditionsPlaceholder": "ex. 50% antecipado, 50% na entrega",
4324
+ "crm.quoteForm.qty": "Qtd",
4325
+ "crm.quoteForm.quoteDate": "Data do Or\xE7amento",
4326
+ "crm.quoteForm.quoteDetails": "Detalhes do Or\xE7amento",
4327
+ "crm.quoteForm.quoteItems": "Itens do Or\xE7amento",
4328
+ "crm.quoteForm.saveChanges": "Salvar Altera\xE7\xF5es",
4329
+ "crm.quoteForm.saveQuote": "Salvar Or\xE7amento",
4330
+ "crm.quoteForm.saving": "Salvando...",
4331
+ "crm.quoteForm.searchClient": "Buscar cliente...",
4332
+ "crm.quoteForm.addAsLead": "Adicionar como lead",
4333
+ "crm.quoteForm.selectItemType": "Selecione o tipo de item:",
4334
+ "crm.quoteForm.statusApproved": "Aprovado",
4335
+ "crm.quoteForm.statusDraft": "Rascunho",
4336
+ "crm.quoteForm.statusExpired": "Expirado",
4337
+ "crm.quoteForm.statusRejected": "Rejeitado",
4338
+ "crm.quoteForm.statusSent": "Enviado",
4339
+ "crm.quoteForm.total": "Total",
4340
+ "crm.quoteForm.unitPrice": "Pre\xE7o Unit\xE1rio",
4341
+ "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
4342
+ "crm.quotes.amount": "Valor",
4343
+ "crm.quotes.contact": "Contato",
4344
+ "crm.quotes.createFirst": "Crie seu primeiro or\xE7amento",
4345
+ "crm.quotes.date": "Data",
4346
+ "crm.quotes.newQuote": "Novo Or\xE7amento",
4347
+ "crm.quotes.noQuotes": "Nenhum or\xE7amento ainda",
4348
+ "crm.quotes.quotesCount": "{{count}} or\xE7amentos",
4349
+ "crm.quotes.status": "Status",
4350
+ "crm.quotes.title": "Or\xE7amentos",
4351
+ "crm.quickActions.newLead": "Novo Lead",
4352
+ "crm.quickActions.newLeadDesc": "Capturar um novo lead",
4353
+ "crm.quickActions.newDeal": "Novo Neg\xF3cio",
4354
+ "crm.quickActions.newDealDesc": "Criar um neg\xF3cio no pipeline",
4355
+ "crm.quickActions.newQuote": "Novo Or\xE7amento",
4356
+ "crm.quickActions.newQuoteDesc": "Enviar uma proposta",
4357
+ "crm.quickActions.logActivity": "Registrar Atividade",
4358
+ "crm.quickActions.logActivityDesc": "Registrar liga\xE7\xE3o, e-mail ou nota",
4359
+ "crm.settingsPage.title": "Configura\xE7\xF5es de Vendas e CRM",
4360
+ "crm.settingsPage.subtitle": "Configurar pipeline, gest\xE3o de leads e registros",
4361
+ "crm.settingsPage.pipeline": "Pipeline",
4362
+ "crm.onboarding.welcome": "Bem-vindo ao Vendas e CRM",
4363
+ "crm.onboarding.description": "Acompanhe leads, gerencie seu pipeline de vendas e feche mais neg\xF3cios.",
4364
+ "crm.onboarding.sources.title": "Fontes de Leads",
4365
+ "crm.onboarding.sources.description": "Fontes padr\xE3o (Instagram, WhatsApp, Google, etc.) est\xE3o prontas. Personalize-as em Configura\xE7\xF5es.",
4366
+ "crm.onboarding.pipeline.title": "Pipeline de Vendas",
4367
+ "crm.onboarding.pipeline.description": "Seu pipeline padr\xE3o com 7 est\xE1gios est\xE1 configurado. Personalize est\xE1gios e probabilidades a qualquer momento.",
4368
+ "crm.onboarding.startSelling": "Come\xE7ar a vender",
4369
+ "crm.onboarding.getStarted": "Come\xE7ar",
4370
+ "crm.onboarding.next": "Pr\xF3ximo",
4371
+ "crm.onboarding.skip": "Pular configura\xE7\xE3o",
4372
+ "crm.settings.leadManagement": "Gest\xE3o de Leads",
4373
+ "crm.settings.leadManagementDesc": "Como leads s\xE3o capturados e gerenciados",
4374
+ "crm.settings.autoAssign": "Auto-atribuir leads",
4375
+ "crm.settings.autoAssignDesc": "Atribuir automaticamente novos leads a membros dispon\xEDveis da equipe",
4376
+ "crm.settings.requireSource": "Exigir fonte do lead",
4377
+ "crm.settings.requireSourceDesc": "Tornar obrigat\xF3ria a sele\xE7\xE3o de fonte ao capturar leads",
4378
+ "crm.settings.leadScoring": "Pontua\xE7\xE3o de leads",
4379
+ "crm.settings.leadScoringDesc": "Pontuar automaticamente leads com base em sinais de engajamento",
4380
+ "crm.settings.duplicateDetection": "Detec\xE7\xE3o de duplicatas",
4381
+ "crm.settings.duplicateDetectionDesc": "Avisar quando um lead com o mesmo e-mail ou telefone j\xE1 existir",
4382
+ "crm.settings.deals": "Neg\xF3cios",
4383
+ "crm.settings.dealsDesc": "Comportamento do pipeline de neg\xF3cios",
4384
+ "crm.settings.autoCreateDeal": "Auto-criar neg\xF3cio na convers\xE3o",
4385
+ "crm.settings.autoCreateDealDesc": "Criar um neg\xF3cio automaticamente quando um lead \xE9 qualificado",
4386
+ "crm.settings.requireCloseDate": "Exigir data de fechamento prevista",
4387
+ "crm.settings.requireCloseDateDesc": "Tornar obrigat\xF3ria a data de fechamento prevista nos neg\xF3cios",
4388
+ "crm.settings.rottingDeals": "Aviso de neg\xF3cios parados",
4389
+ "crm.settings.rottingDealsDesc": "Destacar neg\xF3cios que n\xE3o foram atualizados h\xE1 X dias",
4390
+ "crm.settings.weightedPipeline": "Valor ponderado do pipeline",
4391
+ "crm.settings.weightedPipelineDesc": "Calcular valor do pipeline usando probabilidade do est\xE1gio",
4392
+ "crm.settings.quotes": "Or\xE7amentos",
4393
+ "crm.settings.quotesDesc": "Comportamento de or\xE7amentos e propostas",
4394
+ "crm.settings.autoNumberQuotes": "Numera\xE7\xE3o autom\xE1tica de or\xE7amentos",
4395
+ "crm.settings.autoNumberQuotesDesc": "Gerar automaticamente n\xFAmeros sequenciais de or\xE7amentos",
4396
+ "crm.settings.defaultValidity": "Validade padr\xE3o (30 dias)",
4397
+ "crm.settings.defaultValidityDesc": "Novos or\xE7amentos expiram ap\xF3s 30 dias por padr\xE3o",
4398
+ "crm.settings.requireApproval": "Exigir aprova\xE7\xE3o",
4399
+ "crm.settings.requireApprovalDesc": "Or\xE7amentos precisam de aprova\xE7\xE3o do gerente antes do envio",
4400
+ "crm.settings.notifications": "Notifica\xE7\xF5es",
4401
+ "crm.settings.notificationsDesc": "Alertas e lembretes",
4402
+ "crm.settings.overdueAlerts": "Alertas de atividades atrasadas",
4403
+ "crm.settings.overdueAlertsDesc": "Notificar quando atividades passarem da data de vencimento",
4404
+ "crm.settings.stageChangeAlerts": "Alertas de mudan\xE7a de est\xE1gio",
4405
+ "crm.settings.stageChangeAlertsDesc": "Notificar quando neg\xF3cios mudarem de est\xE1gio",
4406
+ "crm.settings.newLeadNotif": "Notifica\xE7\xE3o de novo lead",
4407
+ "crm.settings.newLeadNotifDesc": "Alertar equipe quando um novo lead \xE9 capturado",
4408
+ "crm.pipelineSettings.title": "Est\xE1gios do Pipeline",
4409
+ "crm.pipelineSettings.description": "Defina os est\xE1gios pelos quais os neg\xF3cios passam. Arraste para reordenar.",
4410
+ "crm.pipelineSettings.probability": "Probabilidade",
4411
+ "crm.pipelineSettings.winStage": "Est\xE1gio de ganho",
4412
+ "crm.pipelineSettings.lossStage": "Est\xE1gio de perda",
4413
+ "crm.pipelineSettings.customizationNote": "A personaliza\xE7\xE3o dos est\xE1gios do pipeline (adicionar, remover, reordenar, editar cores e probabilidades) estar\xE1 dispon\xEDvel quando conectado ao banco de dados.",
4414
+ "crm.title": "CRM",
4415
+ "crm.deals.title": "Neg\xF3cios",
4416
+ "crm.deals.create": "Novo Neg\xF3cio",
4417
+ "crm.deals.value": "Valor",
4418
+ "crm.deals.stage": "Etapa",
4419
+ "crm.deals.probability": "Probabilidade",
4420
+ "crm.deals.expectedClose": "Fechamento Previsto",
4421
+ "crm.deals.empty": "Nenhum neg\xF3cio ainda",
4422
+ "crm.leads.create": "Novo Lead",
4423
+ "crm.leads.status": "Status",
4424
+ "crm.leads.convertToDeal": "Converter em Neg\xF3cio",
4425
+ "crm.contacts.title": "Contatos",
4426
+ "crm.contacts.create": "Novo Contato",
4427
+ "crm.quotes.create": "Novo Or\xE7amento",
4428
+ "crm.quotes.edit": "Editar Or\xE7amento",
4429
+ "crm.quotes.items": "Itens",
4430
+ "crm.quotes.addItem": "Adicionar Item",
4431
+ "crm.quotes.subtotal": "Subtotal",
4432
+ "crm.quotes.discount": "Desconto",
4433
+ "crm.quotes.total": "Total",
4434
+ "crm.quotes.save": "Salvar Or\xE7amento",
4435
+ "crm.quotes.saving": "Salvando...",
4436
+ "crm.quotes.send": "Enviar Or\xE7amento",
4437
+ "crm.quotes.loading": "Carregando...",
4438
+ "crm.settings.title": "Configura\xE7\xF5es do CRM",
4439
+ "crm.settings.pipeline": "Etapas do Pipeline"
4440
+ };
4441
+
4442
+ // src/locales/index.ts
4443
+ var crmLocales = {
4444
+ en,
4445
+ "pt-BR": ptBR
4446
+ };
4447
+
4448
+ // src/index.ts
4449
+ var DEFAULT_LABELS = {
4450
+ pageTitle: "Sales",
4451
+ pageSubtitle: "CRM, leads, deals, and pipeline management",
4452
+ dashboard: "Dashboard",
4453
+ pipeline: "Pipeline",
4454
+ leads: "Leads",
4455
+ leadsNew: "New",
4456
+ leadsList: "List",
4457
+ deals: "Deals",
4458
+ quotes: "Quotes",
4459
+ quotesNew: "New",
4460
+ quotesList: "List",
4461
+ activities: "Activities"
4462
+ };
4463
+ var DEFAULT_CURRENCY = { code: "BRL", locale: "pt-BR", symbol: "R$" };
4464
+ var DEFAULT_ITEM_TYPES = [
4465
+ { value: "service", label: "Service" },
4466
+ { value: "product", label: "Product" },
4467
+ { value: "other", label: "Other" }
4468
+ ];
4469
+ function resolveConfig(options) {
4470
+ return {
4471
+ modules: {
4472
+ quotes: options?.modules?.quotes !== false,
4473
+ activities: options?.modules?.activities !== false,
4474
+ pipeline: options?.modules?.pipeline !== false
4475
+ },
4476
+ labels: { ...DEFAULT_LABELS, ...options?.labels },
4477
+ currency: { ...DEFAULT_CURRENCY, ...options?.currency },
4478
+ itemTypes: options?.itemTypes ?? DEFAULT_ITEM_TYPES,
4479
+ entityLookups: options?.entityLookups ?? {},
4480
+ contactLookup: options?.contactLookup
4481
+ };
4482
+ }
4483
+ function createCrmPlugin(options) {
4484
+ const config = resolveConfig(options);
4485
+ core.registerTranslations(crmLocales);
4486
+ const provider = options?.dataProvider ?? core.createSafeDataProvider(
4487
+ () => createSupabaseCrmProvider({ clientConversion: options?.clientConversion }),
4488
+ () => createMockCrmProvider()
4489
+ );
4490
+ const store = createCrmStore(provider);
4491
+ const PageComponent = () => React15__default.default.createElement(CrmPage, { config, provider, store, registries: crmRegistries });
4492
+ const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
4493
+ return {
4494
+ id: "crm",
4495
+ name: config.labels.pageTitle,
4496
+ icon: "Filter",
4497
+ version: "1.0.0",
4498
+ scope: options?.scope ?? "universal",
4499
+ verticalId: options?.verticalId,
4500
+ defaultEnabled: true,
4501
+ dependencies: [],
4502
+ declaredFeatures: [
4503
+ { id: "sales", label: config.labels.pageTitle, group: config.labels.pageTitle },
4504
+ { id: "crm.leads", label: config.labels.leads, group: config.labels.pageTitle },
4505
+ { id: "crm.quotes", label: config.labels.quotes, group: config.labels.pageTitle },
4506
+ { id: "crm.pipeline", label: config.labels.pipeline, group: config.labels.pageTitle }
4507
+ ],
4508
+ navigation: [
4509
+ {
4510
+ section: options?.navSection ?? "main",
4511
+ position: options?.navPosition ?? 5,
4512
+ label: config.labels.pageTitle,
4513
+ route: "/sales",
4514
+ icon: "Filter",
4515
+ permission: { feature: "sales", action: "read" }
4516
+ }
4517
+ ],
4518
+ routes: [
4519
+ {
4520
+ path: "/sales",
4521
+ component: PageComponent,
4522
+ permission: { feature: "sales", action: "read" }
4523
+ }
4524
+ ],
4525
+ widgets: [],
4526
+ dashboardWidgets,
4527
+ aiTools: [
4528
+ {
4529
+ id: "crm.count-customers",
4530
+ name: "countCustomers",
4531
+ description: "Returns the number of active customers/clients.",
4532
+ icon: "Users",
4533
+ mode: "read",
4534
+ category: "Sales",
4535
+ parameters: {
4536
+ type: "object",
4537
+ properties: {
4538
+ status: { type: "string", enum: ["active", "inactive", "all"] }
4539
+ }
4540
+ },
4541
+ suggestions: [
4542
+ { label: "How many customers do we have?", verticalId: "beauty" },
4543
+ { label: "How many clients do we have?", verticalId: "services" },
4544
+ { label: "How many patients today?", verticalId: "health" },
4545
+ { label: "Who are my top customers?" }
4546
+ ],
4547
+ permission: { feature: "sales", action: "read" }
4548
+ },
4549
+ {
4550
+ id: "crm.list-leads",
4551
+ name: "listLeads",
4552
+ description: "Lists leads with optional filters.",
4553
+ icon: "Target",
4554
+ mode: "read",
4555
+ category: "Sales",
4556
+ parameters: {
4557
+ type: "object",
4558
+ properties: {
4559
+ source: { type: "string", description: "Lead source filter" },
4560
+ status: { type: "string", enum: ["new", "contacted", "qualified", "lost"] }
4561
+ }
4562
+ },
4563
+ permission: { feature: "sales", action: "read" },
4564
+ suggestions: [
4565
+ { label: "Show new leads from this week" },
4566
+ { label: "Which leads need follow-up?" },
4567
+ { label: "What's our conversion rate?" }
4568
+ ]
4569
+ }
4570
+ ],
4571
+ registries: crmRegistries,
4572
+ settings: [
4573
+ {
4574
+ id: "crm",
4575
+ label: "Sales & CRM",
4576
+ icon: "Filter",
4577
+ component: (() => {
4578
+ const Tab = () => React15__default.default.createElement(
4579
+ CrmContextProvider,
4580
+ { config, provider, store },
4581
+ React15__default.default.createElement(
4582
+ "div",
4583
+ { style: { display: "flex", flexDirection: "column", gap: "20px" } },
4584
+ React15__default.default.createElement(CrmGeneralSettings),
4585
+ React15__default.default.createElement(PipelineSettings)
4586
+ )
4587
+ );
4588
+ Tab.displayName = "CrmSettingsTab";
4589
+ return Tab;
4590
+ })(),
4591
+ order: 12,
4592
+ permission: { feature: "sales", action: "read" }
4593
+ }
4594
+ ],
4595
+ locales: crmLocales
4596
+ };
4597
+ }
4598
+
4599
+ exports.createCrmPlugin = createCrmPlugin;
4600
+ //# sourceMappingURL=index.cjs.map
4601
+ //# sourceMappingURL=index.cjs.map