@fayz-ai/plugin-crm 0.32.25 → 0.33.0-canary.20261027164140

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.
@@ -1,14 +1,16 @@
1
1
  import { loadTeamOrNull, loadMyUserId, DotChip, AssigneeName, formatDocument, humanizeTag, DEFAULT_ACTIVITY_TYPES, TagChips, localPhoneKey, normalizeDocument, isValidDocument } from './chunk-BIQL232X.js';
2
2
  import { CrmGeneralSettings } from './chunk-CA24LK57.js';
3
3
  import { resolveSourceView } from './chunk-QJOLAGGN.js';
4
+ import { QuoteFormView, QuoteListView, QuoteDetailView, useCanArchive, QuoteStatusDropdown } from './chunk-3HHSU2HD.js';
5
+ import './chunk-6URPZQQR.js';
4
6
  import { CrmContextProvider, useCrmProvider, useCrmStore, useCrmConfig, formatCurrency } from './chunk-7V46TYYX.js';
5
7
  import * as React from 'react';
6
8
  import React__default, { useCallback, useMemo, useState, useEffect, useRef } from 'react';
7
- import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight, Plus, Settings, Tag, Briefcase, CircleDot, User, Download, CircleDashed, Search, Inbox, X, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, Pencil, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Building2, Star, Trash2, MessageSquareQuote, UserRound, CalendarDays, ThumbsDown, SignalHigh, CalendarRange, TrendingDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Fingerprint, Paperclip, ImageOff, CircleAlert, Link2, CheckCircle2, SlidersHorizontal, ChevronLeft, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
8
- import { PageTransition, ModulePage, Button, useIsWide, PageHeaderActions, usePageSize, toast, FilterChip, MultiSelect, FilterMenu, FilterMenuRow, PersonAvatar, SubpageHeader, ListView, ConfirmDialog, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Textarea, ModalFooter, useSaveBar, SearchSelect, DatePicker, useFilterDraft, FilterPanel, FilterPanelField, RequiredFilter, Card, DataTable, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, PhoneLink, ComingSoon, Switch, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, DashboardCanvas, PageViewBar, Pagination, PersonPicker, cn, HeaderTabs, SheetBody, SheetFooter, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, ModalDescription, normalizePhone } from '@fayz-ai/ui';
9
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight, Plus, Settings, Tag, Briefcase, CircleDot, User, Inbox, X, Play, Clock, Download, Sparkles, Calendar, ArrowRight, MoreHorizontal, Loader2, Network, Building2, Star, Pencil, Trash2, MessageSquareQuote, UserRound, CalendarDays, Search, ThumbsDown, SignalHigh, CalendarRange, TrendingDown, UserCheck, ChevronDown, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Fingerprint, Paperclip, ImageOff, Link2, CheckCircle2, SlidersHorizontal, ChevronLeft, ExternalLink, CalendarClock, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
10
+ import { PageTransition, ModulePage, Button, useIsWide, PageHeaderActions, usePageSize, toast, FilterChip, MultiSelect, FilterMenu, FilterMenuRow, PersonAvatar, SubpageHeader, ListView, ConfirmDialog, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, Textarea, ModalFooter, DataTable, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, PhoneLink, ComingSoon, Switch, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, DashboardCanvas, PageViewBar, DatePicker, Card, Pagination, PersonPicker, cn, HeaderTabs, SheetBody, SheetFooter, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, ModalDescription, normalizePhone } from '@fayz-ai/ui';
9
11
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
10
- import { usePluginRuntimeOptional, useTranslation, currentAppPath, navigateApp, useActiveTenantId, exportCSV, getCurrentLocale, appHref, getSupabaseClientOptional, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
11
- import { useModuleNavigation, usePluginOnboardingGate, useUnitStore, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, adminNavigateTo, PageActions, usePermissionOptional, usePersistedState, useScrollMemory, useLimitGuard, useCatalogedItemTypes, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, createArchetypeLookup, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, CrudFormSkeleton, CrudFormPage, CrudDetailSkeleton, CrudDetailPage, AskAIButton, KanbanBoard, InlineField, useUnitFilter, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, RightRailPage, ContactPicker, useAgentSurface } from '@fayz-ai/admin';
12
+ import { usePluginRuntimeOptional, useTranslation, currentAppPath, navigateApp, useActiveTenantId, exportCSV, getSupabaseClientOptional, appHref, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
13
+ import { useModuleNavigation, usePluginOnboardingGate, useUnitStore, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, adminNavigateTo, PageActions, usePermissionOptional, usePersistedState, useScrollMemory, useLimitGuard, useRecordVisit, CrudFormSkeleton, CrudFormPage, CrudDetailSkeleton, CrudDetailPage, AskAIButton, KanbanBoard, InlineField, useUnitFilter, invalidateLimit, useOrganizationStore, getRailPage, RightRailPage, ContactPicker, PersonLink, useAgentSurface } from '@fayz-ai/admin';
12
14
  import { createPortal } from 'react-dom';
13
15
  import { HelpdeskStatusPanel } from '@fayz-ai/plugin-support';
14
16
 
@@ -476,9 +478,6 @@ function CrmOnboarding({ onComplete }) {
476
478
  function DashboardView() {
477
479
  return /* @__PURE__ */ jsx(DashboardCanvas, { surface: "plugin-home", domain: "crm", showHeader: false, className: "space-y-6" });
478
480
  }
479
- function useCanArchive() {
480
- return useAccessOptional().can("sales", "delete").allowed;
481
- }
482
481
 
483
482
  // src/lib/lost-reasons.ts
484
483
  var LOST_REASONS = ["noInterest", "price", "noBudget", "competitor", "ghosted", "badFit"];
@@ -2715,173 +2714,6 @@ function DealFunnelView({ onStageClick }) {
2715
2714
  }) })
2716
2715
  ] }) }) });
2717
2716
  }
2718
- var STATUS_CONFIG = {
2719
- draft: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: CircleDashed, label: "Draft" },
2720
- sent: { bg: "bg-info-soft text-info-soft-foreground", dot: "bg-info", icon: Send, label: "Sent" },
2721
- approved: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: CircleCheckBig, label: "Approved" },
2722
- rejected: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Ban, label: "Rejected" },
2723
- expired: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: CircleAlert, label: "Expired" },
2724
- archived: { bg: "bg-muted text-muted-foreground", dot: "bg-muted-foreground", icon: Archive, label: "Archived" },
2725
- invoiced: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: "Invoiced" },
2726
- paid: { bg: "bg-success-soft text-success-soft-foreground", dot: "bg-success", icon: Receipt, label: "Paid" },
2727
- partial: { bg: "bg-warning-soft text-warning-soft-foreground", dot: "bg-warning", icon: Receipt, label: "Partial" },
2728
- overdue: { bg: "bg-destructive-soft text-destructive-soft-foreground", dot: "bg-destructive", icon: Receipt, label: "Overdue" }
2729
- };
2730
- var TRANSITIONS = {
2731
- draft: ["sent", "expired"],
2732
- sent: ["approved", "rejected", "expired"],
2733
- approved: [],
2734
- rejected: [],
2735
- expired: [],
2736
- archived: []
2737
- };
2738
- function RejectModal({ onConfirm, onCancel }) {
2739
- const [reason, setReason] = useState("");
2740
- return /* @__PURE__ */ jsx(Modal, { open: true, onOpenChange: (open) => {
2741
- if (!open) onCancel();
2742
- }, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-sm", children: [
2743
- /* @__PURE__ */ jsxs(ModalHeader, { children: [
2744
- /* @__PURE__ */ jsx(ModalTitle, { children: "Reject Quote" }),
2745
- /* @__PURE__ */ jsx(ModalDescription, { children: "Provide a reason for the rejection." })
2746
- ] }),
2747
- /* @__PURE__ */ jsx(ModalBody, { children: /* @__PURE__ */ jsx(
2748
- Textarea,
2749
- {
2750
- value: reason,
2751
- onChange: (e) => setReason(e.target.value),
2752
- rows: 3,
2753
- placeholder: "Reason for rejection...",
2754
- autoFocus: true,
2755
- className: "resize-none"
2756
- }
2757
- ) }),
2758
- /* @__PURE__ */ jsxs(ModalFooter, { children: [
2759
- /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onCancel, children: "Cancel" }),
2760
- /* @__PURE__ */ jsx(Button, { variant: "destructive", size: "sm", onClick: () => onConfirm(reason), disabled: !reason.trim(), children: "Reject Quote" })
2761
- ] })
2762
- ] }) });
2763
- }
2764
- function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
2765
- const sendQuote = useCrmStore((s) => s.sendQuote);
2766
- const approveQuote = useCrmStore((s) => s.approveQuote);
2767
- const rejectQuote = useCrmStore((s) => s.rejectQuote);
2768
- const expireQuote = useCrmStore((s) => s.expireQuote);
2769
- const [loading, setLoading] = useState(false);
2770
- const [showApprove, setShowApprove] = useState(false);
2771
- const [showReject, setShowReject] = useState(false);
2772
- const config = STATUS_CONFIG[quote.status] ?? STATUS_CONFIG.draft;
2773
- const StatusIcon = config.icon;
2774
- const transitions = TRANSITIONS[quote.status] ?? [];
2775
- async function handleTransition(target) {
2776
- if (loading) return;
2777
- setLoading(true);
2778
- try {
2779
- let updated;
2780
- switch (target) {
2781
- case "sent":
2782
- updated = await sendQuote(quote.id);
2783
- break;
2784
- case "approved":
2785
- setShowApprove(true);
2786
- setLoading(false);
2787
- return;
2788
- case "expired":
2789
- updated = await expireQuote(quote.id);
2790
- break;
2791
- default:
2792
- setLoading(false);
2793
- return;
2794
- }
2795
- onStatusChange?.(updated);
2796
- } catch {
2797
- } finally {
2798
- setLoading(false);
2799
- }
2800
- }
2801
- async function handleReject(reason) {
2802
- setShowReject(false);
2803
- setLoading(true);
2804
- try {
2805
- const updated = await rejectQuote(quote.id, reason);
2806
- onStatusChange?.(updated);
2807
- } catch {
2808
- } finally {
2809
- setLoading(false);
2810
- }
2811
- }
2812
- const isSmall = size === "sm";
2813
- if (transitions.length === 0) {
2814
- 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: [
2815
- !isSmall && /* @__PURE__ */ jsx(StatusIcon, { className: "h-3 w-3" }),
2816
- config.label
2817
- ] });
2818
- }
2819
- return /* @__PURE__ */ jsxs(Fragment, { children: [
2820
- /* @__PURE__ */ jsxs(Dropdown, { children: [
2821
- /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
2822
- Button,
2823
- {
2824
- variant: "bare",
2825
- size: "bare",
2826
- onClick: (e) => e.stopPropagation(),
2827
- disabled: loading,
2828
- 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`,
2829
- children: [
2830
- !isSmall && /* @__PURE__ */ jsx(StatusIcon, { className: "h-3 w-3" }),
2831
- config.label,
2832
- 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"}` })
2833
- ]
2834
- }
2835
- ) }),
2836
- /* @__PURE__ */ jsxs(DropdownContent, { align: "end", sideOffset: 4, onClick: (e) => e.stopPropagation(), children: [
2837
- /* @__PURE__ */ jsx(DropdownLabel, { children: "Change status" }),
2838
- /* @__PURE__ */ jsx(DropdownSeparator, {}),
2839
- transitions.map((target) => {
2840
- const t = STATUS_CONFIG[target];
2841
- const TargetIcon = t.icon;
2842
- return /* @__PURE__ */ jsxs(
2843
- DropdownItem,
2844
- {
2845
- onClick: () => target === "rejected" ? setShowReject(true) : handleTransition(target),
2846
- className: "gap-2.5",
2847
- children: [
2848
- /* @__PURE__ */ jsx("span", { className: `h-2 w-2 rounded-full shrink-0 ${t.dot}` }),
2849
- /* @__PURE__ */ jsx(TargetIcon, { className: "h-3.5 w-3.5 shrink-0" }),
2850
- /* @__PURE__ */ jsx("span", { children: t.label })
2851
- ]
2852
- },
2853
- target
2854
- );
2855
- })
2856
- ] })
2857
- ] }),
2858
- /* @__PURE__ */ jsx(
2859
- ConfirmDialog,
2860
- {
2861
- open: showApprove,
2862
- variant: "success",
2863
- title: "Approve this quote?",
2864
- description: "This will create an invoice and convert the lead to a client. This action cannot be undone.",
2865
- confirmLabel: "Approve",
2866
- cancelLabel: "Cancel",
2867
- loading,
2868
- onConfirm: async () => {
2869
- setLoading(true);
2870
- try {
2871
- const updated = await approveQuote(quote.id);
2872
- setShowApprove(false);
2873
- onStatusChange?.(updated);
2874
- } catch {
2875
- } finally {
2876
- setLoading(false);
2877
- }
2878
- },
2879
- onCancel: () => setShowApprove(false)
2880
- }
2881
- ),
2882
- showReject && /* @__PURE__ */ jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
2883
- ] });
2884
- }
2885
2717
 
2886
2718
  // src/lib/form-answers.tsx
2887
2719
  function humanizeKey(key) {
@@ -5624,863 +5456,6 @@ function LeadListView({ onNew, onEdit }) {
5624
5456
  )
5625
5457
  ] });
5626
5458
  }
5627
- var QUOTE_STATUSES = ["draft", "sent", "approved", "rejected", "expired", "archived"];
5628
- var STATUS_COLORS = {
5629
- draft: "bg-muted text-muted-foreground",
5630
- sent: "bg-info-soft text-info-soft-foreground",
5631
- approved: "bg-success-soft text-success-soft-foreground",
5632
- rejected: "bg-destructive-soft text-destructive-soft-foreground",
5633
- expired: "bg-warning-soft text-warning-soft-foreground",
5634
- invoiced: "bg-warning-soft text-warning-soft-foreground",
5635
- paid: "bg-success-soft text-success-soft-foreground",
5636
- partial: "bg-warning-soft text-warning-soft-foreground",
5637
- overdue: "bg-destructive-soft text-destructive-soft-foreground",
5638
- cancelled: "bg-muted text-muted-foreground"
5639
- };
5640
- function useQuoteColumns(currency, onEditQuote, onArchive) {
5641
- const t = useTranslation();
5642
- const cols = [
5643
- { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
5644
- { accessorKey: "contactName", header: t("crm.quotes.contact"), cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: getValue() || "\u2014" }) },
5645
- { accessorKey: "quoteDate", header: t("crm.quotes.date"), cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
5646
- {
5647
- accessorKey: "totalAmount",
5648
- header: t("crm.quotes.amount"),
5649
- cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency(getValue(), currency) })
5650
- },
5651
- {
5652
- accessorKey: "status",
5653
- header: t("crm.quotes.status"),
5654
- cell: ({ getValue }) => {
5655
- const status = getValue();
5656
- 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}`) });
5657
- }
5658
- }
5659
- ];
5660
- if (onEditQuote || onArchive) {
5661
- cols.push({
5662
- id: "actions",
5663
- header: "",
5664
- cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
5665
- onEditQuote && /* @__PURE__ */ jsx(
5666
- Button,
5667
- {
5668
- variant: "ghost",
5669
- size: "icon",
5670
- onClick: (e) => {
5671
- e.stopPropagation();
5672
- onEditQuote(row.original.id);
5673
- },
5674
- className: "h-7 w-7 rounded-md text-muted-foreground",
5675
- title: "Edit quote",
5676
- children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
5677
- }
5678
- ),
5679
- onArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
5680
- /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
5681
- Button,
5682
- {
5683
- variant: "ghost",
5684
- size: "icon",
5685
- onClick: (e) => e.stopPropagation(),
5686
- "aria-label": t("crm.quotes.moreActions"),
5687
- className: "h-7 w-7 rounded-md text-muted-foreground",
5688
- children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3.5 w-3.5" })
5689
- }
5690
- ) }),
5691
- /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onArchive(row.original.id), children: [
5692
- /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
5693
- " ",
5694
- t("crm.quotes.archive")
5695
- ] }) })
5696
- ] })
5697
- ] })
5698
- });
5699
- }
5700
- return cols;
5701
- }
5702
- function QuoteListView({ onNew, onEdit, onEditQuote }) {
5703
- const t = useTranslation();
5704
- const { currency } = useCrmConfig();
5705
- const quotes = useCrmStore((s) => s.quotes);
5706
- const quotesLoading = useCrmStore((s) => s.quotesLoading);
5707
- const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
5708
- const archiveQuote = useCrmStore((s) => s.archiveQuote);
5709
- const canArchive = useCanArchive();
5710
- const hoje = useMemo(() => {
5711
- const d = /* @__PURE__ */ new Date();
5712
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
5713
- }, []);
5714
- const noventaDiasAtras = useMemo(() => {
5715
- const d = /* @__PURE__ */ new Date();
5716
- d.setDate(d.getDate() - 89);
5717
- return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
5718
- }, []);
5719
- const filtros = useFilterDraft(
5720
- { from: noventaDiasAtras, to: hoje, status: [], contactId: "", contactName: "", search: "" },
5721
- { persistKey: "crm.quotes" }
5722
- );
5723
- const { draft, applied, patch } = filtros;
5724
- const contactLookup = useMemo(
5725
- () => createArchetypeLookup({ archetype: "person", kind: ["customer", "lead"] }),
5726
- []
5727
- );
5728
- const limparFiltros = () => patch({ status: [], contactId: "", contactName: "", search: "" });
5729
- const filtrosAtivos = (draft.status.length > 0 ? 1 : 0) + (draft.contactId ? 1 : 0) + (draft.search.trim() ? 1 : 0);
5730
- useEffect(() => {
5731
- const search = applied.search.trim();
5732
- fetchQuotes({
5733
- dateRange: { from: applied.from, to: applied.to },
5734
- status: applied.status.length > 0 ? applied.status : void 0,
5735
- contactId: applied.contactId || void 0,
5736
- search: search || void 0
5737
- });
5738
- }, [applied]);
5739
- const [alvoArquivo, setAlvoArquivo] = useState(null);
5740
- const columns = useQuoteColumns(currency, onEditQuote, canArchive ? setAlvoArquivo : void 0);
5741
- const exportRows = useCallback(() => {
5742
- exportCSV(
5743
- [
5744
- { key: "quoteNumber", label: "#" },
5745
- { key: "quoteDate", label: t("crm.quotes.date") },
5746
- { key: "contactName", label: t("crm.quotes.contact") },
5747
- { key: "totalAmount", label: t("crm.quotes.amount"), format: (v) => formatCurrency(Number(v) || 0, currency) },
5748
- { key: "status", label: t("crm.quotes.status") },
5749
- { key: "validUntil", label: t("crm.quoteForm.validUntil") }
5750
- ],
5751
- quotes,
5752
- "orcamentos"
5753
- );
5754
- toast.success(t("crud.export.toastSuccess", { count: String(quotes.length) }));
5755
- }, [quotes, currency, t]);
5756
- const ancoraRolagem = useScrollMemory("crm.quotes");
5757
- return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
5758
- /* @__PURE__ */ jsx(
5759
- SubpageHeader,
5760
- {
5761
- title: t("crm.quotes.title"),
5762
- actions: /* @__PURE__ */ jsx(Fragment, { children: (onNew || quotes.length > 0) && /* @__PURE__ */ jsx(
5763
- PageActions,
5764
- {
5765
- actions: [
5766
- ...onNew ? [{ id: "new-quote", label: t("crm.quotes.newQuote"), icon: Plus, intent: "primary", onSelect: onNew }] : [],
5767
- // 'utility': ícone só, ao lado do primário — o mesmo lugar que o
5768
- // exportar ocupa em toda lista de CRUD.
5769
- ...quotes.length > 0 ? [{ id: "export", label: t("crud.export.action"), icon: Download, intent: "utility", desktopOnly: true, onSelect: exportRows }] : []
5770
- ]
5771
- }
5772
- ) })
5773
- }
5774
- ),
5775
- /* @__PURE__ */ jsxs(
5776
- FilterPanel,
5777
- {
5778
- title: t("crm.quotes.filtersTitle"),
5779
- onApply: filtros.apply,
5780
- applyLabel: t("crm.quotes.filterApply"),
5781
- onClear: filtrosAtivos > 0 ? limparFiltros : void 0,
5782
- clearLabel: t("crm.quotes.filterClear"),
5783
- busy: quotesLoading,
5784
- children: [
5785
- /* @__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 }) }) }),
5786
- /* @__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 }) }) }),
5787
- /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.status"), children: /* @__PURE__ */ jsx(
5788
- RequiredFilter,
5789
- {
5790
- label: t("crm.quotes.status"),
5791
- 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 }),
5792
- icon: CircleDashed,
5793
- className: "h-9 w-full justify-start",
5794
- align: "start",
5795
- children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
5796
- /* @__PURE__ */ jsx(FilterMenuRow, { active: draft.status.length === 0, onClick: () => patch({ status: [] }), children: t("crm.quotes.filterAllStatuses") }),
5797
- QUOTE_STATUSES.map((st) => {
5798
- const on = draft.status.includes(st);
5799
- return /* @__PURE__ */ jsx(
5800
- FilterMenuRow,
5801
- {
5802
- active: on,
5803
- onClick: () => patch({ status: on ? draft.status.filter((v) => v !== st) : [...draft.status, st] }),
5804
- children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t(`crm.quotes.status.${st}`) })
5805
- },
5806
- st
5807
- );
5808
- })
5809
- ] })
5810
- }
5811
- ) }),
5812
- /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.contact"), compact: true, children: /* @__PURE__ */ jsx(
5813
- SearchSelect,
5814
- {
5815
- className: "w-full",
5816
- value: draft.contactId,
5817
- displayValue: draft.contactName,
5818
- placeholder: t("crm.quotes.filterContactPlaceholder"),
5819
- minChars: 2,
5820
- minCharsLabel: t("crm.quotes.filterMinChars"),
5821
- noResultsLabel: t("crm.quotes.filterNoContact"),
5822
- searchingLabel: t("crm.quotes.filterSearching"),
5823
- loadOnOpen: false,
5824
- clearLabel: t("crm.quotes.filterAllContacts"),
5825
- onChange: (id, option) => patch({ contactId: id, contactName: option?.label ?? "" }),
5826
- onSearch: async (termo) => {
5827
- const results = await contactLookup.search(termo);
5828
- return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
5829
- }
5830
- }
5831
- ) })
5832
- ]
5833
- }
5834
- ),
5835
- /* @__PURE__ */ jsxs(Card, { className: "relative px-3 py-1.5", children: [
5836
- /* @__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" }),
5837
- /* @__PURE__ */ jsx(
5838
- Input,
5839
- {
5840
- type: "text",
5841
- value: draft.search,
5842
- onChange: (e) => patch({ search: e.target.value }),
5843
- onKeyDown: (e) => {
5844
- if (e.key === "Enter") filtros.apply();
5845
- },
5846
- placeholder: t("crm.quotes.searchPlaceholder"),
5847
- "aria-label": t("crm.quotes.searchPlaceholder"),
5848
- 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"
5849
- }
5850
- )
5851
- ] }),
5852
- /* @__PURE__ */ jsx(
5853
- DataTable,
5854
- {
5855
- columns,
5856
- data: quotesLoading ? [] : quotes,
5857
- loading: quotesLoading,
5858
- onRowClick: (row) => onEdit?.(row.id),
5859
- emptyMessage: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 py-6", children: [
5860
- /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
5861
- /* @__PURE__ */ jsx("p", { className: "text-base font-semibold text-foreground", children: t("crm.quotes.noQuotes") }),
5862
- onNew && /* @__PURE__ */ jsx(Button, { size: "lg", onClick: onNew, className: "mt-3 px-3 font-medium", children: t("crm.quotes.createFirst") })
5863
- ] })
5864
- }
5865
- ),
5866
- /* @__PURE__ */ jsx(
5867
- ConfirmDialog,
5868
- {
5869
- open: alvoArquivo !== null,
5870
- onCancel: () => setAlvoArquivo(null),
5871
- variant: "destructive",
5872
- title: t("crm.quotes.archiveTitle"),
5873
- description: t("crm.quotes.archiveDescription"),
5874
- confirmLabel: t("crm.quotes.archive"),
5875
- onConfirm: async () => {
5876
- if (alvoArquivo) await archiveQuote(alvoArquivo);
5877
- setAlvoArquivo(null);
5878
- }
5879
- }
5880
- )
5881
- ] });
5882
- }
5883
- var STATUSES = [
5884
- { value: "draft", labelKey: "crm.quoteForm.statusDraft", color: "bg-primary text-primary-foreground" },
5885
- { value: "sent", labelKey: "crm.quoteForm.statusSent", color: "bg-info-soft text-info-soft-foreground border border-info/30 dark:border-info/30" },
5886
- { value: "approved", labelKey: "crm.quoteForm.statusApproved", color: "bg-success-soft text-success-soft-foreground border border-success/30 dark:border-success/30" },
5887
- { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
5888
- { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
5889
- ];
5890
- var VALIDITY_PRESETS = [
5891
- { days: 7, labelKey: "crm.quoteForm.validOneWeek" },
5892
- { days: 30, labelKey: "crm.quoteForm.validThirtyDays" }
5893
- ];
5894
- function addDays(iso, days) {
5895
- const d = /* @__PURE__ */ new Date(`${iso}T12:00:00`);
5896
- d.setDate(d.getDate() + days);
5897
- return d.toISOString().slice(0, 10);
5898
- }
5899
- function daysBetween(from, to) {
5900
- const ms = (/* @__PURE__ */ new Date(`${to}T12:00:00`)).getTime() - (/* @__PURE__ */ new Date(`${from}T12:00:00`)).getTime();
5901
- return Math.round(ms / 864e5);
5902
- }
5903
- var fid = 1;
5904
- function nextId() {
5905
- return `qi${fid++}`;
5906
- }
5907
- function QuoteFormView({ quoteId, leadId, onSaved }) {
5908
- const t = useTranslation();
5909
- const config = useCrmConfig();
5910
- const provider = useCrmProvider();
5911
- const { currency, itemTypes: declaredItemTypes } = config;
5912
- const translatedItemTypes = React__default.useMemo(
5913
- () => declaredItemTypes.map((tp) => {
5914
- const traduzido = t(`crm.itemType.${tp.value}`);
5915
- return traduzido === `crm.itemType.${tp.value}` ? tp : { ...tp, label: traduzido };
5916
- }),
5917
- [declaredItemTypes, t]
5918
- );
5919
- const itemTypes = useCatalogedItemTypes(translatedItemTypes, config.entityLookups);
5920
- const createQuote = useCrmStore((s) => s.createQuote);
5921
- const updateQuote = useCrmStore((s) => s.updateQuote);
5922
- const guardQuotes = useLimitGuard("quotes");
5923
- const isEdit = !!quoteId;
5924
- const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId);
5925
- const [linkedLeadId, setLinkedLeadId] = useState(leadId ?? "");
5926
- const [linkedDealId, setLinkedDealId] = useState("");
5927
- const [contactName, setContactName] = useState("");
5928
- const [contactId, setContactId] = useState("");
5929
- const [quoteDate, setQuoteDate] = useState((/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
5930
- const [validUntil, setValidUntil] = useState(() => {
5931
- const d = /* @__PURE__ */ new Date();
5932
- d.setDate(d.getDate() + 30);
5933
- return d.toISOString().slice(0, 10);
5934
- });
5935
- const [validityDays, setValidityDays] = useState(30);
5936
- const [currentStatus, setCurrentStatus] = useState("draft");
5937
- const [paymentConditions, setPaymentConditions] = useState("");
5938
- const [observations, setObservations] = useState("");
5939
- const [items, setItems] = useState([]);
5940
- const [expandedItemId, setExpandedItemId] = useState(null);
5941
- const [addingItem, setAddingItem] = useState(false);
5942
- const [saving, setSaving] = useState(false);
5943
- useEffect(() => {
5944
- if (!quoteId) return;
5945
- provider.getQuoteById(quoteId).then((q) => {
5946
- if (q) {
5947
- setContactName(q.contactName ?? "");
5948
- setContactId(q.contactId ?? "");
5949
- setLinkedLeadId(q.leadId ?? "");
5950
- setLinkedDealId(q.dealId ?? "");
5951
- setQuoteDate(q.quoteDate);
5952
- setValidUntil(q.validUntil);
5953
- const span = daysBetween(q.quoteDate, q.validUntil);
5954
- setValidityDays(VALIDITY_PRESETS.some((pr) => pr.days === span) ? span : null);
5955
- setCurrentStatus(q.status);
5956
- setPaymentConditions(q.paymentConditions ?? "");
5957
- setObservations(q.observations ?? "");
5958
- setItems(q.items.map((it) => ({
5959
- _id: nextId(),
5960
- itemKind: it.itemKind,
5961
- description: it.description,
5962
- quantity: it.quantity,
5963
- unitPrice: it.unitPrice,
5964
- discount: it.discount
5965
- })));
5966
- }
5967
- setLoadingExisting(false);
5968
- });
5969
- }, [quoteId]);
5970
- useEffect(() => {
5971
- if (!leadId || quoteId) return;
5972
- provider.getLeadById(leadId).then(async (lead) => {
5973
- if (lead) {
5974
- setContactName(lead.name);
5975
- setContactId(lead.id);
5976
- setLinkedLeadId(lead.id);
5977
- const deal = await provider.getDealByLeadId(lead.id);
5978
- if (deal) setLinkedDealId(deal.id);
5979
- }
5980
- setLoadingExisting(false);
5981
- });
5982
- }, [leadId]);
5983
- function changeQuoteDate(iso) {
5984
- setQuoteDate(iso);
5985
- if (validityDays !== null) setValidUntil(addDays(iso, validityDays));
5986
- }
5987
- const openCustomOnMount = React__default.useRef(false);
5988
- function pickValidity(days) {
5989
- openCustomOnMount.current = days === null && validityDays !== null;
5990
- setValidityDays(days);
5991
- if (days !== null) setValidUntil(addDays(quoteDate, days));
5992
- }
5993
- const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0);
5994
- function startAddItem() {
5995
- if (itemTypes.length === 1) {
5996
- addItemOfKind(itemTypes[0].value);
5997
- return;
5998
- }
5999
- setAddingItem(true);
6000
- }
6001
- function addItemOfKind(kind) {
6002
- const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
6003
- setItems([...items, newItem]);
6004
- setExpandedItemId(newItem._id);
6005
- setAddingItem(false);
6006
- }
6007
- function updateItem(id, data) {
6008
- setItems(items.map((it) => it._id === id ? { ...it, ...data } : it));
6009
- }
6010
- function removeItem(id) {
6011
- setItems(items.filter((it) => it._id !== id));
6012
- if (expandedItemId === id) setExpandedItemId(null);
6013
- }
6014
- async function handleSave() {
6015
- if (items.length === 0) {
6016
- toast.error(t("crm.quoteForm.errNoItems"));
6017
- return;
6018
- }
6019
- if (!isEdit && await guardQuotes() === "blocked") return;
6020
- setSaving(true);
6021
- try {
6022
- const input = {
6023
- contactId: contactId || void 0,
6024
- contactName: contactName || void 0,
6025
- leadId: linkedLeadId || void 0,
6026
- dealId: linkedDealId || void 0,
6027
- quoteDate,
6028
- validUntil,
6029
- paymentConditions: paymentConditions || void 0,
6030
- observations: observations || void 0,
6031
- items: items.map((it) => ({
6032
- itemKind: it.itemKind,
6033
- description: it.description,
6034
- quantity: it.quantity,
6035
- unitPrice: it.unitPrice,
6036
- discount: it.discount,
6037
- totalAmount: it.quantity * it.unitPrice - it.discount
6038
- }))
6039
- };
6040
- if (isEdit) {
6041
- await updateQuote(quoteId, input);
6042
- onSaved?.(quoteId);
6043
- } else {
6044
- const created = await createQuote(input);
6045
- invalidateLimit("quotes");
6046
- onSaved?.(created?.id);
6047
- }
6048
- } finally {
6049
- setSaving(false);
6050
- }
6051
- }
6052
- const currentFields = {
6053
- contactId,
6054
- contactName,
6055
- linkedLeadId,
6056
- linkedDealId,
6057
- quoteDate,
6058
- validUntil,
6059
- currentStatus,
6060
- paymentConditions,
6061
- observations,
6062
- items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
6063
- };
6064
- const snapshot = React__default.useRef(null);
6065
- useEffect(() => {
6066
- if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
6067
- }, [loadingExisting]);
6068
- const dirty = snapshot.current !== null && JSON.stringify(currentFields) !== snapshot.current;
6069
- useSaveBar({
6070
- dirty,
6071
- saving,
6072
- onSave: () => {
6073
- void handleSave();
6074
- },
6075
- onDiscard: () => onSaved?.(),
6076
- saveLabel: isEdit ? t("crm.quoteForm.saveChanges") : t("crm.quoteForm.saveQuote")
6077
- });
6078
- if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t("crm.quotes.title"), onBack: () => onSaved?.() });
6079
- const money = (v) => formatCurrency(v, currency);
6080
- const validUntilLabel = (/* @__PURE__ */ new Date(`${validUntil}T12:00:00`)).toLocaleDateString(getCurrentLocale());
6081
- const contactSection = /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
6082
- SearchSelect,
6083
- {
6084
- value: contactId,
6085
- displayValue: contactName,
6086
- onChange: (id, opt) => {
6087
- setContactId(id);
6088
- setContactName(opt?.label ?? "");
6089
- },
6090
- onSearch: async (q) => {
6091
- if (!config.contactLookup) return [];
6092
- const results = await config.contactLookup.search(q);
6093
- return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
6094
- },
6095
- required: true,
6096
- placeholder: t("crm.quoteForm.searchClient"),
6097
- allowCreate: true,
6098
- createLabel: t("crm.quoteForm.addAsLead"),
6099
- onCreate: async (name) => {
6100
- const lead = await provider.createLead({ name });
6101
- setContactId(lead.id);
6102
- setContactName(lead.name);
6103
- }
6104
- }
6105
- ) });
6106
- const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6107
- /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.quoteDetails"), children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
6108
- /* @__PURE__ */ jsxs("div", { children: [
6109
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.quoteDate") }),
6110
- /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: changeQuoteDate, className: "mt-1" })
6111
- ] }),
6112
- /* @__PURE__ */ jsxs("div", { children: [
6113
- /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
6114
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.validUntil") }),
6115
- validityDays === null ? /* @__PURE__ */ jsx(
6116
- DatePicker,
6117
- {
6118
- variant: "inline",
6119
- format: "numeric",
6120
- value: validUntil,
6121
- onChange: setValidUntil,
6122
- defaultOpen: openCustomOnMount.current
6123
- }
6124
- ) : /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-foreground", children: validUntilLabel })
6125
- ] }),
6126
- /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap gap-1.5", children: [
6127
- VALIDITY_PRESETS.map((preset) => /* @__PURE__ */ jsx(
6128
- Button,
6129
- {
6130
- type: "button",
6131
- variant: "bare",
6132
- size: "bare",
6133
- onClick: () => pickValidity(preset.days),
6134
- 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"}`,
6135
- children: t(preset.labelKey)
6136
- },
6137
- preset.days
6138
- )),
6139
- /* @__PURE__ */ jsx(
6140
- Button,
6141
- {
6142
- type: "button",
6143
- variant: "bare",
6144
- size: "bare",
6145
- onClick: () => pickValidity(null),
6146
- 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"}`,
6147
- children: t("crm.quoteForm.validCustom")
6148
- }
6149
- )
6150
- ] })
6151
- ] })
6152
- ] }) }),
6153
- /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.paymentConditions"), children: /* @__PURE__ */ jsx(
6154
- Textarea,
6155
- {
6156
- value: paymentConditions,
6157
- onChange: (e) => setPaymentConditions(e.target.value),
6158
- rows: 2,
6159
- placeholder: t("crm.quoteForm.paymentConditionsPlaceholder"),
6160
- className: "min-h-0 resize-none"
6161
- }
6162
- ) }),
6163
- /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.notes"), children: /* @__PURE__ */ jsx(
6164
- Textarea,
6165
- {
6166
- value: observations,
6167
- onChange: (e) => setObservations(e.target.value),
6168
- rows: 2,
6169
- placeholder: t("crm.quoteForm.notesPlaceholder"),
6170
- className: "min-h-0 resize-none"
6171
- }
6172
- ) })
6173
- ] });
6174
- return /* @__PURE__ */ jsxs(
6175
- OrderFormView,
6176
- {
6177
- sideSections,
6178
- title: isEdit ? t("crm.quoteForm.editTitle") : t("crm.quoteForm.newTitle"),
6179
- parentLabel: t("crm.quotes.title"),
6180
- onBack: () => onSaved?.(),
6181
- badges: /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: STATUSES.map((s) => /* @__PURE__ */ jsx(
6182
- "span",
6183
- {
6184
- 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"}`,
6185
- children: t(s.labelKey)
6186
- },
6187
- s.value
6188
- )) }),
6189
- children: [
6190
- contactSection,
6191
- /* @__PURE__ */ jsx(
6192
- OrderFormItemsCard,
6193
- {
6194
- label: t("crm.quoteForm.quoteItems"),
6195
- addLabel: t("crm.quoteForm.addItem"),
6196
- onAdd: startAddItem,
6197
- addDisabled: !contactId,
6198
- addDisabledHint: t("crm.quoteForm.selectClientFirst"),
6199
- count: items.length,
6200
- countLabel: t("crm.quoteForm.itemCount", { count: String(items.length) }),
6201
- totalLabel: t("crm.quoteForm.total"),
6202
- total: money(totalAmount),
6203
- emptyLabel: contactId ? t("crm.quoteForm.noItems") : t("crm.quoteForm.selectClientFirst"),
6204
- emptyActionLabel: t("crm.quoteForm.addFirstItem"),
6205
- header: addingItem && /* @__PURE__ */ jsx(
6206
- OrderFormAddItemStep,
6207
- {
6208
- itemTypes,
6209
- onSelect: addItemOfKind,
6210
- onCancel: () => setAddingItem(false),
6211
- label: t("crm.quoteForm.selectItemType"),
6212
- cancelLabel: t("crm.quoteForm.cancel")
6213
- }
6214
- ),
6215
- children: items.map((item, i) => /* @__PURE__ */ jsx(
6216
- OrderFormItemRow,
6217
- {
6218
- index: i,
6219
- itemKind: item.itemKind,
6220
- description: item.description,
6221
- quantity: item.quantity,
6222
- unitPrice: item.unitPrice,
6223
- discount: item.discount,
6224
- itemTypes,
6225
- currency,
6226
- formatMoney: money,
6227
- expanded: expandedItemId === item._id,
6228
- onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
6229
- onChange: (patch) => updateItem(item._id, patch),
6230
- onRemove: () => removeItem(item._id),
6231
- entityLookups: config.entityLookups,
6232
- labels: {
6233
- item: t("crm.quoteForm.description"),
6234
- description: t("crm.quoteForm.description"),
6235
- descriptionPlaceholder: t("crm.quoteForm.itemDescriptionPlaceholder"),
6236
- noDescription: t("crm.quoteForm.noDescription"),
6237
- qty: t("crm.quoteForm.qty"),
6238
- unitPrice: t("crm.quoteForm.unitPrice"),
6239
- discount: t("crm.quoteForm.discount"),
6240
- done: t("crm.quoteForm.done")
6241
- }
6242
- },
6243
- item._id
6244
- ))
6245
- }
6246
- )
6247
- ]
6248
- }
6249
- );
6250
- }
6251
- var SEND_ITEM = "gap-2 px-3 py-2 text-xs";
6252
- function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
6253
- const t = useTranslation();
6254
- const { currency } = useCrmConfig();
6255
- const provider = useCrmProvider();
6256
- const sendQuote = useCrmStore((s) => s.sendQuote);
6257
- const approveQuote = useCrmStore((s) => s.approveQuote);
6258
- const rejectQuote = useCrmStore((s) => s.rejectQuote);
6259
- const [quote, setQuote] = useState(null);
6260
- const [loading, setLoading] = useState(true);
6261
- const [sending, setSending] = useState(false);
6262
- const [approving, setApproving] = useState(false);
6263
- const [rejectOpen, setRejectOpen] = useState(false);
6264
- const [rejectReason, setRejectReason] = useState("");
6265
- const [rejecting, setRejecting] = useState(false);
6266
- useEffect(() => {
6267
- setLoading(true);
6268
- provider.getQuoteById(quoteId).then((q) => {
6269
- setQuote(q);
6270
- setLoading(false);
6271
- });
6272
- }, [quoteId]);
6273
- async function handleSend(_channel) {
6274
- setSending(true);
6275
- try {
6276
- const updated = await sendQuote(quoteId);
6277
- setQuote(updated);
6278
- } finally {
6279
- setSending(false);
6280
- }
6281
- }
6282
- async function handleApprove() {
6283
- setApproving(true);
6284
- try {
6285
- const updated = await approveQuote(quoteId);
6286
- setQuote(updated);
6287
- if (onInvoiceCreated) onInvoiceCreated(quoteId);
6288
- } finally {
6289
- setApproving(false);
6290
- }
6291
- }
6292
- async function handleReject() {
6293
- if (!rejectReason.trim()) return;
6294
- setRejecting(true);
6295
- try {
6296
- const updated = await rejectQuote(quoteId, rejectReason.trim());
6297
- setQuote(updated);
6298
- setRejectOpen(false);
6299
- setRejectReason("");
6300
- } finally {
6301
- setRejecting(false);
6302
- }
6303
- }
6304
- if (loading) return /* @__PURE__ */ jsx(OrderDetailSkeleton, { parentLabel: t("crm.quotes.title"), onBack });
6305
- if (!quote) {
6306
- return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
6307
- /* @__PURE__ */ jsx(SubpageHeader, { title: t("crm.quoteDetail.title"), onBack, parentLabel: t("crm.quotes.title") }),
6308
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted py-12 text-center", children: [
6309
- /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-8 w-8 text-muted-foreground/30" }),
6310
- /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("crm.quoteDetail.notFound") }),
6311
- /* @__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") })
6312
- ] })
6313
- ] });
6314
- }
6315
- const subtotal = quote.items.reduce((sum, it) => sum + it.quantity * it.unitPrice, 0);
6316
- const totalDiscount = quote.items.reduce((sum, it) => sum + it.discount, 0);
6317
- const detailItems = quote.items.map((it, i) => ({
6318
- id: it.id ?? String(i),
6319
- name: it.description || "\u2014",
6320
- description: it.itemKind,
6321
- quantity: it.quantity,
6322
- unitPrice: formatCurrency(it.unitPrice, currency),
6323
- total: formatCurrency(it.totalAmount, currency)
6324
- }));
6325
- const totals = [
6326
- ...totalDiscount > 0 ? [
6327
- { label: t("crm.quoteDetail.subtotal"), value: formatCurrency(subtotal, currency), muted: true },
6328
- { label: t("crm.quoteDetail.discount"), value: `-${formatCurrency(totalDiscount, currency)}`, muted: true }
6329
- ] : [],
6330
- { label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), strong: true }
6331
- ];
6332
- const editable = quote.status !== "approved" && quote.status !== "rejected" && quote.status !== "expired";
6333
- const actions = /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
6334
- quote.status === "draft" && /* @__PURE__ */ jsxs(Dropdown, { children: [
6335
- /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(Button, { type: "button", size: "sm", disabled: sending, className: "h-auto px-3 py-1.5 font-medium", children: [
6336
- /* @__PURE__ */ jsx(Send, { className: "h-3 w-3" }),
6337
- sending ? t("crm.quoteDetail.sending") : t("crm.quoteDetail.send"),
6338
- /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 opacity-60" })
6339
- ] }) }),
6340
- /* @__PURE__ */ jsxs(DropdownContent, { align: "end", className: "w-48", children: [
6341
- /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6342
- /* @__PURE__ */ jsx(Printer, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6343
- " ",
6344
- t("crm.quoteDetail.sendPrint")
6345
- ] }),
6346
- /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6347
- /* @__PURE__ */ jsx(Mail, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6348
- " ",
6349
- t("crm.quoteDetail.sendEmail")
6350
- ] }),
6351
- /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6352
- /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6353
- " ",
6354
- t("crm.quoteDetail.sendWhatsApp")
6355
- ] })
6356
- ] })
6357
- ] }),
6358
- quote.status === "sent" && /* @__PURE__ */ jsxs(Fragment, { children: [
6359
- /* @__PURE__ */ jsxs(
6360
- Button,
6361
- {
6362
- type: "button",
6363
- variant: "default",
6364
- size: "sm",
6365
- onClick: handleApprove,
6366
- disabled: approving,
6367
- className: "border-success bg-success text-success-foreground hover:bg-success/90",
6368
- children: [
6369
- /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }),
6370
- approving ? t("crm.quoteDetail.approving") : t("crm.quoteDetail.approve")
6371
- ]
6372
- }
6373
- ),
6374
- /* @__PURE__ */ jsxs(
6375
- Button,
6376
- {
6377
- type: "button",
6378
- variant: "outline",
6379
- size: "sm",
6380
- onClick: () => setRejectOpen(true),
6381
- className: "border-destructive/30 text-destructive hover:bg-destructive/10",
6382
- children: [
6383
- /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" }),
6384
- t("crm.quoteDetail.reject")
6385
- ]
6386
- }
6387
- )
6388
- ] }),
6389
- onEdit && editable && /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: onEdit, children: [
6390
- /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" }),
6391
- " ",
6392
- t("crm.quoteDetail.edit")
6393
- ] })
6394
- ] });
6395
- const sideBlocks = /* @__PURE__ */ jsxs(Fragment, { children: [
6396
- 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 }) }),
6397
- 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 }) })
6398
- ] });
6399
- const invoiced = ["approved", "invoiced", "paid", "partial", "overdue"].includes(quote.status);
6400
- const banners = /* @__PURE__ */ jsxs(Fragment, { children: [
6401
- 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: [
6402
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
6403
- /* @__PURE__ */ jsx(CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
6404
- /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("crm.quoteDetail.invoiceCreated") })
6405
- ] }),
6406
- /* @__PURE__ */ jsxs("a", { href: appHref("/financial/receivables/list"), className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline", children: [
6407
- t("crm.quoteDetail.viewInvoice"),
6408
- " ",
6409
- /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
6410
- ] })
6411
- ] }),
6412
- 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: [
6413
- /* @__PURE__ */ jsx(Ban, { className: "h-3.5 w-3.5 text-destructive" }),
6414
- /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
6415
- t("crm.quoteDetail.rejectionReason"),
6416
- ": ",
6417
- /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: quote.rejectionReason })
6418
- ] })
6419
- ] }) })
6420
- ] });
6421
- return /* @__PURE__ */ jsxs(Fragment, { children: [
6422
- /* @__PURE__ */ jsx(
6423
- OrderDetailView,
6424
- {
6425
- title: `#${quote.quoteNumber}`,
6426
- badgesNode: /* @__PURE__ */ jsx(QuoteStatusDropdown, { quote, onStatusChange: (q) => setQuote(q) }),
6427
- subtitle: null,
6428
- onBack,
6429
- backLabel: t("crm.quotes.title"),
6430
- actions,
6431
- stats: [
6432
- { id: "total", label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), icon: Receipt },
6433
- { id: "items", label: t("crm.quoteDetail.items"), value: quote.items.length, icon: Package },
6434
- { id: "date", label: t("crm.quoteDetail.date"), value: quote.quoteDate, icon: Calendar },
6435
- { id: "valid", label: t("crm.quoteDetail.validUntil"), value: quote.validUntil, icon: CalendarClock }
6436
- ],
6437
- errorBanner: banners,
6438
- customer: { name: quote.contactName, email: null },
6439
- customerNode: quote.contactName ? /* @__PURE__ */ jsx(PersonLink, { personId: quote.contactId ?? quote.leadId, name: quote.contactName, size: "sm" }) : /* @__PURE__ */ jsx("span", { className: "text-sm text-muted-foreground", children: "\u2014" }),
6440
- items: detailItems,
6441
- itemsLabel: t("crm.quoteDetail.items"),
6442
- totals,
6443
- totalsLabel: t("crm.quoteDetail.summary"),
6444
- extraSections: sideBlocks
6445
- }
6446
- ),
6447
- /* @__PURE__ */ jsx(Modal, { open: rejectOpen, onOpenChange: setRejectOpen, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-sm", children: [
6448
- /* @__PURE__ */ jsxs(ModalBody, { children: [
6449
- /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center gap-3", children: [
6450
- /* @__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" }) }),
6451
- /* @__PURE__ */ jsxs("div", { children: [
6452
- /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("crm.quoteDetail.reject") }),
6453
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("crm.quoteDetail.rejectDescription") })
6454
- ] })
6455
- ] }),
6456
- /* @__PURE__ */ jsx(
6457
- Textarea,
6458
- {
6459
- value: rejectReason,
6460
- onChange: (e) => setRejectReason(e.target.value),
6461
- placeholder: t("crm.quoteDetail.rejectReasonPlaceholder"),
6462
- className: "h-20 resize-none",
6463
- autoFocus: true
6464
- }
6465
- )
6466
- ] }),
6467
- /* @__PURE__ */ jsxs(ModalFooter, { children: [
6468
- /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => setRejectOpen(false), children: t("common.cancel") }),
6469
- /* @__PURE__ */ jsx(
6470
- Button,
6471
- {
6472
- type: "button",
6473
- variant: "destructive",
6474
- size: "sm",
6475
- onClick: handleReject,
6476
- disabled: rejecting || !rejectReason.trim(),
6477
- children: rejecting ? t("crm.quoteDetail.rejecting") : t("crm.quoteDetail.confirmReject")
6478
- }
6479
- )
6480
- ] })
6481
- ] }) })
6482
- ] });
6483
- }
6484
5459
  function PersonPhones({ personId, onOpenPerson }) {
6485
5460
  const t = useTranslation();
6486
5461
  const provider = useCrmProvider();
@@ -10171,5 +9146,5 @@ function CrmPage({ config, provider, store, registries }) {
10171
9146
  }
10172
9147
 
10173
9148
  export { CrmPage };
10174
- //# sourceMappingURL=CrmPage-4BPA22DO.js.map
10175
- //# sourceMappingURL=CrmPage-4BPA22DO.js.map
9149
+ //# sourceMappingURL=CrmPage-JNJOATIH.js.map
9150
+ //# sourceMappingURL=CrmPage-JNJOATIH.js.map