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

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,16 +1,14 @@
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';
6
4
  import { CrmContextProvider, useCrmProvider, useCrmStore, useCrmConfig, formatCurrency } from './chunk-7V46TYYX.js';
7
5
  import * as React from 'react';
8
6
  import React__default, { useCallback, useMemo, useState, useEffect, useRef } from 'react';
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';
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';
11
9
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
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';
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, AddressesTab, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, CrudFormSkeleton, CrudFormPage, CrudDetailSkeleton, CrudDetailPage, AskAIButton, KanbanBoard, InlineField, useUnitFilter, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, RightRailPage, ContactPicker, useAgentSurface } from '@fayz-ai/admin';
14
12
  import { createPortal } from 'react-dom';
15
13
  import { HelpdeskStatusPanel } from '@fayz-ai/plugin-support';
16
14
 
@@ -478,6 +476,9 @@ function CrmOnboarding({ onComplete }) {
478
476
  function DashboardView() {
479
477
  return /* @__PURE__ */ jsx(DashboardCanvas, { surface: "plugin-home", domain: "crm", showHeader: false, className: "space-y-6" });
480
478
  }
479
+ function useCanArchive() {
480
+ return useAccessOptional().can("sales", "delete").allowed;
481
+ }
481
482
 
482
483
  // src/lib/lost-reasons.ts
483
484
  var LOST_REASONS = ["noInterest", "price", "noBudget", "competitor", "ghosted", "badFit"];
@@ -2714,6 +2715,173 @@ function DealFunnelView({ onStageClick }) {
2714
2715
  }) })
2715
2716
  ] }) }) });
2716
2717
  }
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
+ }
2717
2885
 
2718
2886
  // src/lib/form-answers.tsx
2719
2887
  function humanizeKey(key) {
@@ -2828,7 +2996,11 @@ function FormAnswers({ lead }) {
2828
2996
  entries.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
2829
2997
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: formId ? `${t("crm.leadDetail.formAnswers")} \xB7 ${formId}` : t("crm.leadDetail.formAnswers") }),
2830
2998
  /* @__PURE__ */ jsx("div", { className: "rounded-xl border divide-y", children: entries.map(([key, value]) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3 px-4 py-2.5", children: [
2831
- /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground shrink-0 min-w-24", children: humanizeKey(key) }),
2999
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground shrink-0 min-w-24", children: (() => {
3000
+ const k = `crm.formField.${key}`;
3001
+ const v = t(k);
3002
+ return v && v !== k ? v : humanizeKey(key);
3003
+ })() }),
2832
3004
  /* @__PURE__ */ jsx("span", { className: "text-xs text-right flex-1 break-words", children: renderFieldValue(value) ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
2833
3005
  ] }, key)) })
2834
3006
  ] }),
@@ -5456,6 +5628,863 @@ function LeadListView({ onNew, onEdit }) {
5456
5628
  )
5457
5629
  ] });
5458
5630
  }
5631
+ var QUOTE_STATUSES = ["draft", "sent", "approved", "rejected", "expired", "archived"];
5632
+ var STATUS_COLORS = {
5633
+ draft: "bg-muted text-muted-foreground",
5634
+ sent: "bg-info-soft text-info-soft-foreground",
5635
+ approved: "bg-success-soft text-success-soft-foreground",
5636
+ rejected: "bg-destructive-soft text-destructive-soft-foreground",
5637
+ expired: "bg-warning-soft text-warning-soft-foreground",
5638
+ invoiced: "bg-warning-soft text-warning-soft-foreground",
5639
+ paid: "bg-success-soft text-success-soft-foreground",
5640
+ partial: "bg-warning-soft text-warning-soft-foreground",
5641
+ overdue: "bg-destructive-soft text-destructive-soft-foreground",
5642
+ cancelled: "bg-muted text-muted-foreground"
5643
+ };
5644
+ function useQuoteColumns(currency, onEditQuote, onArchive) {
5645
+ const t = useTranslation();
5646
+ const cols = [
5647
+ { accessorKey: "quoteNumber", header: "#", cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
5648
+ { accessorKey: "contactName", header: t("crm.quotes.contact"), cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: getValue() || "\u2014" }) },
5649
+ { accessorKey: "quoteDate", header: t("crm.quotes.date"), cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: getValue() }) },
5650
+ {
5651
+ accessorKey: "totalAmount",
5652
+ header: t("crm.quotes.amount"),
5653
+ cell: ({ getValue }) => /* @__PURE__ */ jsx("span", { className: "font-medium", children: formatCurrency(getValue(), currency) })
5654
+ },
5655
+ {
5656
+ accessorKey: "status",
5657
+ header: t("crm.quotes.status"),
5658
+ cell: ({ getValue }) => {
5659
+ const status = getValue();
5660
+ 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}`) });
5661
+ }
5662
+ }
5663
+ ];
5664
+ if (onEditQuote || onArchive) {
5665
+ cols.push({
5666
+ id: "actions",
5667
+ header: "",
5668
+ cell: ({ row }) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-end gap-0.5", children: [
5669
+ onEditQuote && /* @__PURE__ */ jsx(
5670
+ Button,
5671
+ {
5672
+ variant: "ghost",
5673
+ size: "icon",
5674
+ onClick: (e) => {
5675
+ e.stopPropagation();
5676
+ onEditQuote(row.original.id);
5677
+ },
5678
+ className: "h-7 w-7 rounded-md text-muted-foreground",
5679
+ title: "Edit quote",
5680
+ children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
5681
+ }
5682
+ ),
5683
+ onArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
5684
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
5685
+ Button,
5686
+ {
5687
+ variant: "ghost",
5688
+ size: "icon",
5689
+ onClick: (e) => e.stopPropagation(),
5690
+ "aria-label": t("crm.quotes.moreActions"),
5691
+ className: "h-7 w-7 rounded-md text-muted-foreground",
5692
+ children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3.5 w-3.5" })
5693
+ }
5694
+ ) }),
5695
+ /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onArchive(row.original.id), children: [
5696
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
5697
+ " ",
5698
+ t("crm.quotes.archive")
5699
+ ] }) })
5700
+ ] })
5701
+ ] })
5702
+ });
5703
+ }
5704
+ return cols;
5705
+ }
5706
+ function QuoteListView({ onNew, onEdit, onEditQuote }) {
5707
+ const t = useTranslation();
5708
+ const { currency } = useCrmConfig();
5709
+ const quotes = useCrmStore((s) => s.quotes);
5710
+ const quotesLoading = useCrmStore((s) => s.quotesLoading);
5711
+ const fetchQuotes = useCrmStore((s) => s.fetchQuotes);
5712
+ const archiveQuote = useCrmStore((s) => s.archiveQuote);
5713
+ const canArchive = useCanArchive();
5714
+ const hoje = useMemo(() => {
5715
+ const d = /* @__PURE__ */ new Date();
5716
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
5717
+ }, []);
5718
+ const noventaDiasAtras = useMemo(() => {
5719
+ const d = /* @__PURE__ */ new Date();
5720
+ d.setDate(d.getDate() - 89);
5721
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
5722
+ }, []);
5723
+ const filtros = useFilterDraft(
5724
+ { from: noventaDiasAtras, to: hoje, status: [], contactId: "", contactName: "", search: "" },
5725
+ { persistKey: "crm.quotes" }
5726
+ );
5727
+ const { draft, applied, patch } = filtros;
5728
+ const contactLookup = useMemo(
5729
+ () => createArchetypeLookup({ archetype: "person", kind: ["customer", "lead"] }),
5730
+ []
5731
+ );
5732
+ const limparFiltros = () => patch({ status: [], contactId: "", contactName: "", search: "" });
5733
+ const filtrosAtivos = (draft.status.length > 0 ? 1 : 0) + (draft.contactId ? 1 : 0) + (draft.search.trim() ? 1 : 0);
5734
+ useEffect(() => {
5735
+ const search = applied.search.trim();
5736
+ fetchQuotes({
5737
+ dateRange: { from: applied.from, to: applied.to },
5738
+ status: applied.status.length > 0 ? applied.status : void 0,
5739
+ contactId: applied.contactId || void 0,
5740
+ search: search || void 0
5741
+ });
5742
+ }, [applied]);
5743
+ const [alvoArquivo, setAlvoArquivo] = useState(null);
5744
+ const columns = useQuoteColumns(currency, onEditQuote, canArchive ? setAlvoArquivo : void 0);
5745
+ const exportRows = useCallback(() => {
5746
+ exportCSV(
5747
+ [
5748
+ { key: "quoteNumber", label: "#" },
5749
+ { key: "quoteDate", label: t("crm.quotes.date") },
5750
+ { key: "contactName", label: t("crm.quotes.contact") },
5751
+ { key: "totalAmount", label: t("crm.quotes.amount"), format: (v) => formatCurrency(Number(v) || 0, currency) },
5752
+ { key: "status", label: t("crm.quotes.status") },
5753
+ { key: "validUntil", label: t("crm.quoteForm.validUntil") }
5754
+ ],
5755
+ quotes,
5756
+ "orcamentos"
5757
+ );
5758
+ toast.success(t("crud.export.toastSuccess", { count: String(quotes.length) }));
5759
+ }, [quotes, currency, t]);
5760
+ const ancoraRolagem = useScrollMemory("crm.quotes");
5761
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
5762
+ /* @__PURE__ */ jsx(
5763
+ SubpageHeader,
5764
+ {
5765
+ title: t("crm.quotes.title"),
5766
+ actions: /* @__PURE__ */ jsx(Fragment, { children: (onNew || quotes.length > 0) && /* @__PURE__ */ jsx(
5767
+ PageActions,
5768
+ {
5769
+ actions: [
5770
+ ...onNew ? [{ id: "new-quote", label: t("crm.quotes.newQuote"), icon: Plus, intent: "primary", onSelect: onNew }] : [],
5771
+ // 'utility': ícone só, ao lado do primário — o mesmo lugar que o
5772
+ // exportar ocupa em toda lista de CRUD.
5773
+ ...quotes.length > 0 ? [{ id: "export", label: t("crud.export.action"), icon: Download, intent: "utility", desktopOnly: true, onSelect: exportRows }] : []
5774
+ ]
5775
+ }
5776
+ ) })
5777
+ }
5778
+ ),
5779
+ /* @__PURE__ */ jsxs(
5780
+ FilterPanel,
5781
+ {
5782
+ title: t("crm.quotes.filtersTitle"),
5783
+ onApply: filtros.apply,
5784
+ applyLabel: t("crm.quotes.filterApply"),
5785
+ onClear: filtrosAtivos > 0 ? limparFiltros : void 0,
5786
+ clearLabel: t("crm.quotes.filterClear"),
5787
+ busy: quotesLoading,
5788
+ children: [
5789
+ /* @__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 }) }) }),
5790
+ /* @__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 }) }) }),
5791
+ /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.status"), children: /* @__PURE__ */ jsx(
5792
+ RequiredFilter,
5793
+ {
5794
+ label: t("crm.quotes.status"),
5795
+ 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 }),
5796
+ icon: CircleDashed,
5797
+ className: "h-9 w-full justify-start",
5798
+ align: "start",
5799
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
5800
+ /* @__PURE__ */ jsx(FilterMenuRow, { active: draft.status.length === 0, onClick: () => patch({ status: [] }), children: t("crm.quotes.filterAllStatuses") }),
5801
+ QUOTE_STATUSES.map((st) => {
5802
+ const on = draft.status.includes(st);
5803
+ return /* @__PURE__ */ jsx(
5804
+ FilterMenuRow,
5805
+ {
5806
+ active: on,
5807
+ onClick: () => patch({ status: on ? draft.status.filter((v) => v !== st) : [...draft.status, st] }),
5808
+ children: /* @__PURE__ */ jsx("span", { className: "truncate", children: t(`crm.quotes.status.${st}`) })
5809
+ },
5810
+ st
5811
+ );
5812
+ })
5813
+ ] })
5814
+ }
5815
+ ) }),
5816
+ /* @__PURE__ */ jsx(FilterPanelField, { label: t("crm.quotes.contact"), compact: true, children: /* @__PURE__ */ jsx(
5817
+ SearchSelect,
5818
+ {
5819
+ className: "w-full",
5820
+ value: draft.contactId,
5821
+ displayValue: draft.contactName,
5822
+ placeholder: t("crm.quotes.filterContactPlaceholder"),
5823
+ minChars: 2,
5824
+ minCharsLabel: t("crm.quotes.filterMinChars"),
5825
+ noResultsLabel: t("crm.quotes.filterNoContact"),
5826
+ searchingLabel: t("crm.quotes.filterSearching"),
5827
+ loadOnOpen: false,
5828
+ clearLabel: t("crm.quotes.filterAllContacts"),
5829
+ onChange: (id, option) => patch({ contactId: id, contactName: option?.label ?? "" }),
5830
+ onSearch: async (termo) => {
5831
+ const results = await contactLookup.search(termo);
5832
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
5833
+ }
5834
+ }
5835
+ ) })
5836
+ ]
5837
+ }
5838
+ ),
5839
+ /* @__PURE__ */ jsxs(Card, { className: "relative px-3 py-1.5", children: [
5840
+ /* @__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" }),
5841
+ /* @__PURE__ */ jsx(
5842
+ Input,
5843
+ {
5844
+ type: "text",
5845
+ value: draft.search,
5846
+ onChange: (e) => patch({ search: e.target.value }),
5847
+ onKeyDown: (e) => {
5848
+ if (e.key === "Enter") filtros.apply();
5849
+ },
5850
+ placeholder: t("crm.quotes.searchPlaceholder"),
5851
+ "aria-label": t("crm.quotes.searchPlaceholder"),
5852
+ 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"
5853
+ }
5854
+ )
5855
+ ] }),
5856
+ /* @__PURE__ */ jsx(
5857
+ DataTable,
5858
+ {
5859
+ columns,
5860
+ data: quotesLoading ? [] : quotes,
5861
+ loading: quotesLoading,
5862
+ onRowClick: (row) => onEdit?.(row.id),
5863
+ emptyMessage: /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 py-6", children: [
5864
+ /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
5865
+ /* @__PURE__ */ jsx("p", { className: "text-base font-semibold text-foreground", children: t("crm.quotes.noQuotes") }),
5866
+ onNew && /* @__PURE__ */ jsx(Button, { size: "lg", onClick: onNew, className: "mt-3 px-3 font-medium", children: t("crm.quotes.createFirst") })
5867
+ ] })
5868
+ }
5869
+ ),
5870
+ /* @__PURE__ */ jsx(
5871
+ ConfirmDialog,
5872
+ {
5873
+ open: alvoArquivo !== null,
5874
+ onCancel: () => setAlvoArquivo(null),
5875
+ variant: "destructive",
5876
+ title: t("crm.quotes.archiveTitle"),
5877
+ description: t("crm.quotes.archiveDescription"),
5878
+ confirmLabel: t("crm.quotes.archive"),
5879
+ onConfirm: async () => {
5880
+ if (alvoArquivo) await archiveQuote(alvoArquivo);
5881
+ setAlvoArquivo(null);
5882
+ }
5883
+ }
5884
+ )
5885
+ ] });
5886
+ }
5887
+ var STATUSES = [
5888
+ { value: "draft", labelKey: "crm.quoteForm.statusDraft", color: "bg-primary text-primary-foreground" },
5889
+ { value: "sent", labelKey: "crm.quoteForm.statusSent", color: "bg-info-soft text-info-soft-foreground border border-info/30 dark:border-info/30" },
5890
+ { value: "approved", labelKey: "crm.quoteForm.statusApproved", color: "bg-success-soft text-success-soft-foreground border border-success/30 dark:border-success/30" },
5891
+ { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
5892
+ { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
5893
+ ];
5894
+ var VALIDITY_PRESETS = [
5895
+ { days: 7, labelKey: "crm.quoteForm.validOneWeek" },
5896
+ { days: 30, labelKey: "crm.quoteForm.validThirtyDays" }
5897
+ ];
5898
+ function addDays(iso, days) {
5899
+ const d = /* @__PURE__ */ new Date(`${iso}T12:00:00`);
5900
+ d.setDate(d.getDate() + days);
5901
+ return d.toISOString().slice(0, 10);
5902
+ }
5903
+ function daysBetween(from, to) {
5904
+ const ms = (/* @__PURE__ */ new Date(`${to}T12:00:00`)).getTime() - (/* @__PURE__ */ new Date(`${from}T12:00:00`)).getTime();
5905
+ return Math.round(ms / 864e5);
5906
+ }
5907
+ var fid = 1;
5908
+ function nextId() {
5909
+ return `qi${fid++}`;
5910
+ }
5911
+ function QuoteFormView({ quoteId, leadId, onSaved }) {
5912
+ const t = useTranslation();
5913
+ const config = useCrmConfig();
5914
+ const provider = useCrmProvider();
5915
+ const { currency, itemTypes: declaredItemTypes } = config;
5916
+ const translatedItemTypes = React__default.useMemo(
5917
+ () => declaredItemTypes.map((tp) => {
5918
+ const traduzido = t(`crm.itemType.${tp.value}`);
5919
+ return traduzido === `crm.itemType.${tp.value}` ? tp : { ...tp, label: traduzido };
5920
+ }),
5921
+ [declaredItemTypes, t]
5922
+ );
5923
+ const itemTypes = useCatalogedItemTypes(translatedItemTypes, config.entityLookups);
5924
+ const createQuote = useCrmStore((s) => s.createQuote);
5925
+ const updateQuote = useCrmStore((s) => s.updateQuote);
5926
+ const guardQuotes = useLimitGuard("quotes");
5927
+ const isEdit = !!quoteId;
5928
+ const [loadingExisting, setLoadingExisting] = useState(isEdit || !!leadId);
5929
+ const [linkedLeadId, setLinkedLeadId] = useState(leadId ?? "");
5930
+ const [linkedDealId, setLinkedDealId] = useState("");
5931
+ const [contactName, setContactName] = useState("");
5932
+ const [contactId, setContactId] = useState("");
5933
+ const [quoteDate, setQuoteDate] = useState((/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
5934
+ const [validUntil, setValidUntil] = useState(() => {
5935
+ const d = /* @__PURE__ */ new Date();
5936
+ d.setDate(d.getDate() + 30);
5937
+ return d.toISOString().slice(0, 10);
5938
+ });
5939
+ const [validityDays, setValidityDays] = useState(30);
5940
+ const [currentStatus, setCurrentStatus] = useState("draft");
5941
+ const [paymentConditions, setPaymentConditions] = useState("");
5942
+ const [observations, setObservations] = useState("");
5943
+ const [items, setItems] = useState([]);
5944
+ const [expandedItemId, setExpandedItemId] = useState(null);
5945
+ const [addingItem, setAddingItem] = useState(false);
5946
+ const [saving, setSaving] = useState(false);
5947
+ useEffect(() => {
5948
+ if (!quoteId) return;
5949
+ provider.getQuoteById(quoteId).then((q) => {
5950
+ if (q) {
5951
+ setContactName(q.contactName ?? "");
5952
+ setContactId(q.contactId ?? "");
5953
+ setLinkedLeadId(q.leadId ?? "");
5954
+ setLinkedDealId(q.dealId ?? "");
5955
+ setQuoteDate(q.quoteDate);
5956
+ setValidUntil(q.validUntil);
5957
+ const span = daysBetween(q.quoteDate, q.validUntil);
5958
+ setValidityDays(VALIDITY_PRESETS.some((pr) => pr.days === span) ? span : null);
5959
+ setCurrentStatus(q.status);
5960
+ setPaymentConditions(q.paymentConditions ?? "");
5961
+ setObservations(q.observations ?? "");
5962
+ setItems(q.items.map((it) => ({
5963
+ _id: nextId(),
5964
+ itemKind: it.itemKind,
5965
+ description: it.description,
5966
+ quantity: it.quantity,
5967
+ unitPrice: it.unitPrice,
5968
+ discount: it.discount
5969
+ })));
5970
+ }
5971
+ setLoadingExisting(false);
5972
+ });
5973
+ }, [quoteId]);
5974
+ useEffect(() => {
5975
+ if (!leadId || quoteId) return;
5976
+ provider.getLeadById(leadId).then(async (lead) => {
5977
+ if (lead) {
5978
+ setContactName(lead.name);
5979
+ setContactId(lead.id);
5980
+ setLinkedLeadId(lead.id);
5981
+ const deal = await provider.getDealByLeadId(lead.id);
5982
+ if (deal) setLinkedDealId(deal.id);
5983
+ }
5984
+ setLoadingExisting(false);
5985
+ });
5986
+ }, [leadId]);
5987
+ function changeQuoteDate(iso) {
5988
+ setQuoteDate(iso);
5989
+ if (validityDays !== null) setValidUntil(addDays(iso, validityDays));
5990
+ }
5991
+ const openCustomOnMount = React__default.useRef(false);
5992
+ function pickValidity(days) {
5993
+ openCustomOnMount.current = days === null && validityDays !== null;
5994
+ setValidityDays(days);
5995
+ if (days !== null) setValidUntil(addDays(quoteDate, days));
5996
+ }
5997
+ const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0);
5998
+ function startAddItem() {
5999
+ if (itemTypes.length === 1) {
6000
+ addItemOfKind(itemTypes[0].value);
6001
+ return;
6002
+ }
6003
+ setAddingItem(true);
6004
+ }
6005
+ function addItemOfKind(kind) {
6006
+ const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
6007
+ setItems([...items, newItem]);
6008
+ setExpandedItemId(newItem._id);
6009
+ setAddingItem(false);
6010
+ }
6011
+ function updateItem(id, data) {
6012
+ setItems(items.map((it) => it._id === id ? { ...it, ...data } : it));
6013
+ }
6014
+ function removeItem(id) {
6015
+ setItems(items.filter((it) => it._id !== id));
6016
+ if (expandedItemId === id) setExpandedItemId(null);
6017
+ }
6018
+ async function handleSave() {
6019
+ if (items.length === 0) {
6020
+ toast.error(t("crm.quoteForm.errNoItems"));
6021
+ return;
6022
+ }
6023
+ if (!isEdit && await guardQuotes() === "blocked") return;
6024
+ setSaving(true);
6025
+ try {
6026
+ const input = {
6027
+ contactId: contactId || void 0,
6028
+ contactName: contactName || void 0,
6029
+ leadId: linkedLeadId || void 0,
6030
+ dealId: linkedDealId || void 0,
6031
+ quoteDate,
6032
+ validUntil,
6033
+ paymentConditions: paymentConditions || void 0,
6034
+ observations: observations || void 0,
6035
+ items: items.map((it) => ({
6036
+ itemKind: it.itemKind,
6037
+ description: it.description,
6038
+ quantity: it.quantity,
6039
+ unitPrice: it.unitPrice,
6040
+ discount: it.discount,
6041
+ totalAmount: it.quantity * it.unitPrice - it.discount
6042
+ }))
6043
+ };
6044
+ if (isEdit) {
6045
+ await updateQuote(quoteId, input);
6046
+ onSaved?.(quoteId);
6047
+ } else {
6048
+ const created = await createQuote(input);
6049
+ invalidateLimit("quotes");
6050
+ onSaved?.(created?.id);
6051
+ }
6052
+ } finally {
6053
+ setSaving(false);
6054
+ }
6055
+ }
6056
+ const currentFields = {
6057
+ contactId,
6058
+ contactName,
6059
+ linkedLeadId,
6060
+ linkedDealId,
6061
+ quoteDate,
6062
+ validUntil,
6063
+ currentStatus,
6064
+ paymentConditions,
6065
+ observations,
6066
+ items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
6067
+ };
6068
+ const snapshot = React__default.useRef(null);
6069
+ useEffect(() => {
6070
+ if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
6071
+ }, [loadingExisting]);
6072
+ const dirty = snapshot.current !== null && JSON.stringify(currentFields) !== snapshot.current;
6073
+ useSaveBar({
6074
+ dirty,
6075
+ saving,
6076
+ onSave: () => {
6077
+ void handleSave();
6078
+ },
6079
+ onDiscard: () => onSaved?.(),
6080
+ saveLabel: isEdit ? t("crm.quoteForm.saveChanges") : t("crm.quoteForm.saveQuote")
6081
+ });
6082
+ if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t("crm.quotes.title"), onBack: () => onSaved?.() });
6083
+ const money = (v) => formatCurrency(v, currency);
6084
+ const validUntilLabel = (/* @__PURE__ */ new Date(`${validUntil}T12:00:00`)).toLocaleDateString(getCurrentLocale());
6085
+ const contactSection = /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
6086
+ SearchSelect,
6087
+ {
6088
+ value: contactId,
6089
+ displayValue: contactName,
6090
+ onChange: (id, opt) => {
6091
+ setContactId(id);
6092
+ setContactName(opt?.label ?? "");
6093
+ },
6094
+ onSearch: async (q) => {
6095
+ if (!config.contactLookup) return [];
6096
+ const results = await config.contactLookup.search(q);
6097
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
6098
+ },
6099
+ required: true,
6100
+ placeholder: t("crm.quoteForm.searchClient"),
6101
+ allowCreate: true,
6102
+ createLabel: t("crm.quoteForm.addAsLead"),
6103
+ onCreate: async (name) => {
6104
+ const lead = await provider.createLead({ name });
6105
+ setContactId(lead.id);
6106
+ setContactName(lead.name);
6107
+ }
6108
+ }
6109
+ ) });
6110
+ const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6111
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.quoteDetails"), children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
6112
+ /* @__PURE__ */ jsxs("div", { children: [
6113
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.quoteDate") }),
6114
+ /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: changeQuoteDate, className: "mt-1" })
6115
+ ] }),
6116
+ /* @__PURE__ */ jsxs("div", { children: [
6117
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
6118
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t("crm.quoteForm.validUntil") }),
6119
+ validityDays === null ? /* @__PURE__ */ jsx(
6120
+ DatePicker,
6121
+ {
6122
+ variant: "inline",
6123
+ format: "numeric",
6124
+ value: validUntil,
6125
+ onChange: setValidUntil,
6126
+ defaultOpen: openCustomOnMount.current
6127
+ }
6128
+ ) : /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-foreground", children: validUntilLabel })
6129
+ ] }),
6130
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap gap-1.5", children: [
6131
+ VALIDITY_PRESETS.map((preset) => /* @__PURE__ */ jsx(
6132
+ Button,
6133
+ {
6134
+ type: "button",
6135
+ variant: "bare",
6136
+ size: "bare",
6137
+ onClick: () => pickValidity(preset.days),
6138
+ 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"}`,
6139
+ children: t(preset.labelKey)
6140
+ },
6141
+ preset.days
6142
+ )),
6143
+ /* @__PURE__ */ jsx(
6144
+ Button,
6145
+ {
6146
+ type: "button",
6147
+ variant: "bare",
6148
+ size: "bare",
6149
+ onClick: () => pickValidity(null),
6150
+ 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"}`,
6151
+ children: t("crm.quoteForm.validCustom")
6152
+ }
6153
+ )
6154
+ ] })
6155
+ ] })
6156
+ ] }) }),
6157
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.paymentConditions"), children: /* @__PURE__ */ jsx(
6158
+ Textarea,
6159
+ {
6160
+ value: paymentConditions,
6161
+ onChange: (e) => setPaymentConditions(e.target.value),
6162
+ rows: 2,
6163
+ placeholder: t("crm.quoteForm.paymentConditionsPlaceholder"),
6164
+ className: "min-h-0 resize-none"
6165
+ }
6166
+ ) }),
6167
+ /* @__PURE__ */ jsx(OrderFormBlock, { title: t("crm.quoteForm.notes"), children: /* @__PURE__ */ jsx(
6168
+ Textarea,
6169
+ {
6170
+ value: observations,
6171
+ onChange: (e) => setObservations(e.target.value),
6172
+ rows: 2,
6173
+ placeholder: t("crm.quoteForm.notesPlaceholder"),
6174
+ className: "min-h-0 resize-none"
6175
+ }
6176
+ ) })
6177
+ ] });
6178
+ return /* @__PURE__ */ jsxs(
6179
+ OrderFormView,
6180
+ {
6181
+ sideSections,
6182
+ title: isEdit ? t("crm.quoteForm.editTitle") : t("crm.quoteForm.newTitle"),
6183
+ parentLabel: t("crm.quotes.title"),
6184
+ onBack: () => onSaved?.(),
6185
+ badges: /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-2", children: STATUSES.map((s) => /* @__PURE__ */ jsx(
6186
+ "span",
6187
+ {
6188
+ 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"}`,
6189
+ children: t(s.labelKey)
6190
+ },
6191
+ s.value
6192
+ )) }),
6193
+ children: [
6194
+ contactSection,
6195
+ /* @__PURE__ */ jsx(
6196
+ OrderFormItemsCard,
6197
+ {
6198
+ label: t("crm.quoteForm.quoteItems"),
6199
+ addLabel: t("crm.quoteForm.addItem"),
6200
+ onAdd: startAddItem,
6201
+ addDisabled: !contactId,
6202
+ addDisabledHint: t("crm.quoteForm.selectClientFirst"),
6203
+ count: items.length,
6204
+ countLabel: t("crm.quoteForm.itemCount", { count: String(items.length) }),
6205
+ totalLabel: t("crm.quoteForm.total"),
6206
+ total: money(totalAmount),
6207
+ emptyLabel: contactId ? t("crm.quoteForm.noItems") : t("crm.quoteForm.selectClientFirst"),
6208
+ emptyActionLabel: t("crm.quoteForm.addFirstItem"),
6209
+ header: addingItem && /* @__PURE__ */ jsx(
6210
+ OrderFormAddItemStep,
6211
+ {
6212
+ itemTypes,
6213
+ onSelect: addItemOfKind,
6214
+ onCancel: () => setAddingItem(false),
6215
+ label: t("crm.quoteForm.selectItemType"),
6216
+ cancelLabel: t("crm.quoteForm.cancel")
6217
+ }
6218
+ ),
6219
+ children: items.map((item, i) => /* @__PURE__ */ jsx(
6220
+ OrderFormItemRow,
6221
+ {
6222
+ index: i,
6223
+ itemKind: item.itemKind,
6224
+ description: item.description,
6225
+ quantity: item.quantity,
6226
+ unitPrice: item.unitPrice,
6227
+ discount: item.discount,
6228
+ itemTypes,
6229
+ currency,
6230
+ formatMoney: money,
6231
+ expanded: expandedItemId === item._id,
6232
+ onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
6233
+ onChange: (patch) => updateItem(item._id, patch),
6234
+ onRemove: () => removeItem(item._id),
6235
+ entityLookups: config.entityLookups,
6236
+ labels: {
6237
+ item: t("crm.quoteForm.description"),
6238
+ description: t("crm.quoteForm.description"),
6239
+ descriptionPlaceholder: t("crm.quoteForm.itemDescriptionPlaceholder"),
6240
+ noDescription: t("crm.quoteForm.noDescription"),
6241
+ qty: t("crm.quoteForm.qty"),
6242
+ unitPrice: t("crm.quoteForm.unitPrice"),
6243
+ discount: t("crm.quoteForm.discount"),
6244
+ done: t("crm.quoteForm.done")
6245
+ }
6246
+ },
6247
+ item._id
6248
+ ))
6249
+ }
6250
+ )
6251
+ ]
6252
+ }
6253
+ );
6254
+ }
6255
+ var SEND_ITEM = "gap-2 px-3 py-2 text-xs";
6256
+ function QuoteDetailView({ quoteId, onBack, onEdit, onInvoiceCreated }) {
6257
+ const t = useTranslation();
6258
+ const { currency } = useCrmConfig();
6259
+ const provider = useCrmProvider();
6260
+ const sendQuote = useCrmStore((s) => s.sendQuote);
6261
+ const approveQuote = useCrmStore((s) => s.approveQuote);
6262
+ const rejectQuote = useCrmStore((s) => s.rejectQuote);
6263
+ const [quote, setQuote] = useState(null);
6264
+ const [loading, setLoading] = useState(true);
6265
+ const [sending, setSending] = useState(false);
6266
+ const [approving, setApproving] = useState(false);
6267
+ const [rejectOpen, setRejectOpen] = useState(false);
6268
+ const [rejectReason, setRejectReason] = useState("");
6269
+ const [rejecting, setRejecting] = useState(false);
6270
+ useEffect(() => {
6271
+ setLoading(true);
6272
+ provider.getQuoteById(quoteId).then((q) => {
6273
+ setQuote(q);
6274
+ setLoading(false);
6275
+ });
6276
+ }, [quoteId]);
6277
+ async function handleSend(_channel) {
6278
+ setSending(true);
6279
+ try {
6280
+ const updated = await sendQuote(quoteId);
6281
+ setQuote(updated);
6282
+ } finally {
6283
+ setSending(false);
6284
+ }
6285
+ }
6286
+ async function handleApprove() {
6287
+ setApproving(true);
6288
+ try {
6289
+ const updated = await approveQuote(quoteId);
6290
+ setQuote(updated);
6291
+ if (onInvoiceCreated) onInvoiceCreated(quoteId);
6292
+ } finally {
6293
+ setApproving(false);
6294
+ }
6295
+ }
6296
+ async function handleReject() {
6297
+ if (!rejectReason.trim()) return;
6298
+ setRejecting(true);
6299
+ try {
6300
+ const updated = await rejectQuote(quoteId, rejectReason.trim());
6301
+ setQuote(updated);
6302
+ setRejectOpen(false);
6303
+ setRejectReason("");
6304
+ } finally {
6305
+ setRejecting(false);
6306
+ }
6307
+ }
6308
+ if (loading) return /* @__PURE__ */ jsx(OrderDetailSkeleton, { parentLabel: t("crm.quotes.title"), onBack });
6309
+ if (!quote) {
6310
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
6311
+ /* @__PURE__ */ jsx(SubpageHeader, { title: t("crm.quoteDetail.title"), onBack, parentLabel: t("crm.quotes.title") }),
6312
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center justify-center rounded-lg border-2 border-dashed border-muted py-12 text-center", children: [
6313
+ /* @__PURE__ */ jsx(FileText, { className: "mb-2 h-8 w-8 text-muted-foreground/30" }),
6314
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t("crm.quoteDetail.notFound") }),
6315
+ /* @__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") })
6316
+ ] })
6317
+ ] });
6318
+ }
6319
+ const subtotal = quote.items.reduce((sum, it) => sum + it.quantity * it.unitPrice, 0);
6320
+ const totalDiscount = quote.items.reduce((sum, it) => sum + it.discount, 0);
6321
+ const detailItems = quote.items.map((it, i) => ({
6322
+ id: it.id ?? String(i),
6323
+ name: it.description || "\u2014",
6324
+ description: it.itemKind,
6325
+ quantity: it.quantity,
6326
+ unitPrice: formatCurrency(it.unitPrice, currency),
6327
+ total: formatCurrency(it.totalAmount, currency)
6328
+ }));
6329
+ const totals = [
6330
+ ...totalDiscount > 0 ? [
6331
+ { label: t("crm.quoteDetail.subtotal"), value: formatCurrency(subtotal, currency), muted: true },
6332
+ { label: t("crm.quoteDetail.discount"), value: `-${formatCurrency(totalDiscount, currency)}`, muted: true }
6333
+ ] : [],
6334
+ { label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), strong: true }
6335
+ ];
6336
+ const editable = quote.status !== "approved" && quote.status !== "rejected" && quote.status !== "expired";
6337
+ const actions = /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5", children: [
6338
+ quote.status === "draft" && /* @__PURE__ */ jsxs(Dropdown, { children: [
6339
+ /* @__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: [
6340
+ /* @__PURE__ */ jsx(Send, { className: "h-3 w-3" }),
6341
+ sending ? t("crm.quoteDetail.sending") : t("crm.quoteDetail.send"),
6342
+ /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 opacity-60" })
6343
+ ] }) }),
6344
+ /* @__PURE__ */ jsxs(DropdownContent, { align: "end", className: "w-48", children: [
6345
+ /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6346
+ /* @__PURE__ */ jsx(Printer, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6347
+ " ",
6348
+ t("crm.quoteDetail.sendPrint")
6349
+ ] }),
6350
+ /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6351
+ /* @__PURE__ */ jsx(Mail, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6352
+ " ",
6353
+ t("crm.quoteDetail.sendEmail")
6354
+ ] }),
6355
+ /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => void handleSend(), className: SEND_ITEM, children: [
6356
+ /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5 text-muted-foreground" }),
6357
+ " ",
6358
+ t("crm.quoteDetail.sendWhatsApp")
6359
+ ] })
6360
+ ] })
6361
+ ] }),
6362
+ quote.status === "sent" && /* @__PURE__ */ jsxs(Fragment, { children: [
6363
+ /* @__PURE__ */ jsxs(
6364
+ Button,
6365
+ {
6366
+ type: "button",
6367
+ variant: "default",
6368
+ size: "sm",
6369
+ onClick: handleApprove,
6370
+ disabled: approving,
6371
+ className: "border-success bg-success text-success-foreground hover:bg-success/90",
6372
+ children: [
6373
+ /* @__PURE__ */ jsx(Check, { className: "h-3.5 w-3.5" }),
6374
+ approving ? t("crm.quoteDetail.approving") : t("crm.quoteDetail.approve")
6375
+ ]
6376
+ }
6377
+ ),
6378
+ /* @__PURE__ */ jsxs(
6379
+ Button,
6380
+ {
6381
+ type: "button",
6382
+ variant: "outline",
6383
+ size: "sm",
6384
+ onClick: () => setRejectOpen(true),
6385
+ className: "border-destructive/30 text-destructive hover:bg-destructive/10",
6386
+ children: [
6387
+ /* @__PURE__ */ jsx(X, { className: "h-3.5 w-3.5" }),
6388
+ t("crm.quoteDetail.reject")
6389
+ ]
6390
+ }
6391
+ )
6392
+ ] }),
6393
+ onEdit && editable && /* @__PURE__ */ jsxs(Button, { type: "button", variant: "outline", size: "sm", onClick: onEdit, children: [
6394
+ /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" }),
6395
+ " ",
6396
+ t("crm.quoteDetail.edit")
6397
+ ] })
6398
+ ] });
6399
+ const sideBlocks = /* @__PURE__ */ jsxs(Fragment, { children: [
6400
+ 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 }) }),
6401
+ 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 }) })
6402
+ ] });
6403
+ const invoiced = ["approved", "invoiced", "paid", "partial", "overdue"].includes(quote.status);
6404
+ const banners = /* @__PURE__ */ jsxs(Fragment, { children: [
6405
+ 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: [
6406
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 text-xs", children: [
6407
+ /* @__PURE__ */ jsx(CircleCheckBig, { className: "h-3.5 w-3.5 text-success" }),
6408
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: t("crm.quoteDetail.invoiceCreated") })
6409
+ ] }),
6410
+ /* @__PURE__ */ jsxs("a", { href: appHref("/financial/receivables/list"), className: "inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline", children: [
6411
+ t("crm.quoteDetail.viewInvoice"),
6412
+ " ",
6413
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
6414
+ ] })
6415
+ ] }),
6416
+ 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: [
6417
+ /* @__PURE__ */ jsx(Ban, { className: "h-3.5 w-3.5 text-destructive" }),
6418
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
6419
+ t("crm.quoteDetail.rejectionReason"),
6420
+ ": ",
6421
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: quote.rejectionReason })
6422
+ ] })
6423
+ ] }) })
6424
+ ] });
6425
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
6426
+ /* @__PURE__ */ jsx(
6427
+ OrderDetailView,
6428
+ {
6429
+ title: `#${quote.quoteNumber}`,
6430
+ badgesNode: /* @__PURE__ */ jsx(QuoteStatusDropdown, { quote, onStatusChange: (q) => setQuote(q) }),
6431
+ subtitle: null,
6432
+ onBack,
6433
+ backLabel: t("crm.quotes.title"),
6434
+ actions,
6435
+ stats: [
6436
+ { id: "total", label: t("crm.quoteDetail.total"), value: formatCurrency(quote.totalAmount, currency), icon: Receipt },
6437
+ { id: "items", label: t("crm.quoteDetail.items"), value: quote.items.length, icon: Package },
6438
+ { id: "date", label: t("crm.quoteDetail.date"), value: quote.quoteDate, icon: Calendar },
6439
+ { id: "valid", label: t("crm.quoteDetail.validUntil"), value: quote.validUntil, icon: CalendarClock }
6440
+ ],
6441
+ errorBanner: banners,
6442
+ customer: { name: quote.contactName, email: null },
6443
+ 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" }),
6444
+ items: detailItems,
6445
+ itemsLabel: t("crm.quoteDetail.items"),
6446
+ totals,
6447
+ totalsLabel: t("crm.quoteDetail.summary"),
6448
+ extraSections: sideBlocks
6449
+ }
6450
+ ),
6451
+ /* @__PURE__ */ jsx(Modal, { open: rejectOpen, onOpenChange: setRejectOpen, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-sm", children: [
6452
+ /* @__PURE__ */ jsxs(ModalBody, { children: [
6453
+ /* @__PURE__ */ jsxs("div", { className: "mb-3 flex items-center gap-3", children: [
6454
+ /* @__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" }) }),
6455
+ /* @__PURE__ */ jsxs("div", { children: [
6456
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: t("crm.quoteDetail.reject") }),
6457
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t("crm.quoteDetail.rejectDescription") })
6458
+ ] })
6459
+ ] }),
6460
+ /* @__PURE__ */ jsx(
6461
+ Textarea,
6462
+ {
6463
+ value: rejectReason,
6464
+ onChange: (e) => setRejectReason(e.target.value),
6465
+ placeholder: t("crm.quoteDetail.rejectReasonPlaceholder"),
6466
+ className: "h-20 resize-none",
6467
+ autoFocus: true
6468
+ }
6469
+ )
6470
+ ] }),
6471
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
6472
+ /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", size: "sm", onClick: () => setRejectOpen(false), children: t("common.cancel") }),
6473
+ /* @__PURE__ */ jsx(
6474
+ Button,
6475
+ {
6476
+ type: "button",
6477
+ variant: "destructive",
6478
+ size: "sm",
6479
+ onClick: handleReject,
6480
+ disabled: rejecting || !rejectReason.trim(),
6481
+ children: rejecting ? t("crm.quoteDetail.rejecting") : t("crm.quoteDetail.confirmReject")
6482
+ }
6483
+ )
6484
+ ] })
6485
+ ] }) })
6486
+ ] });
6487
+ }
5459
6488
  function PersonPhones({ personId, onOpenPerson }) {
5460
6489
  const t = useTranslation();
5461
6490
  const provider = useCrmProvider();
@@ -5961,6 +6990,12 @@ function humanizeKey2(key) {
5961
6990
  const spaced = key.replace(/[_-]+/g, " ").replace(/([a-z\d])([A-Z])/g, "$1 $2");
5962
6991
  return spaced.charAt(0).toUpperCase() + spaced.slice(1);
5963
6992
  }
6993
+ function answerLabel(t, key) {
6994
+ const k = `crm.formField.${key}`;
6995
+ const v = t(k);
6996
+ return v && v !== k ? v : humanizeKey2(key);
6997
+ }
6998
+ var PERSONAL_KEYS = /* @__PURE__ */ new Set(["gender", "rg", "passport"]);
5964
6999
  function renderFieldValue2(value) {
5965
7000
  if (value === null || value === void 0 || value === "") return null;
5966
7001
  if (Array.isArray(value)) return value.length ? value.join(", ") : null;
@@ -5995,6 +7030,17 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5995
7030
  archetypeKind: "lead"
5996
7031
  } : null);
5997
7032
  const [deal, setDeal] = useState(null);
7033
+ const [identity, setIdentity] = useState({});
7034
+ useEffect(() => {
7035
+ let alive = true;
7036
+ void provider.getPersonIdentity(leadId).then((r) => {
7037
+ if (alive) setIdentity(r);
7038
+ }).catch(() => {
7039
+ });
7040
+ return () => {
7041
+ alive = false;
7042
+ };
7043
+ }, [leadId, recarga]);
5998
7044
  const [quotes, setQuotes] = useState([]);
5999
7045
  const [loading, setLoading] = useState(true);
6000
7046
  const [activities, setActivities] = useState([]);
@@ -6200,6 +7246,22 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
6200
7246
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: t("crm.leadDetail.source"), value: lead.sourceName }) })
6201
7247
  ] }) })
6202
7248
  ] }),
7249
+ (() => {
7250
+ const f = lead.metadata?.fields ?? {};
7251
+ const dob = identity.dateOfBirth ? (/* @__PURE__ */ new Date(`${identity.dateOfBirth}T12:00:00`)).toLocaleDateString(locale) : null;
7252
+ const rows = [
7253
+ [t("crm.leadDetail.cpf"), identity.documentNumber ? /* @__PURE__ */ jsx("span", { className: "tabular-nums", children: formatDocument(identity.documentNumber) }) : null],
7254
+ [t("crm.leadDetail.birthDate"), dob],
7255
+ [t("crm.formField.gender"), renderFieldValue2(f.gender)],
7256
+ [t("crm.formField.rg"), renderFieldValue2(f.rg)],
7257
+ ...f.passport ? [[t("crm.formField.passport"), renderFieldValue2(f.passport)]] : []
7258
+ ];
7259
+ return /* @__PURE__ */ jsxs("div", { children: [
7260
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t("crm.leadDetail.personalData") }),
7261
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: rows.map(([label2, value]) => /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: label2, value }) }, label2)) }) })
7262
+ ] });
7263
+ })(),
7264
+ /* @__PURE__ */ jsx(AddressesTab, { item: { id: lead.id } }),
6203
7265
  /* @__PURE__ */ jsx(LeadQualification, { lead }),
6204
7266
  /* @__PURE__ */ jsx(PersonPhones, { personId: lead.id, onOpenPerson: (pid) => onOpenPerson?.(pid) }),
6205
7267
  /* @__PURE__ */ jsxs("div", { children: [
@@ -6217,14 +7279,14 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
6217
7279
  ] }),
6218
7280
  (() => {
6219
7281
  const meta = lead.metadata ?? {};
6220
- const fields = Object.entries(meta.fields ?? {}).filter(([, v]) => renderFieldValue2(v) !== null);
7282
+ const fields = Object.entries(meta.fields ?? {}).filter(([k, v]) => !PERSONAL_KEYS.has(k) && renderFieldValue2(v) !== null);
6221
7283
  const utm = Object.entries(meta.utm ?? {}).filter(([, v]) => renderFieldValue2(v) !== null);
6222
7284
  const attachments = leadAttachments(lead.metadata);
6223
7285
  if (!fields.length && !utm.length && !attachments.length) return null;
6224
7286
  return /* @__PURE__ */ jsxs("div", { children: [
6225
7287
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t("crm.leadDetail.formAnswers") }),
6226
7288
  /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card shadow-sm", children: [
6227
- /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: fields.map(([key, value]) => /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: humanizeKey2(key), value: renderFieldValue2(value) }) }, key)) }),
7289
+ /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: fields.map(([key, value]) => /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: answerLabel(t, key), value: renderFieldValue2(value) }) }, key)) }),
6228
7290
  attachments.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-t px-5 py-3", children: /* @__PURE__ */ jsx(LeadAttachments, { attachments }) }),
6229
7291
  utm.length > 0 && /* @__PURE__ */ jsx("div", { className: "border-t px-5 py-3 flex flex-wrap gap-x-4 gap-y-1", children: utm.map(([key, value]) => /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
6230
7292
  humanizeKey2(key.replace(/^utm_/, "")),
@@ -6654,9 +7716,12 @@ function buildCompanyEntity(t, companyId) {
6654
7716
  displayField: "name",
6655
7717
  subtitleField: "legalName",
6656
7718
  formColumns: 2,
7719
+ // The street lives in the address book, shown as its own section.
7720
+ addressOwnerType: "crm_company",
6657
7721
  fieldGroups: [
6658
7722
  { id: "identity", label: t("crm.companyDetail.identity"), columns: 2 },
6659
- { id: "contact", label: t("crm.companyDetail.contact"), columns: 2 }
7723
+ { id: "contact", label: t("crm.companyDetail.contact"), columns: 2 },
7724
+ { id: "profile", label: t("crm.companyDetail.profile"), columns: 2 }
6660
7725
  ],
6661
7726
  fields: [
6662
7727
  { key: "name", label: t("crm.companyForm.name"), type: "text", required: true, placeholder: t("crm.companyForm.namePlaceholder"), group: "identity" },
@@ -6693,10 +7758,40 @@ function buildCompanyEntity(t, companyId) {
6693
7758
  },
6694
7759
  { key: "city", label: t("crm.companyForm.city"), type: "text", group: "contact" },
6695
7760
  { key: "state", label: t("crm.companyForm.state"), type: "text", group: "contact" },
6696
- { key: "notes", label: t("crm.companyForm.notes"), type: "textarea", group: "contact", span: 2 }
7761
+ { key: "notes", label: t("crm.companyForm.notes"), type: "textarea", group: "contact", span: 2 },
7762
+ ...PROFILE_FIELDS.map(([key]) => ({
7763
+ key: profileFieldKey(key),
7764
+ label: t(`crm.companyProfile.${key}`),
7765
+ type: "text",
7766
+ group: "profile",
7767
+ showInTable: false
7768
+ }))
6697
7769
  ]
6698
7770
  };
6699
7771
  }
7772
+ var PROFILE_FIELDS = [
7773
+ ["venueType"],
7774
+ ["salesChannels"],
7775
+ ["units"],
7776
+ ["structure"],
7777
+ ["headcount"],
7778
+ ["revenue"],
7779
+ ["abraselMember"]
7780
+ ];
7781
+ var profileFieldKey = (k) => `profile_${k}`;
7782
+ function companyRecord(c) {
7783
+ const out = { ...c };
7784
+ for (const [k] of PROFILE_FIELDS) out[profileFieldKey(k)] = c.profile?.[k];
7785
+ return out;
7786
+ }
7787
+ function profileFromValues(values) {
7788
+ const out = {};
7789
+ for (const [k] of PROFILE_FIELDS) {
7790
+ const v = values[profileFieldKey(k)];
7791
+ if (typeof v === "string") out[k] = v.trim();
7792
+ }
7793
+ return Object.keys(out).length ? out : void 0;
7794
+ }
6700
7795
  function toCompanyInput(values, id) {
6701
7796
  const s = (k) => typeof values[k] === "string" ? values[k].trim() : values[k] ?? "";
6702
7797
  return {
@@ -6710,7 +7805,8 @@ function toCompanyInput(values, id) {
6710
7805
  instagram: normalizeInstagram(s("instagram")) ?? "",
6711
7806
  city: s("city"),
6712
7807
  state: s("state"),
6713
- notes: s("notes")
7808
+ notes: s("notes"),
7809
+ profile: profileFromValues(values)
6714
7810
  };
6715
7811
  }
6716
7812
  function CompanyFormView({ companyId, onSaved, onCancel }) {
@@ -6724,7 +7820,7 @@ function CompanyFormView({ companyId, onSaved, onCancel }) {
6724
7820
  let cancelled = false;
6725
7821
  void provider.getCompanyById(companyId).then((c) => {
6726
7822
  if (cancelled) return;
6727
- setInitialData(c ? { ...c, documentNumber: c.documentNumber ? formatDocument(c.documentNumber) : "" } : {});
7823
+ setInitialData(c ? { ...companyRecord(c), documentNumber: c.documentNumber ? formatDocument(c.documentNumber) : "" } : {});
6728
7824
  });
6729
7825
  return () => {
6730
7826
  cancelled = true;
@@ -6927,46 +8023,77 @@ function ReceitaTab({ receita }) {
6927
8023
  const t = useTranslation();
6928
8024
  const { currency } = useCrmConfig();
6929
8025
  if (!receita) return /* @__PURE__ */ jsx("p", { className: "px-1 py-4 text-sm text-muted-foreground", children: t("crm.companyDetail.receitaNone") });
6930
- return /* @__PURE__ */ jsxs("div", { children: [
6931
- receita.consultadoEm && /* @__PURE__ */ jsxs("p", { className: "mb-2 flex items-center gap-1.5 text-xs text-muted-foreground", children: [
8026
+ const r = receita;
8027
+ const yesNo = (v, since, until) => {
8028
+ if (v == null) return null;
8029
+ if (!v) return until ? `${t("crm.companyDetail.no")} \xB7 ${t("crm.companyDetail.receitaExcludedOn")} ${until}` : t("crm.companyDetail.no");
8030
+ return since ? `${t("crm.companyDetail.yes")} \xB7 ${t("crm.companyDetail.receitaSince")} ${since}` : t("crm.companyDetail.yes");
8031
+ };
8032
+ const endereco = [r.logradouro, r.bairro, [r.municipio, r.uf].filter(Boolean).join("/"), r.cep].filter(Boolean).join(" \xB7 ") || null;
8033
+ const rows = [
8034
+ [t("crm.companyDetail.receitaSituacao"), r.situacao ? (
8035
+ // "BAIXADA" é a empresa não existir mais; em cinza passa despercebido.
8036
+ /* @__PURE__ */ jsxs("span", { className: r.situacao === "ATIVA" ? void 0 : "font-medium text-destructive", children: [
8037
+ r.situacao,
8038
+ r.dataSituacao && /* @__PURE__ */ jsxs("span", { className: "ml-1.5 font-normal text-muted-foreground", children: [
8039
+ t("crm.companyDetail.receitaSince"),
8040
+ " ",
8041
+ r.dataSituacao
8042
+ ] }),
8043
+ r.motivoSituacao && r.motivoSituacao !== "SEM MOTIVO" && /* @__PURE__ */ jsx("span", { className: "block text-xs font-normal text-muted-foreground", children: r.motivoSituacao })
8044
+ ] })
8045
+ ) : null],
8046
+ [t("crm.companyDetail.receitaLegalName"), r.razaoSocial ?? null],
8047
+ [t("crm.companyDetail.receitaTradeName"), r.nomeFantasia ?? null],
8048
+ [t("crm.companyDetail.receitaNature"), r.naturezaJuridica ?? null],
8049
+ [t("crm.companyDetail.receitaPorte"), r.porte ?? null],
8050
+ [t("crm.companyDetail.receitaCapital"), r.capitalSocial != null ? formatCurrency(r.capitalSocial, currency) : null],
8051
+ [t("crm.companyDetail.receitaOpened"), r.abertura ?? null],
8052
+ [t("crm.companyDetail.receitaHeadOffice"), r.eMatriz == null ? null : r.eMatriz ? t("crm.companyDetail.receitaMatriz") : t("crm.companyDetail.receitaFilial")],
8053
+ [t("crm.companyDetail.receitaSimples"), yesNo(r.opcaoSimples, r.dataOpcaoSimples, r.dataExclusaoSimples)],
8054
+ [t("crm.companyDetail.receitaMei"), yesNo(r.opcaoMei, r.dataOpcaoMei, r.dataExclusaoMei)],
8055
+ [t("crm.companyDetail.receitaRegime"), r.regimeTributario ?? null],
8056
+ [t("crm.companyDetail.receitaAddress"), endereco, true],
8057
+ [t("crm.companyDetail.receitaPhones"), r.telefones?.length ? r.telefones.join(" \xB7 ") : null],
8058
+ [t("crm.companyDetail.receitaEmail"), r.email ?? null],
8059
+ [t("crm.companyDetail.receitaSpecial"), r.situacaoEspecial ?? null],
8060
+ [t("crm.companyDetail.receitaCnae"), r.cnaeDescricao ? /* @__PURE__ */ jsxs("span", { children: [
8061
+ r.cnaeDescricao,
8062
+ r.cnae && /* @__PURE__ */ jsx("span", { className: "ml-1.5 tabular-nums text-muted-foreground", children: r.cnae })
8063
+ ] }) : r.cnae ?? null, true],
8064
+ [t("crm.companyDetail.receitaCnaes2"), r.cnaesSecundarios?.length ? /* @__PURE__ */ jsx("ul", { className: "space-y-0.5", children: r.cnaesSecundarios.map((c) => /* @__PURE__ */ jsxs("li", { children: [
8065
+ c.descricao ?? c.codigo,
8066
+ /* @__PURE__ */ jsx("span", { className: "ml-1.5 tabular-nums text-muted-foreground", children: c.codigo })
8067
+ ] }, c.codigo)) }) : null, true]
8068
+ ];
8069
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
8070
+ r.consultadoEm && /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-1.5 text-xs text-muted-foreground", children: [
6932
8071
  /* @__PURE__ */ jsx(Fingerprint, { className: "h-3.5 w-3.5" }),
6933
8072
  t("crm.companyDetail.receitaCheckedOn"),
6934
8073
  " ",
6935
- receita.consultadoEm
8074
+ r.consultadoEm
6936
8075
  ] }),
6937
- /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
6938
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow2, { label: t("crm.companyDetail.receitaSituacao"), value: receita.situacao ? (
6939
- // "BAIXADA" é a empresa não existir mais; em cinza passa despercebido.
6940
- /* @__PURE__ */ jsx("span", { className: receita.situacao === "ATIVA" ? void 0 : "font-medium text-destructive", children: receita.situacao })
6941
- ) : null }) }),
6942
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow2, { label: t("crm.companyDetail.receitaLegalName"), value: receita.razaoSocial ?? null }) }),
6943
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow2, { label: t("crm.companyDetail.receitaPorte"), value: receita.porte ?? null }) }),
6944
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(
6945
- FieldRow2,
6946
- {
6947
- label: t("crm.companyDetail.receitaCapital"),
6948
- value: receita.capitalSocial != null ? formatCurrency(receita.capitalSocial, currency) : null
6949
- }
6950
- ) }),
6951
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow2, { label: t("crm.companyDetail.receitaOpened"), value: receita.abertura ?? null }) }),
6952
- /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(
6953
- FieldRow2,
6954
- {
6955
- label: t("crm.companyDetail.receitaPartners"),
6956
- value: receita.socios != null ? String(receita.socios) : null
6957
- }
6958
- ) }),
6959
- /* @__PURE__ */ jsx("div", { className: "px-5 md:col-span-2 md:border-t", children: /* @__PURE__ */ jsx(
6960
- FieldRow2,
6961
- {
6962
- label: t("crm.companyDetail.receitaCnae"),
6963
- value: receita.cnaeDescricao ? /* @__PURE__ */ jsxs("span", { children: [
6964
- receita.cnaeDescricao,
6965
- receita.cnae && /* @__PURE__ */ jsx("span", { className: "ml-1.5 tabular-nums text-muted-foreground", children: receita.cnae })
6966
- ] }) : receita.cnae ?? null
6967
- }
6968
- ) })
6969
- ] }) })
8076
+ /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsx("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: rows.map(([label2, value, wide]) => /* @__PURE__ */ jsx("div", { className: wide ? "px-5 md:col-span-2 md:border-b" : "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow2, { label: label2, value }) }, label2)) }) }),
8077
+ /* @__PURE__ */ jsxs("div", { children: [
8078
+ /* @__PURE__ */ jsxs("h3", { className: "mb-1 text-sm font-semibold text-foreground", children: [
8079
+ t("crm.companyDetail.receitaPartners"),
8080
+ r.socios != null && /* @__PURE__ */ jsx("span", { className: "ml-1.5 font-normal text-muted-foreground", children: r.socios })
8081
+ ] }),
8082
+ /* @__PURE__ */ jsxs("div", { className: "divide-y rounded-card border bg-card shadow-sm", children: [
8083
+ !r.quadroSocietario?.length && /* @__PURE__ */ jsx("p", { className: "px-5 py-4 text-sm text-muted-foreground", children: t("crm.companyDetail.receitaNoPartners") }),
8084
+ r.quadroSocietario?.map((q, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 px-5 py-3", children: [
8085
+ /* @__PURE__ */ jsxs("span", { className: "flex flex-col", children: [
8086
+ /* @__PURE__ */ jsx("span", { className: "text-sm", children: q.nome }),
8087
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: [q.qualificacao, q.faixaEtaria].filter(Boolean).join(" \xB7 ") })
8088
+ ] }),
8089
+ q.desde && /* @__PURE__ */ jsxs("span", { className: "text-xs text-muted-foreground", children: [
8090
+ t("crm.companyDetail.receitaSince"),
8091
+ " ",
8092
+ q.desde
8093
+ ] })
8094
+ ] }, `${q.nome}-${i}`))
8095
+ ] })
8096
+ ] })
6970
8097
  ] });
6971
8098
  }
6972
8099
  function PeopleTab({ people, groupSiblings, onLink, onUnlink, onOpenLead }) {
@@ -7128,7 +8255,8 @@ function CompanyDetailView({
7128
8255
  instagram: instagram === void 0 ? void 0 : normalizeInstagram(instagram) ?? "",
7129
8256
  city: s("city"),
7130
8257
  state: s("state"),
7131
- notes: s("notes")
8258
+ notes: s("notes"),
8259
+ profile: profileFromValues(values)
7132
8260
  });
7133
8261
  await load();
7134
8262
  }
@@ -7139,7 +8267,7 @@ function CompanyDetailView({
7139
8267
  CrudDetailPage,
7140
8268
  {
7141
8269
  entityDef: entity,
7142
- item: company,
8270
+ item: companyRecord(company),
7143
8271
  namePlural: t("crm.companies.title"),
7144
8272
  basePath: "/sales/companies",
7145
8273
  initialTab,
@@ -9146,5 +10274,5 @@ function CrmPage({ config, provider, store, registries }) {
9146
10274
  }
9147
10275
 
9148
10276
  export { CrmPage };
9149
- //# sourceMappingURL=CrmPage-JNJOATIH.js.map
9150
- //# sourceMappingURL=CrmPage-JNJOATIH.js.map
10277
+ //# sourceMappingURL=CrmPage-GWYW2YMM.js.map
10278
+ //# sourceMappingURL=CrmPage-GWYW2YMM.js.map