@fayz-ai/plugin-crm 0.39.2 → 0.40.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 (54) hide show
  1. package/dist/{CrmPage-BJASPPQI.js → CrmPage-DLFFHQJP.js} +80 -1111
  2. package/dist/CrmPage-DLFFHQJP.js.map +1 -0
  3. package/dist/CrmQuotesSurface-KLH533QS.js +43 -0
  4. package/dist/CrmQuotesSurface-KLH533QS.js.map +1 -0
  5. package/dist/chunk-5AB4K3PY.js +1166 -0
  6. package/dist/chunk-5AB4K3PY.js.map +1 -0
  7. package/dist/chunk-VI25ZESQ.js +12 -0
  8. package/dist/chunk-VI25ZESQ.js.map +1 -0
  9. package/dist/chunk-ZWUFORDV.js +26 -0
  10. package/dist/chunk-ZWUFORDV.js.map +1 -0
  11. package/dist/components/QuoteAttachments.d.ts +18 -0
  12. package/dist/components/QuoteAttachments.d.ts.map +1 -0
  13. package/dist/components/QuoteClient.d.ts +26 -0
  14. package/dist/components/QuoteClient.d.ts.map +1 -0
  15. package/dist/components/QuoteStatusDropdown.d.ts +2 -0
  16. package/dist/components/QuoteStatusDropdown.d.ts.map +1 -1
  17. package/dist/components/TalkToPerson.d.ts +13 -0
  18. package/dist/components/TalkToPerson.d.ts.map +1 -1
  19. package/dist/data/mock.d.ts.map +1 -1
  20. package/dist/data/supabase.d.ts.map +1 -1
  21. package/dist/data/types.d.ts +7 -1
  22. package/dist/data/types.d.ts.map +1 -1
  23. package/dist/index.d.ts +6 -0
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +321 -22
  26. package/dist/index.js.map +1 -1
  27. package/dist/lib/crm-scope.d.ts +16 -0
  28. package/dist/lib/crm-scope.d.ts.map +1 -0
  29. package/dist/lib/customer-extensions.d.ts +64 -0
  30. package/dist/lib/customer-extensions.d.ts.map +1 -0
  31. package/dist/lib/deal-headline.d.ts +3 -2
  32. package/dist/lib/deal-headline.d.ts.map +1 -1
  33. package/dist/lib/quote-extensions.d.ts +87 -0
  34. package/dist/lib/quote-extensions.d.ts.map +1 -0
  35. package/dist/locales/en.d.ts.map +1 -1
  36. package/dist/locales/pt-BR.d.ts.map +1 -1
  37. package/dist/types.d.ts +26 -0
  38. package/dist/types.d.ts.map +1 -1
  39. package/dist/views/CrmPage.d.ts.map +1 -1
  40. package/dist/views/CrmQuotesSurface.d.ts +26 -0
  41. package/dist/views/CrmQuotesSurface.d.ts.map +1 -0
  42. package/dist/views/CustomersCrudPage.d.ts +23 -0
  43. package/dist/views/CustomersCrudPage.d.ts.map +1 -0
  44. package/dist/views/DistributionView.d.ts.map +1 -1
  45. package/dist/views/LeadDetailView.d.ts.map +1 -1
  46. package/dist/views/LeadListView.d.ts.map +1 -1
  47. package/dist/views/QuoteDetailView.d.ts.map +1 -1
  48. package/dist/views/QuoteEditRoute.d.ts +7 -0
  49. package/dist/views/QuoteEditRoute.d.ts.map +1 -0
  50. package/dist/views/QuoteFormView.d.ts.map +1 -1
  51. package/dist/views/QuoteListView.d.ts +7 -1
  52. package/dist/views/QuoteListView.d.ts.map +1 -1
  53. package/package.json +6 -6
  54. package/dist/CrmPage-BJASPPQI.js.map +0 -1
@@ -0,0 +1,1166 @@
1
+ import { getQuoteExtensions, quoteStatusOverride } from './chunk-ZWUFORDV.js';
2
+ import { useCrmConfig, useCrmStore, useCrmProvider, formatCurrency } from './chunk-7V46TYYX.js';
3
+ import React2, { useMemo, useEffect, useState, useCallback } from 'react';
4
+ import { Plus, Download, CircleDashed, Search, FileText, Receipt, Archive, CircleAlert, Ban, CircleCheckBig, Send, Loader2, ChevronDown, MessageCircle, Mail, Printer, Check, X, Pencil, ArrowRight, Package, Calendar, CalendarClock, MoreHorizontal, Paperclip } from 'lucide-react';
5
+ import { useFilterDraft, toast, SubpageHeader, FilterPanel, FilterPanelField, DatePicker, SegmentedControl, RequiredFilter, FilterMenuRow, SearchSelect, Card, Input, DataTable, Button, ConfirmDialog, useSaveBar, Textarea, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, Modal, ModalContent, ModalBody, ModalFooter, ModalHeader, ModalTitle, ModalDescription } from '@fayz-ai/ui';
6
+ import { useAccessOptional, createArchetypeLookup, useScrollMemory, PageActions, useCatalogedItemTypes, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, invalidateLimit, PersonLink, AttachmentsModal } from '@fayz-ai/admin';
7
+ import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
8
+ import { useTranslation, exportCSV, getCurrentLocale, tl, appHref } from '@fayz-ai/core';
9
+
10
+ // src/lib/deal-headline.ts
11
+ function dealHeadline(deal) {
12
+ return deal.groupName || deal.companyName || deal.contactName || deal.title || "";
13
+ }
14
+ function dealHouseLine(deal) {
15
+ return deal.groupName && deal.companyName ? deal.companyName : null;
16
+ }
17
+ function QuoteClientName({ quote, link = false, size = "md" }) {
18
+ const headline = dealHeadline(quote);
19
+ if (!headline) return /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "\u2014" });
20
+ const house = dealHouseLine(quote);
21
+ const person = quote.contactName && quote.contactName !== headline ? quote.contactName : null;
22
+ const second = [house, person].filter(Boolean).join(" \xB7 ");
23
+ const personId = quote.contactId ?? quote.leadId;
24
+ const titleCls = size === "sm" ? "text-sm font-medium" : "font-medium";
25
+ return /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
26
+ link && personId && !person ? /* @__PURE__ */ jsx(PersonLink, { personId, name: headline, size: "sm" }) : /* @__PURE__ */ jsx("div", { className: `truncate ${titleCls}`, children: headline }),
27
+ second && (link && personId ? /* @__PURE__ */ jsx("div", { className: "truncate text-xs text-muted-foreground", children: /* @__PURE__ */ jsx(PersonLink, { personId, name: second, size: "sm" }) }) : /* @__PURE__ */ jsx("div", { className: "truncate text-xs text-muted-foreground", children: second }))
28
+ ] });
29
+ }
30
+ function quoteContactLabel(c) {
31
+ const headline = dealHeadline({ groupName: c.groupName, companyName: c.companyName, contactName: c.name });
32
+ const house = dealHouseLine(c);
33
+ const subtitle = headline === c.name ? void 0 : [house, c.name].filter(Boolean).join(" \xB7 ");
34
+ return { label: headline, subtitle };
35
+ }
36
+ function toQuoteContactOptions(results) {
37
+ return results.map((c) => ({ id: c.id, ...quoteContactLabel(c), group: c.kind, data: c }));
38
+ }
39
+ function useCanArchive() {
40
+ return useAccessOptional().can("sales", "delete").allowed;
41
+ }
42
+ var QUOTE_STATUSES = ["draft", "sent", "approved", "rejected", "expired", "archived"];
43
+ var STATUS_COLORS = {
44
+ draft: "bg-muted text-muted-foreground",
45
+ sent: "bg-info-soft text-info-soft-foreground",
46
+ approved: "bg-success-soft text-success-soft-foreground",
47
+ rejected: "bg-destructive-soft text-destructive-soft-foreground",
48
+ expired: "bg-warning-soft text-warning-soft-foreground",
49
+ invoiced: "bg-warning-soft text-warning-soft-foreground",
50
+ paid: "bg-success-soft text-success-soft-foreground",
51
+ partial: "bg-warning-soft text-warning-soft-foreground",
52
+ overdue: "bg-destructive-soft text-destructive-soft-foreground",
53
+ cancelled: "bg-muted text-muted-foreground"
54
+ };
55
+ function useQuoteColumns(currency, onEditQuote, onArchive, custom) {
56
+ const t = useTranslation();
57
+ const cols = custom?.length ? custom.map((c) => ({
58
+ id: c.id,
59
+ header: c.header,
60
+ meta: { ...c.mobile ? { mobile: c.mobile } : {}, ...c.align === "right" ? { align: "right" } : {} },
61
+ cell: ({ row }) => /* @__PURE__ */ jsx("div", { className: c.align === "right" ? "text-right" : void 0, children: c.cell(row.original) })
62
+ })) : [
63
+ // Imported numbers run long ("P-proposta-chefcontrol-…"); unbounded, the column pushed date, amount and status off the screen.
64
+ { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "block max-w-[11rem] truncate text-xs text-muted-foreground", title: getValue(), children: getValue() }) },
65
+ // Two lines (house · person) in a bounded column: a long group name must not push amount and status off the screen.
66
+ { accessorKey: "contactName", header: t("crm.quotes.contact"), meta: { truncate: true, mobile: "title" }, cell: ({ row }) => /* @__PURE__ */ jsx(QuoteClientName, { quote: row.original, size: "sm" }) },
67
+ { accessorKey: "quoteDate", header: t("crm.quotes.date"), cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
68
+ {
69
+ accessorKey: "totalAmount",
70
+ header: t("crm.quotes.amount"),
71
+ cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency(getValue(), currency) })
72
+ },
73
+ {
74
+ accessorKey: "status",
75
+ header: t("crm.quotes.status"),
76
+ cell: ({ getValue, row }) => {
77
+ const override = quoteStatusOverride(row.original);
78
+ if (override) return override;
79
+ const status = getValue();
80
+ return /* @__PURE__ */ jsx("span", { className: `inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-medium ${STATUS_COLORS[status] ?? "bg-muted text-muted-foreground"}`, children: t(`crm.quotes.status.${status}`) });
81
+ }
82
+ }
83
+ ];
84
+ if (onEditQuote || onArchive) {
85
+ cols.push({
86
+ id: "actions",
87
+ header: "",
88
+ cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
89
+ onEditQuote && /* @__PURE__ */ jsx(
90
+ Button,
91
+ {
92
+ variant: "ghost",
93
+ size: "icon",
94
+ onClick: (e) => {
95
+ e.stopPropagation();
96
+ onEditQuote(row.original.id);
97
+ },
98
+ className: "h-7 w-7 rounded-md text-muted-foreground",
99
+ title: "Edit quote",
100
+ children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
101
+ }
102
+ ),
103
+ onArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
104
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
105
+ Button,
106
+ {
107
+ variant: "ghost",
108
+ size: "icon",
109
+ onClick: (e) => e.stopPropagation(),
110
+ "aria-label": t("crm.quotes.moreActions"),
111
+ className: "h-7 w-7 rounded-md text-muted-foreground",
112
+ children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3.5 w-3.5" })
113
+ }
114
+ ) }),
115
+ /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onArchive(row.original.id), children: [
116
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
117
+ " ",
118
+ t("crm.quotes.archive")
119
+ ] }) })
120
+ ] })
121
+ ] })
122
+ });
123
+ }
124
+ return cols;
125
+ }
126
+ function QuoteListView({ onNew, onEdit, onEditQuote, labels, list }) {
127
+ const t = useTranslation();
128
+ const { currency } = useCrmConfig();
129
+ const quotes = useCrmStore((s) => s.quotes);
130
+ const quotesLoading = useCrmStore((s) => s.quotesLoading);
131
+ const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
132
+ const archiveQuote = useCrmStore((s) => s.archiveQuote);
133
+ const canArchive = useCanArchive();
134
+ const hoje = useMemo(() => {
135
+ const d = /* @__PURE__ */ new Date();
136
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
137
+ }, []);
138
+ const noventaDiasAtras = useMemo(() => {
139
+ const d = /* @__PURE__ */ new Date();
140
+ d.setDate(d.getDate() - 89);
141
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
142
+ }, []);
143
+ const tabs = list?.statusTabs ?? [];
144
+ const filtros = useFilterDraft(
145
+ { from: noventaDiasAtras, to: hoje, status: [], contactId: "", contactName: "", search: "", tab: tabs[0]?.id ?? "" },
146
+ { persistKey: list?.persistKey ?? (list?.metadataKey ? `crm.quotes.${list.metadataKey}` : "crm.quotes") }
147
+ );
148
+ const { draft, applied, patch } = filtros;
149
+ const provider = useCrmProvider();
150
+ const contactLookup = useMemo(
151
+ () => createArchetypeLookup({ archetype: "person", kind: ["customer", "lead"] }),
152
+ []
153
+ );
154
+ const limparFiltros = () => patch({ status: [], contactId: "", contactName: "", search: "" });
155
+ const filtrosAtivos = (draft.status.length > 0 ? 1 : 0) + (draft.contactId ? 1 : 0) + (draft.search.trim() ? 1 : 0);
156
+ const clientSearch = !!list?.search;
157
+ useEffect(() => {
158
+ const search = applied.search.trim();
159
+ fetchQuotes({
160
+ dateRange: list?.noPeriod ? void 0 : { from: applied.from, to: applied.to },
161
+ status: !tabs.length && applied.status.length > 0 ? applied.status : void 0,
162
+ contactId: list?.hideContactFilter ? void 0 : applied.contactId || void 0,
163
+ search: clientSearch ? void 0 : search || void 0,
164
+ ...list?.includeArchived ? { includeArchived: true } : {},
165
+ ...list?.metadataKey ? { metadataKey: list.metadataKey } : {},
166
+ ...list ? { pageSize: 500 } : {}
167
+ });
168
+ }, [JSON.stringify({ ...applied, tab: void 0, search: clientSearch ? void 0 : applied.search })]);
169
+ const tab = tabs.find((x) => x.id === draft.tab) ?? tabs[0];
170
+ const rows = useMemo(() => {
171
+ let out = quotes;
172
+ if (tab) out = out.filter((q) => tab.match(q));
173
+ const term = draft.search.trim();
174
+ if (list?.search && term) out = out.filter((q) => list.search.match(q, term));
175
+ return out;
176
+ }, [quotes, tab, draft.search, list]);
177
+ const [alvoArquivo, setAlvoArquivo] = useState(null);
178
+ const columns = useQuoteColumns(currency, onEditQuote, canArchive ? setAlvoArquivo : void 0, list?.columns);
179
+ const exportRows = useCallback(() => {
180
+ exportCSV(
181
+ [
182
+ { key: "quoteNumber", label: "#" },
183
+ { key: "quoteDate", label: t("crm.quotes.date") },
184
+ { key: "contactName", label: t("crm.quotes.contact") },
185
+ { key: "totalAmount", label: t("crm.quotes.amount"), format: (v) => formatCurrency(Number(v) || 0, currency) },
186
+ { key: "status", label: t("crm.quotes.status") },
187
+ { key: "validUntil", label: t("crm.quoteForm.validUntil") }
188
+ ],
189
+ quotes,
190
+ "orcamentos"
191
+ );
192
+ toast.success(t("crud.export.toastSuccess", { count: String(quotes.length) }));
193
+ }, [quotes, currency, t]);
194
+ const ancoraRolagem = useScrollMemory("crm.quotes");
195
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
196
+ /* @__PURE__ */ jsx(
197
+ SubpageHeader,
198
+ {
199
+ title: labels?.title ?? t("crm.quotes.title"),
200
+ actions: /* @__PURE__ */ jsx(Fragment, { children: (onNew || quotes.length > 0) && /* @__PURE__ */ jsx(
201
+ PageActions,
202
+ {
203
+ actions: [
204
+ ...onNew ? [{ id: "new-quote", label: labels?.newQuote ?? t("crm.quotes.newQuote"), icon: Plus, intent: "primary", onSelect: onNew }] : [],
205
+ // 'utility': ícone só, ao lado do primário — o mesmo lugar que o
206
+ // exportar ocupa em toda lista de CRUD.
207
+ ...quotes.length > 0 ? [{ id: "export", label: t("crud.export.action"), icon: Download, intent: "utility", desktopOnly: true, onSelect: exportRows }] : []
208
+ ]
209
+ }
210
+ ) })
211
+ }
212
+ ),
213
+ /* @__PURE__ */ jsxs(
214
+ FilterPanel,
215
+ {
216
+ title: t("crm.quotes.filtersTitle"),
217
+ onApply: filtros.apply,
218
+ applyLabel: t("crm.quotes.filterApply"),
219
+ onClear: filtrosAtivos > 0 ? limparFiltros : void 0,
220
+ clearLabel: t("crm.quotes.filterClear"),
221
+ busy: quotesLoading,
222
+ children: [
223
+ !list?.noPeriod && /* @__PURE__ */ jsxs(Fragment, { children: [
224
+ /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.filterFrom"), children: /* @__PURE__ */ jsx(DatePicker, { variant: "input", format: "numeric", className: "w-full", value: draft.from, onChange: (v) => v && patch({ from: v }) }) }),
225
+ /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.filterTo"), children: /* @__PURE__ */ jsx(DatePicker, { variant: "input", format: "numeric", className: "w-full", value: draft.to, onChange: (v) => v && patch({ to: v }) }) })
226
+ ] }),
227
+ tabs.length > 0 ? /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.status"), children: /* @__PURE__ */ jsx(
228
+ SegmentedControl,
229
+ {
230
+ "aria-label": t("crm.quotes.status"),
231
+ options: tabs.map((x) => ({ value: x.id, label: x.label })),
232
+ value: tab?.id ?? "",
233
+ onChange: (id) => patch({ tab: id }),
234
+ size: "md"
235
+ }
236
+ ) }) : /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.status"), children: /* @__PURE__ */ jsx(
237
+ RequiredFilter,
238
+ {
239
+ label: t("crm.quotes.status"),
240
+ value: draft.status.length === 0 ? t("crm.quotes.filterAllStatuses") : draft.status.length === 1 ? t(`crm.quotes.status.${draft.status[0]}`) : t("crud.list.selectedMany", { count: draft.status.length }),
241
+ icon: CircleDashed,
242
+ className: "h-9 w-full justify-start",
243
+ align: "start",
244
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
245
+ /* @__PURE__ */ jsx(FilterMenuRow, { active: draft.status.length === 0, onClick: () => patch({ status: [] }), children: t("crm.quotes.filterAllStatuses") }),
246
+ QUOTE_STATUSES.map((st) => {
247
+ const on = draft.status.includes(st);
248
+ return /* @__PURE__ */ jsx(
249
+ FilterMenuRow,
250
+ {
251
+ active: on,
252
+ onClick: () => patch({ status: on ? draft.status.filter((v) => v !== st) : [...draft.status, st] }),
253
+ children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t(`crm.quotes.status.${st}`) })
254
+ },
255
+ st
256
+ );
257
+ })
258
+ ] })
259
+ }
260
+ ) }),
261
+ !list?.hideContactFilter && /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.contact"), compact: true, children: /* @__PURE__ */ jsx(
262
+ SearchSelect,
263
+ {
264
+ className: "w-full",
265
+ value: draft.contactId,
266
+ displayValue: draft.contactName,
267
+ placeholder: t("crm.quotes.filterContactPlaceholder"),
268
+ minChars: 2,
269
+ minCharsLabel: t("crm.quotes.filterMinChars"),
270
+ noResultsLabel: t("crm.quotes.filterNoContact"),
271
+ searchingLabel: t("crm.quotes.filterSearching"),
272
+ loadOnOpen: false,
273
+ clearLabel: t("crm.quotes.filterAllContacts"),
274
+ onChange: (id, option) => patch({ contactId: id, contactName: option?.label ?? "" }),
275
+ onSearch: async (termo) => {
276
+ if (provider.searchQuoteContacts) return toQuoteContactOptions(await provider.searchQuoteContacts(termo));
277
+ const results = await contactLookup.search(termo);
278
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
279
+ }
280
+ }
281
+ ) })
282
+ ]
283
+ }
284
+ ),
285
+ /* @__PURE__ */ jsxs(Card, { className: "relative px-3 py-1.5", children: [
286
+ /* @__PURE__ */ jsx(Search, { className: "pointer-events-none absolute left-5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground" }),
287
+ /* @__PURE__ */ jsx(
288
+ Input,
289
+ {
290
+ type: "text",
291
+ value: draft.search,
292
+ onChange: (e) => patch({ search: e.target.value }),
293
+ onKeyDown: (e) => {
294
+ if (e.key === "Enter") filtros.apply();
295
+ },
296
+ placeholder: list?.search?.placeholder ?? t("crm.quotes.searchPlaceholder"),
297
+ "aria-label": list?.search?.placeholder ?? t("crm.quotes.searchPlaceholder"),
298
+ className: "h-auto rounded-none border-0 bg-transparent py-1.5 pl-8 pr-3 shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
299
+ }
300
+ )
301
+ ] }),
302
+ /* @__PURE__ */ jsx(
303
+ DataTable,
304
+ {
305
+ columns,
306
+ data: quotesLoading ? [] : rows,
307
+ loading: quotesLoading,
308
+ onRowClick: (row) => onEdit?.(row.id),
309
+ emptyMessage: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 py-6", children: [
310
+ /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
311
+ /* @__PURE__ */ jsx("p", { className: "text-base font-semibold text-foreground", children: list?.emptyLabel ?? t("crm.quotes.noQuotes") }),
312
+ onNew && /* @__PURE__ */ jsx(Button, { size: "lg", onClick: onNew, className: "mt-3 px-3 font-medium", children: labels?.newQuote ?? t("crm.quotes.createFirst") })
313
+ ] })
314
+ }
315
+ ),
316
+ /* @__PURE__ */ jsx(
317
+ ConfirmDialog,
318
+ {
319
+ open: alvoArquivo !== null,
320
+ onCancel: () => setAlvoArquivo(null),
321
+ variant: "destructive",
322
+ title: t("crm.quotes.archiveTitle"),
323
+ description: t("crm.quotes.archiveDescription"),
324
+ confirmLabel: t("crm.quotes.archive"),
325
+ onConfirm: async () => {
326
+ if (alvoArquivo) await archiveQuote(alvoArquivo);
327
+ setAlvoArquivo(null);
328
+ }
329
+ }
330
+ )
331
+ ] });
332
+ }
333
+ var STATUSES = [
334
+ { value: "draft", labelKey: "crm.quoteForm.statusDraft", color: "bg-primary text-primary-foreground" },
335
+ { value: "sent", labelKey: "crm.quoteForm.statusSent", color: "bg-info-soft text-info-soft-foreground border border-info/30 dark:border-info/30" },
336
+ { value: "approved", labelKey: "crm.quoteForm.statusApproved", color: "bg-success-soft text-success-soft-foreground border border-success/30 dark:border-success/30" },
337
+ { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
338
+ { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
339
+ ];
340
+ var VALIDITY_PRESETS = [
341
+ { days: 7, labelKey: "crm.quoteForm.validOneWeek" },
342
+ { days: 30, labelKey: "crm.quoteForm.validThirtyDays" }
343
+ ];
344
+ function addDays(iso, days) {
345
+ const d = /* @__PURE__ */ new Date(`${iso}T12:00:00`);
346
+ d.setDate(d.getDate() + days);
347
+ return d.toISOString().slice(0, 10);
348
+ }
349
+ function daysBetween(from, to) {
350
+ const ms = (/* @__PURE__ */ new Date(`${to}T12:00:00`)).getTime() - (/* @__PURE__ */ new Date(`${from}T12:00:00`)).getTime();
351
+ return Math.round(ms / 864e5);
352
+ }
353
+ var fid = 1;
354
+ function nextId() {
355
+ return `qi${fid++}`;
356
+ }
357
+ function QuoteFormView({ quoteId, leadId, onSaved }) {
358
+ const t = useTranslation();
359
+ const config = useCrmConfig();
360
+ const provider = useCrmProvider();
361
+ const { currency, itemTypes: declaredItemTypes } = config;
362
+ const translatedItemTypes = React2.useMemo(
363
+ () => declaredItemTypes.map((tp) => {
364
+ const traduzido = t(`crm.itemType.${tp.value}`);
365
+ return traduzido === `crm.itemType.${tp.value}` ? tp : { ...tp, label: traduzido };
366
+ }),
367
+ [declaredItemTypes, t]
368
+ );
369
+ const itemTypes = useCatalogedItemTypes(translatedItemTypes, config.entityLookups);
370
+ const createQuote = useCrmStore((s) => s.createQuote);
371
+ const updateQuote = useCrmStore((s) => s.updateQuote);
372
+ const guardQuotes = useLimitGuard("quotes");
373
+ const isEdit = !!quoteId;
374
+ const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId);
375
+ const [linkedLeadId, setLinkedLeadId] = useState(leadId ?? "");
376
+ const [linkedDealId, setLinkedDealId] = useState("");
377
+ const [contactName, setContactName] = useState("");
378
+ const [contactDisplay, setContactDisplay] = useState("");
379
+ const [contactId, setContactId] = useState("");
380
+ const [quoteDate, setQuoteDate] = useState((/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
381
+ const [validUntil, setValidUntil] = useState(() => {
382
+ const d = /* @__PURE__ */ new Date();
383
+ d.setDate(d.getDate() + 30);
384
+ return d.toISOString().slice(0, 10);
385
+ });
386
+ const [validityDays, setValidityDays] = useState(30);
387
+ const [currentStatus, setCurrentStatus] = useState("draft");
388
+ const [paymentConditions, setPaymentConditions] = useState("");
389
+ const [observations, setObservations] = useState("");
390
+ const [items, setItems] = useState([]);
391
+ const [expandedItemId, setExpandedItemId] = useState(null);
392
+ const [addingItem, setAddingItem] = useState(false);
393
+ const [saving, setSaving] = useState(false);
394
+ useEffect(() => {
395
+ if (!quoteId) return;
396
+ provider.getQuoteById(quoteId).then((q) => {
397
+ if (q) {
398
+ setContactName(q.contactName ?? "");
399
+ setContactDisplay([dealHeadline(q), q.contactName && dealHeadline(q) !== q.contactName ? q.contactName : null].filter(Boolean).join(" \xB7 "));
400
+ setContactId(q.contactId ?? "");
401
+ setLinkedLeadId(q.leadId ?? "");
402
+ setLinkedDealId(q.dealId ?? "");
403
+ setQuoteDate(q.quoteDate);
404
+ setValidUntil(q.validUntil);
405
+ const span = daysBetween(q.quoteDate, q.validUntil);
406
+ setValidityDays(VALIDITY_PRESETS.some((pr) => pr.days === span) ? span : null);
407
+ setCurrentStatus(q.status);
408
+ setPaymentConditions(q.paymentConditions ?? "");
409
+ setObservations(q.observations ?? "");
410
+ setItems(q.items.map((it) => ({
411
+ _id: nextId(),
412
+ itemKind: it.itemKind,
413
+ description: it.description,
414
+ quantity: it.quantity,
415
+ unitPrice: it.unitPrice,
416
+ discount: it.discount
417
+ })));
418
+ }
419
+ setLoadingExisting(false);
420
+ });
421
+ }, [quoteId]);
422
+ useEffect(() => {
423
+ if (!leadId || quoteId) return;
424
+ provider.getLeadById(leadId).then(async (lead) => {
425
+ if (lead) {
426
+ setContactName(lead.name);
427
+ setContactDisplay([lead.companyName ?? lead.company, lead.name].filter(Boolean).join(" \xB7 "));
428
+ setContactId(lead.id);
429
+ setLinkedLeadId(lead.id);
430
+ const deal = await provider.getDealByLeadId(lead.id);
431
+ if (deal) setLinkedDealId(deal.id);
432
+ }
433
+ setLoadingExisting(false);
434
+ });
435
+ }, [leadId]);
436
+ function changeQuoteDate(iso) {
437
+ setQuoteDate(iso);
438
+ if (validityDays !== null) setValidUntil(addDays(iso, validityDays));
439
+ }
440
+ const openCustomOnMount = React2.useRef(false);
441
+ function pickValidity(days) {
442
+ openCustomOnMount.current = days === null && validityDays !== null;
443
+ setValidityDays(days);
444
+ if (days !== null) setValidUntil(addDays(quoteDate, days));
445
+ }
446
+ const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0);
447
+ function startAddItem() {
448
+ if (itemTypes.length === 1) {
449
+ addItemOfKind(itemTypes[0].value);
450
+ return;
451
+ }
452
+ setAddingItem(true);
453
+ }
454
+ function addItemOfKind(kind) {
455
+ const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
456
+ setItems([...items, newItem]);
457
+ setExpandedItemId(newItem._id);
458
+ setAddingItem(false);
459
+ }
460
+ function updateItem(id, data) {
461
+ setItems(items.map((it) => it._id === id ? { ...it, ...data } : it));
462
+ }
463
+ function removeItem(id) {
464
+ setItems(items.filter((it) => it._id !== id));
465
+ if (expandedItemId === id) setExpandedItemId(null);
466
+ }
467
+ async function handleSave() {
468
+ if (items.length === 0) {
469
+ toast.error(t("crm.quoteForm.errNoItems"));
470
+ return;
471
+ }
472
+ if (!isEdit && await guardQuotes() === "blocked") return;
473
+ setSaving(true);
474
+ try {
475
+ const input = {
476
+ contactId: contactId || void 0,
477
+ contactName: contactName || void 0,
478
+ leadId: linkedLeadId || void 0,
479
+ dealId: linkedDealId || void 0,
480
+ quoteDate,
481
+ validUntil,
482
+ paymentConditions: paymentConditions || void 0,
483
+ observations: observations || void 0,
484
+ items: items.map((it) => ({
485
+ itemKind: it.itemKind,
486
+ description: it.description,
487
+ quantity: it.quantity,
488
+ unitPrice: it.unitPrice,
489
+ discount: it.discount,
490
+ totalAmount: it.quantity * it.unitPrice - it.discount
491
+ }))
492
+ };
493
+ if (isEdit) {
494
+ await updateQuote(quoteId, input);
495
+ onSaved?.(quoteId);
496
+ } else {
497
+ const created = await createQuote(input);
498
+ invalidateLimit("quotes");
499
+ onSaved?.(created?.id);
500
+ }
501
+ } finally {
502
+ setSaving(false);
503
+ }
504
+ }
505
+ const currentFields = {
506
+ contactId,
507
+ contactName,
508
+ linkedLeadId,
509
+ linkedDealId,
510
+ quoteDate,
511
+ validUntil,
512
+ currentStatus,
513
+ paymentConditions,
514
+ observations,
515
+ items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
516
+ };
517
+ const snapshot = React2.useRef(null);
518
+ useEffect(() => {
519
+ if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
520
+ }, [loadingExisting]);
521
+ const dirty = snapshot.current !== null && JSON.stringify(currentFields) !== snapshot.current;
522
+ useSaveBar({
523
+ dirty,
524
+ saving,
525
+ onSave: () => {
526
+ void handleSave();
527
+ },
528
+ onDiscard: () => onSaved?.(),
529
+ saveLabel: isEdit ? t("crm.quoteForm.saveChanges") : t("crm.quoteForm.saveQuote")
530
+ });
531
+ if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t("crm.quotes.title"), onBack: () => onSaved?.() });
532
+ const money = (v) => formatCurrency(v, currency);
533
+ const validUntilLabel = (/* @__PURE__ */ new Date(`${validUntil}T12:00:00`)).toLocaleDateString(getCurrentLocale());
534
+ const contactSection = /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
535
+ SearchSelect,
536
+ {
537
+ value: contactId,
538
+ displayValue: contactDisplay || contactName,
539
+ onChange: (id, opt) => {
540
+ const c = opt?.data;
541
+ setContactId(id);
542
+ setContactName(c?.name ?? opt?.label ?? "");
543
+ setContactDisplay(c ? [quoteContactLabel(c).label, quoteContactLabel(c).subtitle].filter(Boolean).join(" \xB7 ") : opt?.label ?? "");
544
+ },
545
+ onSearch: async (q) => {
546
+ if (provider.searchQuoteContacts) return toQuoteContactOptions(await provider.searchQuoteContacts(q));
547
+ if (!config.contactLookup) return [];
548
+ const results = await config.contactLookup.search(q);
549
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
550
+ },
551
+ required: true,
552
+ placeholder: t("crm.quoteForm.searchClient"),
553
+ allowCreate: true,
554
+ createLabel: t("crm.quoteForm.addAsLead"),
555
+ onCreate: async (name) => {
556
+ const lead = await provider.createLead({ name });
557
+ setContactId(lead.id);
558
+ setContactName(lead.name);
559
+ setContactDisplay(lead.name);
560
+ }
561
+ }
562
+ ) });
563
+ const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
564
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.quoteDetails"), children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
565
+ /* @__PURE__ */ jsxs("div", { children: [
566
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.quoteDate") }),
567
+ /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: changeQuoteDate, className: "mt-1" })
568
+ ] }),
569
+ /* @__PURE__ */ jsxs("div", { children: [
570
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
571
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.validUntil") }),
572
+ validityDays === null ? /* @__PURE__ */ jsx(
573
+ DatePicker,
574
+ {
575
+ variant: "inline",
576
+ format: "numeric",
577
+ value: validUntil,
578
+ onChange: setValidUntil,
579
+ defaultOpen: openCustomOnMount.current
580
+ }
581
+ ) : /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-foreground", children: validUntilLabel })
582
+ ] }),
583
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap gap-1.5", children: [
584
+ VALIDITY_PRESETS.map((preset) => /* @__PURE__ */ jsx(
585
+ Button,
586
+ {
587
+ type: "button",
588
+ variant: "bare",
589
+ size: "bare",
590
+ onClick: () => pickValidity(preset.days),
591
+ className: `rounded-full border px-2.5 py-1 text-xs font-normal ${validityDays === preset.days ? "border-primary bg-primary text-primary-foreground" : "border-input bg-card text-muted-foreground hover:bg-muted/50"}`,
592
+ children: t(preset.labelKey)
593
+ },
594
+ preset.days
595
+ )),
596
+ /* @__PURE__ */ jsx(
597
+ Button,
598
+ {
599
+ type: "button",
600
+ variant: "bare",
601
+ size: "bare",
602
+ onClick: () => pickValidity(null),
603
+ className: `rounded-full border px-2.5 py-1 text-xs font-normal ${validityDays === null ? "border-primary bg-primary text-primary-foreground" : "border-input bg-card text-muted-foreground hover:bg-muted/50"}`,
604
+ children: t("crm.quoteForm.validCustom")
605
+ }
606
+ )
607
+ ] })
608
+ ] })
609
+ ] }) }),
610
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.paymentConditions"), children: /* @__PURE__ */ jsx(
611
+ Textarea,
612
+ {
613
+ value: paymentConditions,
614
+ onChange: (e) => setPaymentConditions(e.target.value),
615
+ rows: 2,
616
+ placeholder: t("crm.quoteForm.paymentConditionsPlaceholder"),
617
+ className: "min-h-0 resize-none"
618
+ }
619
+ ) }),
620
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.notes"), children: /* @__PURE__ */ jsx(
621
+ Textarea,
622
+ {
623
+ value: observations,
624
+ onChange: (e) => setObservations(e.target.value),
625
+ rows: 2,
626
+ placeholder: t("crm.quoteForm.notesPlaceholder"),
627
+ className: "min-h-0 resize-none"
628
+ }
629
+ ) })
630
+ ] });
631
+ return /* @__PURE__ */ jsxs(
632
+ OrderFormView,
633
+ {
634
+ sideSections,
635
+ title: isEdit ? t("crm.quoteForm.editTitle") : t("crm.quoteForm.newTitle"),
636
+ parentLabel: t("crm.quotes.title"),
637
+ onBack: () => onSaved?.(),
638
+ badges: /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: STATUSES.map((s) => /* @__PURE__ */ jsx(
639
+ "span",
640
+ {
641
+ 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"}`,
642
+ children: t(s.labelKey)
643
+ },
644
+ s.value
645
+ )) }),
646
+ children: [
647
+ contactSection,
648
+ /* @__PURE__ */ jsx(
649
+ OrderFormItemsCard,
650
+ {
651
+ label: t("crm.quoteForm.quoteItems"),
652
+ addLabel: t("crm.quoteForm.addItem"),
653
+ onAdd: startAddItem,
654
+ addDisabled: !contactId,
655
+ addDisabledHint: t("crm.quoteForm.selectClientFirst"),
656
+ count: items.length,
657
+ countLabel: t("crm.quoteForm.itemCount", { count: String(items.length) }),
658
+ totalLabel: t("crm.quoteForm.total"),
659
+ total: money(totalAmount),
660
+ emptyLabel: contactId ? t("crm.quoteForm.noItems") : t("crm.quoteForm.selectClientFirst"),
661
+ emptyActionLabel: t("crm.quoteForm.addFirstItem"),
662
+ header: addingItem && /* @__PURE__ */ jsx(
663
+ OrderFormAddItemStep,
664
+ {
665
+ itemTypes,
666
+ onSelect: addItemOfKind,
667
+ onCancel: () => setAddingItem(false),
668
+ label: t("crm.quoteForm.selectItemType"),
669
+ cancelLabel: t("crm.quoteForm.cancel")
670
+ }
671
+ ),
672
+ children: items.map((item, i) => /* @__PURE__ */ jsx(
673
+ OrderFormItemRow,
674
+ {
675
+ index: i,
676
+ itemKind: item.itemKind,
677
+ description: item.description,
678
+ quantity: item.quantity,
679
+ unitPrice: item.unitPrice,
680
+ discount: item.discount,
681
+ itemTypes,
682
+ currency,
683
+ formatMoney: money,
684
+ expanded: expandedItemId === item._id,
685
+ onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
686
+ onChange: (patch) => updateItem(item._id, patch),
687
+ onRemove: () => removeItem(item._id),
688
+ entityLookups: config.entityLookups,
689
+ labels: {
690
+ item: t("crm.quoteForm.description"),
691
+ description: t("crm.quoteForm.description"),
692
+ descriptionPlaceholder: t("crm.quoteForm.itemDescriptionPlaceholder"),
693
+ noDescription: t("crm.quoteForm.noDescription"),
694
+ qty: t("crm.quoteForm.qty"),
695
+ unitPrice: t("crm.quoteForm.unitPrice"),
696
+ discount: t("crm.quoteForm.discount"),
697
+ done: t("crm.quoteForm.done")
698
+ }
699
+ },
700
+ item._id
701
+ ))
702
+ }
703
+ )
704
+ ]
705
+ }
706
+ );
707
+ }
708
+ function QuoteEditRoute({ quoteId, onSaved, onBack }) {
709
+ const t = useTranslation();
710
+ const provider = useCrmProvider();
711
+ const [quote, setQuote] = useState(void 0);
712
+ const owners = getQuoteExtensions().filter((ext) => ext.editor);
713
+ useEffect(() => {
714
+ if (!owners.length) {
715
+ setQuote(null);
716
+ return;
717
+ }
718
+ let alive = true;
719
+ provider.getQuoteById(quoteId).then((q) => {
720
+ if (alive) setQuote(q);
721
+ }).catch(() => {
722
+ if (alive) setQuote(null);
723
+ });
724
+ return () => {
725
+ alive = false;
726
+ };
727
+ }, [provider, quoteId, owners.length]);
728
+ if (quote === void 0) return /* @__PURE__ */ jsx(OrderDetailSkeleton, { parentLabel: t("crm.quotes.title"), onBack });
729
+ const owner = quote ? owners.find((ext) => ext.editor.owns(quote)) : void 0;
730
+ if (owner) return /* @__PURE__ */ jsx(Fragment, { children: owner.editor.render({ quoteId, onSaved, onBack }) });
731
+ return /* @__PURE__ */ jsx(QuoteFormView, { quoteId, onSaved });
732
+ }
733
+ var STATUS_CONFIG = {
734
+ draft: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: CircleDashed, label: (t) => t("crm.quotes.status.draft") },
735
+ sent: { bg: "bg-info-soft text-info-soft-foreground", dot: "bg-info", icon: Send, label: (t) => t("crm.quotes.status.sent") },
736
+ approved: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: CircleCheckBig, label: (t) => t("crm.quotes.status.approved") },
737
+ rejected: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Ban, label: (t) => t("crm.quotes.status.rejected") },
738
+ expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: CircleAlert, label: (t) => t("crm.quotes.status.expired") },
739
+ archived: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: Archive, label: (t) => t("crm.quotes.status.archived") },
740
+ invoiced: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: () => tl("Invoiced", "Faturado") },
741
+ paid: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: Receipt, label: () => tl("Paid", "Pago") },
742
+ partial: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: () => tl("Partial", "Pago em parte") },
743
+ overdue: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Receipt, label: () => tl("Overdue", "Em atraso") }
744
+ };
745
+ var TRANSITIONS = {
746
+ draft: ["sent", "expired"],
747
+ sent: ["approved", "rejected", "expired"],
748
+ approved: [],
749
+ rejected: [],
750
+ expired: [],
751
+ archived: []
752
+ };
753
+ function RejectModal({ onConfirm, onCancel }) {
754
+ const t = useTranslation();
755
+ const [reason, setReason] = useState("");
756
+ return /* @__PURE__ */ jsx(Modal, { open: true, onOpenChange: (open) => {
757
+ if (!open) onCancel();
758
+ }, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-sm", children: [
759
+ /* @__PURE__ */ jsxs(ModalHeader, { children: [
760
+ /* @__PURE__ */ jsx(ModalTitle, { children: t("crm.quoteDetail.confirmReject") }),
761
+ /* @__PURE__ */ jsx(ModalDescription, { children: t("crm.quoteDetail.rejectDescription") })
762
+ ] }),
763
+ /* @__PURE__ */ jsx(ModalBody, { children: /* @__PURE__ */ jsx(
764
+ Textarea,
765
+ {
766
+ value: reason,
767
+ onChange: (e) => setReason(e.target.value),
768
+ rows: 3,
769
+ placeholder: t("crm.quoteDetail.rejectReasonPlaceholder"),
770
+ autoFocus: true,
771
+ className: "resize-none"
772
+ }
773
+ ) }),
774
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
775
+ /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onCancel, children: t("crm.quoteForm.cancel") }),
776
+ /* @__PURE__ */ jsx(Button, { variant: "destructive", size: "sm", onClick: () => onConfirm(reason), disabled: !reason.trim(), children: t("crm.quoteDetail.reject") })
777
+ ] })
778
+ ] }) });
779
+ }
780
+ function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
781
+ const t = useTranslation();
782
+ const sendQuote = useCrmStore((s) => s.sendQuote);
783
+ const approveQuote = useCrmStore((s) => s.approveQuote);
784
+ const rejectQuote = useCrmStore((s) => s.rejectQuote);
785
+ const expireQuote = useCrmStore((s) => s.expireQuote);
786
+ const [loading, setLoading] = useState(false);
787
+ const [showApprove, setShowApprove] = useState(false);
788
+ const [showReject, setShowReject] = useState(false);
789
+ const config = STATUS_CONFIG[quote.status] ?? STATUS_CONFIG.draft;
790
+ const StatusIcon = config.icon;
791
+ const transitions = TRANSITIONS[quote.status] ?? [];
792
+ async function handleTransition(target) {
793
+ if (loading) return;
794
+ setLoading(true);
795
+ try {
796
+ let updated;
797
+ switch (target) {
798
+ case "sent":
799
+ updated = await sendQuote(quote.id);
800
+ break;
801
+ case "approved":
802
+ setShowApprove(true);
803
+ setLoading(false);
804
+ return;
805
+ case "expired":
806
+ updated = await expireQuote(quote.id);
807
+ break;
808
+ default:
809
+ setLoading(false);
810
+ return;
811
+ }
812
+ onStatusChange?.(updated);
813
+ } catch {
814
+ } finally {
815
+ setLoading(false);
816
+ }
817
+ }
818
+ async function handleReject(reason) {
819
+ setShowReject(false);
820
+ setLoading(true);
821
+ try {
822
+ const updated = await rejectQuote(quote.id, reason);
823
+ onStatusChange?.(updated);
824
+ } catch {
825
+ } finally {
826
+ setLoading(false);
827
+ }
828
+ }
829
+ const isSmall = size === "sm";
830
+ if (transitions.length === 0) {
831
+ return /* @__PURE__ */ 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: [
832
+ !isSmall && /* @__PURE__ */ jsx(StatusIcon, { className: "h-3 w-3" }),
833
+ config.label(t)
834
+ ] });
835
+ }
836
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
837
+ /* @__PURE__ */ jsxs(Dropdown, { children: [
838
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
839
+ Button,
840
+ {
841
+ variant: "bare",
842
+ size: "bare",
843
+ onClick: (e) => e.stopPropagation(),
844
+ disabled: loading,
845
+ className: `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`,
846
+ children: [
847
+ !isSmall && /* @__PURE__ */ jsx(StatusIcon, { className: "h-3 w-3" }),
848
+ config.label(t),
849
+ loading ? /* @__PURE__ */ jsx(Loader2, { className: `animate-spin ${isSmall ? "h-2.5 w-2.5" : "h-3 w-3"}` }) : /* @__PURE__ */ jsx(ChevronDown, { className: `opacity-50 ${isSmall ? "h-2.5 w-2.5" : "h-3 w-3"}` })
850
+ ]
851
+ }
852
+ ) }),
853
+ /* @__PURE__ */ jsxs(DropdownContent, { align: "end", sideOffset: 4, onClick: (e) => e.stopPropagation(), children: [
854
+ /* @__PURE__ */ jsx(DropdownLabel, { children: tl("Change status", "Mudar status") }),
855
+ /* @__PURE__ */ jsx(DropdownSeparator, {}),
856
+ transitions.map((target) => {
857
+ const cfg = STATUS_CONFIG[target];
858
+ const TargetIcon = cfg.icon;
859
+ return /* @__PURE__ */ jsxs(
860
+ DropdownItem,
861
+ {
862
+ onClick: () => target === "rejected" ? setShowReject(true) : handleTransition(target),
863
+ className: "gap-2.5",
864
+ children: [
865
+ /* @__PURE__ */ jsx("span", { className: `h-2 w-2 rounded-full shrink-0 ${cfg.dot}` }),
866
+ /* @__PURE__ */ jsx(TargetIcon, { className: "h-3.5 w-3.5 shrink-0" }),
867
+ /* @__PURE__ */ jsx("span", { children: cfg.label(t) })
868
+ ]
869
+ },
870
+ target
871
+ );
872
+ })
873
+ ] })
874
+ ] }),
875
+ /* @__PURE__ */ jsx(
876
+ ConfirmDialog,
877
+ {
878
+ open: showApprove,
879
+ variant: "success",
880
+ title: tl("Approve this quote?", "Aprovar este or\xE7amento?"),
881
+ description: tl("This will create an invoice and convert the lead to a client. This action cannot be undone.", "Isso cria uma fatura e converte o lead em cliente. N\xE3o d\xE1 para desfazer."),
882
+ confirmLabel: t("crm.quoteDetail.approve"),
883
+ cancelLabel: t("crm.quoteForm.cancel"),
884
+ loading,
885
+ onConfirm: async () => {
886
+ setLoading(true);
887
+ try {
888
+ const updated = await approveQuote(quote.id);
889
+ setShowApprove(false);
890
+ onStatusChange?.(updated);
891
+ } catch {
892
+ } finally {
893
+ setLoading(false);
894
+ }
895
+ },
896
+ onCancel: () => setShowApprove(false)
897
+ }
898
+ ),
899
+ showReject && /* @__PURE__ */ jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
900
+ ] });
901
+ }
902
+ var MAX_BYTES = 25 * 1024 * 1024;
903
+ function QuoteAttachmentsModal({ quoteId, onClose, onChanged }) {
904
+ const t = useTranslation();
905
+ const provider = useCrmProvider();
906
+ return /* @__PURE__ */ jsx(
907
+ AttachmentsModal,
908
+ {
909
+ labels: {
910
+ title: t("crm.quoteDetail.attachments"),
911
+ emptyTitle: t("crm.quoteDetail.attachmentsEmpty"),
912
+ emptyHint: t("crm.quoteDetail.attachmentsHint"),
913
+ dropzone: t("crm.quoteDetail.attachDropzone"),
914
+ dropzoneHint: t("crm.quoteDetail.attachDropzoneHint"),
915
+ uploading: t("crm.quoteDetail.attaching"),
916
+ pendingShort: t("crm.quoteDetail.attachmentPending"),
917
+ remove: t("crm.quoteDetail.attachmentRemove"),
918
+ removeConfirm: t("crm.quoteDetail.attachmentRemoveConfirm"),
919
+ cancel: t("common.cancel"),
920
+ close: t("common.close"),
921
+ done: t("common.done"),
922
+ invalidFile: t("crm.quoteDetail.attachmentTooLarge")
923
+ },
924
+ maxBytes: MAX_BYTES,
925
+ load: () => provider.getQuoteAttachments?.(quoteId) ?? Promise.resolve([]),
926
+ upload: provider.addQuoteAttachment ? async (file) => {
927
+ await provider.addQuoteAttachment(quoteId, file);
928
+ } : void 0,
929
+ remove: provider.removeQuoteAttachment ? (a) => provider.removeQuoteAttachment(quoteId, a.id) : void 0,
930
+ onClose,
931
+ onChanged
932
+ }
933
+ );
934
+ }
935
+ function useQuoteAttachmentsAction(quoteId) {
936
+ const t = useTranslation();
937
+ const provider = useCrmProvider();
938
+ const supported = !!provider.getQuoteAttachments;
939
+ const [count, setCount] = useState(0);
940
+ const [open, setOpen] = useState(false);
941
+ const refresh = useCallback(() => {
942
+ if (!supported) return;
943
+ provider.getQuoteAttachments(quoteId).then((rows) => setCount(rows.length)).catch(() => setCount(0));
944
+ }, [provider, quoteId, supported]);
945
+ useEffect(() => {
946
+ refresh();
947
+ }, [refresh]);
948
+ if (!supported) return { action: null, modal: null };
949
+ return {
950
+ action: {
951
+ id: "attachments",
952
+ label: count > 0 ? `${t("crm.quoteDetail.attachments")} \xB7 ${count}` : t("crm.quoteDetail.attach"),
953
+ icon: Paperclip,
954
+ intent: "utility",
955
+ count,
956
+ testId: "quote-attachments-action",
957
+ onSelect: () => setOpen(true)
958
+ },
959
+ modal: open ? /* @__PURE__ */ jsx(QuoteAttachmentsModal, { quoteId, onClose: () => setOpen(false), onChanged: refresh }) : null
960
+ };
961
+ }
962
+ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
963
+ const t = useTranslation();
964
+ const { currency } = useCrmConfig();
965
+ const provider = useCrmProvider();
966
+ const sendQuote = useCrmStore((s) => s.sendQuote);
967
+ const approveQuote = useCrmStore((s) => s.approveQuote);
968
+ const rejectQuote = useCrmStore((s) => s.rejectQuote);
969
+ const [quote, setQuote] = useState(null);
970
+ const [loading, setLoading] = useState(true);
971
+ const [sending, setSending] = useState(false);
972
+ const [approving, setApproving] = useState(false);
973
+ const [rejectOpen, setRejectOpen] = useState(false);
974
+ const [rejectReason, setRejectReason] = useState("");
975
+ const [rejecting, setRejecting] = useState(false);
976
+ const { action: attachmentsAction, modal: attachmentsModal } = useQuoteAttachmentsAction(quoteId);
977
+ useEffect(() => {
978
+ setLoading(true);
979
+ provider.getQuoteById(quoteId).then((q) => {
980
+ setQuote(q);
981
+ setLoading(false);
982
+ });
983
+ }, [quoteId]);
984
+ const reload = useCallback(() => {
985
+ provider.getQuoteById(quoteId).then((q) => {
986
+ if (q) setQuote({ ...q });
987
+ });
988
+ }, [provider, quoteId]);
989
+ async function handleSend(_channel) {
990
+ setSending(true);
991
+ try {
992
+ const updated = await sendQuote(quoteId);
993
+ setQuote(updated);
994
+ } finally {
995
+ setSending(false);
996
+ }
997
+ }
998
+ async function handleApprove() {
999
+ setApproving(true);
1000
+ try {
1001
+ const updated = await approveQuote(quoteId);
1002
+ setQuote(updated);
1003
+ if (onInvoiceCreated) onInvoiceCreated(quoteId);
1004
+ } finally {
1005
+ setApproving(false);
1006
+ }
1007
+ }
1008
+ async function handleReject() {
1009
+ if (!rejectReason.trim()) return;
1010
+ setRejecting(true);
1011
+ try {
1012
+ const updated = await rejectQuote(quoteId, rejectReason.trim());
1013
+ setQuote(updated);
1014
+ setRejectOpen(false);
1015
+ setRejectReason("");
1016
+ } finally {
1017
+ setRejecting(false);
1018
+ }
1019
+ }
1020
+ if (loading) return /* @__PURE__ */ jsx(OrderDetailSkeleton, { parentLabel: t("crm.quotes.title"), onBack });
1021
+ if (!quote) {
1022
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
1023
+ /* @__PURE__ */ jsx(SubpageHeader, { title: t("crm.quoteDetail.title"), onBack, parentLabel: t("crm.quotes.title") }),
1024
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted py-12 text-center", children: [
1025
+ /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-8 w-8 text-muted-foreground/30" }),
1026
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("crm.quoteDetail.notFound") }),
1027
+ /* @__PURE__ */ jsx(Button, { variant: "bare", size: "bare", onClick: onBack, className: "mt-1 text-xs font-normal text-primary hover:underline", children: t("crm.quoteDetail.backToList") })
1028
+ ] })
1029
+ ] });
1030
+ }
1031
+ const subtotal = quote.items.reduce((sum, it) => sum + it.quantity * it.unitPrice, 0);
1032
+ const totalDiscount = quote.items.reduce((sum, it) => sum + it.discount, 0);
1033
+ const detailItems = quote.items.map((it, i) => ({
1034
+ id: it.id ?? String(i),
1035
+ name: it.description || "\u2014",
1036
+ description: it.itemKind,
1037
+ quantity: it.quantity,
1038
+ unitPrice: formatCurrency(it.unitPrice, currency),
1039
+ total: formatCurrency(it.totalAmount, currency)
1040
+ }));
1041
+ const totals = [
1042
+ ...totalDiscount > 0 ? [
1043
+ { label: t("crm.quoteDetail.subtotal"), value: formatCurrency(subtotal, currency), muted: true },
1044
+ { label: t("crm.quoteDetail.discount"), value: `-${formatCurrency(totalDiscount, currency)}`, muted: true }
1045
+ ] : [],
1046
+ { label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), strong: true }
1047
+ ];
1048
+ const editable = quote.status !== "approved" && quote.status !== "rejected" && quote.status !== "expired";
1049
+ const extensions = getQuoteExtensions();
1050
+ const extensionActions = extensions.flatMap((ext) => ext.actions?.(quote) ?? []);
1051
+ const extensionSections = extensions.filter((ext) => ext.section);
1052
+ const ownActions = [
1053
+ ...quote.status === "draft" ? [
1054
+ { id: "send-whatsapp", label: t("crm.quoteDetail.sendWhatsApp"), icon: MessageCircle, intent: "primary", disabled: sending, onSelect: () => handleSend() },
1055
+ { id: "send-email", label: t("crm.quoteDetail.sendEmail"), icon: Mail, intent: "secondary", disabled: sending, onSelect: () => handleSend() },
1056
+ { id: "send-print", label: t("crm.quoteDetail.sendPrint"), icon: Printer, intent: "secondary", disabled: sending, onSelect: () => handleSend() }
1057
+ ] : [],
1058
+ ...quote.status === "sent" ? [
1059
+ { id: "approve", label: approving ? t("crm.quoteDetail.approving") : t("crm.quoteDetail.approve"), icon: Check, intent: "primary", disabled: approving, onSelect: () => handleApprove() },
1060
+ { id: "reject", label: t("crm.quoteDetail.reject"), icon: X, intent: "danger", onSelect: () => setRejectOpen(true) }
1061
+ ] : [],
1062
+ ...onEdit && editable ? [
1063
+ { id: "edit", label: t("crm.quoteDetail.edit"), icon: Pencil, intent: "secondary", onSelect: () => onEdit() }
1064
+ ] : [],
1065
+ ...attachmentsAction ? [attachmentsAction] : []
1066
+ ];
1067
+ const hidden = new Set(extensions.flatMap((ext) => ext.hidesActions?.(quote) ?? []));
1068
+ const actions = /* @__PURE__ */ jsx(PageActions, { actions: [...ownActions.filter((a) => !hidden.has(a.id)), ...extensionActions] });
1069
+ const sideBlocks = /* @__PURE__ */ jsxs(Fragment, { children: [
1070
+ quote.paymentConditions && /* @__PURE__ */ jsx(OrderDetailBlock, { title: t("crm.quoteDetail.paymentConditions"), children: /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm text-muted-foreground", children: quote.paymentConditions }) }),
1071
+ quote.observations && /* @__PURE__ */ jsx(OrderDetailBlock, { title: t("crm.quoteDetail.notes"), children: /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm text-muted-foreground", children: quote.observations }) }),
1072
+ extensionSections.map((ext) => {
1073
+ const Section = ext.section;
1074
+ return /* @__PURE__ */ jsx(Section, { quote, reload }, ext.id);
1075
+ })
1076
+ ] });
1077
+ const invoiced = ["approved", "invoiced", "paid", "partial", "overdue"].includes(quote.status) && !(quote.status === "approved" && hidden.has("approve") && !quote.convertedInvoiceId);
1078
+ const banners = /* @__PURE__ */ jsxs(Fragment, { children: [
1079
+ invoiced && /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between rounded-lg border border-success/30 bg-success/5 px-4 py-2.5", children: [
1080
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1081
+ /* @__PURE__ */ jsx(CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
1082
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("crm.quoteDetail.invoiceCreated") })
1083
+ ] }),
1084
+ /* @__PURE__ */ jsxs("a", { href: appHref("/financial/receivables/list"), className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline", children: [
1085
+ t("crm.quoteDetail.viewInvoice"),
1086
+ " ",
1087
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
1088
+ ] })
1089
+ ] }),
1090
+ quote.status === "rejected" && quote.rejectionReason && /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between rounded-lg border border-destructive/30 bg-destructive/5 px-4 py-2.5", children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
1091
+ /* @__PURE__ */ jsx(Ban, { className: "h-3.5 w-3.5 text-destructive" }),
1092
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
1093
+ t("crm.quoteDetail.rejectionReason"),
1094
+ ": ",
1095
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: quote.rejectionReason })
1096
+ ] })
1097
+ ] }) })
1098
+ ] });
1099
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1100
+ /* @__PURE__ */ jsx(
1101
+ OrderDetailView,
1102
+ {
1103
+ title: `#${quote.quoteNumber}`,
1104
+ badgesNode: quoteStatusOverride(quote) ?? /* @__PURE__ */ jsx(QuoteStatusDropdown, { quote, onStatusChange: (q) => setQuote(q) }),
1105
+ subtitle: null,
1106
+ onBack,
1107
+ backLabel: t("crm.quotes.title"),
1108
+ actions,
1109
+ stats: [
1110
+ { id: "total", label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), icon: Receipt },
1111
+ { id: "items", label: t("crm.quoteDetail.items"), value: quote.items.length, icon: Package },
1112
+ { id: "date", label: t("crm.quoteDetail.date"), value: quote.quoteDate, icon: Calendar },
1113
+ { id: "valid", label: t("crm.quoteDetail.validUntil"), value: quote.validUntil, icon: CalendarClock }
1114
+ ],
1115
+ errorBanner: banners,
1116
+ customer: { name: dealHeadline(quote) || quote.contactName, email: null },
1117
+ customerNode: /* @__PURE__ */ jsx(QuoteClientName, { quote, link: true }),
1118
+ items: detailItems,
1119
+ itemsLabel: t("crm.quoteDetail.items"),
1120
+ totals,
1121
+ totalsLabel: t("crm.quoteDetail.summary"),
1122
+ extraSections: sideBlocks
1123
+ }
1124
+ ),
1125
+ attachmentsModal,
1126
+ /* @__PURE__ */ jsx(Modal, { open: rejectOpen, onOpenChange: setRejectOpen, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-sm", children: [
1127
+ /* @__PURE__ */ jsxs(ModalBody, { children: [
1128
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center gap-3", children: [
1129
+ /* @__PURE__ */ jsx("div", { className: "flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-destructive/10", children: /* @__PURE__ */ jsx(X, { className: "h-5 w-5 text-destructive" }) }),
1130
+ /* @__PURE__ */ jsxs("div", { children: [
1131
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("crm.quoteDetail.reject") }),
1132
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("crm.quoteDetail.rejectDescription") })
1133
+ ] })
1134
+ ] }),
1135
+ /* @__PURE__ */ jsx(
1136
+ Textarea,
1137
+ {
1138
+ value: rejectReason,
1139
+ onChange: (e) => setRejectReason(e.target.value),
1140
+ placeholder: t("crm.quoteDetail.rejectReasonPlaceholder"),
1141
+ className: "h-20 resize-none",
1142
+ autoFocus: true
1143
+ }
1144
+ )
1145
+ ] }),
1146
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
1147
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => setRejectOpen(false), children: t("common.cancel") }),
1148
+ /* @__PURE__ */ jsx(
1149
+ Button,
1150
+ {
1151
+ type: "button",
1152
+ variant: "destructive",
1153
+ size: "sm",
1154
+ onClick: handleReject,
1155
+ disabled: rejecting || !rejectReason.trim(),
1156
+ children: rejecting ? t("crm.quoteDetail.rejecting") : t("crm.quoteDetail.confirmReject")
1157
+ }
1158
+ )
1159
+ ] })
1160
+ ] }) })
1161
+ ] });
1162
+ }
1163
+
1164
+ export { QuoteDetailView, QuoteEditRoute, QuoteFormView, QuoteListView, QuoteStatusDropdown, dealHeadline, dealHouseLine, useCanArchive };
1165
+ //# sourceMappingURL=chunk-5AB4K3PY.js.map
1166
+ //# sourceMappingURL=chunk-5AB4K3PY.js.map