@fayz-ai/plugin-crm 0.29.2 → 0.31.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.
Files changed (41) hide show
  1. package/dist/components/LinkCompanyPrompt.d.ts +31 -0
  2. package/dist/components/LinkCompanyPrompt.d.ts.map +1 -0
  3. package/dist/components/LostReasonDialog.d.ts +19 -0
  4. package/dist/components/LostReasonDialog.d.ts.map +1 -0
  5. package/dist/data/mock.d.ts.map +1 -1
  6. package/dist/data/registries.d.ts.map +1 -1
  7. package/dist/data/supabase.d.ts.map +1 -1
  8. package/dist/data/tables.d.ts +3 -0
  9. package/dist/data/tables.d.ts.map +1 -1
  10. package/dist/data/types.d.ts +3 -1
  11. package/dist/data/types.d.ts.map +1 -1
  12. package/dist/index.js +1940 -602
  13. package/dist/index.js.map +1 -1
  14. package/dist/lib/board-filter.d.ts +43 -0
  15. package/dist/lib/board-filter.d.ts.map +1 -0
  16. package/dist/lib/lost-reasons.d.ts +18 -0
  17. package/dist/lib/lost-reasons.d.ts.map +1 -0
  18. package/dist/lib/pipeline-agent-surface.d.ts +36 -0
  19. package/dist/lib/pipeline-agent-surface.d.ts.map +1 -0
  20. package/dist/lib/pipeline-scope.d.ts +19 -0
  21. package/dist/lib/pipeline-scope.d.ts.map +1 -0
  22. package/dist/locales/en.d.ts.map +1 -1
  23. package/dist/locales/pt-BR.d.ts.map +1 -1
  24. package/dist/migrations/index.d.ts +2 -0
  25. package/dist/migrations/index.d.ts.map +1 -1
  26. package/dist/store.d.ts +7 -1
  27. package/dist/store.d.ts.map +1 -1
  28. package/dist/types.d.ts +10 -0
  29. package/dist/types.d.ts.map +1 -1
  30. package/dist/views/DealCardModal.d.ts +13 -2
  31. package/dist/views/DealCardModal.d.ts.map +1 -1
  32. package/dist/views/DealFunnelView.d.ts.map +1 -1
  33. package/dist/views/DealListView.d.ts.map +1 -1
  34. package/dist/views/DealsView.d.ts.map +1 -1
  35. package/dist/views/LeadDetailView.d.ts.map +1 -1
  36. package/dist/views/LeadListView.d.ts.map +1 -1
  37. package/dist/views/PipelineView.d.ts +12 -1
  38. package/dist/views/PipelineView.d.ts.map +1 -1
  39. package/dist/views/QuoteFormView.d.ts.map +1 -1
  40. package/dist/views/customerEntity.d.ts.map +1 -1
  41. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
- import { tl, useTranslation, getSupabaseClientOptional, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
- import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, usePluginOnboardingGate, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
4
- import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, Building2, CircleDot, User, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, SlidersHorizontal, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
2
+ import { tl, useTranslation, getSupabaseClientOptional, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, RECORD_GROUP, recordRailFields, activeFacet, countByTenant, usePluginRuntimeOptional, getActiveUnitId, useActiveTenantId, exportCSV, getCurrentLocale, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
+ import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, usePluginOnboardingGate, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, useCatalogedItemTypes, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, AskAIButton, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker, useAgentSurface } from '@fayz-ai/admin';
4
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, Building2, CircleDot, User, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, Search, ThumbsDown, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, SlidersHorizontal, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
5
5
  import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, PageViewBar, ViewTabs, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, PageHeaderActions, FilterChip, MultiSelect, FilterMenu, FilterMenuRow, PersonAvatar, ListView, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, PersonPicker, CurrencyInput, HeaderTabs, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
7
  import { createPortal } from 'react-dom';
@@ -853,18 +853,81 @@ function TagChips({ tags, defs, max, size = "xs", className }) {
853
853
  )
854
854
  ] });
855
855
  }
856
- function periodToRange(period, customFrom, customTo) {
857
- if (period === "all") return {};
858
- if (period === "24h") {
859
- return { createdFrom: new Date(Date.now() - 24 * 60 * 60 * 1e3).toISOString() };
860
- }
861
- if (period === "7d") {
862
- return { createdFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3).toISOString() };
863
- }
864
- return {
865
- ...customFrom ? { createdFrom: (/* @__PURE__ */ new Date(`${customFrom}T00:00:00`)).toISOString() } : {},
866
- ...customTo ? { createdTo: (/* @__PURE__ */ new Date(`${customTo}T23:59:59.999`)).toISOString() } : {}
867
- };
856
+
857
+ // src/lib/lost-reasons.ts
858
+ var LOST_REASONS = ["noInterest", "price", "noBudget", "competitor", "ghosted", "badFit"];
859
+ var KNOWN = new Set(LOST_REASONS);
860
+ function isLostReasonKey(value) {
861
+ return !!value && KNOWN.has(value);
862
+ }
863
+ function lostReasonLabel(value, t2) {
864
+ if (!value) return void 0;
865
+ return isLostReasonKey(value) ? t2(`crm.lostReason.${value}`) : value;
866
+ }
867
+ function LostReasonDialog({
868
+ open,
869
+ saving,
870
+ onCancel,
871
+ onConfirm
872
+ }) {
873
+ const t2 = useTranslation();
874
+ const [picked, setPicked] = useState();
875
+ const [other, setOther] = useState("");
876
+ useEffect(() => {
877
+ if (!open) {
878
+ setPicked(void 0);
879
+ setOther("");
880
+ }
881
+ }, [open]);
882
+ const reason = picked ?? (other.trim() || void 0);
883
+ return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (v) => {
884
+ if (!v && !saving) onCancel();
885
+ }, children: /* @__PURE__ */ jsxs(ModalContent, { className: "max-w-md", children: [
886
+ /* @__PURE__ */ jsx(ModalHeader, { children: /* @__PURE__ */ jsx(ModalTitle, { children: t2("crm.card.lostReasonTitle") }) }),
887
+ /* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
888
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: t2("crm.card.lostReasonHint") }),
889
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: LOST_REASONS.map((key) => {
890
+ const active = picked === key;
891
+ return /* @__PURE__ */ jsx(
892
+ "button",
893
+ {
894
+ type: "button",
895
+ "aria-pressed": active,
896
+ onClick: () => {
897
+ setPicked(active ? void 0 : key);
898
+ if (!active) setOther("");
899
+ },
900
+ className: "rounded-full border px-3 py-1.5 text-xs font-medium transition-colors " + (active ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-muted hover:text-foreground"),
901
+ children: t2(`crm.lostReason.${key}`)
902
+ },
903
+ key
904
+ );
905
+ }) }),
906
+ /* @__PURE__ */ jsxs("div", { children: [
907
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.card.lostReasonOther") }),
908
+ /* @__PURE__ */ jsx(
909
+ Input,
910
+ {
911
+ value: other,
912
+ onChange: (e) => {
913
+ setOther(e.target.value);
914
+ if (e.target.value) setPicked(void 0);
915
+ },
916
+ placeholder: t2("crm.card.lostReasonPrompt"),
917
+ className: "mt-1"
918
+ }
919
+ )
920
+ ] })
921
+ ] }),
922
+ /* @__PURE__ */ jsxs(ModalFooter, { children: [
923
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", disabled: saving, onClick: onCancel, children: t2("common.cancel") }),
924
+ /* @__PURE__ */ jsxs(Button, { variant: "destructive", disabled: saving, onClick: () => onConfirm(reason), children: [
925
+ /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3.5 w-3.5" }),
926
+ " ",
927
+ t2("crm.card.lostReasonConfirm")
928
+ ] })
929
+ ] })
930
+ ] }) });
868
931
  }
869
932
 
870
933
  // src/lib/relative-time.ts
@@ -960,6 +1023,56 @@ function dealHeadline(deal) {
960
1023
  function dealHouseLine(deal) {
961
1024
  return deal.groupName && deal.companyName ? deal.companyName : null;
962
1025
  }
1026
+ function periodToRange(period, customFrom, customTo) {
1027
+ if (period === "all") return {};
1028
+ if (period === "24h") {
1029
+ return { createdFrom: new Date(Date.now() - 24 * 60 * 60 * 1e3).toISOString() };
1030
+ }
1031
+ if (period === "7d") {
1032
+ return { createdFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3).toISOString() };
1033
+ }
1034
+ return {
1035
+ ...customFrom ? { createdFrom: (/* @__PURE__ */ new Date(`${customFrom}T00:00:00`)).toISOString() } : {},
1036
+ ...customTo ? { createdTo: (/* @__PURE__ */ new Date(`${customTo}T23:59:59.999`)).toISOString() } : {}
1037
+ };
1038
+ }
1039
+
1040
+ // src/lib/board-filter.ts
1041
+ function buildBoardFilter(input) {
1042
+ const termo = input.search?.trim();
1043
+ return {
1044
+ ...input.selectedTags.length ? { tags: input.selectedTags } : {},
1045
+ ...termo ? {
1046
+ search: termo,
1047
+ // O de-para nome→slug mora do lado da tela porque é lá que o cadastro de
1048
+ // etiquetas está: procura-se por "Coorte 1" e o banco guarda o slug.
1049
+ searchTags: [...input.tagDefs?.values() ?? []].filter((d) => d.name.toLowerCase().includes(termo.toLowerCase())).map((d) => d.slug)
1050
+ } : {},
1051
+ ...periodToRange(input.period, input.customFrom, input.customTo),
1052
+ ...input.owner ? { assignedToId: input.owner } : {}
1053
+ };
1054
+ }
1055
+ var CHAVES_DO_QUADRO = {
1056
+ owner: "crm.board.owner",
1057
+ period: "crm.board.period",
1058
+ customFrom: "crm.board.customFrom",
1059
+ customTo: "crm.board.customTo",
1060
+ tags: "crm.board.tags"
1061
+ };
1062
+ function useBoardFilterValue(myUserId) {
1063
+ const [owner] = usePersistedState(CHAVES_DO_QUADRO.owner, void 0);
1064
+ const [period] = usePersistedState(CHAVES_DO_QUADRO.period, "all");
1065
+ const [customFrom] = usePersistedState(CHAVES_DO_QUADRO.customFrom, "");
1066
+ const [customTo] = usePersistedState(CHAVES_DO_QUADRO.customTo, "");
1067
+ const [selectedTags] = usePersistedState(CHAVES_DO_QUADRO.tags, []);
1068
+ return buildBoardFilter({
1069
+ selectedTags,
1070
+ period,
1071
+ customFrom,
1072
+ customTo,
1073
+ owner: owner === "__me__" ? myUserId ?? void 0 : owner
1074
+ });
1075
+ }
963
1076
  async function loadTeam() {
964
1077
  const supabase = getSupabaseClientOptional();
965
1078
  if (!supabase) return [];
@@ -995,6 +1108,302 @@ async function loadMyUserId() {
995
1108
  return null;
996
1109
  }
997
1110
  }
1111
+ var INSTRUCTIONS = `Voc\xEA est\xE1 com o FUNIL do CRM aberto e \xE9 VOC\xCA quem desenha as etapas com a pessoa.
1112
+
1113
+ COMO CONDUZIR (o padr\xE3o desta tela):
1114
+ - N\xE3o pe\xE7a "quais etapas voc\xEA quer" \u2014 quem sabe responder isso n\xE3o precisava de voc\xEA. Pergunte como a casa VENDE e derive as etapas disso.
1115
+ - Fa\xE7a UMA pergunta por vez, no m\xE1ximo quatro no total, e sempre com exemplos para a pessoa s\xF3 escolher. Nesta ordem:
1116
+ 1. O que voc\xEAs vendem, e para quem (empresa ou pessoa)?
1117
+ 2. Como o cliente chega at\xE9 voc\xEAs (indica\xE7\xE3o, an\xFAncio, WhatsApp, loja)?
1118
+ 3. O que precisa acontecer ANTES de mandar pre\xE7o \u2014 reuni\xE3o, visita, or\xE7amento, amostra?
1119
+ 4. Quando a venda \xE9 ganha: assinatura, pagamento, primeira entrega?
1120
+ - Se a pessoa j\xE1 disser tudo na primeira mensagem, n\xE3o pergunte de novo: proponha.
1121
+
1122
+ O QUE PROPOR:
1123
+ - Entre 4 e 7 etapas. Menos que 4 n\xE3o mede nada; mais que 7 vira um quadro que ningu\xE9m arrasta.
1124
+ - Uma etapa \xE9 um ESTADO do neg\xF3cio ("Proposta enviada"), nunca uma tarefa ("Ligar").
1125
+ - Sempre exatamente uma etapa de entrada, uma de ganho e uma de perda. \`probability\` sobe do come\xE7o ao fim: entrada baixa (5\u201315), ganho 100, perda 0.
1126
+ - Liste as etapas na resposta, uma linha cada, E CHAME \`applyFunnelStages\` NA MESMA RESPOSTA. A lista \xE9 o texto do cart\xE3o de confirma\xE7\xE3o, n\xE3o um pedido de autoriza\xE7\xE3o \u2014 quem autoriza \xE9 o cart\xE3o que a ferramenta abre.
1127
+ - NUNCA termine um turno com "vou aplicar agora", "vou configurar" ou "j\xE1 configuro" sem ter chamado a ferramenta nesse mesmo turno. Anunciar sem chamar deixa a pessoa esperando por uma coisa que n\xE3o vai acontecer.
1128
+
1129
+ FERRAMENTAS:
1130
+ - \`applyFunnelStages\` \xE9 a que desenha o funil inteiro de uma vez. Mande a lista COMPLETA, na ordem: o que j\xE1 existe com o mesmo nome \xE9 atualizado, o que falta \xE9 criado.
1131
+ - \`replaceExisting: true\` remove as etapas que ficaram de fora. S\xF3 use quando a pessoa disser que o funil atual n\xE3o serve. Etapa com neg\xF3cio dentro NUNCA \xE9 removida \u2014 a ferramenta devolve quais sobraram e voc\xEA conta isso a ela.
1132
+ - \`renameFunnelStage\`, \`reorderFunnelStages\` e \`removeFunnelStage\` s\xE3o para ajuste pontual depois \u2014 nunca para montar o funil inteiro.
1133
+ - \`createFunnel\` s\xF3 quando a pessoa quiser um SEGUNDO funil (outra linha de neg\xF3cio, outro time). Ele j\xE1 nasce com tr\xEAs etapas; redesenhe-as com \`applyFunnelStages\`.
1134
+
1135
+ Nunca invente que configurou algo que a ferramenta n\xE3o devolveu \`ok\`. E n\xE3o mande a pessoa ir em Configura\xE7\xF5es fazer \xE0 m\xE3o o que voc\xEA acabou de receber ferramenta para fazer.`;
1136
+ function normalizeStageName(raw) {
1137
+ return (raw ?? "").normalize("NFD").replace(/[\u0300-\u036f]/g, "").trim().toLowerCase().replace(/\s+/g, " ");
1138
+ }
1139
+ var STAGE_COLORS = ["#64748B", "#0EA5E9", "#6366F1", "#8B5CF6", "#F59E0B", "#EC4899"];
1140
+ var WON_COLOR = "#16A34A";
1141
+ var LOST_COLOR = "#DC2626";
1142
+ function normalizeProposal(stages) {
1143
+ const fixed = [];
1144
+ const seen = /* @__PURE__ */ new Set();
1145
+ const clean = stages.map((s) => ({ ...s, name: (s.name ?? "").trim() })).filter((s) => {
1146
+ if (!s.name) return false;
1147
+ const key = normalizeStageName(s.name);
1148
+ if (seen.has(key)) {
1149
+ fixed.push(`etapa repetida descartada: "${s.name}"`);
1150
+ return false;
1151
+ }
1152
+ seen.add(key);
1153
+ return true;
1154
+ });
1155
+ if (!clean.length) return { stages: [], fixed };
1156
+ let initialAt = clean.findIndex((s) => s.isInitial);
1157
+ if (initialAt < 0) {
1158
+ initialAt = 0;
1159
+ fixed.push(`sem etapa de entrada declarada: "${clean[0].name}" virou a entrada`);
1160
+ }
1161
+ let wonAt = clean.findIndex((s) => s.isWon);
1162
+ let lostAt = clean.findIndex((s) => s.isLost);
1163
+ if (wonAt < 0) {
1164
+ wonAt = clean.length - 1;
1165
+ fixed.push(`sem etapa de ganho: "${clean[wonAt].name}" virou o ganho`);
1166
+ }
1167
+ if (lostAt < 0) {
1168
+ clean.push({ name: "Perdido", isLost: true, probability: 0 });
1169
+ lostAt = clean.length - 1;
1170
+ fixed.push('sem etapa de perda: "Perdido" foi acrescentada');
1171
+ }
1172
+ let colorAt = 0;
1173
+ const out = clean.map((s, i) => {
1174
+ const isInitial = i === initialAt;
1175
+ const isWon = i === wonAt;
1176
+ const isLost = i === lostAt;
1177
+ const probability = isWon ? 100 : isLost ? 0 : typeof s.probability === "number" && s.probability >= 0 && s.probability <= 100 ? Math.round(s.probability) : Math.min(90, 10 + Math.round(i / Math.max(1, clean.length - 1) * 80));
1178
+ const color = s.color && /^#[0-9a-fA-F]{6}$/.test(s.color) ? s.color : isWon ? WON_COLOR : isLost ? LOST_COLOR : STAGE_COLORS[colorAt++ % STAGE_COLORS.length];
1179
+ return { name: s.name, probability, color, isInitial, isWon, isLost };
1180
+ });
1181
+ return { stages: out, fixed };
1182
+ }
1183
+ function tool(id, name, description, properties, required, requiresConfirmation = false) {
1184
+ return {
1185
+ id,
1186
+ name,
1187
+ description,
1188
+ mode: "persist",
1189
+ parameters: { type: "object", properties, required },
1190
+ execution: { plane: "client" },
1191
+ requiresConfirmation,
1192
+ permission: { feature: "sales", action: "edit" }
1193
+ };
1194
+ }
1195
+ function usePipelineAgentSurface(deps) {
1196
+ const contribution = useMemo(() => {
1197
+ const activePipeline = deps.pipelines.find((p) => p.id === deps.activePipelineId);
1198
+ const findStage = (name) => {
1199
+ const key = normalizeStageName(name);
1200
+ return deps.stages.find((s) => normalizeStageName(s.name) === key) ?? deps.stages.find((s) => normalizeStageName(s.name).includes(key));
1201
+ };
1202
+ const requirePipeline = () => {
1203
+ if (!deps.activePipelineId) {
1204
+ return { error: "no_pipeline", message: "Nenhum funil aberto. Crie um com createFunnel." };
1205
+ }
1206
+ return deps.activePipelineId;
1207
+ };
1208
+ const tools = [
1209
+ {
1210
+ tool: tool(
1211
+ "crm.funnel.apply-stages",
1212
+ "applyFunnelStages",
1213
+ "Desenha o funil aberto: cria as etapas que faltam, atualiza as que j\xE1 existem (casadas pelo NOME) e p\xF5e tudo na ordem da lista. Mande a lista COMPLETA e final.",
1214
+ {
1215
+ stages: {
1216
+ type: "array",
1217
+ description: "As etapas, da primeira \xE0 \xFAltima. Entre 4 e 7.",
1218
+ items: {
1219
+ type: "object",
1220
+ properties: {
1221
+ name: { type: "string", description: 'O estado do neg\xF3cio, como a casa fala. Ex.: "Proposta enviada".' },
1222
+ probability: { type: "number", description: "Chance de fechar nesta etapa, 0 a 100. Cresce ao longo do funil." },
1223
+ color: { type: "string", description: "Cor hex (#RRGGBB). Opcional \u2014 sem ela a paleta da tela escolhe." },
1224
+ isInitial: { type: "boolean", description: "Onde o lead entra. Exatamente uma." },
1225
+ isWon: { type: "boolean", description: "Venda fechada. Exatamente uma." },
1226
+ isLost: { type: "boolean", description: "Neg\xF3cio perdido. Exatamente uma." }
1227
+ },
1228
+ required: ["name"]
1229
+ }
1230
+ },
1231
+ replaceExisting: {
1232
+ type: "boolean",
1233
+ description: "Remove as etapas atuais que n\xE3o est\xE3o na lista. Etapa com neg\xF3cio dentro \xE9 mantida e devolvida em `kept`."
1234
+ }
1235
+ },
1236
+ ["stages"],
1237
+ // O único write que redesenha o quadro inteiro. O cartão de
1238
+ // confirmação é onde a pessoa lê as seis etapas como lista antes de
1239
+ // elas existirem — a decisão é dela, não da conversa.
1240
+ true
1241
+ ),
1242
+ execute: async ({ stages, replaceExisting }) => {
1243
+ const pipelineId = requirePipeline();
1244
+ if (typeof pipelineId !== "string") return pipelineId;
1245
+ const proposal = normalizeProposal(stages ?? []);
1246
+ if (!proposal.stages.length) return { error: "empty_proposal" };
1247
+ const before = deps.stages;
1248
+ const created = [];
1249
+ const updated = [];
1250
+ const orderedIds = [];
1251
+ for (const [i, s] of proposal.stages.entries()) {
1252
+ const existing = before.find((e) => normalizeStageName(e.name) === normalizeStageName(s.name));
1253
+ const saved = await deps.provider.saveStage({
1254
+ ...existing ? { id: existing.id } : {},
1255
+ pipelineId,
1256
+ name: s.name,
1257
+ color: s.color,
1258
+ probability: s.probability,
1259
+ isInitial: s.isInitial,
1260
+ isWon: s.isWon,
1261
+ isLost: s.isLost,
1262
+ order: i + 1
1263
+ });
1264
+ orderedIds.push(saved.id);
1265
+ (existing ? updated : created).push(s.name);
1266
+ }
1267
+ const removed = [];
1268
+ const kept = [];
1269
+ if (replaceExisting === true) {
1270
+ const keepIds = new Set(orderedIds);
1271
+ for (const stage of before) {
1272
+ if (keepIds.has(stage.id)) continue;
1273
+ try {
1274
+ await deps.provider.deleteStage(stage.id);
1275
+ removed.push(stage.name);
1276
+ } catch {
1277
+ kept.push(`${stage.name} (${deps.dealCountByStage.get(stage.id) ?? 0} neg\xF3cio(s))`);
1278
+ }
1279
+ }
1280
+ }
1281
+ await deps.provider.reorderStages(pipelineId, orderedIds);
1282
+ await deps.refresh();
1283
+ return {
1284
+ ok: true,
1285
+ funnel: activePipeline?.name,
1286
+ stages: proposal.stages.map((s) => s.name),
1287
+ created,
1288
+ updated,
1289
+ ...removed.length ? { removed } : {},
1290
+ ...kept.length ? { kept } : {},
1291
+ ...proposal.fixed.length ? { adjusted: proposal.fixed } : {}
1292
+ };
1293
+ }
1294
+ },
1295
+ {
1296
+ tool: tool(
1297
+ "crm.funnel.rename-stage",
1298
+ "renameFunnelStage",
1299
+ "Renomeia UMA etapa do funil aberto. O c\xF3digo interno n\xE3o muda, ent\xE3o nenhuma automa\xE7\xE3o apontada para ela quebra.",
1300
+ {
1301
+ currentName: { type: "string" },
1302
+ newName: { type: "string" }
1303
+ },
1304
+ ["currentName", "newName"]
1305
+ ),
1306
+ execute: async ({ currentName, newName }) => {
1307
+ const pipelineId = requirePipeline();
1308
+ if (typeof pipelineId !== "string") return pipelineId;
1309
+ const stage = findStage(String(currentName ?? ""));
1310
+ if (!stage) return { error: "stage_not_found", currentName, available: deps.stages.map((s) => s.name) };
1311
+ await deps.provider.saveStage({ id: stage.id, pipelineId, name: String(newName ?? "").trim() });
1312
+ await deps.refresh();
1313
+ return { ok: true, from: stage.name, to: newName };
1314
+ }
1315
+ },
1316
+ {
1317
+ tool: tool(
1318
+ "crm.funnel.reorder-stages",
1319
+ "reorderFunnelStages",
1320
+ "P\xF5e as etapas do funil aberto nesta ordem. Mande TODOS os nomes \u2014 o que ficar de fora vai para o fim.",
1321
+ { orderedNames: { type: "array", items: { type: "string" } } },
1322
+ ["orderedNames"]
1323
+ ),
1324
+ execute: async ({ orderedNames }) => {
1325
+ const pipelineId = requirePipeline();
1326
+ if (typeof pipelineId !== "string") return pipelineId;
1327
+ const named = (orderedNames ?? []).map((n) => findStage(n)).filter((s) => !!s);
1328
+ const missing = (orderedNames ?? []).filter((n) => !findStage(n));
1329
+ const rest = deps.stages.filter((s) => !named.some((n) => n.id === s.id));
1330
+ if (!named.length) return { error: "no_match", available: deps.stages.map((s) => s.name) };
1331
+ await deps.provider.reorderStages(pipelineId, [...named, ...rest].map((s) => s.id));
1332
+ await deps.refresh();
1333
+ return { ok: true, order: [...named, ...rest].map((s) => s.name), ...missing.length ? { unknown: missing } : {} };
1334
+ }
1335
+ },
1336
+ {
1337
+ tool: tool(
1338
+ "crm.funnel.remove-stage",
1339
+ "removeFunnelStage",
1340
+ "Remove UMA etapa do funil aberto. Recusa quando a etapa tem neg\xF3cio dentro \u2014 mova os cards primeiro.",
1341
+ { name: { type: "string" } },
1342
+ ["name"],
1343
+ true
1344
+ ),
1345
+ execute: async ({ name }) => {
1346
+ const stage = findStage(String(name ?? ""));
1347
+ if (!stage) return { error: "stage_not_found", name, available: deps.stages.map((s) => s.name) };
1348
+ try {
1349
+ await deps.provider.deleteStage(stage.id);
1350
+ } catch (e) {
1351
+ return { error: "stage_has_deals", name: stage.name, deals: deps.dealCountByStage.get(stage.id) ?? 0, message: e.message };
1352
+ }
1353
+ await deps.refresh();
1354
+ return { ok: true, removed: stage.name };
1355
+ }
1356
+ },
1357
+ {
1358
+ tool: tool(
1359
+ "crm.funnel.create",
1360
+ "createFunnel",
1361
+ "Cria um SEGUNDO funil (outra linha de neg\xF3cio, outro time). Nasce com tr\xEAs etapas padr\xE3o \u2014 redesenhe com applyFunnelStages depois.",
1362
+ {
1363
+ name: { type: "string" },
1364
+ makeDefault: { type: "boolean", description: "Passa a ser o funil padr\xE3o da casa." }
1365
+ },
1366
+ ["name"],
1367
+ true
1368
+ ),
1369
+ execute: async ({ name, makeDefault }) => {
1370
+ const created = await deps.provider.savePipeline({
1371
+ name: String(name ?? "").trim(),
1372
+ ...makeDefault === true ? { isDefault: true } : {}
1373
+ });
1374
+ await deps.refresh();
1375
+ return { ok: true, funnel: created.name, id: created.id };
1376
+ }
1377
+ }
1378
+ ];
1379
+ return {
1380
+ id: "crm.funnel",
1381
+ pluginId: "crm",
1382
+ instructions: INSTRUCTIONS,
1383
+ tools,
1384
+ describe: () => ({
1385
+ title: activePipeline ? `Funil \u2014 ${activePipeline.name}` : "Funil do CRM",
1386
+ state: {
1387
+ funnel: activePipeline?.name,
1388
+ allFunnels: deps.pipelines.map((p) => p.name),
1389
+ // O estado que decide a conversa: um funil ainda no padrão de fábrica
1390
+ // (Novo / Ganho / Perdido) é o caso que esta tela existe para
1391
+ // resolver, e o modelo precisa reconhecê-lo sem perguntar.
1392
+ stages: deps.stages.map((s) => ({
1393
+ name: s.name,
1394
+ probability: s.probability,
1395
+ entry: s.isInitial || void 0,
1396
+ won: s.isWon || void 0,
1397
+ lost: s.isLost || void 0,
1398
+ openDeals: deps.dealCountByStage.get(s.id) ?? 0
1399
+ })),
1400
+ looksUnconfigured: deps.stages.length > 0 && deps.stages.length <= 3
1401
+ }
1402
+ })
1403
+ };
1404
+ }, [deps.provider, deps.pipelines, deps.activePipelineId, deps.stages, deps.dealCountByStage, deps.refresh]);
1405
+ useAgentSurface(contribution);
1406
+ }
998
1407
  var CHIP_ROW = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition-colors hover:bg-muted";
999
1408
  function BoardFilterChip({ trigger, onClear, clearLabel, closeOnSelect, children }) {
1000
1409
  const [open, setOpen] = React.useState(false);
@@ -1226,7 +1635,11 @@ function DealCard({ deal, saving, currency, tagDefs, temperature, risk, display,
1226
1635
  }
1227
1636
  ),
1228
1637
  display.contact && deal.contactStatusName && deal.contactStatusDerivedFrom !== "no_activity" && /* @__PURE__ */ jsx(DotChip, { color: deal.contactStatusColor ?? "#64748b", label: deal.contactStatusName }),
1229
- display.tags && /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, max: 3 })
1638
+ display.tags && /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, max: 3 }),
1639
+ deal.status === "lost" && deal.lostReason && /* @__PURE__ */ jsxs("span", { className: "inline-flex h-[18px] items-center gap-1 rounded-full bg-destructive-soft px-1.5 text-[9px] font-medium text-destructive-soft-foreground", children: [
1640
+ /* @__PURE__ */ jsx(ThumbsDown, { className: "h-2.5 w-2.5 shrink-0" }),
1641
+ lostReasonLabel(deal.lostReason, t2)
1642
+ ] })
1230
1643
  ] }),
1231
1644
  /* @__PURE__ */ jsxs("div", { className: "mt-2 flex items-center justify-between gap-2 empty:mt-0", children: [
1232
1645
  display.value && deal.value > 0 ? /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold", children: formatCurrency(deal.value, currency) }) : /* @__PURE__ */ jsx("span", {}),
@@ -1405,10 +1818,11 @@ function StageCards({ stageId, deals, total, onLoadMore, loadMoreLabel, savingDe
1405
1818
  )
1406
1819
  ] });
1407
1820
  }
1408
- function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1821
+ function PipelineView({ onDealClick, onAddLead, onOpenSettings, onStageIntent, modeControl }) {
1409
1822
  const { currency } = useCrmConfig();
1410
1823
  const pipelines = useCrmStore((s) => s.pipelines);
1411
1824
  const activePipelineId = useCrmStore((s) => s.activePipelineId);
1825
+ const stagesPipelineId = useCrmStore((s) => s.stagesPipelineId);
1412
1826
  const stages = useCrmStore((s) => s.stages);
1413
1827
  const dealsByStage = useCrmStore((s) => s.dealsByStage);
1414
1828
  const dealStageTotals = useCrmStore((s) => s.dealStageTotals);
@@ -1429,6 +1843,7 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1429
1843
  const canArchive = useCanArchive();
1430
1844
  const provider = useCrmProvider();
1431
1845
  const [menu, setMenu] = useState(null);
1846
+ const [pendingLost, setPendingLost] = useState(null);
1432
1847
  const [team, setTeam] = useState(null);
1433
1848
  useEffect(() => {
1434
1849
  void loadTeamOrNull().then(setTeam);
@@ -1457,18 +1872,41 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1457
1872
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
1458
1873
  const [optimisticBoard, setOptimisticBoard] = useState(null);
1459
1874
  const t2 = useTranslation();
1875
+ const refreshFunnel = useCallback(async () => {
1876
+ await fetchPipelines();
1877
+ await refreshBoard();
1878
+ }, [fetchPipelines, refreshBoard]);
1879
+ usePipelineAgentSurface({
1880
+ provider,
1881
+ pipelines,
1882
+ activePipelineId,
1883
+ stages,
1884
+ dealCountByStage: dealStageTotals,
1885
+ refresh: refreshFunnel
1886
+ });
1887
+ const funnelAI = {
1888
+ prompt: t2("crm.pipeline.ai.prompt"),
1889
+ hint: t2("crm.pipeline.ai.hint"),
1890
+ intro: {
1891
+ pitch: t2("crm.pipeline.ai.pitch"),
1892
+ description: t2("crm.pipeline.ai.description"),
1893
+ suggestions: [
1894
+ { label: t2("crm.pipeline.ai.suggestionDescribe") },
1895
+ { label: t2("crm.pipeline.ai.suggestionReview") }
1896
+ ]
1897
+ }
1898
+ };
1460
1899
  const dragRef = useRef(null);
1461
1900
  const savingRef = useRef(savingDealIds);
1462
1901
  savingRef.current = savingDealIds;
1463
- const boardFilter = useMemo(() => ({
1464
- ...selectedTags.length ? { tags: selectedTags } : {},
1465
- ...searchNoBanco ? {
1466
- search: searchNoBanco,
1467
- // O de-para nome→slug vive aqui porque é aqui que o cadastro está.
1468
- searchTags: [...tagDefs?.values() ?? []].filter((d) => d.name.toLowerCase().includes(searchNoBanco.toLowerCase())).map((d) => d.slug)
1469
- } : {},
1470
- ...periodToRange(period, customFrom, customTo),
1471
- ...effectiveOwner ? { assignedToId: effectiveOwner } : {}
1902
+ const boardFilter = useMemo(() => buildBoardFilter({
1903
+ selectedTags,
1904
+ search: searchNoBanco,
1905
+ tagDefs,
1906
+ period,
1907
+ customFrom,
1908
+ customTo,
1909
+ owner: effectiveOwner
1472
1910
  }), [selectedTags, searchNoBanco, tagDefs, period, customFrom, customTo, effectiveOwner]);
1473
1911
  const filterKey = JSON.stringify(boardFilter);
1474
1912
  const availableTags = useMemo(() => [...tagDefs.keys()], [tagDefs]);
@@ -1556,7 +1994,7 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1556
1994
  if (!c) return false;
1557
1995
  return !c.phone && !c.email;
1558
1996
  }, [channels]);
1559
- const visibleStages = stages.filter((s) => !s.isLost);
1997
+ const visibleStages = stages;
1560
1998
  const rawBoard = optimisticBoard ?? dealsByStage;
1561
1999
  const query = useMemo(() => prepareDealQuery(search), [search]);
1562
2000
  const displayBoard = useMemo(() => {
@@ -1567,7 +2005,8 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1567
2005
  }
1568
2006
  return next;
1569
2007
  }, [rawBoard, query, tagDefs, unreachable]);
1570
- const boardPending = dealsByStage.size === 0 && (pipelinesLoading || dealsLoading || pipelines.length > 0 && stages.length > 0);
2008
+ const stagesLoadedForActive = !!activePipelineId && stagesPipelineId === activePipelineId;
2009
+ const boardPending = dealsByStage.size === 0 && (pipelinesLoading || dealsLoading || pipelines.length > 0 && !stagesLoadedForActive);
1571
2010
  function handleDragStart(dealId, fromStageId) {
1572
2011
  dragRef.current = { dealId, fromStageId };
1573
2012
  }
@@ -1582,6 +2021,21 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1582
2021
  }
1583
2022
  function commitMove(dealId, fromStageId, toStageId) {
1584
2023
  if (fromStageId === toStageId) return;
2024
+ const target = stages.find((s) => s.id === toStageId);
2025
+ if (target?.isLost) {
2026
+ setPendingLost({ dealId, fromStageId, toStageId });
2027
+ return;
2028
+ }
2029
+ if (onStageIntent && !target?.isWon) {
2030
+ const card = (optimisticBoard ?? dealsByStage).get(fromStageId)?.find((d) => d.id === dealId);
2031
+ if (card && target) {
2032
+ onStageIntent(card, target);
2033
+ return;
2034
+ }
2035
+ }
2036
+ applyMove(dealId, fromStageId, toStageId);
2037
+ }
2038
+ function applyMove(dealId, fromStageId, toStageId, lostReason) {
1585
2039
  const targetStage = stages.find((s) => s.id === toStageId);
1586
2040
  const currentBoard = optimisticBoard ?? dealsByStage;
1587
2041
  const nextBoard = new Map(currentBoard);
@@ -1590,6 +2044,8 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1590
2044
  if (!movedDeal) return;
1591
2045
  const updatedDeal = {
1592
2046
  ...movedDeal,
2047
+ status: targetStage?.isWon ? "won" : targetStage?.isLost ? "lost" : "open",
2048
+ lostReason: targetStage?.isLost ? lostReason : void 0,
1593
2049
  stageId: toStageId,
1594
2050
  stageName: targetStage?.name,
1595
2051
  stageColor: targetStage?.color,
@@ -1599,7 +2055,12 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1599
2055
  nextBoard.set(toStageId, [...nextBoard.get(toStageId) ?? [], updatedDeal]);
1600
2056
  setOptimisticBoard(nextBoard);
1601
2057
  setSavingDealIds((prev) => new Set(prev).add(dealId));
1602
- moveDealToStage(dealId, toStageId).then(() => {
2058
+ moveDealToStage(dealId, toStageId).then(async () => {
2059
+ const reasonWrite = targetStage?.isLost ? lostReason : movedDeal.lostReason ? "" : void 0;
2060
+ if (reasonWrite !== void 0) {
2061
+ await provider.updateDeal(dealId, { lostReason: reasonWrite });
2062
+ patchBoardDeal(dealId, { lostReason: reasonWrite || void 0 });
2063
+ }
1603
2064
  toast.success(t2("crm.pipeline.movedTo", { stage: targetStage?.name ?? "stage" }));
1604
2065
  }).catch(() => {
1605
2066
  setOptimisticBoard(null);
@@ -1851,7 +2312,10 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1851
2312
  /* @__PURE__ */ jsx(Filter, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
1852
2313
  /* @__PURE__ */ jsx("p", { className: "text-base font-semibold text-foreground", children: t2("crm.pipeline.noStages") }),
1853
2314
  /* @__PURE__ */ jsx("p", { className: "max-w-sm text-sm text-muted-foreground", children: t2("crm.pipeline.noStagesHint") }),
1854
- onOpenSettings && /* @__PURE__ */ jsx(Button, { className: "mt-3", onClick: onOpenSettings, children: t2("crm.pipeline.setupStages") })
2315
+ /* @__PURE__ */ jsxs("div", { className: "mt-3 flex flex-wrap items-center justify-center gap-2", children: [
2316
+ /* @__PURE__ */ jsx(AskAIButton, { ...funnelAI, label: t2("crm.pipeline.setupWithAI") }),
2317
+ onOpenSettings && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: onOpenSettings, children: t2("crm.pipeline.setupStages") })
2318
+ ] })
1855
2319
  ] })
1856
2320
  ) : /* @__PURE__ */ jsx(
1857
2321
  KanbanBoard,
@@ -1882,7 +2346,14 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1882
2346
  addCardLabel: t2("crm.pipeline.addLead"),
1883
2347
  dropProps: (col) => ({
1884
2348
  onDragOver: (e) => handleDragOver(col.id, e),
1885
- onDragLeave: () => {
2349
+ // O PISCA-PISCA. `dragleave` BORBULHA: passar do fundo da coluna
2350
+ // para cima de um card dispara "saí" na coluna, o `dragover`
2351
+ // seguinte repinta, e o realce liga e desliga a cada movimento do
2352
+ // mouse. Só é saída de verdade quando o destino do ponteiro está
2353
+ // fora desta coluna — `relatedTarget` é quem diz isso.
2354
+ onDragLeave: (e) => {
2355
+ const indo = e.relatedTarget;
2356
+ if (indo && e.currentTarget.contains(indo)) return;
1886
2357
  if (dragOverStageId === col.id) setDragOverStageId(null);
1887
2358
  },
1888
2359
  onDrop: () => handleDrop(col.id)
@@ -1913,6 +2384,18 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, modeControl }) {
1913
2384
  )
1914
2385
  }
1915
2386
  ),
2387
+ /* @__PURE__ */ jsx(
2388
+ LostReasonDialog,
2389
+ {
2390
+ open: pendingLost !== null,
2391
+ onCancel: () => setPendingLost(null),
2392
+ onConfirm: (reason) => {
2393
+ const p = pendingLost;
2394
+ setPendingLost(null);
2395
+ if (p) applyMove(p.dealId, p.fromStageId, p.toStageId, reason);
2396
+ }
2397
+ }
2398
+ ),
1916
2399
  menu && /* @__PURE__ */ jsx(
1917
2400
  BoardMenu,
1918
2401
  {
@@ -2096,6 +2579,7 @@ function DealListView({ onOpenDeal }) {
2096
2579
  const [search, setSearch] = usePersistedState("crm.deals.search", "");
2097
2580
  const [stage, setStage] = usePersistedState("crm.deals.stage", void 0);
2098
2581
  const [status, setStatus] = usePersistedState("crm.deals.status", void 0);
2582
+ const [outcome, setOutcome] = usePersistedState("crm.deals.outcome", "open");
2099
2583
  const [cohort, setCohort] = usePersistedState("crm.deals.cohort", void 0);
2100
2584
  const [city, setCity] = usePersistedState("crm.deals.city", void 0);
2101
2585
  const [companyName, setCompanyName] = usePersistedState("crm.deals.company", void 0);
@@ -2114,12 +2598,19 @@ function DealListView({ onOpenDeal }) {
2114
2598
  }, []);
2115
2599
  useEffect(() => {
2116
2600
  if (!activePipelineId) return;
2117
- void fetchDeals({ pipelineId: activePipelineId, status: "open", pageSize: LOAD_CAP });
2118
- }, [activePipelineId]);
2601
+ const desfecho = outcome === "all" ? ["open", "won", "lost"] : outcome;
2602
+ void fetchDeals({ pipelineId: activePipelineId, status: desfecho, pageSize: LOAD_CAP });
2603
+ }, [activePipelineId, outcome]);
2119
2604
  const stageOptions = useMemo(
2120
- () => stages.filter((s) => !s.isLost).map((s) => ({ value: s.id, label: s.name, dot: s.color })),
2605
+ () => stages.map((s) => ({ value: s.id, label: s.name, dot: s.color })),
2121
2606
  [stages]
2122
2607
  );
2608
+ const outcomeOptions = useMemo(() => [
2609
+ { value: "open", label: t2("crm.deals.outcomeOpen") },
2610
+ { value: "won", label: t2("crm.deals.outcomeWon") },
2611
+ { value: "lost", label: t2("crm.deals.outcomeLost") },
2612
+ { value: "all", label: t2("crm.deals.outcomeAll") }
2613
+ ], [t2]);
2123
2614
  const statusOptions = useMemo(() => {
2124
2615
  const base = optionsFrom(deals.map((d) => d.contactStatusName));
2125
2616
  const cores = /* @__PURE__ */ new Map();
@@ -2280,11 +2771,12 @@ function DealListView({ onOpenDeal }) {
2280
2771
  cohort && t2("crm.deals.cohort"),
2281
2772
  companyName && t2("crm.card.companyTitle")
2282
2773
  ].filter(Boolean);
2283
- const filtrosAtivos = (stage ? 1 : 0) + (status ? 1 : 0) + (cohort ? 1 : 0) + (city ? 1 : 0) + (companyName ? 1 : 0) + (tags.length ? 1 : 0) + (owner ? 1 : 0);
2774
+ const filtrosAtivos = (stage ? 1 : 0) + (status ? 1 : 0) + (cohort ? 1 : 0) + (outcome !== "open" ? 1 : 0) + (city ? 1 : 0) + (companyName ? 1 : 0) + (tags.length ? 1 : 0) + (owner ? 1 : 0);
2284
2775
  const limparFiltros = () => {
2285
2776
  setStage(void 0);
2286
2777
  setStatus(void 0);
2287
2778
  setCohort(void 0);
2779
+ setOutcome("open");
2288
2780
  setCity(void 0);
2289
2781
  setCompanyName(void 0);
2290
2782
  setTags([]);
@@ -2336,6 +2828,24 @@ function DealListView({ onOpenDeal }) {
2336
2828
  clearLabel: t2("crm.leads.filters.clear"),
2337
2829
  fields: [
2338
2830
  ...stageOptions.length > 0 ? [singleField("stage", t2("crm.dealSidebar.stage"), Filter, t2("crm.deals.allStages"), stageOptions, stage, setStage)] : [],
2831
+ {
2832
+ id: "outcome",
2833
+ label: t2("crm.deals.outcome"),
2834
+ icon: ThumbsDown,
2835
+ activeCount: outcome !== "open" ? 1 : 0,
2836
+ render: (close) => /* @__PURE__ */ jsx(Fragment, { children: outcomeOptions.map((o) => /* @__PURE__ */ jsx(
2837
+ FilterMenuRow,
2838
+ {
2839
+ active: outcome === o.value,
2840
+ onClick: () => {
2841
+ setOutcome(o.value);
2842
+ close();
2843
+ },
2844
+ children: /* @__PURE__ */ jsx("span", { className: "truncate", children: o.label })
2845
+ },
2846
+ o.value
2847
+ )) })
2848
+ },
2339
2849
  ...statusOptions.length > 0 ? [singleField("status", t2("crm.deals.colStatus"), SignalHigh, t2("crm.deals.allStatuses"), statusOptions, status, setStatus)] : [],
2340
2850
  ...cohortOptions.length > 0 ? [singleField("cohort", t2("crm.deals.cohort"), CalendarRange, t2("crm.deals.allCohorts"), cohortOptions, cohort, setCohort)] : [],
2341
2851
  ...tagOptions.length > 0 ? [{
@@ -2392,6 +2902,17 @@ function DealListView({ onOpenDeal }) {
2392
2902
  onChange: setStage
2393
2903
  }
2394
2904
  ),
2905
+ outcome !== "open" && /* @__PURE__ */ jsx(
2906
+ FilterChip,
2907
+ {
2908
+ label: t2("crm.deals.outcome"),
2909
+ icon: ThumbsDown,
2910
+ allLabel: t2("crm.deals.outcomeOpen"),
2911
+ options: outcomeOptions,
2912
+ value: outcome,
2913
+ onChange: (v) => setOutcome(v ?? "open")
2914
+ }
2915
+ ),
2395
2916
  status && /* @__PURE__ */ jsx(
2396
2917
  FilterChip,
2397
2918
  {
@@ -2616,9 +3137,15 @@ function DealFunnelView({ onStageClick }) {
2616
3137
  const funnel = useCrmStore((s) => s.funnel);
2617
3138
  const fetchFunnel = useCrmStore((s) => s.fetchFunnel);
2618
3139
  const activePipelineId = useCrmStore((s) => s.activePipelineId);
3140
+ const [myUserId, setMyUserId] = useState(null);
2619
3141
  useEffect(() => {
2620
- if (activePipelineId) void fetchFunnel(activePipelineId);
2621
- }, [activePipelineId]);
3142
+ void loadMyUserId().then(setMyUserId);
3143
+ }, []);
3144
+ const boardFilter = useBoardFilterValue(myUserId);
3145
+ const filterKey = JSON.stringify(boardFilter);
3146
+ useEffect(() => {
3147
+ if (activePipelineId) void fetchFunnel(activePipelineId, boardFilter);
3148
+ }, [activePipelineId, filterKey]);
2622
3149
  if (!funnel.length) {
2623
3150
  return /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 rounded-lg border border-dashed py-12 text-center", children: [
2624
3151
  /* @__PURE__ */ jsx(Filter, { className: "mb-2 h-9 w-9 text-muted-foreground/40", strokeWidth: 1.5 }),
@@ -3241,7 +3768,12 @@ var T = {
3241
3768
  // são invisíveis para a raiz do CNPJ, e são metade dos casos reais.
3242
3769
  companyBrandCandidates: "v_crm_company_brand_candidates",
3243
3770
  companyGroupRollup: "v_crm_company_group_rollup",
3244
- leadDuplicates: "v_crm_lead_duplicates"
3771
+ leadDuplicates: "v_crm_lead_duplicates",
3772
+ // O funil com os vínculos já agregados (060). A tela lê daqui; as duas
3773
+ // tabelas abaixo são para ESCREVER o vínculo.
3774
+ pipelinesView: "v_crm_pipelines",
3775
+ pipelineUnits: "plg_crm_pipeline_units",
3776
+ pipelineTeams: "plg_crm_pipeline_teams"
3245
3777
  };
3246
3778
  function PartnerUnitsInput({ value, onChange }) {
3247
3779
  const t2 = useTranslation();
@@ -3466,20 +3998,43 @@ var tagEntity = {
3466
3998
  ],
3467
3999
  data: { table: T.tags, tenantScoped: true }
3468
4000
  };
3469
- var pipelineEntity = {
3470
- name: "Pipeline",
3471
- namePlural: "Pipelines",
3472
- icon: "GitBranch",
3473
- displayField: "name",
3474
- defaultSort: "name",
4001
+ var pipelineUnitEntity = {
4002
+ name: "Unit",
4003
+ namePlural: "Units",
4004
+ icon: "Building2",
4005
+ displayField: "unitId",
3475
4006
  fields: [
3476
- { key: "name", label: "Name", type: "text", required: true, showInTable: true, searchable: true },
3477
- // One default per tenant; the provider clears the flag on the others when
3478
- // this one is set. It is the funnel a lead falls into when nobody chose.
3479
- { key: "isDefault", label: "Default", type: "boolean", showInTable: true, defaultValue: false },
3480
- { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
4007
+ {
4008
+ key: "unitId",
4009
+ label: "Unit",
4010
+ type: "relation",
4011
+ required: true,
4012
+ showInTable: true,
4013
+ relation: { table: "v_units", labelField: "name" }
4014
+ },
4015
+ { key: "pipelineId", label: "Pipeline", type: "relation", required: true, relation: { table: T.pipelines, labelField: "name" } }
3481
4016
  ],
3482
- data: { table: T.pipelines, tenantScoped: true }
4017
+ data: { table: T.pipelineUnits, tenantScoped: true }
4018
+ };
4019
+ var pipelineTeamEntity = {
4020
+ name: "Team",
4021
+ namePlural: "Teams",
4022
+ icon: "Users",
4023
+ displayField: "teamId",
4024
+ fields: [
4025
+ {
4026
+ key: "teamId",
4027
+ label: "Team",
4028
+ type: "relation",
4029
+ required: true,
4030
+ showInTable: true,
4031
+ // A equipe é a categoria `staff_team` (139 do espinha) — a mesma que os
4032
+ // Cadastros criam na aba Equipes dos Profissionais.
4033
+ relation: { table: "categories", labelField: "name", filter: { kind: "staff_team" } }
4034
+ },
4035
+ { key: "pipelineId", label: "Pipeline", type: "relation", required: true, relation: { table: T.pipelines, labelField: "name" } }
4036
+ ],
4037
+ data: { table: T.pipelineTeams, tenantScoped: true }
3483
4038
  };
3484
4039
  var pipelineStageEntity = {
3485
4040
  name: "Stage",
@@ -3515,6 +4070,50 @@ var pipelineStageEntity = {
3515
4070
  ],
3516
4071
  data: { table: T.pipelineStages, tenantScoped: true }
3517
4072
  };
4073
+ var pipelineEntity = {
4074
+ name: "Pipeline",
4075
+ namePlural: "Pipelines",
4076
+ icon: "GitBranch",
4077
+ displayField: "name",
4078
+ defaultSort: "name",
4079
+ fields: [
4080
+ { key: "name", label: "Name", type: "text", required: true, showInTable: true, searchable: true },
4081
+ // One default per tenant; the provider clears the flag on the others when
4082
+ // this one is set. It is the funnel a lead falls into when nobody chose.
4083
+ { key: "isDefault", label: "Default", type: "boolean", showInTable: true, defaultValue: false },
4084
+ { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
4085
+ ],
4086
+ // O funil ABERTO mostra o que é dele: as etapas primeiro, porque são o
4087
+ // funil, e depois para quem ele serve. Antes as etapas moravam numa lista
4088
+ // irmã com uma coluna "Pipeline" — para saber as etapas DESTE funil era
4089
+ // preciso sair dele e filtrar uma lista de todos.
4090
+ relatedLists: [
4091
+ { id: "stages", label: "Stages", icon: "Workflow", entity: pipelineStageEntity, foreignKey: "pipelineId" }
4092
+ ],
4093
+ // Unidades e equipes são SEÇÃO, não aba: são duas ou três pastilhas, e para
4094
+ // quem o funil serve se lê junto com o nome dele. Numa aba própria seriam
4095
+ // dois cliques para descobrir uma linha de configuração — e quem abre o
4096
+ // funil para conferir o recorte teria de abrir as duas.
4097
+ relatedSections: [
4098
+ {
4099
+ id: "units",
4100
+ label: "Units",
4101
+ icon: "Building2",
4102
+ entity: pipelineUnitEntity,
4103
+ foreignKey: "pipelineId",
4104
+ emptyHint: "Sem unidade: este funil serve a conta inteira."
4105
+ },
4106
+ {
4107
+ id: "teams",
4108
+ label: "Teams",
4109
+ icon: "Users",
4110
+ entity: pipelineTeamEntity,
4111
+ foreignKey: "pipelineId",
4112
+ emptyHint: "Sem equipe: este funil serve todas as equipes."
4113
+ }
4114
+ ],
4115
+ data: { table: T.pipelines, tenantScoped: true }
4116
+ };
3518
4117
  var dealStatusEntity = {
3519
4118
  name: "Contact status",
3520
4119
  namePlural: "Contact statuses",
@@ -3762,6 +4361,68 @@ function buildCrmRegistries(activityTypes) {
3762
4361
  } : registry
3763
4362
  );
3764
4363
  }
4364
+ function LinkCompanyPrompt({ personId, companyText, onLinked }) {
4365
+ const t2 = useTranslation();
4366
+ const provider = useCrmProvider();
4367
+ const saveCompany = useCrmStore((s) => s.saveCompany);
4368
+ const [existente, setExistente] = useState(null);
4369
+ const [ligando, setLigando] = useState(false);
4370
+ const nome = companyText?.trim();
4371
+ useEffect(() => {
4372
+ if (!nome) {
4373
+ setExistente(null);
4374
+ return;
4375
+ }
4376
+ let vivo = true;
4377
+ provider.searchCompanies(nome, 5).then((rs) => {
4378
+ if (!vivo) return;
4379
+ const exato = rs.find((r) => r.name.trim().toLowerCase() === nome.toLowerCase());
4380
+ setExistente(exato ? { id: exato.id, name: exato.name } : null);
4381
+ }).catch(() => {
4382
+ if (vivo) setExistente(null);
4383
+ });
4384
+ return () => {
4385
+ vivo = false;
4386
+ };
4387
+ }, [provider, nome]);
4388
+ if (!nome) return null;
4389
+ async function vincular() {
4390
+ if (!nome || ligando) return;
4391
+ setLigando(true);
4392
+ try {
4393
+ const companyId = existente?.id ?? (await saveCompany({ name: nome })).id;
4394
+ await provider.linkCompanyPerson({ companyId, personId, isPrimary: true });
4395
+ toast.success(t2("crm.linkCompany.done", { name: nome }));
4396
+ onLinked?.(companyId);
4397
+ } catch (err) {
4398
+ toast.error(t2("crm.linkCompany.failed"), { description: err?.message });
4399
+ } finally {
4400
+ setLigando(false);
4401
+ }
4402
+ }
4403
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-card border border-dashed bg-muted/20 px-3 py-3", children: [
4404
+ /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4405
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4406
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: nome }),
4407
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] text-muted-foreground", children: t2(existente ? "crm.linkCompany.hintExisting" : "crm.linkCompany.hintNew") })
4408
+ ] }),
4409
+ /* @__PURE__ */ jsxs(
4410
+ "button",
4411
+ {
4412
+ type: "button",
4413
+ onClick: () => {
4414
+ void vincular();
4415
+ },
4416
+ disabled: ligando,
4417
+ className: "inline-flex shrink-0 items-center gap-1.5 rounded-button bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-button transition-opacity hover:opacity-90 disabled:opacity-60",
4418
+ children: [
4419
+ ligando ? /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }) : /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3" }),
4420
+ t2(existente ? "crm.linkCompany.link" : "crm.linkCompany.create")
4421
+ ]
4422
+ }
4423
+ )
4424
+ ] });
4425
+ }
3765
4426
  var STYLE = {
3766
4427
  hot: { icon: Flame, cls: "bg-destructive-soft text-destructive-soft-foreground" },
3767
4428
  warm: { icon: Sun, cls: "bg-warning-soft text-warning-soft-foreground" },
@@ -3899,7 +4560,7 @@ function CopyDocument({ document: doc, label: label2 }) {
3899
4560
  }
3900
4561
  );
3901
4562
  }
3902
- function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewCompany, onCreateQuote, seed }) {
4563
+ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewCompany, onCreateQuote, seed, pendingStage, onPendingResolved }) {
3903
4564
  const t2 = useTranslation();
3904
4565
  const provider = useCrmProvider();
3905
4566
  const { currency } = useCrmConfig();
@@ -3909,6 +4570,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3909
4570
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
3910
4571
  const patchBoardDeal = useCrmStore((s) => s.patchBoardDeal);
3911
4572
  const removeBoardDeal = useCrmStore((s) => s.removeBoardDeal);
4573
+ const refreshBoard = useCrmStore((s) => s.refreshBoard);
3912
4574
  const tagDefs = useCrmStore((s) => s.tagDefs);
3913
4575
  const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3914
4576
  const [deal, setDeal] = useState(null);
@@ -3922,6 +4584,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3922
4584
  const [movingStage, setMovingStage] = useState(false);
3923
4585
  const [saving, setSaving] = useState(false);
3924
4586
  const [closing, setClosing] = useState(false);
4587
+ const [askingLost, setAskingLost] = useState(false);
3925
4588
  const [draft, setDraft] = useState(null);
3926
4589
  const [company, setCompany] = useState(null);
3927
4590
  const [pessoasDaCasa, setPessoasDaCasa] = useState([]);
@@ -3998,6 +4661,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3998
4661
  const id = requestAnimationFrame(() => composerRef.current?.focus());
3999
4662
  return () => cancelAnimationFrame(id);
4000
4663
  }, [composerOpen]);
4664
+ useEffect(() => {
4665
+ if (open && pendingStage) setComposerOpen(true);
4666
+ }, [open, pendingStage?.id]);
4001
4667
  useEffect(() => {
4002
4668
  if (!seed || seed.id !== dealId) return;
4003
4669
  setDeal((d) => d && d.id === seed.id && d.stageId !== seed.stageId ? { ...d, stageId: seed.stageId, stageName: seed.stageName, stageColor: seed.stageColor, probability: seed.probability } : d);
@@ -4069,6 +4735,11 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4069
4735
  assignedToId: deal?.assignedToId
4070
4736
  }) : void 0;
4071
4737
  setActivities((prev) => futureTask ? [futureTask, logged, ...prev] : [logged, ...prev]);
4738
+ if (pendingStage && deal && pendingStage.id !== deal.stageId) {
4739
+ await moveDealToStage(deal.id, pendingStage.id);
4740
+ setDeal({ ...deal, stageId: pendingStage.id, stageName: pendingStage.name, stageColor: pendingStage.color, probability: pendingStage.probability });
4741
+ onPendingResolved?.(true);
4742
+ }
4072
4743
  setCnote("");
4073
4744
  setCoutcome("connected");
4074
4745
  setCfutureDate("");
@@ -4187,20 +4858,18 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4187
4858
  setMovingStage(false);
4188
4859
  }
4189
4860
  }
4190
- async function close(outcome) {
4861
+ async function close(outcome, reason) {
4191
4862
  if (!deal || closing) return;
4192
- let reason;
4193
- if (outcome === "lost") {
4194
- const answer = window.prompt(t2("crm.card.lostReasonPrompt"));
4195
- if (answer === null) return;
4196
- reason = answer.trim() || void 0;
4197
- }
4198
4863
  setClosing(true);
4199
4864
  try {
4865
+ const lostStage = outcome === "lost" ? stages.find((s) => s.isLost) : void 0;
4866
+ if (lostStage && lostStage.id !== deal.stageId) await moveDealToStage(deal.id, lostStage.id);
4200
4867
  const patched = await provider.updateDeal(deal.id, { status: outcome, lostReason: reason });
4201
4868
  setDeal(patched);
4202
- if (outcome === "lost") removeBoardDeal(deal.id);
4203
- else patchBoardDeal(deal.id, { status: "won" });
4869
+ if (outcome === "lost") {
4870
+ if (lostStage) void refreshBoard();
4871
+ else removeBoardDeal(deal.id);
4872
+ } else patchBoardDeal(deal.id, { status: "won" });
4204
4873
  const refreshed = await provider.getActivities({ dealId });
4205
4874
  setActivities(refreshed.data);
4206
4875
  toast.success(t2(outcome === "won" ? "crm.card.markedWon" : "crm.card.markedLost"));
@@ -4276,414 +4945,460 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4276
4945
  setSaving(false);
4277
4946
  }
4278
4947
  }
4279
- return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
4280
- if (!o) onClose();
4281
- }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4282
- /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4283
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
4284
- /* @__PURE__ */ jsx(ModalTitle, { className: "min-w-0 flex-1 truncate text-base", children: loading && !deal ? /* @__PURE__ */ jsx("span", { className: "inline-block h-5 w-40 animate-pulse rounded bg-muted/40 align-middle" }) : deal ? dealHeadline(deal) || t2("crm.dealSidebar.deal") : t2("crm.dealSidebar.deal") }),
4285
- /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4286
- deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => {
4287
- void close("lost");
4288
- }, children: [
4289
- /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4290
- " ",
4291
- t2("crm.card.markLost")
4292
- ] }) : deal ? /* @__PURE__ */ jsxs(
4293
- "span",
4294
- {
4295
- className: "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium " + (deal.status === "won" ? "bg-success-soft text-success-soft-foreground" : "bg-destructive-soft text-destructive-soft-foreground"),
4296
- title: deal.lostReason ?? void 0,
4297
- children: [
4298
- deal.status === "won" ? /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4299
- t2(deal.status === "won" ? "crm.card.won" : "crm.card.lost"),
4300
- deal.lostReason && /* @__PURE__ */ jsxs("span", { className: "font-normal opacity-80", children: [
4301
- "\xB7 ",
4302
- deal.lostReason
4948
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
4949
+ /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
4950
+ if (!o) onClose();
4951
+ }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4952
+ /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4953
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
4954
+ /* @__PURE__ */ jsx(ModalTitle, { className: "min-w-0 flex-1 truncate text-base", children: loading && !deal ? /* @__PURE__ */ jsx("span", { className: "inline-block h-5 w-40 animate-pulse rounded bg-muted/40 align-middle" }) : deal ? dealHeadline(deal) || t2("crm.dealSidebar.deal") : t2("crm.dealSidebar.deal") }),
4955
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4956
+ deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => setAskingLost(true), children: [
4957
+ /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4958
+ " ",
4959
+ t2("crm.card.markLost")
4960
+ ] }) : deal ? /* @__PURE__ */ jsxs(
4961
+ "span",
4962
+ {
4963
+ className: "inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-medium " + (deal.status === "won" ? "bg-success-soft text-success-soft-foreground" : "bg-destructive-soft text-destructive-soft-foreground"),
4964
+ title: lostReasonLabel(deal.lostReason, t2),
4965
+ children: [
4966
+ deal.status === "won" ? /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4967
+ t2(deal.status === "won" ? "crm.card.won" : "crm.card.lost"),
4968
+ deal.lostReason && /* @__PURE__ */ jsxs("span", { className: "font-normal opacity-80", children: [
4969
+ "\xB7 ",
4970
+ lostReasonLabel(deal.lostReason, t2)
4971
+ ] })
4972
+ ]
4973
+ }
4974
+ ) : null,
4975
+ deal && (onCreateQuote || onViewLead || canArchive) && /* @__PURE__ */ jsxs(Dropdown, { children: [
4976
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", "aria-label": t2("crm.card.moreActions"), className: "h-8 w-8 p-0", children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }) }) }),
4977
+ /* @__PURE__ */ jsxs(DropdownContent, { align: "end", children: [
4978
+ onCreateQuote && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onCreateQuote(lead.id), children: [
4979
+ /* @__PURE__ */ jsx(FileText, { className: "h-3.5 w-3.5" }),
4980
+ " ",
4981
+ t2("crm.leadDetail.createQuote")
4982
+ ] }),
4983
+ onViewLead && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onViewLead(lead.id), children: [
4984
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5" }),
4985
+ " ",
4986
+ t2("crm.dealSidebar.viewLeadProfile")
4987
+ ] }),
4988
+ canArchive && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => {
4989
+ void archiveDeal(deal.id).then(onClose);
4990
+ }, children: [
4991
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
4992
+ " ",
4993
+ t2("crm.pipeline.archive")
4303
4994
  ] })
4304
- ]
4305
- }
4306
- ) : null,
4307
- deal && (onCreateQuote || onViewLead || canArchive) && /* @__PURE__ */ jsxs(Dropdown, { children: [
4308
- /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", "aria-label": t2("crm.card.moreActions"), className: "h-8 w-8 p-0", children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" }) }) }),
4309
- /* @__PURE__ */ jsxs(DropdownContent, { align: "end", children: [
4310
- onCreateQuote && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onCreateQuote(lead.id), children: [
4311
- /* @__PURE__ */ jsx(FileText, { className: "h-3.5 w-3.5" }),
4312
- " ",
4313
- t2("crm.leadDetail.createQuote")
4314
- ] }),
4315
- onViewLead && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onViewLead(lead.id), children: [
4316
- /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5" }),
4317
- " ",
4318
- t2("crm.dealSidebar.viewLeadProfile")
4319
- ] }),
4320
- canArchive && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => {
4321
- void archiveDeal(deal.id).then(onClose);
4322
- }, children: [
4323
- /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
4324
- " ",
4325
- t2("crm.pipeline.archive")
4326
4995
  ] })
4327
4996
  ] })
4328
4997
  ] })
4329
- ] })
4330
- ] }),
4331
- deal?.status === "open" && (journeyStages.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [
4332
- journeyStages.map((s) => {
4333
- const active = s.id === deal?.stageId;
4334
- return /* @__PURE__ */ jsxs(
4335
- "button",
4336
- {
4337
- type: "button",
4338
- disabled: movingStage,
4339
- onClick: () => {
4340
- void changeStage(s);
4998
+ ] }),
4999
+ deal?.status === "open" && (journeyStages.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [
5000
+ journeyStages.map((s) => {
5001
+ const active = s.id === deal?.stageId;
5002
+ return /* @__PURE__ */ jsxs(
5003
+ "button",
5004
+ {
5005
+ type: "button",
5006
+ disabled: movingStage,
5007
+ onClick: () => {
5008
+ void changeStage(s);
5009
+ },
5010
+ "aria-pressed": active,
5011
+ className: "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors disabled:opacity-60 " + (active ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-muted hover:text-foreground"),
5012
+ children: [
5013
+ /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: s.color } }),
5014
+ s.name
5015
+ ]
4341
5016
  },
4342
- "aria-pressed": active,
4343
- className: "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium transition-colors disabled:opacity-60 " + (active ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-muted hover:text-foreground"),
4344
- children: [
4345
- /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: s.color } }),
4346
- s.name
4347
- ]
4348
- },
4349
- s.id
4350
- );
4351
- }),
4352
- movingStage && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-muted-foreground" }),
4353
- /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", disabled: closing, onClick: () => {
4354
- void close("won");
4355
- }, children: [
4356
- /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3 text-success" }),
4357
- " ",
4358
- t2("crm.card.markWon")
4359
- ] })
4360
- ] }) : /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1.5", "aria-hidden": true, children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsx("div", { className: "h-[26px] w-20 animate-pulse rounded-full bg-muted/40" }, i)) }))
4361
- ] }),
4362
- /* @__PURE__ */ jsx(ModalBody, { className: wide ? "overflow-hidden p-0" : "sm:max-h-[70vh] overflow-y-auto p-0", children: loading || !draft ? (
4363
- // O esqueleto tem a MESMA silhueta das três colunas — carregar não
4364
- // pode trocar o desenho da tela no meio.
4365
- /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
4366
- /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-5", style: wide ? { width: "18rem" } : void 0, children: [
4367
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2", children: [
4368
- /* @__PURE__ */ jsx("div", { className: "h-14 w-14 animate-pulse rounded-full bg-muted/40" }),
4369
- /* @__PURE__ */ jsx("div", { className: "h-4 w-32 animate-pulse rounded bg-muted/40" }),
4370
- /* @__PURE__ */ jsx("div", { className: "h-3 w-24 animate-pulse rounded bg-muted/30" })
5017
+ s.id
5018
+ );
5019
+ }),
5020
+ movingStage && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-muted-foreground" }),
5021
+ /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", disabled: closing, onClick: () => {
5022
+ void close("won");
5023
+ }, children: [
5024
+ /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3 text-success" }),
5025
+ " ",
5026
+ t2("crm.card.markWon")
5027
+ ] })
5028
+ ] }) : /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1.5", "aria-hidden": true, children: [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsx("div", { className: "h-[26px] w-20 animate-pulse rounded-full bg-muted/40" }, i)) }))
5029
+ ] }),
5030
+ /* @__PURE__ */ jsx(ModalBody, { className: wide ? "overflow-hidden p-0" : "sm:max-h-[70vh] overflow-y-auto p-0", children: loading || !draft ? (
5031
+ // O esqueleto tem a MESMA silhueta das três colunas — carregar não
5032
+ // pode trocar o desenho da tela no meio.
5033
+ /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
5034
+ /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-5", style: wide ? { width: "18rem" } : void 0, children: [
5035
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2", children: [
5036
+ /* @__PURE__ */ jsx("div", { className: "h-14 w-14 animate-pulse rounded-full bg-muted/40" }),
5037
+ /* @__PURE__ */ jsx("div", { className: "h-4 w-32 animate-pulse rounded bg-muted/40" }),
5038
+ /* @__PURE__ */ jsx("div", { className: "h-3 w-24 animate-pulse rounded bg-muted/30" })
5039
+ ] }),
5040
+ [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/30" }, i))
4371
5041
  ] }),
4372
- [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/30" }, i))
4373
- ] }),
4374
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
4375
- /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/40" }),
4376
- [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-14 animate-pulse rounded-lg bg-muted/30" }, i))
4377
- ] }),
4378
- wide && /* @__PURE__ */ jsx("div", { className: "space-y-3 p-5", style: { width: "18rem" }, children: [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-16 animate-pulse rounded-lg bg-muted/30" }, i)) })
4379
- ] })
4380
- ) : /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
4381
- /* @__PURE__ */ jsxs("div", { className: (wide ? "min-h-0 shrink-0 overflow-y-auto border-r" : "border-b") + " space-y-5 p-5", style: wide ? { width: "18rem" } : void 0, children: [
4382
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2 text-center", children: [
4383
- /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
4384
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4385
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: draft.name || deal?.contactName || "\u2014" }),
4386
- (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company }),
4387
- pessoaDoCard?.companyRole && /* @__PURE__ */ jsx("p", { className: "truncate text-[11px] text-muted-foreground/80", children: pessoaDoCard.companyRole })
5042
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
5043
+ /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/40" }),
5044
+ [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-14 animate-pulse rounded-lg bg-muted/30" }, i))
5045
+ ] }),
5046
+ wide && /* @__PURE__ */ jsx("div", { className: "space-y-3 p-5", style: { width: "18rem" }, children: [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-16 animate-pulse rounded-lg bg-muted/30" }, i)) })
5047
+ ] })
5048
+ ) : /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
5049
+ /* @__PURE__ */ jsxs("div", { className: (wide ? "min-h-0 shrink-0 overflow-y-auto border-r" : "border-b") + " space-y-5 p-5", style: wide ? { width: "18rem" } : void 0, children: [
5050
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2 text-center", children: [
5051
+ /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
5052
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
5053
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: draft.name || deal?.contactName || "\u2014" }),
5054
+ (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company }),
5055
+ pessoaDoCard?.companyRole && /* @__PURE__ */ jsx("p", { className: "truncate text-[11px] text-muted-foreground/80", children: pessoaDoCard.companyRole })
5056
+ ] }),
5057
+ score === void 0 ? /* @__PURE__ */ jsx("span", { className: "h-5 w-20 animate-pulse rounded-full bg-muted/40", "aria-hidden": true }) : score ? /* @__PURE__ */ jsx(TemperatureBadge, { score }) : null,
5058
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-center gap-3 pt-1", children: [
5059
+ pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
5060
+ /* @__PURE__ */ jsx(
5061
+ TalkToPerson,
5062
+ {
5063
+ personId: pessoaDoCard.id,
5064
+ name: pessoaDoCard.name,
5065
+ phone: pessoaDoCard.phone,
5066
+ variant: "icon",
5067
+ className: "flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm transition-opacity hover:opacity-85"
5068
+ }
5069
+ ),
5070
+ /* @__PURE__ */ jsx("span", { className: "text-[10px] text-muted-foreground", children: t2("crm.card.quickTalk") })
5071
+ ] }),
5072
+ /* @__PURE__ */ jsx(QuickAction, { icon: Phone, label: t2("crm.card.quickCall"), href: draft.phone ? `tel:${draft.phone}` : void 0, onClick: draft.phone ? () => prepActivity("call") : void 0 }),
5073
+ /* @__PURE__ */ jsx(QuickAction, { icon: Mail, label: t2("crm.card.quickEmail"), href: draft.email ? `mailto:${draft.email}` : void 0, onClick: draft.email ? () => prepActivity("email") : void 0 }),
5074
+ /* @__PURE__ */ jsx(QuickAction, { icon: Pencil, label: t2("crm.card.quickNote"), onClick: () => prepActivity("note") })
5075
+ ] })
4388
5076
  ] }),
4389
- score === void 0 ? /* @__PURE__ */ jsx("span", { className: "h-5 w-20 animate-pulse rounded-full bg-muted/40", "aria-hidden": true }) : score ? /* @__PURE__ */ jsx(TemperatureBadge, { score }) : null,
4390
- /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-center gap-3 pt-1", children: [
4391
- pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
5077
+ /* @__PURE__ */ jsx(Section, { title: t2("crm.card.pointOfContact"), children: /* @__PURE__ */ jsx(
5078
+ PersonPicker,
5079
+ {
5080
+ options: pessoasDaCasa.map((x) => ({
5081
+ id: x.personId,
5082
+ name: x.personName ?? "\u2014",
5083
+ // De QUAL casa, quando o negócio carrega mais de uma
5084
+ // (057). Sem isto, duas pessoas de CNPJs diferentes
5085
+ // ficam duas linhas iguais, e escolher vira sorteio.
5086
+ subtitle: [x.role, casasDoNegocio > 1 ? x.companyName : null].filter(Boolean).join(" \xB7 ") || null
5087
+ })),
5088
+ value: deal?.contactId ?? null,
5089
+ onChange: (id) => {
5090
+ void trocarPontoDeContato(id);
5091
+ },
5092
+ placeholder: t2("crm.card.pointOfContactEmpty"),
5093
+ disabled: trocandoContato || pessoasDaCasa.length === 0
5094
+ }
5095
+ ) }),
5096
+ /* @__PURE__ */ jsx(
5097
+ Section,
5098
+ {
5099
+ title: t2("crm.card.about"),
5100
+ action: /* @__PURE__ */ jsx(
5101
+ "button",
5102
+ {
5103
+ type: "button",
5104
+ onClick: () => setEditing((e) => !e),
5105
+ title: t2("crm.card.edit"),
5106
+ className: "rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
5107
+ children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
5108
+ }
5109
+ ),
5110
+ children: !editing ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
5111
+ /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.phone"), value: draft.phone }),
5112
+ /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.email"), value: draft.email }),
5113
+ /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.value"), value: draft.value ? formatCurrency(draft.value, currency) : void 0 }),
5114
+ /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.expectedClose"), value: draft.expectedCloseDate }),
5115
+ draft.notes && /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.notes"), value: /* @__PURE__ */ jsx("span", { className: "whitespace-pre-wrap text-xs", children: draft.notes }) })
5116
+ ] }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
5117
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.name"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }) }) }),
5118
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.phone"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.phone, onChange: (e) => setDraft({ ...draft, phone: e.target.value }) }) }),
5119
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.email"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", type: "email", value: draft.email, onChange: (e) => setDraft({ ...draft, email: e.target.value }) }) }),
5120
+ !company && /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.company"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.company, onChange: (e) => setDraft({ ...draft, company: e.target.value }) }) }),
5121
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.value"), children: /* @__PURE__ */ jsx(CurrencyInput, { value: draft.value, onChange: (v) => setDraft({ ...draft, value: v ?? 0 }) }) }),
5122
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.expectedClose"), children: /* @__PURE__ */ jsx(DatePicker, { value: draft.expectedCloseDate, onChange: (v) => setDraft({ ...draft, expectedCloseDate: v }) }) }),
5123
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.notes"), children: /* @__PURE__ */ jsx(
5124
+ "textarea",
5125
+ {
5126
+ rows: 3,
5127
+ value: draft.notes,
5128
+ onChange: (e) => setDraft({ ...draft, notes: e.target.value }),
5129
+ className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
5130
+ }
5131
+ ) }),
5132
+ /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
5133
+ /* @__PURE__ */ jsxs(Button, { className: "flex-1", onClick: () => {
5134
+ void save().then(() => setEditing(false));
5135
+ }, disabled: saving, children: [
5136
+ saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
5137
+ t2("crm.card.save")
5138
+ ] }),
5139
+ /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setEditing(false), children: t2("crm.card.cancelEdit") })
5140
+ ] })
5141
+ ] })
5142
+ }
5143
+ ),
5144
+ /* @__PURE__ */ jsx(Section, { title: t2("crm.card.owner"), children: team === null ? /* @__PURE__ */ jsx("div", { className: "h-9 animate-pulse rounded-lg bg-muted/40", "aria-hidden": true }) : team.length === 0 ? (
5145
+ // Lista vazia aqui quase sempre é falta de `members.read`, e
5146
+ // não uma casa sem equipe. Dizer "ninguém" seria mentir.
5147
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
5148
+ ) : (
5149
+ // Uma linha só: quem é o dono (PersonPicker, com o retrato
5150
+ // — o rosto é o que distingue duas Anas em meio segundo) e,
5151
+ // ao lado, o ASSUMIR de um clique. Pegar a fila é o gesto
5152
+ // mais repetido do dia de prospecção; o botão some quando o
5153
+ // negócio já é de quem olha.
5154
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4392
5155
  /* @__PURE__ */ jsx(
4393
- TalkToPerson,
5156
+ PersonPicker,
4394
5157
  {
4395
- personId: pessoaDoCard.id,
4396
- name: pessoaDoCard.name,
4397
- phone: pessoaDoCard.phone,
4398
- variant: "icon",
4399
- className: "flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm transition-opacity hover:opacity-85"
5158
+ className: "min-w-0 flex-1",
5159
+ options: team.map((m) => ({ id: m.userId, name: m.name })),
5160
+ value: deal?.assignedToId ?? null,
5161
+ onChange: (id) => {
5162
+ void changeOwner(id);
5163
+ },
5164
+ placeholder: t2("crm.card.noOwner"),
5165
+ clearable: true,
5166
+ onClear: () => {
5167
+ void changeOwner(void 0);
5168
+ },
5169
+ disabled: savingOwner
4400
5170
  }
4401
5171
  ),
4402
- /* @__PURE__ */ jsx("span", { className: "text-[10px] text-muted-foreground", children: t2("crm.card.quickTalk") })
5172
+ myUserId && deal?.assignedToId !== myUserId && /* @__PURE__ */ jsxs(
5173
+ "button",
5174
+ {
5175
+ onClick: () => {
5176
+ void changeOwner(myUserId);
5177
+ },
5178
+ disabled: savingOwner,
5179
+ className: "inline-flex h-9 shrink-0 items-center gap-1.5 rounded-button border border-primary/30 bg-primary/5 px-3 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:opacity-60",
5180
+ children: [
5181
+ /* @__PURE__ */ jsx(UserCheck, { className: "h-3.5 w-3.5" }),
5182
+ deal?.assignedToId ? t2("crm.card.takeOverFrom") : t2("crm.card.takeOver")
5183
+ ]
5184
+ }
5185
+ )
5186
+ ] })
5187
+ ) }),
5188
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-5 gap-y-1 text-[11px] text-muted-foreground", children: [
5189
+ /* @__PURE__ */ jsxs("span", { children: [
5190
+ t2("crm.dealSidebar.probability"),
5191
+ ": ",
5192
+ /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
5193
+ deal?.probability ?? 0,
5194
+ "%"
5195
+ ] })
4403
5196
  ] }),
4404
- /* @__PURE__ */ jsx(QuickAction, { icon: Phone, label: t2("crm.card.quickCall"), href: draft.phone ? `tel:${draft.phone}` : void 0, onClick: draft.phone ? () => prepActivity("call") : void 0 }),
4405
- /* @__PURE__ */ jsx(QuickAction, { icon: Mail, label: t2("crm.card.quickEmail"), href: draft.email ? `mailto:${draft.email}` : void 0, onClick: draft.email ? () => prepActivity("email") : void 0 }),
4406
- /* @__PURE__ */ jsx(QuickAction, { icon: Pencil, label: t2("crm.card.quickNote"), onClick: () => prepActivity("note") })
5197
+ deal?.createdAt && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
5198
+ /* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
5199
+ formatDateTime(deal.createdAt, currency.locale),
5200
+ " (",
5201
+ formatRelativeTime(deal.createdAt, currency.locale),
5202
+ ")"
5203
+ ] })
4407
5204
  ] })
4408
5205
  ] }),
4409
- /* @__PURE__ */ jsx(Section, { title: t2("crm.card.pointOfContact"), children: /* @__PURE__ */ jsx(
4410
- PersonPicker,
4411
- {
4412
- options: pessoasDaCasa.map((x) => ({
4413
- id: x.personId,
4414
- name: x.personName ?? "\u2014",
4415
- // De QUAL casa, quando o negócio carrega mais de uma
4416
- // (057). Sem isto, duas pessoas de CNPJs diferentes
4417
- // ficam duas linhas iguais, e escolher vira sorteio.
4418
- subtitle: [x.role, casasDoNegocio > 1 ? x.companyName : null].filter(Boolean).join(" \xB7 ") || null
4419
- })),
4420
- value: deal?.contactId ?? null,
4421
- onChange: (id) => {
4422
- void trocarPontoDeContato(id);
4423
- },
4424
- placeholder: t2("crm.card.pointOfContactEmpty"),
4425
- disabled: trocandoContato || pessoasDaCasa.length === 0
4426
- }
4427
- ) }),
4428
- /* @__PURE__ */ jsx(
4429
- Section,
4430
- {
4431
- title: t2("crm.card.about"),
4432
- action: /* @__PURE__ */ jsx(
5206
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
5207
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
5208
+ /* @__PURE__ */ jsx("h3", { className: "text-[11px] font-semibold uppercase tracking-wider text-muted-foreground", children: t2("crm.card.timeline") }),
5209
+ /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: [["all", t2("crm.card.tabAll")], ["contact", t2("crm.card.tabContacts")], ["note", t2("crm.card.tabNotes")], ["task", t2("crm.card.tabTasks")]].map(([v, label2]) => /* @__PURE__ */ jsx(
4433
5210
  "button",
4434
5211
  {
4435
5212
  type: "button",
4436
- onClick: () => setEditing((e) => !e),
4437
- title: t2("crm.card.edit"),
4438
- className: "rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
4439
- children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
4440
- }
4441
- ),
4442
- children: !editing ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
4443
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.phone"), value: draft.phone }),
4444
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.email"), value: draft.email }),
4445
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.value"), value: draft.value ? formatCurrency(draft.value, currency) : void 0 }),
4446
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.expectedClose"), value: draft.expectedCloseDate }),
4447
- draft.notes && /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.notes"), value: /* @__PURE__ */ jsx("span", { className: "whitespace-pre-wrap text-xs", children: draft.notes }) })
4448
- ] }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
4449
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.name"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }) }) }),
4450
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.phone"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.phone, onChange: (e) => setDraft({ ...draft, phone: e.target.value }) }) }),
4451
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.email"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", type: "email", value: draft.email, onChange: (e) => setDraft({ ...draft, email: e.target.value }) }) }),
4452
- !company && /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.company"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.company, onChange: (e) => setDraft({ ...draft, company: e.target.value }) }) }),
4453
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.value"), children: /* @__PURE__ */ jsx(CurrencyInput, { value: draft.value, onChange: (v) => setDraft({ ...draft, value: v ?? 0 }) }) }),
4454
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.expectedClose"), children: /* @__PURE__ */ jsx(DatePicker, { value: draft.expectedCloseDate, onChange: (v) => setDraft({ ...draft, expectedCloseDate: v }) }) }),
4455
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.notes"), children: /* @__PURE__ */ jsx(
4456
- "textarea",
4457
- {
4458
- rows: 3,
4459
- value: draft.notes,
4460
- onChange: (e) => setDraft({ ...draft, notes: e.target.value }),
4461
- className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
4462
- }
4463
- ) }),
4464
- /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
4465
- /* @__PURE__ */ jsxs(Button, { className: "flex-1", onClick: () => {
4466
- void save().then(() => setEditing(false));
4467
- }, disabled: saving, children: [
4468
- saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
4469
- t2("crm.card.save")
4470
- ] }),
4471
- /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setEditing(false), children: t2("crm.card.cancelEdit") })
4472
- ] })
4473
- ] })
4474
- }
4475
- ),
4476
- /* @__PURE__ */ jsx(Section, { title: t2("crm.card.owner"), children: team === null ? /* @__PURE__ */ jsx("div", { className: "h-9 animate-pulse rounded-lg bg-muted/40", "aria-hidden": true }) : team.length === 0 ? (
4477
- // Lista vazia aqui quase sempre é falta de `members.read`, e
4478
- // não uma casa sem equipe. Dizer "ninguém" seria mentir.
4479
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
4480
- ) : (
4481
- // Uma linha só: quem é o dono (PersonPicker, com o retrato
4482
- // — o rosto é o que distingue duas Anas em meio segundo) e,
4483
- // ao lado, o ASSUMIR de um clique. Pegar a fila é o gesto
4484
- // mais repetido do dia de prospecção; o botão some quando o
4485
- // negócio já é de quem olha.
4486
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
5213
+ onClick: () => setTimelineTab(v),
5214
+ className: "rounded-button px-2 py-0.5 text-xs transition-colors " + (timelineTab === v ? "bg-primary/10 font-medium text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"),
5215
+ children: label2
5216
+ },
5217
+ v
5218
+ )) })
5219
+ ] }),
5220
+ pendingStage && deal && pendingStage.id !== deal.stageId && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2 rounded-card border border-primary/30 bg-primary/5 px-3 py-2 text-xs", children: [
5221
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5 shrink-0 text-primary" }),
5222
+ /* @__PURE__ */ jsx("span", { className: "text-foreground", children: t2("crm.card.stageIntent").replace("{from}", deal.stageName ?? "\u2014").replace("{to}", pendingStage.name) }),
4487
5223
  /* @__PURE__ */ jsx(
4488
- PersonPicker,
4489
- {
4490
- className: "min-w-0 flex-1",
4491
- options: team.map((m) => ({ id: m.userId, name: m.name })),
4492
- value: deal?.assignedToId ?? null,
4493
- onChange: (id) => {
4494
- void changeOwner(id);
4495
- },
4496
- placeholder: t2("crm.card.noOwner"),
4497
- clearable: true,
4498
- onClear: () => {
4499
- void changeOwner(void 0);
4500
- },
4501
- disabled: savingOwner
4502
- }
4503
- ),
4504
- myUserId && deal?.assignedToId !== myUserId && /* @__PURE__ */ jsxs(
4505
5224
  "button",
4506
5225
  {
4507
- onClick: () => {
4508
- void changeOwner(myUserId);
4509
- },
4510
- disabled: savingOwner,
4511
- className: "inline-flex h-9 shrink-0 items-center gap-1.5 rounded-button border border-primary/30 bg-primary/5 px-3 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:opacity-60",
4512
- children: [
4513
- /* @__PURE__ */ jsx(UserCheck, { className: "h-3.5 w-3.5" }),
4514
- deal?.assignedToId ? t2("crm.card.takeOverFrom") : t2("crm.card.takeOver")
4515
- ]
5226
+ type: "button",
5227
+ className: "ml-auto text-muted-foreground underline-offset-2 hover:text-foreground hover:underline",
5228
+ onClick: () => onPendingResolved?.(false),
5229
+ children: t2("crm.card.stageIntentCancel")
4516
5230
  }
4517
5231
  )
4518
- ] })
4519
- ) }),
4520
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-5 gap-y-1 text-[11px] text-muted-foreground", children: [
4521
- /* @__PURE__ */ jsxs("span", { children: [
4522
- t2("crm.dealSidebar.probability"),
4523
- ": ",
4524
- /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
4525
- deal?.probability ?? 0,
4526
- "%"
4527
- ] })
4528
5232
  ] }),
4529
- deal?.createdAt && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
4530
- /* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
4531
- formatDateTime(deal.createdAt, currency.locale),
4532
- " (",
4533
- formatRelativeTime(deal.createdAt, currency.locale),
4534
- ")"
4535
- ] })
4536
- ] })
4537
- ] }),
4538
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
4539
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
4540
- /* @__PURE__ */ jsx("h3", { className: "text-[11px] font-semibold uppercase tracking-wider text-muted-foreground", children: t2("crm.card.timeline") }),
4541
- /* @__PURE__ */ jsx("div", { className: "flex items-center gap-1", children: [["all", t2("crm.card.tabAll")], ["contact", t2("crm.card.tabContacts")], ["note", t2("crm.card.tabNotes")], ["task", t2("crm.card.tabTasks")]].map(([v, label2]) => /* @__PURE__ */ jsx(
5233
+ !composerOpen ? /* @__PURE__ */ jsx(
4542
5234
  "button",
4543
5235
  {
4544
5236
  type: "button",
4545
- onClick: () => setTimelineTab(v),
4546
- className: "rounded-button px-2 py-0.5 text-xs transition-colors " + (timelineTab === v ? "bg-primary/10 font-medium text-primary" : "text-muted-foreground hover:bg-muted hover:text-foreground"),
4547
- children: label2
4548
- },
4549
- v
4550
- )) })
4551
- ] }),
4552
- !composerOpen ? /* @__PURE__ */ jsx(
4553
- "button",
4554
- {
4555
- type: "button",
4556
- onClick: () => prepActivity(ctype),
4557
- className: "w-full rounded-card border bg-card px-3 py-2.5 text-left text-sm text-muted-foreground shadow-sm transition-colors hover:bg-muted/30",
4558
- children: t2("crm.followUp.placeholder")
4559
- }
4560
- ) : /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-card border bg-card p-3 shadow-sm", children: [
4561
- /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: orderedTypes.map((tp) => /* @__PURE__ */ jsx(
4562
- "button",
4563
- {
4564
- type: "button",
4565
- onClick: () => setCtype(tp.value),
4566
- className: "rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors " + (ctype === tp.value ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-muted hover:text-foreground"),
4567
- children: tp.label
4568
- },
4569
- tp.value
4570
- )) }),
4571
- /* @__PURE__ */ jsx(
4572
- "textarea",
4573
- {
4574
- ref: composerRef,
4575
- rows: 2,
4576
- value: cnote,
4577
- onChange: (e) => setCnote(e.target.value),
4578
- onKeyDown: (e) => {
4579
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
4580
- e.preventDefault();
4581
- void logFromComposer();
4582
- }
4583
- },
4584
- placeholder: t2("crm.followUp.placeholder"),
4585
- className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-ring"
5237
+ onClick: () => prepActivity(ctype),
5238
+ className: "w-full rounded-card border bg-card px-3 py-2.5 text-left text-sm text-muted-foreground shadow-sm transition-colors hover:bg-muted/30",
5239
+ children: t2("crm.followUp.placeholder")
4586
5240
  }
4587
- ),
4588
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
4589
- CONTACT_TYPES2.has(ctype) && /* @__PURE__ */ jsxs(Select, { value: coutcome, onValueChange: (v) => {
4590
- const nextOutcome = v;
4591
- setCoutcome(nextOutcome);
4592
- if (nextOutcome === "not_now" && !cfutureDate) setCfutureDate(defaultFutureContactDate());
4593
- }, children: [
4594
- /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-auto min-w-[10rem] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
4595
- /* @__PURE__ */ jsx(SelectContent, { children: ["connected", "no_answer", "left_message", "replied", "scheduled", "not_now"].map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o, children: t2(`crm.outcome.${o}`) }, o)) })
4596
- ] }),
4597
- ctype === "task" && /* @__PURE__ */ jsx(
4598
- "input",
5241
+ ) : /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-card border bg-card p-3 shadow-sm", children: [
5242
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: orderedTypes.map((tp) => /* @__PURE__ */ jsx(
5243
+ "button",
4599
5244
  {
4600
- type: "date",
4601
- value: cdue,
4602
- onChange: (e) => setCdue(e.target.value),
4603
- className: "h-8 rounded-lg border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring"
5245
+ type: "button",
5246
+ onClick: () => setCtype(tp.value),
5247
+ className: "rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors " + (ctype === tp.value ? "border-primary bg-primary/10 text-primary" : "border-border text-muted-foreground hover:bg-muted hover:text-foreground"),
5248
+ children: tp.label
5249
+ },
5250
+ tp.value
5251
+ )) }),
5252
+ /* @__PURE__ */ jsx(
5253
+ "textarea",
5254
+ {
5255
+ ref: composerRef,
5256
+ rows: 2,
5257
+ value: cnote,
5258
+ onChange: (e) => setCnote(e.target.value),
5259
+ onKeyDown: (e) => {
5260
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
5261
+ e.preventDefault();
5262
+ void logFromComposer();
5263
+ }
5264
+ },
5265
+ placeholder: t2("crm.followUp.placeholder"),
5266
+ className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none placeholder:text-muted-foreground focus:ring-2 focus:ring-ring"
4604
5267
  }
4605
5268
  ),
4606
- CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && /* @__PURE__ */ jsx(FutureContactPicker, { value: cfutureDate, onChange: setCfutureDate, required: true }),
4607
- /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-1.5", children: [
4608
- /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => setComposerOpen(false), children: t2("crm.card.cancelEdit") }),
4609
- /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => {
4610
- void logFromComposer();
4611
- }, disabled: csaving || CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && !cfutureDate, children: [
4612
- csaving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }),
4613
- t2("crm.followUp.save")
5269
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
5270
+ CONTACT_TYPES2.has(ctype) && /* @__PURE__ */ jsxs(Select, { value: coutcome, onValueChange: (v) => {
5271
+ const nextOutcome = v;
5272
+ setCoutcome(nextOutcome);
5273
+ if (nextOutcome === "not_now" && !cfutureDate) setCfutureDate(defaultFutureContactDate());
5274
+ }, children: [
5275
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-auto min-w-[10rem] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
5276
+ /* @__PURE__ */ jsx(SelectContent, { children: ["connected", "no_answer", "left_message", "replied", "scheduled", "not_now"].map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o, children: t2(`crm.outcome.${o}`) }, o)) })
5277
+ ] }),
5278
+ ctype === "task" && /* @__PURE__ */ jsx(
5279
+ "input",
5280
+ {
5281
+ type: "date",
5282
+ value: cdue,
5283
+ onChange: (e) => setCdue(e.target.value),
5284
+ className: "h-8 rounded-lg border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring"
5285
+ }
5286
+ ),
5287
+ CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && /* @__PURE__ */ jsx(FutureContactPicker, { value: cfutureDate, onChange: setCfutureDate, required: true }),
5288
+ /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-1.5", children: [
5289
+ /* @__PURE__ */ jsx(
5290
+ Button,
5291
+ {
5292
+ size: "sm",
5293
+ variant: "ghost",
5294
+ onClick: () => {
5295
+ setComposerOpen(false);
5296
+ if (pendingStage) onPendingResolved?.(false);
5297
+ },
5298
+ children: t2("crm.card.cancelEdit")
5299
+ }
5300
+ ),
5301
+ /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => {
5302
+ void logFromComposer();
5303
+ }, disabled: csaving || CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && !cfutureDate, children: [
5304
+ csaving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }),
5305
+ pendingStage ? t2("crm.card.stageIntentSave") : t2("crm.followUp.save")
5306
+ ] })
4614
5307
  ] })
4615
5308
  ] })
4616
- ] })
5309
+ ] }),
5310
+ /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4617
5311
  ] }),
4618
- /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4619
- ] }),
4620
- /* @__PURE__ */ jsxs("div", { className: (wide ? "min-h-0 shrink-0 overflow-y-auto border-l" : "border-t") + " space-y-5 p-5", style: wide ? { width: "18rem" } : void 0, children: [
4621
- deal?.groupName && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.groupTitle"), children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-card border bg-muted/20 px-3 py-3", children: [
4622
- /* @__PURE__ */ jsx(Network, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4623
- /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4624
- /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: deal.groupName }),
4625
- deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
4626
- ] })
4627
- ] }) }),
4628
- company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4629
- "button",
4630
- {
4631
- type: "button",
4632
- onClick: () => onViewCompany?.(company.id),
4633
- disabled: !onViewCompany,
4634
- className: "flex w-full items-center gap-3 rounded-card border bg-card px-3 py-3 text-left shadow-sm transition-colors enabled:hover:bg-muted/20",
4635
- children: [
4636
- /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4637
- /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4638
- /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: company.name }),
4639
- /* @__PURE__ */ jsxs("span", { className: "block truncate text-[11px] text-muted-foreground", children: [
4640
- company.documentNumber ? `CNPJ ${formatDocument(company.documentNumber)}` : t2("crm.card.noDocument"),
4641
- company.peopleCount ? ` \xB7 ${t2("crm.card.peopleCount", { count: String(company.peopleCount) })}` : ""
4642
- ] })
4643
- ] }),
4644
- company.documentNumber && /* @__PURE__ */ jsx(CopyDocument, { document: company.documentNumber, label: t2("crm.card.copyDocument") }),
4645
- onViewCompany && /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" })
4646
- ]
4647
- }
4648
- ) }),
4649
- /* @__PURE__ */ jsx(
4650
- Section,
4651
- {
4652
- title: t2("crm.dealSidebar.quotes"),
4653
- action: onCreateQuote && lead ? /* @__PURE__ */ jsx(
4654
- "button",
4655
- {
4656
- type: "button",
4657
- onClick: () => onCreateQuote(lead.id),
4658
- className: "text-[11px] font-medium text-primary hover:underline",
4659
- children: t2("crm.leadDetail.createQuote")
5312
+ /* @__PURE__ */ jsxs("div", { className: (wide ? "min-h-0 shrink-0 overflow-y-auto border-l" : "border-t") + " space-y-5 p-5", style: wide ? { width: "18rem" } : void 0, children: [
5313
+ deal?.groupName && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.groupTitle"), children: /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-card border bg-muted/20 px-3 py-3", children: [
5314
+ /* @__PURE__ */ jsx(Network, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
5315
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
5316
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: deal.groupName }),
5317
+ deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
5318
+ ] })
5319
+ ] }) }),
5320
+ !company && pessoaDoCard?.id && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsx(
5321
+ LinkCompanyPrompt,
5322
+ {
5323
+ personId: pessoaDoCard.id,
5324
+ companyText: pessoaDoCard.company ?? draft.company,
5325
+ onLinked: () => {
5326
+ void provider.getLiveDealById(dealId).then((d) => d && setDeal(d));
4660
5327
  }
4661
- ) : void 0,
4662
- children: quotes2.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "\u2014" }) : /* @__PURE__ */ jsx("div", { className: "divide-y rounded-card border", children: quotes2.map((q) => /* @__PURE__ */ jsxs(
4663
- "div",
4664
- {
4665
- onClick: () => onViewQuote?.(q.id),
4666
- className: "flex cursor-pointer items-center justify-between px-3 py-2.5 transition-colors hover:bg-muted/20",
4667
- children: [
4668
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4669
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: q.quoteNumber }),
4670
- /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: q.quoteDate })
4671
- ] }),
4672
- /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", onClick: (e) => e.stopPropagation(), children: [
4673
- /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: formatCurrency(q.totalAmount, currency) }),
4674
- /* @__PURE__ */ jsx(QuoteStatusDropdown, { quote: q, size: "sm", onStatusChange: (u) => setQuotes(quotes2.map((x) => x.id === u.id ? u : x)) })
5328
+ }
5329
+ ) }),
5330
+ company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
5331
+ "button",
5332
+ {
5333
+ type: "button",
5334
+ onClick: () => onViewCompany?.(company.id),
5335
+ disabled: !onViewCompany,
5336
+ className: "flex w-full items-center gap-3 rounded-card border bg-card px-3 py-3 text-left shadow-sm transition-colors enabled:hover:bg-muted/20",
5337
+ children: [
5338
+ /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
5339
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
5340
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: company.name }),
5341
+ /* @__PURE__ */ jsxs("span", { className: "block truncate text-[11px] text-muted-foreground", children: [
5342
+ company.documentNumber ? `CNPJ ${formatDocument(company.documentNumber)}` : t2("crm.card.noDocument"),
5343
+ company.peopleCount ? ` \xB7 ${t2("crm.card.peopleCount", { count: String(company.peopleCount) })}` : ""
4675
5344
  ] })
4676
- ]
4677
- },
4678
- q.id
4679
- )) })
4680
- }
4681
- ),
4682
- deal && deal.tags.length > 0 && /* @__PURE__ */ jsx(Section, { title: t2("crm.dealSidebar.tags"), children: /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, size: "sm", className: "gap-1.5" }) }),
4683
- /* @__PURE__ */ jsx(FormAnswers, { lead })
4684
- ] })
4685
- ] }) })
4686
- ] }) });
5345
+ ] }),
5346
+ company.documentNumber && /* @__PURE__ */ jsx(CopyDocument, { document: company.documentNumber, label: t2("crm.card.copyDocument") }),
5347
+ onViewCompany && /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" })
5348
+ ]
5349
+ }
5350
+ ) }),
5351
+ /* @__PURE__ */ jsx(
5352
+ Section,
5353
+ {
5354
+ title: t2("crm.dealSidebar.quotes"),
5355
+ action: onCreateQuote && lead ? /* @__PURE__ */ jsx(
5356
+ "button",
5357
+ {
5358
+ type: "button",
5359
+ onClick: () => onCreateQuote(lead.id),
5360
+ className: "text-[11px] font-medium text-primary hover:underline",
5361
+ children: t2("crm.leadDetail.createQuote")
5362
+ }
5363
+ ) : void 0,
5364
+ children: quotes2.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "\u2014" }) : /* @__PURE__ */ jsx("div", { className: "divide-y rounded-card border", children: quotes2.map((q) => /* @__PURE__ */ jsxs(
5365
+ "div",
5366
+ {
5367
+ onClick: () => onViewQuote?.(q.id),
5368
+ className: "flex cursor-pointer items-center justify-between px-3 py-2.5 transition-colors hover:bg-muted/20",
5369
+ children: [
5370
+ /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
5371
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: q.quoteNumber }),
5372
+ /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: q.quoteDate })
5373
+ ] }),
5374
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", onClick: (e) => e.stopPropagation(), children: [
5375
+ /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: formatCurrency(q.totalAmount, currency) }),
5376
+ /* @__PURE__ */ jsx(QuoteStatusDropdown, { quote: q, size: "sm", onStatusChange: (u) => setQuotes(quotes2.map((x) => x.id === u.id ? u : x)) })
5377
+ ] })
5378
+ ]
5379
+ },
5380
+ q.id
5381
+ )) })
5382
+ }
5383
+ ),
5384
+ deal && deal.tags.length > 0 && /* @__PURE__ */ jsx(Section, { title: t2("crm.dealSidebar.tags"), children: /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, size: "sm", className: "gap-1.5" }) }),
5385
+ /* @__PURE__ */ jsx(FormAnswers, { lead })
5386
+ ] })
5387
+ ] }) })
5388
+ ] }) }),
5389
+ /* @__PURE__ */ jsx(
5390
+ LostReasonDialog,
5391
+ {
5392
+ open: askingLost,
5393
+ saving: closing,
5394
+ onCancel: () => setAskingLost(false),
5395
+ onConfirm: (reason) => {
5396
+ setAskingLost(false);
5397
+ void close("lost", reason);
5398
+ }
5399
+ }
5400
+ )
5401
+ ] });
4687
5402
  }
4688
5403
 
4689
5404
  // src/lib/instagram.ts
@@ -4866,6 +5581,7 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
4866
5581
  } catch {
4867
5582
  }
4868
5583
  };
5584
+ const [pendingStage, setPendingStage] = useState(null);
4869
5585
  const [novoLead, setNovoLead] = useState(false);
4870
5586
  const refreshBoard = useCrmStore((s) => s.refreshBoard);
4871
5587
  const addLead = onAddLead ? () => setNovoLead(true) : void 0;
@@ -4944,7 +5660,19 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
4944
5660
  p.id
4945
5661
  );
4946
5662
  }) }),
4947
- mode === "board" && /* @__PURE__ */ jsx(PipelineView, { onDealClick: openCard, onAddLead: addLead, onOpenSettings, modeControl }),
5663
+ mode === "board" && /* @__PURE__ */ jsx(
5664
+ PipelineView,
5665
+ {
5666
+ onDealClick: openCard,
5667
+ onAddLead: addLead,
5668
+ onOpenSettings,
5669
+ onStageIntent: (deal, stage) => {
5670
+ setPendingStage(stage);
5671
+ openCard(deal.id);
5672
+ },
5673
+ modeControl
5674
+ }
5675
+ ),
4948
5676
  mode === "list" && /* @__PURE__ */ jsxs(Fragment, { children: [
4949
5677
  /* @__PURE__ */ jsxs(PageViewBar, { children: [
4950
5678
  /* @__PURE__ */ jsx("div", { className: "min-w-0", children: modeControl }),
@@ -4985,7 +5713,15 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
4985
5713
  dealId: openId ?? "",
4986
5714
  open: !!openId,
4987
5715
  seed: seedDeal,
4988
- onClose: closeCard,
5716
+ pendingStage,
5717
+ onPendingResolved: (moved) => {
5718
+ setPendingStage(null);
5719
+ if (!moved) closeCard();
5720
+ },
5721
+ onClose: () => {
5722
+ setPendingStage(null);
5723
+ closeCard();
5724
+ },
4989
5725
  onViewLead,
4990
5726
  onViewQuote,
4991
5727
  onViewCompany,
@@ -5320,46 +6056,7 @@ function LeadListView({ onNew, onEdit }) {
5320
6056
  });
5321
6057
  }
5322
6058
  }));
5323
- const whatsappAction = {
5324
- id: "whatsapp-campaign",
5325
- label: t2("crm.leads.bulkWhatsapp"),
5326
- icon: Send,
5327
- disabled: bulkBusy,
5328
- onSelect: async (rows) => {
5329
- const comFone = rows.filter((l) => (l.phone ?? "").replace(/\D/g, "").length >= 10);
5330
- if (comFone.length === 0) {
5331
- toast.error(t2("crm.leads.bulkWhatsappNoPhone"));
5332
- return;
5333
- }
5334
- try {
5335
- const sb = getSupabaseClientOptional();
5336
- if (!sb) throw new Error(t2("crm.leads.bulkWhatsappFailed"));
5337
- const tenantId = getActiveTenantId();
5338
- const nome = `Leads \xB7 ${(/* @__PURE__ */ new Date()).toLocaleDateString()} \xB7 ${comFone.length}`;
5339
- const { data: camp, error: e1 } = await sb.from("plg_conversations_campaigns").insert({ tenant_id: tenantId, name: nome, status: "draft" }).select("id").single();
5340
- if (e1) throw new Error(e1.message);
5341
- const alvos = comFone.map((l) => ({
5342
- tenant_id: tenantId,
5343
- campaign_id: camp.id,
5344
- phone_e164: (l.phone ?? "").replace(/\D/g, ""),
5345
- person_id: l.id
5346
- }));
5347
- for (let i = 0; i < alvos.length; i += 200) {
5348
- const { error: e2 } = await sb.from("plg_conversations_campaign_targets").upsert(alvos.slice(i, i + 200), {
5349
- onConflict: "campaign_id,phone_e164,rotation",
5350
- ignoreDuplicates: true
5351
- });
5352
- if (e2) throw new Error(e2.message);
5353
- }
5354
- toast.success(t2("crm.leads.bulkWhatsappQueued", { count: String(comFone.length) }));
5355
- window.location.hash = "#/conversations/campaigns";
5356
- } catch (e) {
5357
- toast.error(e?.message ?? t2("crm.leads.bulkWhatsappFailed"));
5358
- }
5359
- }
5360
- };
5361
6059
  return [
5362
- whatsappAction,
5363
6060
  ...statusActions,
5364
6061
  ...can("sales", "delete") ? [{
5365
6062
  id: "archive",
@@ -5963,6 +6660,19 @@ var STATUSES = [
5963
6660
  { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
5964
6661
  { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
5965
6662
  ];
6663
+ var VALIDITY_PRESETS = [
6664
+ { days: 7, labelKey: "crm.quoteForm.validOneWeek" },
6665
+ { days: 30, labelKey: "crm.quoteForm.validThirtyDays" }
6666
+ ];
6667
+ function addDays(iso, days) {
6668
+ const d = /* @__PURE__ */ new Date(`${iso}T12:00:00`);
6669
+ d.setDate(d.getDate() + days);
6670
+ return d.toISOString().slice(0, 10);
6671
+ }
6672
+ function daysBetween2(from, to) {
6673
+ const ms = (/* @__PURE__ */ new Date(`${to}T12:00:00`)).getTime() - (/* @__PURE__ */ new Date(`${from}T12:00:00`)).getTime();
6674
+ return Math.round(ms / 864e5);
6675
+ }
5966
6676
  var fid = 1;
5967
6677
  function nextId() {
5968
6678
  return `qi${fid++}`;
@@ -5971,7 +6681,15 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
5971
6681
  const t2 = useTranslation();
5972
6682
  const config = useCrmConfig();
5973
6683
  const provider = useCrmProvider();
5974
- const { currency, itemTypes } = config;
6684
+ const { currency, itemTypes: declaredItemTypes } = config;
6685
+ const translatedItemTypes = React.useMemo(
6686
+ () => declaredItemTypes.map((tp) => {
6687
+ const traduzido = t2(`crm.itemType.${tp.value}`);
6688
+ return traduzido === `crm.itemType.${tp.value}` ? tp : { ...tp, label: traduzido };
6689
+ }),
6690
+ [declaredItemTypes, t2]
6691
+ );
6692
+ const itemTypes = useCatalogedItemTypes(translatedItemTypes, config.entityLookups);
5975
6693
  const createQuote = useCrmStore((s) => s.createQuote);
5976
6694
  const updateQuote = useCrmStore((s) => s.updateQuote);
5977
6695
  const guardQuotes = useLimitGuard("quotes");
@@ -5987,6 +6705,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
5987
6705
  d.setDate(d.getDate() + 30);
5988
6706
  return d.toISOString().slice(0, 10);
5989
6707
  });
6708
+ const [validityDays, setValidityDays] = useState(30);
5990
6709
  const [currentStatus, setCurrentStatus] = useState("draft");
5991
6710
  const [paymentConditions, setPaymentConditions] = useState("");
5992
6711
  const [observations, setObservations] = useState("");
@@ -6004,6 +6723,8 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6004
6723
  setLinkedDealId(q.dealId ?? "");
6005
6724
  setQuoteDate(q.quoteDate);
6006
6725
  setValidUntil(q.validUntil);
6726
+ const span = daysBetween2(q.quoteDate, q.validUntil);
6727
+ setValidityDays(VALIDITY_PRESETS.some((pr) => pr.days === span) ? span : null);
6007
6728
  setCurrentStatus(q.status);
6008
6729
  setPaymentConditions(q.paymentConditions ?? "");
6009
6730
  setObservations(q.observations ?? "");
@@ -6032,7 +6753,24 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6032
6753
  setLoadingExisting(false);
6033
6754
  });
6034
6755
  }, [leadId]);
6756
+ function changeQuoteDate(iso) {
6757
+ setQuoteDate(iso);
6758
+ if (validityDays !== null) setValidUntil(addDays(iso, validityDays));
6759
+ }
6760
+ const openCustomOnMount = React.useRef(false);
6761
+ function pickValidity(days) {
6762
+ openCustomOnMount.current = days === null && validityDays !== null;
6763
+ setValidityDays(days);
6764
+ if (days !== null) setValidUntil(addDays(quoteDate, days));
6765
+ }
6035
6766
  const totalAmount = items.reduce((sum, it) => sum + (it.quantity * it.unitPrice - it.discount), 0);
6767
+ function startAddItem() {
6768
+ if (itemTypes.length === 1) {
6769
+ addItemOfKind(itemTypes[0].value);
6770
+ return;
6771
+ }
6772
+ setAddingItem(true);
6773
+ }
6036
6774
  function addItemOfKind(kind) {
6037
6775
  const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
6038
6776
  setItems([...items, newItem]);
@@ -6112,40 +6850,73 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6112
6850
  });
6113
6851
  if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t2("crm.quotes.title"), onBack: () => onSaved?.() });
6114
6852
  const money2 = (v) => formatCurrency(v, currency);
6115
- const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6116
- /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
6117
- SearchSelect,
6118
- {
6119
- value: contactId,
6120
- displayValue: contactName,
6121
- onChange: (id, opt) => {
6122
- setContactId(id);
6123
- setContactName(opt?.label ?? "");
6124
- },
6125
- onSearch: async (q) => {
6126
- if (!config.contactLookup) return [];
6127
- const results = await config.contactLookup.search(q);
6128
- return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
6129
- },
6130
- required: true,
6131
- placeholder: t2("crm.quoteForm.searchClient"),
6132
- allowCreate: true,
6133
- createLabel: t2("crm.quoteForm.addAsLead"),
6134
- onCreate: async (name) => {
6135
- const lead = await provider.createLead({ name });
6136
- setContactId(lead.id);
6137
- setContactName(lead.name);
6138
- }
6853
+ const validUntilLabel = (/* @__PURE__ */ new Date(`${validUntil}T12:00:00`)).toLocaleDateString(getCurrentLocale());
6854
+ const contactSection = /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
6855
+ SearchSelect,
6856
+ {
6857
+ value: contactId,
6858
+ displayValue: contactName,
6859
+ onChange: (id, opt) => {
6860
+ setContactId(id);
6861
+ setContactName(opt?.label ?? "");
6862
+ },
6863
+ onSearch: async (q) => {
6864
+ if (!config.contactLookup) return [];
6865
+ const results = await config.contactLookup.search(q);
6866
+ return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
6867
+ },
6868
+ required: true,
6869
+ placeholder: t2("crm.quoteForm.searchClient"),
6870
+ allowCreate: true,
6871
+ createLabel: t2("crm.quoteForm.addAsLead"),
6872
+ onCreate: async (name) => {
6873
+ const lead = await provider.createLead({ name });
6874
+ setContactId(lead.id);
6875
+ setContactName(lead.name);
6139
6876
  }
6140
- ) }),
6877
+ }
6878
+ ) });
6879
+ const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6141
6880
  /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.quoteDetails"), children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
6142
6881
  /* @__PURE__ */ jsxs("div", { children: [
6143
6882
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.quoteDate") }),
6144
- /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: setQuoteDate, className: "mt-1" })
6883
+ /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: changeQuoteDate, className: "mt-1" })
6145
6884
  ] }),
6146
6885
  /* @__PURE__ */ jsxs("div", { children: [
6147
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.validUntil") }),
6148
- /* @__PURE__ */ jsx(DatePicker, { value: validUntil, onChange: setValidUntil, className: "mt-1" })
6886
+ /* @__PURE__ */ jsxs("div", { className: "flex items-baseline justify-between gap-2", children: [
6887
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.validUntil") }),
6888
+ validityDays === null ? /* @__PURE__ */ jsx(
6889
+ DatePicker,
6890
+ {
6891
+ variant: "inline",
6892
+ format: "numeric",
6893
+ value: validUntil,
6894
+ onChange: setValidUntil,
6895
+ defaultOpen: openCustomOnMount.current
6896
+ }
6897
+ ) : /* @__PURE__ */ jsx("span", { className: "text-xs tabular-nums text-foreground", children: validUntilLabel })
6898
+ ] }),
6899
+ /* @__PURE__ */ jsxs("div", { className: "mt-1 flex flex-wrap gap-1.5", children: [
6900
+ VALIDITY_PRESETS.map((preset) => /* @__PURE__ */ jsx(
6901
+ "button",
6902
+ {
6903
+ type: "button",
6904
+ onClick: () => pickValidity(preset.days),
6905
+ className: `rounded-full border px-2.5 py-1 text-xs transition-colors ${validityDays === preset.days ? "border-primary bg-primary text-primary-foreground" : "border-input bg-card text-muted-foreground hover:bg-muted/50"}`,
6906
+ children: t2(preset.labelKey)
6907
+ },
6908
+ preset.days
6909
+ )),
6910
+ /* @__PURE__ */ jsx(
6911
+ "button",
6912
+ {
6913
+ type: "button",
6914
+ onClick: () => pickValidity(null),
6915
+ className: `rounded-full border px-2.5 py-1 text-xs transition-colors ${validityDays === null ? "border-primary bg-primary text-primary-foreground" : "border-input bg-card text-muted-foreground hover:bg-muted/50"}`,
6916
+ children: t2("crm.quoteForm.validCustom")
6917
+ }
6918
+ )
6919
+ ] })
6149
6920
  ] })
6150
6921
  ] }) }),
6151
6922
  /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.paymentConditions"), children: /* @__PURE__ */ jsx(
@@ -6169,7 +6940,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6169
6940
  }
6170
6941
  ) })
6171
6942
  ] });
6172
- return /* @__PURE__ */ jsx(
6943
+ return /* @__PURE__ */ jsxs(
6173
6944
  OrderFormView,
6174
6945
  {
6175
6946
  sideSections,
@@ -6184,60 +6955,65 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6184
6955
  },
6185
6956
  s.value
6186
6957
  )) }),
6187
- children: /* @__PURE__ */ jsx(
6188
- OrderFormItemsCard,
6189
- {
6190
- label: t2("crm.quoteForm.quoteItems"),
6191
- addLabel: t2("crm.quoteForm.addItem"),
6192
- onAdd: () => setAddingItem(true),
6193
- count: items.length,
6194
- countLabel: t2("crm.quoteForm.itemCount", { count: String(items.length) }),
6195
- totalLabel: t2("crm.quoteForm.total"),
6196
- total: money2(totalAmount),
6197
- emptyLabel: t2("crm.quoteForm.noItems"),
6198
- emptyActionLabel: t2("crm.quoteForm.addFirstItem"),
6199
- header: addingItem && /* @__PURE__ */ jsx(
6200
- OrderFormAddItemStep,
6201
- {
6202
- itemTypes,
6203
- onSelect: addItemOfKind,
6204
- onCancel: () => setAddingItem(false),
6205
- label: t2("crm.quoteForm.selectItemType"),
6206
- cancelLabel: t2("crm.quoteForm.cancel")
6207
- }
6208
- ),
6209
- children: items.map((item, i) => /* @__PURE__ */ jsx(
6210
- OrderFormItemRow,
6211
- {
6212
- index: i,
6213
- itemKind: item.itemKind,
6214
- description: item.description,
6215
- quantity: item.quantity,
6216
- unitPrice: item.unitPrice,
6217
- discount: item.discount,
6218
- itemTypes,
6219
- currency,
6220
- formatMoney: money2,
6221
- expanded: expandedItemId === item._id,
6222
- onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
6223
- onChange: (patch) => updateItem(item._id, patch),
6224
- onRemove: () => removeItem(item._id),
6225
- entityLookups: config.entityLookups,
6226
- labels: {
6227
- item: t2("crm.quoteForm.description"),
6228
- description: t2("crm.quoteForm.description"),
6229
- descriptionPlaceholder: t2("crm.quoteForm.itemDescriptionPlaceholder"),
6230
- noDescription: t2("crm.quoteForm.noDescription"),
6231
- qty: t2("crm.quoteForm.qty"),
6232
- unitPrice: t2("crm.quoteForm.unitPrice"),
6233
- discount: t2("crm.quoteForm.discount"),
6234
- done: t2("crm.quoteForm.done")
6958
+ children: [
6959
+ contactSection,
6960
+ /* @__PURE__ */ jsx(
6961
+ OrderFormItemsCard,
6962
+ {
6963
+ label: t2("crm.quoteForm.quoteItems"),
6964
+ addLabel: t2("crm.quoteForm.addItem"),
6965
+ onAdd: startAddItem,
6966
+ addDisabled: !contactId,
6967
+ addDisabledHint: t2("crm.quoteForm.selectClientFirst"),
6968
+ count: items.length,
6969
+ countLabel: t2("crm.quoteForm.itemCount", { count: String(items.length) }),
6970
+ totalLabel: t2("crm.quoteForm.total"),
6971
+ total: money2(totalAmount),
6972
+ emptyLabel: contactId ? t2("crm.quoteForm.noItems") : t2("crm.quoteForm.selectClientFirst"),
6973
+ emptyActionLabel: t2("crm.quoteForm.addFirstItem"),
6974
+ header: addingItem && /* @__PURE__ */ jsx(
6975
+ OrderFormAddItemStep,
6976
+ {
6977
+ itemTypes,
6978
+ onSelect: addItemOfKind,
6979
+ onCancel: () => setAddingItem(false),
6980
+ label: t2("crm.quoteForm.selectItemType"),
6981
+ cancelLabel: t2("crm.quoteForm.cancel")
6235
6982
  }
6236
- },
6237
- item._id
6238
- ))
6239
- }
6240
- )
6983
+ ),
6984
+ children: items.map((item, i) => /* @__PURE__ */ jsx(
6985
+ OrderFormItemRow,
6986
+ {
6987
+ index: i,
6988
+ itemKind: item.itemKind,
6989
+ description: item.description,
6990
+ quantity: item.quantity,
6991
+ unitPrice: item.unitPrice,
6992
+ discount: item.discount,
6993
+ itemTypes,
6994
+ currency,
6995
+ formatMoney: money2,
6996
+ expanded: expandedItemId === item._id,
6997
+ onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
6998
+ onChange: (patch) => updateItem(item._id, patch),
6999
+ onRemove: () => removeItem(item._id),
7000
+ entityLookups: config.entityLookups,
7001
+ labels: {
7002
+ item: t2("crm.quoteForm.description"),
7003
+ description: t2("crm.quoteForm.description"),
7004
+ descriptionPlaceholder: t2("crm.quoteForm.itemDescriptionPlaceholder"),
7005
+ noDescription: t2("crm.quoteForm.noDescription"),
7006
+ qty: t2("crm.quoteForm.qty"),
7007
+ unitPrice: t2("crm.quoteForm.unitPrice"),
7008
+ discount: t2("crm.quoteForm.discount"),
7009
+ done: t2("crm.quoteForm.done")
7010
+ }
7011
+ },
7012
+ item._id
7013
+ ))
7014
+ }
7015
+ )
7016
+ ]
6241
7017
  }
6242
7018
  );
6243
7019
  }
@@ -7071,6 +7847,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7071
7847
  const [archiving, setArchiving] = useState(false);
7072
7848
  const [confirmandoArquivo, setConfirmandoArquivo] = useState(false);
7073
7849
  const [lead, setLead] = useState(null);
7850
+ const [recarga, setRecarga] = useState(0);
7074
7851
  useRecordVisit(lead ? {
7075
7852
  id: lead.id,
7076
7853
  kind: "lead",
@@ -7114,7 +7891,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7114
7891
  }
7115
7892
  setLoading(false);
7116
7893
  });
7117
- }, [leadId]);
7894
+ }, [leadId, recarga]);
7118
7895
  if (loading) {
7119
7896
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
7120
7897
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leadDetail.loading"), parentLabel: t2("crm.leads.title"), onBack }),
@@ -7235,12 +8012,21 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7235
8012
  ] })
7236
8013
  ]
7237
8014
  }
7238
- ) : (
8015
+ ) : lead.company ? (
7239
8016
  /* Sem vínculo ainda: mostra o texto livre que veio da
7240
- importação. Trocar um pelo outro apagaria a única coisa
7241
- que 297 leads importados têm. */
7242
- lead.company
7243
- )
8017
+ importação — e OFERECE transformá-lo em cadastro. Trocar
8018
+ um pelo outro apagaria a única coisa que 297 leads
8019
+ importados têm; deixá-lo como texto morto era o que fazia
8020
+ o card do funil cair no nome da pessoa. */
8021
+ /* @__PURE__ */ jsx(
8022
+ LinkCompanyPrompt,
8023
+ {
8024
+ personId: leadId,
8025
+ companyText: lead.company,
8026
+ onLinked: () => setRecarga((n) => n + 1)
8027
+ }
8028
+ )
8029
+ ) : null
7244
8030
  }
7245
8031
  ) }),
7246
8032
  lead.credentialCompany && lead.credentialCompany.trim().toLowerCase() !== (lead.companyName ?? "").trim().toLowerCase() && /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
@@ -11054,7 +11840,8 @@ function createMockCrmProvider(options) {
11054
11840
  const map = /* @__PURE__ */ new Map();
11055
11841
  const totals = /* @__PURE__ */ new Map();
11056
11842
  for (const stage of stages) {
11057
- const todos = store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d));
11843
+ const cabe = (d) => stage.isLost ? d.status === "lost" : d.status !== "lost" && d.status !== "archived";
11844
+ const todos = store.deals.filter((d) => d.stageId === stage.id && cabe(d) && matches2(d));
11058
11845
  totals.set(stage.id, todos.length);
11059
11846
  map.set(stage.id, todos.slice(0, limits?.[stage.id] ?? MOCK_DEALS_POR_ETAPA));
11060
11847
  }
@@ -11997,10 +12784,10 @@ function createMockCrmProvider(options) {
11997
12784
  if (!key) return [];
11998
12785
  return store.personPhones.filter((p) => p.phoneKey === key);
11999
12786
  },
12000
- async getFunnel(pipelineId) {
12787
+ async getFunnel(pipelineId, filter) {
12001
12788
  const stages = store.stages.filter((s) => s.pipelineId === pipelineId && !s.isLost).sort((a, b) => a.order - b.order);
12002
12789
  return stages.map((stage) => {
12003
- const deals = store.deals.filter((d) => d.stageId === stage.id);
12790
+ const deals = store.deals.filter((d) => d.stageId === stage.id && (!filter?.tags?.length || (d.tags ?? []).some((t2) => filter.tags.includes(t2))) && (!filter?.assignedToId || (filter.assignedToId === "none" ? !d.assignedToId : d.assignedToId === filter.assignedToId)) && (!filter?.createdFrom || (d.createdAt ?? "") >= filter.createdFrom) && (!filter?.createdTo || (d.createdAt ?? "") <= filter.createdTo));
12004
12791
  return {
12005
12792
  stageId: stage.id,
12006
12793
  stageName: stage.name,
@@ -12097,6 +12884,26 @@ var t;
12097
12884
  function getCrmTenantId() {
12098
12885
  return t;
12099
12886
  }
12887
+ function serves(pipeline2, scope) {
12888
+ const units = pipeline2.unitIds ?? [];
12889
+ const teams = pipeline2.teamIds ?? [];
12890
+ if (units.length > 0 && scope.unitId && !units.includes(scope.unitId)) return false;
12891
+ if (teams.length > 0 && scope.teamId && !teams.includes(scope.teamId)) return false;
12892
+ return true;
12893
+ }
12894
+ function pipelinesForSession(pipelines, scope) {
12895
+ const mine = pipelines.filter((p) => serves(p, scope));
12896
+ return mine.length > 0 ? mine : pipelines;
12897
+ }
12898
+ async function fetchMyTeamId(tenantId, userId) {
12899
+ const db = getSupabaseClientOptional();
12900
+ if (!db) return null;
12901
+ const { data: membership } = await db.from("v_team_members").select("person_id").eq("tenant_id", tenantId).eq("user_id", userId).maybeSingle();
12902
+ if (!membership?.person_id) return null;
12903
+ const { data: person } = await db.from("people").select("custom_fields").eq("id", membership.person_id).maybeSingle();
12904
+ const teamId = person?.custom_fields?.teamId;
12905
+ return typeof teamId === "string" && teamId ? teamId : null;
12906
+ }
12100
12907
 
12101
12908
  // src/data/supabase.ts
12102
12909
  function orTerm(raw) {
@@ -12346,8 +13153,17 @@ function createSupabaseCrmProvider(options) {
12346
13153
  const { pub } = getClients();
12347
13154
  const tenantId = getTenantId();
12348
13155
  if (!tenantId) return [];
12349
- const { data } = await pub.from(T.pipelines).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("is_default", { ascending: false }).order("name");
12350
- return (data ?? []).map((r) => snakeToCamel(r));
13156
+ const ler = (from) => pub.from(from).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("is_default", { ascending: false }).order("name");
13157
+ let { data, error } = await ler(T.pipelinesView);
13158
+ if (error) ({ data } = await ler(T.pipelines));
13159
+ const todos = (data ?? []).map((r) => ({
13160
+ ...snakeToCamel(r),
13161
+ unitIds: r.unit_ids ?? [],
13162
+ teamIds: r.team_ids ?? []
13163
+ }));
13164
+ const userId = await loadMyUserId();
13165
+ const teamId = userId ? await fetchMyTeamId(tenantId, userId).catch(() => null) : null;
13166
+ return pipelinesForSession(todos, { unitId: getActiveUnitId(), teamId });
12351
13167
  },
12352
13168
  async getPipelineStages(pipelineId) {
12353
13169
  const { pub } = getClients();
@@ -12564,8 +13380,9 @@ function createSupabaseCrmProvider(options) {
12564
13380
  async getDealsByStage(pipelineId, filter, knownStages, limits) {
12565
13381
  const { pub } = getClients();
12566
13382
  const stages = knownStages ?? await provider.getPipelineStages(pipelineId);
12567
- const montar = async (stageId) => {
12568
- let qb = pub.from("v_deals").select("*", { count: "exact" }).eq("pipeline_id", pipelineId).eq("stage_id", stageId).not("status", "in", "(lost,archived)");
13383
+ const montar = async (stage) => {
13384
+ let qb = pub.from("v_deals").select("*", { count: "exact" }).eq("pipeline_id", pipelineId).eq("stage_id", stage.id);
13385
+ qb = stage.isLost ? qb.neq("status", "archived") : qb.not("status", "in", "(lost,archived)");
12569
13386
  if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
12570
13387
  if (filter?.search) {
12571
13388
  const t2 = filter.search.replace(/[(),]/g, " ").trim();
@@ -12579,11 +13396,11 @@ function createSupabaseCrmProvider(options) {
12579
13396
  if (filter?.createdTo) qb = qb.lte("created_at", filter.createdTo);
12580
13397
  if (filter?.assignedToId === "none") qb = qb.is("assigned_to_id", null);
12581
13398
  else if (filter?.assignedToId) qb = qb.eq("assigned_to_id", filter.assignedToId);
12582
- const teto = limits?.[stageId] ?? DEALS_POR_ETAPA;
13399
+ const teto = limits?.[stage.id] ?? DEALS_POR_ETAPA;
12583
13400
  const { data: data2, count } = await qb.order("updated_at", { ascending: false }).limit(teto);
12584
- return { stageId, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
13401
+ return { stageId: stage.id, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
12585
13402
  };
12586
- const porEtapa = await Promise.all(stages.map((s) => montar(s.id)));
13403
+ const porEtapa = await Promise.all(stages.map((s) => montar(s)));
12587
13404
  const totals = new Map(porEtapa.map((r) => [r.stageId, r.total]));
12588
13405
  const data = porEtapa.flatMap((r) => r.rows);
12589
13406
  const deals = (data ?? []).map(toDeal);
@@ -13934,10 +14751,13 @@ function createSupabaseCrmProvider(options) {
13934
14751
  const { data } = await pub.from(T.personPhones).select("*").eq("phone_key", key);
13935
14752
  return (data ?? []).map((r) => snakeToCamel(r));
13936
14753
  },
13937
- async getFunnel(pipelineId) {
14754
+ async getFunnel(pipelineId, filter) {
13938
14755
  const { pub } = getClients();
13939
14756
  const stages = await provider.getPipelineStages(pipelineId);
13940
- const { data, error } = await pub.rpc("crm_funnel", { p_pipeline_id: pipelineId });
14757
+ const { data, error } = await pub.rpc("crm_funnel", {
14758
+ p_pipeline_id: pipelineId,
14759
+ p_filter: filter ?? {}
14760
+ });
13941
14761
  if (error) throw new Error(error.message);
13942
14762
  const porEtapa = /* @__PURE__ */ new Map();
13943
14763
  for (const r of data ?? []) {
@@ -14290,6 +15110,7 @@ function createCrmStore(provider) {
14290
15110
  stages: [],
14291
15111
  activePipelineId: null,
14292
15112
  pipelinesLoading: true,
15113
+ stagesPipelineId: null,
14293
15114
  leads: [],
14294
15115
  leadsTotal: 0,
14295
15116
  leadsLoading: false,
@@ -14383,16 +15204,17 @@ function createCrmStore(provider) {
14383
15204
  set({ pipelines });
14384
15205
  return;
14385
15206
  }
14386
- set({ pipelines, stages, activePipelineId: active });
15207
+ set({ pipelines, stages, stagesPipelineId: active, activePipelineId: active });
14387
15208
  });
14388
15209
  } finally {
14389
15210
  set({ pipelinesLoading: false });
14390
15211
  }
14391
15212
  },
14392
15213
  async selectPipeline(pipelineId) {
14393
- if (get().activePipelineId === pipelineId) return;
15214
+ const { activePipelineId, stagesPipelineId } = get();
15215
+ if (activePipelineId === pipelineId && stagesPipelineId === pipelineId) return;
14394
15216
  const stages = await provider.getPipelineStages(pipelineId);
14395
- set({ stages, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map(), dealStageTotals: /* @__PURE__ */ new Map(), dealStageLimits: {} });
15217
+ set({ stages, stagesPipelineId: pipelineId, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map(), dealStageTotals: /* @__PURE__ */ new Map(), dealStageLimits: {} });
14396
15218
  },
14397
15219
  async fetchTagDefs() {
14398
15220
  return dedup(sid + "crm:tag-defs", async () => {
@@ -14418,9 +15240,9 @@ function createCrmStore(provider) {
14418
15240
  set({ summary, summaryLoading: false });
14419
15241
  });
14420
15242
  },
14421
- async fetchFunnel(pipelineId) {
14422
- return dedup(sid + "crm:funnel:" + pipelineId, async () => {
14423
- const funnel = await provider.getFunnel(pipelineId);
15243
+ async fetchFunnel(pipelineId, filter) {
15244
+ return dedup(sid + "crm:funnel:" + pipelineId + ":" + JSON.stringify(filter ?? {}), async () => {
15245
+ const funnel = await provider.getFunnel(pipelineId, filter);
14424
15246
  set({ funnel });
14425
15247
  });
14426
15248
  },
@@ -14770,7 +15592,11 @@ function createCrmStore(provider) {
14770
15592
  stageId,
14771
15593
  stageName: alvo?.name ?? movido.stageName,
14772
15594
  stageColor: alvo?.color ?? movido.stageColor,
14773
- probability: alvo?.probability ?? movido.probability
15595
+ probability: alvo?.probability ?? movido.probability,
15596
+ // The outcome follows the column here too — the provider writes it
15597
+ // from the stage, and a patched card that kept 'open' inside the lost
15598
+ // column read as open until the next refetch.
15599
+ status: alvo ? alvo.isWon ? "won" : alvo.isLost ? "lost" : "open" : movido.status
14774
15600
  };
14775
15601
  novo.set(stageId, [atualizado, ...novo.get(stageId) ?? []]);
14776
15602
  totais.set(stageId, (totais.get(stageId) ?? 0) + 1);
@@ -28763,6 +29589,304 @@ SELECT c.id,
28763
29589
  GRANT SELECT ON public.v_crm_companies_enriched TO authenticated;
28764
29590
  GRANT SELECT ON public.v_crm_companies_enriched TO service_role;
28765
29591
  `;
29592
+ var MIGRATION_060_O_FUNIL_SABE_DE_QUEM_ELE_E = `-- ---------------------------------------------------------------------------
29593
+ -- 060_o_funil_sabe_de_quem_ele_e.sql \u2014 o funil deixa de ser um s\xF3, para todos.
29594
+ -- ---------------------------------------------------------------------------
29595
+ -- \`plg_crm_pipelines\` j\xE1 aceita mais de uma linha e a tela j\xE1 troca entre elas.
29596
+ -- O que n\xE3o existia era o RECORTE: um funil valia para a conta inteira, ent\xE3o
29597
+ -- abrir dois significava mostrar os dois a todo mundo e torcer para que cada um
29598
+ -- clicasse no seu. Numa casa com duas marcas e duas equipes de venda isso n\xE3o \xE9
29599
+ -- inconveni\xEAncia, \xE9 o funil errado carregado por padr\xE3o todo dia.
29600
+ --
29601
+ -- \u2500\u2500 duas tabelas de v\xEDnculo, e n\xE3o duas colunas \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29602
+ --
29603
+ -- Um funil pode servir duas unidades (a marca que vende nas duas pra\xE7as) e duas
29604
+ -- equipes (SDR e closer trabalhando o mesmo pipe). Coluna \`unit_id\` no funil
29605
+ -- responderia "uma", e a segunda casa chegaria no m\xEAs seguinte.
29606
+ --
29607
+ -- \u2500\u2500 e o vazio quer dizer TODOS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29608
+ --
29609
+ -- Funil sem v\xEDnculo nenhum vale para a conta inteira. \xC9 o oposto do
29610
+ -- deny-by-default que a RLS de unidade usa, e de prop\xF3sito: ali o vazio \xE9 "n\xE3o
29611
+ -- disse quem pode ver" e o risco \xE9 vazar; aqui o vazio \xE9 "n\xE3o disse para quem
29612
+ -- serve" e o risco \xE9 a conta acordar sem funil nenhum na tela depois de uma
29613
+ -- migration. O recorte \xE9 de APRESENTA\xC7\xC3O \u2014 quem pode LER o funil continua sendo
29614
+ -- pergunta da RLS, que n\xE3o muda aqui.
29615
+ --
29616
+ -- A equipe \xE9 a categoria \`staff_team\` da 139 do espinha. Sem FK para
29617
+ -- \`categories\` porque a tabela \xE9 do n\xFAcleo e o v\xEDnculo \xE9 do plugin: o mesmo
29618
+ -- motivo pelo qual \`plg_crm_deals.assigned_to_id\` n\xE3o referencia \`auth.users\`.
29619
+ -- O ON DELETE que importa \xE9 o do funil, e esse existe.
29620
+ -- ---------------------------------------------------------------------------
29621
+
29622
+ CREATE TABLE IF NOT EXISTS public.plg_crm_pipeline_units (
29623
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
29624
+ tenant_id uuid NOT NULL,
29625
+ pipeline_id uuid NOT NULL,
29626
+ unit_id uuid NOT NULL,
29627
+ created_at timestamptz DEFAULT now() NOT NULL,
29628
+ CONSTRAINT plg_crm_pipeline_units_pkey PRIMARY KEY (id),
29629
+ CONSTRAINT plg_crm_pipeline_units_pair_key UNIQUE (pipeline_id, unit_id)
29630
+ );
29631
+
29632
+ CREATE TABLE IF NOT EXISTS public.plg_crm_pipeline_teams (
29633
+ id uuid DEFAULT gen_random_uuid() NOT NULL,
29634
+ tenant_id uuid NOT NULL,
29635
+ pipeline_id uuid NOT NULL,
29636
+ team_id uuid NOT NULL,
29637
+ created_at timestamptz DEFAULT now() NOT NULL,
29638
+ CONSTRAINT plg_crm_pipeline_teams_pkey PRIMARY KEY (id),
29639
+ CONSTRAINT plg_crm_pipeline_teams_pair_key UNIQUE (pipeline_id, team_id)
29640
+ );
29641
+
29642
+ -- \u2500\u2500 constraints \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29643
+
29644
+ ALTER TABLE public.plg_crm_pipeline_units
29645
+ DROP CONSTRAINT IF EXISTS plg_crm_pipeline_units_tenant_fkey;
29646
+ ALTER TABLE public.plg_crm_pipeline_units
29647
+ ADD CONSTRAINT plg_crm_pipeline_units_tenant_fkey
29648
+ FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
29649
+
29650
+ ALTER TABLE public.plg_crm_pipeline_units
29651
+ DROP CONSTRAINT IF EXISTS plg_crm_pipeline_units_pipeline_fkey;
29652
+ ALTER TABLE public.plg_crm_pipeline_units
29653
+ ADD CONSTRAINT plg_crm_pipeline_units_pipeline_fkey
29654
+ FOREIGN KEY (pipeline_id) REFERENCES public.plg_crm_pipelines(id) ON DELETE CASCADE;
29655
+
29656
+ ALTER TABLE public.plg_crm_pipeline_teams
29657
+ DROP CONSTRAINT IF EXISTS plg_crm_pipeline_teams_tenant_fkey;
29658
+ ALTER TABLE public.plg_crm_pipeline_teams
29659
+ ADD CONSTRAINT plg_crm_pipeline_teams_tenant_fkey
29660
+ FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
29661
+
29662
+ ALTER TABLE public.plg_crm_pipeline_teams
29663
+ DROP CONSTRAINT IF EXISTS plg_crm_pipeline_teams_pipeline_fkey;
29664
+ ALTER TABLE public.plg_crm_pipeline_teams
29665
+ ADD CONSTRAINT plg_crm_pipeline_teams_pipeline_fkey
29666
+ FOREIGN KEY (pipeline_id) REFERENCES public.plg_crm_pipelines(id) ON DELETE CASCADE;
29667
+
29668
+ -- \u2500\u2500 index \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29669
+
29670
+ CREATE INDEX IF NOT EXISTS plg_crm_pipeline_units_pipeline_idx
29671
+ ON public.plg_crm_pipeline_units (tenant_id, pipeline_id);
29672
+ CREATE INDEX IF NOT EXISTS plg_crm_pipeline_units_unit_idx
29673
+ ON public.plg_crm_pipeline_units (tenant_id, unit_id);
29674
+ CREATE INDEX IF NOT EXISTS plg_crm_pipeline_teams_pipeline_idx
29675
+ ON public.plg_crm_pipeline_teams (tenant_id, pipeline_id);
29676
+ CREATE INDEX IF NOT EXISTS plg_crm_pipeline_teams_team_idx
29677
+ ON public.plg_crm_pipeline_teams (tenant_id, team_id);
29678
+
29679
+ -- \u2500\u2500 RLS \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29680
+ --
29681
+ -- Ler o v\xEDnculo \xE9 ler a configura\xE7\xE3o do funil: \`sales.read\`. Escrev\xEA-lo \xE9
29682
+ -- configurar, e configura\xE7\xE3o de funil segue o mesmo verbo que criar a etapa.
29683
+
29684
+ ALTER TABLE public.plg_crm_pipeline_units ENABLE ROW LEVEL SECURITY;
29685
+ ALTER TABLE public.plg_crm_pipeline_units FORCE ROW LEVEL SECURITY;
29686
+ ALTER TABLE public.plg_crm_pipeline_teams ENABLE ROW LEVEL SECURITY;
29687
+ ALTER TABLE public.plg_crm_pipeline_teams FORCE ROW LEVEL SECURITY;
29688
+
29689
+ DROP POLICY IF EXISTS plg_crm_pipeline_units_authz_select ON public.plg_crm_pipeline_units;
29690
+ CREATE POLICY plg_crm_pipeline_units_authz_select ON public.plg_crm_pipeline_units
29691
+ FOR SELECT TO authenticated USING (
29692
+ tenant_id = (SELECT app.current_tenant_id())
29693
+ AND (SELECT app.has_permission('sales.read', NULL::uuid)));
29694
+
29695
+ DROP POLICY IF EXISTS plg_crm_pipeline_units_authz_insert ON public.plg_crm_pipeline_units;
29696
+ CREATE POLICY plg_crm_pipeline_units_authz_insert ON public.plg_crm_pipeline_units
29697
+ FOR INSERT TO authenticated WITH CHECK (
29698
+ tenant_id = (SELECT app.current_tenant_id())
29699
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29700
+
29701
+ DROP POLICY IF EXISTS plg_crm_pipeline_units_authz_update ON public.plg_crm_pipeline_units;
29702
+ CREATE POLICY plg_crm_pipeline_units_authz_update ON public.plg_crm_pipeline_units
29703
+ FOR UPDATE TO authenticated USING (
29704
+ tenant_id = (SELECT app.current_tenant_id())
29705
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
29706
+ WITH CHECK (
29707
+ tenant_id = (SELECT app.current_tenant_id())
29708
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29709
+
29710
+ DROP POLICY IF EXISTS plg_crm_pipeline_units_authz_delete ON public.plg_crm_pipeline_units;
29711
+ CREATE POLICY plg_crm_pipeline_units_authz_delete ON public.plg_crm_pipeline_units
29712
+ FOR DELETE TO authenticated USING (
29713
+ tenant_id = (SELECT app.current_tenant_id())
29714
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29715
+
29716
+ DROP POLICY IF EXISTS plg_crm_pipeline_teams_authz_select ON public.plg_crm_pipeline_teams;
29717
+ CREATE POLICY plg_crm_pipeline_teams_authz_select ON public.plg_crm_pipeline_teams
29718
+ FOR SELECT TO authenticated USING (
29719
+ tenant_id = (SELECT app.current_tenant_id())
29720
+ AND (SELECT app.has_permission('sales.read', NULL::uuid)));
29721
+
29722
+ DROP POLICY IF EXISTS plg_crm_pipeline_teams_authz_insert ON public.plg_crm_pipeline_teams;
29723
+ CREATE POLICY plg_crm_pipeline_teams_authz_insert ON public.plg_crm_pipeline_teams
29724
+ FOR INSERT TO authenticated WITH CHECK (
29725
+ tenant_id = (SELECT app.current_tenant_id())
29726
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29727
+
29728
+ DROP POLICY IF EXISTS plg_crm_pipeline_teams_authz_update ON public.plg_crm_pipeline_teams;
29729
+ CREATE POLICY plg_crm_pipeline_teams_authz_update ON public.plg_crm_pipeline_teams
29730
+ FOR UPDATE TO authenticated USING (
29731
+ tenant_id = (SELECT app.current_tenant_id())
29732
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
29733
+ WITH CHECK (
29734
+ tenant_id = (SELECT app.current_tenant_id())
29735
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29736
+
29737
+ DROP POLICY IF EXISTS plg_crm_pipeline_teams_authz_delete ON public.plg_crm_pipeline_teams;
29738
+ CREATE POLICY plg_crm_pipeline_teams_authz_delete ON public.plg_crm_pipeline_teams
29739
+ FOR DELETE TO authenticated USING (
29740
+ tenant_id = (SELECT app.current_tenant_id())
29741
+ AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
29742
+
29743
+ GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_pipeline_units TO authenticated;
29744
+ GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_pipeline_teams TO authenticated;
29745
+ GRANT ALL ON public.plg_crm_pipeline_units TO service_role;
29746
+ GRANT ALL ON public.plg_crm_pipeline_teams TO service_role;
29747
+
29748
+ -- \u2500\u2500 a vista que a tela l\xEA \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29749
+ --
29750
+ -- O funil com os v\xEDnculos J\xC1 AGREGADOS: sem ela o quadro faria tr\xEAs consultas
29751
+ -- para responder "qual funil \xE9 meu" \u2014 e faria isso a cada montagem, antes de
29752
+ -- poder sequer come\xE7ar a buscar os cards.
29753
+ --
29754
+ -- \`security_invoker\`: a RLS acima \xE9 que decide as linhas. Uma vista definidora
29755
+ -- aqui devolveria o funil de outra casa para quem soubesse o id.
29756
+ CREATE OR REPLACE VIEW public.v_crm_pipelines WITH (security_invoker = true) AS
29757
+ SELECT p.id, p.tenant_id, p.name, p.is_default, p.is_active,
29758
+ p.created_at, p.updated_at,
29759
+ coalesce((SELECT array_agg(u.unit_id)
29760
+ FROM public.plg_crm_pipeline_units u
29761
+ WHERE u.pipeline_id = p.id), '{}'::uuid[]) AS unit_ids,
29762
+ coalesce((SELECT array_agg(t.team_id)
29763
+ FROM public.plg_crm_pipeline_teams t
29764
+ WHERE t.pipeline_id = p.id), '{}'::uuid[]) AS team_ids
29765
+ FROM public.plg_crm_pipelines p;
29766
+
29767
+ GRANT SELECT ON public.v_crm_pipelines TO authenticated;
29768
+ GRANT SELECT ON public.v_crm_pipelines TO service_role;
29769
+ `;
29770
+ var MIGRATION_061_A_CONVERSAO_RESPEITA_O_FILTRO_DO_QUADRO = `-- 061 \u2014 The conversion chart answers the question the filter asked.
29771
+ --
29772
+ -- \u2500\u2500 The bug \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29773
+ --
29774
+ -- Board, List and Conversion are three modes of one screen, and the board's
29775
+ -- filters are persisted (\`crm.board.owner\`, \`crm.board.period\`, the tag chips).
29776
+ -- The board is honest: \`getDealsByStage\` asks the database once per stage with
29777
+ -- \`count: 'exact'\` and every predicate applied, so its column numbers shrink
29778
+ -- with the filter.
29779
+ --
29780
+ -- \`crm_funnel(p_pipeline_id uuid)\` takes ONE argument. It never saw a filter.
29781
+ -- So: filter the board, switch to Conversion, and the chart counts the whole
29782
+ -- funnel while the filter bar above it still says otherwise. Switch back and
29783
+ -- the numbers are right again. That is why it was reported as real and could
29784
+ -- not be reproduced on demand \u2014 through the board's SEARCH box it never fails
29785
+ -- (the header count has a special case for it), and through the filter menu it
29786
+ -- fails every time, but only after changing mode.
29787
+ --
29788
+ -- \u2500\u2500 Why an overload and not a wider signature \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29789
+ --
29790
+ -- Replacing \`crm_funnel(uuid)\` with a wider one is not replay-safe: the chain
29791
+ -- is replayed, 034 creates the 1-arg version, and a later DROP/CREATE of a
29792
+ -- different signature leaves two functions anyway. So the 1-arg stays exactly
29793
+ -- as 034 left it \u2014 untouched, still correct for a caller with no filter \u2014 and
29794
+ -- the filtered read is a second, 2-arg function. No DEFAULT on the new one:
29795
+ -- \`crm_funnel(uuid)\` and \`crm_funnel(uuid, jsonb DEFAULT \u2026)\` would be ambiguous
29796
+ -- for a one-argument call and Postgres would refuse to choose.
29797
+ --
29798
+ -- \u2500\u2500 The filter is jsonb on purpose \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
29799
+ --
29800
+ -- \`BoardFilter\` has grown twice already (tags, then search+searchTags, then the
29801
+ -- period, then the owner). A positional signature would need a migration each
29802
+ -- time and would break every caller on the way. A bag costs one cast per key
29803
+ -- and the shape stays the board's to decide.
29804
+
29805
+ CREATE OR REPLACE FUNCTION public.crm_funnel(p_pipeline_id uuid, p_filter jsonb)
29806
+ RETURNS TABLE(stage_id uuid, deals bigint, total_value numeric)
29807
+ LANGUAGE plpgsql
29808
+ STABLE
29809
+ SECURITY DEFINER
29810
+ SET search_path TO ''
29811
+ AS $function$
29812
+ declare
29813
+ v_tenant uuid := app.current_tenant_id();
29814
+ v_foco uuid := nullif(app.current_unit_id(), '00000000-0000-0000-0000-000000000000'::uuid);
29815
+ v_negado boolean := app.current_unit_id() = '00000000-0000-0000-0000-000000000000'::uuid;
29816
+ v_unidades uuid[];
29817
+ v_sem_unidade boolean;
29818
+ v_dono boolean;
29819
+ v_uid uuid := auth.uid();
29820
+ -- O recorte, lido do saco. Tudo opcional: um \`{}\` devolve o mesmo que a
29821
+ -- fun\xE7\xE3o de um argumento.
29822
+ v_tags text[] := case when p_filter ? 'tags'
29823
+ then array(select jsonb_array_elements_text(p_filter->'tags')) end;
29824
+ v_busca text := nullif(trim(coalesce(p_filter->>'search', '')), '');
29825
+ v_busca_tags text[] := case when p_filter ? 'searchTags'
29826
+ then array(select jsonb_array_elements_text(p_filter->'searchTags')) end;
29827
+ v_de timestamptz := nullif(p_filter->>'createdFrom', '')::timestamptz;
29828
+ v_ate timestamptz := nullif(p_filter->>'createdTo', '')::timestamptz;
29829
+ v_dono_f text := nullif(p_filter->>'assignedToId', '');
29830
+ begin
29831
+ if v_tenant is null or v_negado then
29832
+ return;
29833
+ end if;
29834
+
29835
+ select coalesce(array_agg(a.unit_id), '{}'::uuid[])
29836
+ into v_unidades
29837
+ from app.user_unit_access a
29838
+ where a.tenant_id = v_tenant
29839
+ and a.user_id = v_uid
29840
+ and (v_foco is null or a.unit_id = v_foco)
29841
+ and app.has_permission('crm.pipeline.read', a.unit_id);
29842
+
29843
+ v_sem_unidade := app.has_permission('crm.pipeline.read', null::uuid);
29844
+ v_dono := app.owner_scoped('crm.deal');
29845
+
29846
+ return query
29847
+ -- A TABELA para a cerca, a VISTA para o texto.
29848
+ --
29849
+ -- \`v_deals\` n\xE3o exp\xF5e \`unit_id\` nem \`owner_id\` \u2014 s\xE3o exatamente as duas
29850
+ -- colunas de que a permiss\xE3o depende, e ler a permiss\xE3o de uma linha que n\xE3o
29851
+ -- as tem seria escrever uma cerca que n\xE3o fecha. Ent\xE3o a base continua sendo
29852
+ -- \`plg_crm_deals\`, como na 034, e a vista entra s\xF3 para dar ao termo de busca
29853
+ -- as mesmas colunas que a coluna do quadro procura.
29854
+ select d.stage_id, count(*), coalesce(sum(d.value), 0)
29855
+ from public.plg_crm_deals d
29856
+ join public.v_deals v on v.id = d.id
29857
+ where d.tenant_id = v_tenant
29858
+ and d.pipeline_id = p_pipeline_id
29859
+ and d.status = 'open'
29860
+ and ( (d.unit_id is null and v_sem_unidade)
29861
+ or (d.unit_id = any (v_unidades)))
29862
+ and (not v_dono or d.owner_id is null or d.owner_id = v_uid)
29863
+ -- Os MESMOS predicados que \`getDealsByStage\` aplica, para que a coluna e
29864
+ -- o gr\xE1fico n\xE3o possam divergir por um detalhe.
29865
+ and (v_tags is null or d.tags && v_tags)
29866
+ and (v_de is null or d.created_at >= v_de)
29867
+ and (v_ate is null or d.created_at <= v_ate)
29868
+ and (v_dono_f is null
29869
+ or (v_dono_f = 'none' and d.assigned_to_id is null)
29870
+ or (v_dono_f <> 'none' and d.assigned_to_id = v_dono_f::uuid))
29871
+ -- A busca \xE9 um OU entre as colunas do quadro e as etiquetas resolvidas no
29872
+ -- cliente \u2014 alternativa ao texto, n\xE3o afunilamento dele.
29873
+ and (v_busca is null
29874
+ or v.title ilike '%' || v_busca || '%'
29875
+ or v.contact_name ilike '%' || v_busca || '%'
29876
+ or v.company_name ilike '%' || v_busca || '%'
29877
+ or v.notes ilike '%' || v_busca || '%'
29878
+ or v.lost_reason ilike '%' || v_busca || '%'
29879
+ or v.stage_name ilike '%' || v_busca || '%'
29880
+ or v.contact_status_name ilike '%' || v_busca || '%'
29881
+ or (v_busca_tags is not null and d.tags && v_busca_tags))
29882
+ group by d.stage_id;
29883
+ end
29884
+ $function$;
29885
+
29886
+ REVOKE ALL ON FUNCTION public.crm_funnel(uuid, jsonb) FROM public;
29887
+ GRANT EXECUTE ON FUNCTION public.crm_funnel(uuid, jsonb) TO authenticated;
29888
+ GRANT EXECUTE ON FUNCTION public.crm_funnel(uuid, jsonb) TO service_role;
29889
+ `;
28766
29890
  var MIGRATIONS = [
28767
29891
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28768
29892
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28822,7 +29946,9 @@ var MIGRATIONS = [
28822
29946
  { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO },
28823
29947
  { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ },
28824
29948
  { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO },
28825
- { id: "059_a_empresa_mostra_o_instagram_que_ela_guarda", sql: MIGRATION_059_A_EMPRESA_MOSTRA_O_INSTAGRAM_QUE_ELA_GUARDA }
29949
+ { id: "059_a_empresa_mostra_o_instagram_que_ela_guarda", sql: MIGRATION_059_A_EMPRESA_MOSTRA_O_INSTAGRAM_QUE_ELA_GUARDA },
29950
+ { id: "060_o_funil_sabe_de_quem_ele_e", sql: MIGRATION_060_O_FUNIL_SABE_DE_QUEM_ELE_E },
29951
+ { id: "061_a_conversao_respeita_o_filtro_do_quadro", sql: MIGRATION_061_A_CONVERSAO_RESPEITA_O_FILTRO_DO_QUADRO }
28826
29952
  ];
28827
29953
 
28828
29954
  // src/locales/en.ts
@@ -29045,6 +30171,26 @@ var en = {
29045
30171
  "crm.rota.count": "{{count}} in the rota",
29046
30172
  "crm.pipeline.pickFunnel": "Pick a funnel",
29047
30173
  "crm.pipeline.setupStages": "Set up stages",
30174
+ "chat.tool.applyFunnelStages": "Draw the funnel stages",
30175
+ "chat.tool.renameFunnelStage": "Rename the stage",
30176
+ "chat.tool.reorderFunnelStages": "Reorder the stages",
30177
+ "chat.tool.removeFunnelStage": "Delete the stage",
30178
+ "chat.tool.createFunnel": "Create a funnel",
30179
+ "chat.field.applyFunnelStages.stages": "Stages",
30180
+ "chat.field.applyFunnelStages.replaceExisting": "Replace the current ones",
30181
+ "chat.field.renameFunnelStage.currentName": "Stage",
30182
+ "chat.field.renameFunnelStage.newName": "New name",
30183
+ "chat.field.reorderFunnelStages.orderedNames": "New order",
30184
+ "chat.field.removeFunnelStage.name": "Stage",
30185
+ "chat.field.createFunnel.name": "Funnel name",
30186
+ "chat.field.createFunnel.makeDefault": "Make it the default funnel",
30187
+ "crm.pipeline.setupWithAI": "Set up with AI",
30188
+ "crm.pipeline.ai.pitch": "Let's design your funnel",
30189
+ "crm.pipeline.ai.description": "Tell me in two sentences how your company sells and I'll build the board's stages \u2014 name, order and odds of closing in each. You read the list before anything is created.",
30190
+ "crm.pipeline.ai.prompt": "I want to set up my funnel stages. Ask me whatever you need.",
30191
+ "crm.pipeline.ai.hint": "e.g. we sell consulting to companies, clients come by referral\u2026",
30192
+ "crm.pipeline.ai.suggestionDescribe": "Design the funnel from scratch",
30193
+ "crm.pipeline.ai.suggestionReview": "Review the stages I already have",
29048
30194
  "crm.pipeline.loadMore": "Show {n} more",
29049
30195
  "crm.pipeline.noDeals": "No deals",
29050
30196
  "crm.pipeline.addLead": "Add lead",
@@ -29138,6 +30284,25 @@ var en = {
29138
30284
  "crm.card.markedWon": "Deal marked won",
29139
30285
  "crm.card.markedLost": "Deal marked lost",
29140
30286
  "crm.card.lostReasonPrompt": "Why was it lost? (price, went quiet, went with a competitor\u2026)",
30287
+ "crm.card.stageIntent": "Moving from {from} to {to} \u2014 log what happened to confirm.",
30288
+ "crm.card.stageIntentSave": "Save and move",
30289
+ "crm.card.stageIntentCancel": "Cancel move",
30290
+ "crm.card.lostReasonTitle": "Why was this deal lost?",
30291
+ "crm.card.lostReasonHint": "The reason is what turns a column of lost deals into a decision. Pick one or write your own.",
30292
+ "crm.card.lostReasonOther": "Another reason (optional)",
30293
+ "crm.card.lostReasonConfirm": "Mark as lost",
30294
+ "crm.lostReason.label": "Lost reason",
30295
+ "crm.lostReason.noInterest": "Not interested",
30296
+ "crm.lostReason.price": "Price",
30297
+ "crm.lostReason.noBudget": "No budget right now",
30298
+ "crm.lostReason.competitor": "Went with a competitor",
30299
+ "crm.lostReason.ghosted": "Went quiet",
30300
+ "crm.lostReason.badFit": "Not a fit",
30301
+ "crm.deals.outcome": "Outcome",
30302
+ "crm.deals.outcomeOpen": "Open",
30303
+ "crm.deals.outcomeWon": "Won",
30304
+ "crm.deals.outcomeLost": "Lost",
30305
+ "crm.deals.outcomeAll": "All",
29141
30306
  "crm.deals.colCity": "City",
29142
30307
  "crm.deals.cohort": "Cohort",
29143
30308
  "crm.deals.campaign": "Campaign",
@@ -29147,6 +30312,12 @@ var en = {
29147
30312
  "crm.deals.allCampaigns": "All campaigns",
29148
30313
  "crm.deals.allCities": "All cities",
29149
30314
  "crm.card.companyTitle": "Company",
30315
+ "crm.linkCompany.hintNew": "Written on the record, but not a company here yet",
30316
+ "crm.linkCompany.hintExisting": "This company already exists \u2014 this person is not linked to it",
30317
+ "crm.linkCompany.create": "Create",
30318
+ "crm.linkCompany.link": "Link",
30319
+ "crm.linkCompany.done": "{{name}} linked",
30320
+ "crm.linkCompany.failed": "Could not link the company",
29150
30321
  "crm.card.groupTitle": "Economic group",
29151
30322
  "crm.card.groupCompanies": "{{count}} companies",
29152
30323
  "crm.card.takeOver": "Take this lead",
@@ -29199,6 +30370,9 @@ var en = {
29199
30370
  "crm.quoteDetail.unitPrice": "Unit Price",
29200
30371
  "crm.quoteDetail.validUntil": "Valid Until",
29201
30372
  "crm.quoteDetail.viewInvoice": "View Invoice",
30373
+ "crm.itemType.service": "Service",
30374
+ "crm.itemType.product": "Product",
30375
+ "crm.itemType.other": "Other",
29202
30376
  "crm.quoteForm.addFirstItem": "Add your first item",
29203
30377
  "crm.quoteForm.addItem": "Add Item",
29204
30378
  "crm.quoteForm.cancel": "Cancel",
@@ -29229,6 +30403,7 @@ var en = {
29229
30403
  "crm.quoteForm.saving": "Saving...",
29230
30404
  "crm.quoteForm.searchClient": "Search client...",
29231
30405
  "crm.quoteForm.addAsLead": "Add as lead",
30406
+ "crm.quoteForm.selectClientFirst": "Select the client before adding items.",
29232
30407
  "crm.quoteForm.selectItemType": "Select item type:",
29233
30408
  "crm.quoteForm.statusApproved": "Approved",
29234
30409
  "crm.quoteForm.statusDraft": "Draft",
@@ -29237,6 +30412,9 @@ var en = {
29237
30412
  "crm.quoteForm.statusSent": "Sent",
29238
30413
  "crm.quoteForm.total": "Total",
29239
30414
  "crm.quoteForm.unitPrice": "Unit Price",
30415
+ "crm.quoteForm.validCustom": "Custom",
30416
+ "crm.quoteForm.validOneWeek": "1 week",
30417
+ "crm.quoteForm.validThirtyDays": "30 days",
29240
30418
  "crm.quoteForm.validUntil": "Valid Until",
29241
30419
  "crm.quotes.amount": "Amount",
29242
30420
  "crm.quotes.archive": "Archive",
@@ -29898,6 +31076,26 @@ var ptBR = {
29898
31076
  "crm.rota.count": "{{count}} na rota",
29899
31077
  "crm.pipeline.pickFunnel": "Escolher funil",
29900
31078
  "crm.pipeline.setupStages": "Configurar etapas",
31079
+ "chat.tool.applyFunnelStages": "Desenhar as etapas do funil",
31080
+ "chat.tool.renameFunnelStage": "Renomear a etapa",
31081
+ "chat.tool.reorderFunnelStages": "Reordenar as etapas",
31082
+ "chat.tool.removeFunnelStage": "Excluir a etapa",
31083
+ "chat.tool.createFunnel": "Criar um funil",
31084
+ "chat.field.applyFunnelStages.stages": "Etapas",
31085
+ "chat.field.applyFunnelStages.replaceExisting": "Substituir as atuais",
31086
+ "chat.field.renameFunnelStage.currentName": "Etapa",
31087
+ "chat.field.renameFunnelStage.newName": "Novo nome",
31088
+ "chat.field.reorderFunnelStages.orderedNames": "Nova ordem",
31089
+ "chat.field.removeFunnelStage.name": "Etapa",
31090
+ "chat.field.createFunnel.name": "Nome do funil",
31091
+ "chat.field.createFunnel.makeDefault": "Virar o funil padr\xE3o",
31092
+ "crm.pipeline.setupWithAI": "Configurar com IA",
31093
+ "crm.pipeline.ai.pitch": "Vamos desenhar o seu funil",
31094
+ "crm.pipeline.ai.description": "Me conta em duas frases como a sua empresa vende e eu monto as etapas do quadro \u2014 nome, ordem e chance de fechar em cada uma. Voc\xEA confere a lista antes de qualquer coisa ser criada.",
31095
+ "crm.pipeline.ai.prompt": "Quero configurar as etapas do meu funil. Me pergunte o que precisar.",
31096
+ "crm.pipeline.ai.hint": "Ex.: vendemos consultoria para empresas, o cliente chega por indica\xE7\xE3o\u2026",
31097
+ "crm.pipeline.ai.suggestionDescribe": "Desenhar o funil do zero",
31098
+ "crm.pipeline.ai.suggestionReview": "Revisar as etapas que j\xE1 tenho",
29901
31099
  "crm.pipeline.loadMore": "Ver mais {n}",
29902
31100
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
29903
31101
  "crm.pipeline.addLead": "Adicionar lead",
@@ -29991,6 +31189,25 @@ var ptBR = {
29991
31189
  "crm.card.markedWon": "Neg\xF3cio marcado como ganho",
29992
31190
  "crm.card.markedLost": "Neg\xF3cio marcado como perdido",
29993
31191
  "crm.card.lostReasonPrompt": "Por que foi perdido? (pre\xE7o, sumiu, fechou com o concorrente\u2026)",
31192
+ "crm.card.stageIntent": "Mudando de {from} para {to} \u2014 registre o que aconteceu para confirmar.",
31193
+ "crm.card.stageIntentSave": "Salvar e mover",
31194
+ "crm.card.stageIntentCancel": "Cancelar mudan\xE7a",
31195
+ "crm.card.lostReasonTitle": "Por que este neg\xF3cio foi perdido?",
31196
+ "crm.card.lostReasonHint": "O motivo \xE9 o que transforma uma coluna de perdidos numa decis\xE3o. Escolha um ou escreva o seu.",
31197
+ "crm.card.lostReasonOther": "Outro motivo (opcional)",
31198
+ "crm.card.lostReasonConfirm": "Marcar como perdido",
31199
+ "crm.lostReason.label": "Motivo da perda",
31200
+ "crm.lostReason.noInterest": "N\xE3o tenho interesse",
31201
+ "crm.lostReason.price": "Pre\xE7o",
31202
+ "crm.lostReason.noBudget": "Sem verba agora",
31203
+ "crm.lostReason.competitor": "Fechou com o concorrente",
31204
+ "crm.lostReason.ghosted": "Sumiu / n\xE3o respondeu",
31205
+ "crm.lostReason.badFit": "Fora do perfil",
31206
+ "crm.deals.outcome": "Desfecho",
31207
+ "crm.deals.outcomeOpen": "Em aberto",
31208
+ "crm.deals.outcomeWon": "Ganhos",
31209
+ "crm.deals.outcomeLost": "Perdidos",
31210
+ "crm.deals.outcomeAll": "Todos",
29994
31211
  "crm.deals.colCity": "Cidade",
29995
31212
  "crm.deals.cohort": "Safra",
29996
31213
  "crm.deals.campaign": "Campanha",
@@ -30000,6 +31217,12 @@ var ptBR = {
30000
31217
  "crm.deals.allCampaigns": "Todas as campanhas",
30001
31218
  "crm.deals.allCities": "Todas as cidades",
30002
31219
  "crm.card.companyTitle": "Empresa",
31220
+ "crm.linkCompany.hintNew": "Escrito no cadastro, mas ainda n\xE3o \xE9 uma empresa aqui",
31221
+ "crm.linkCompany.hintExisting": "Esta empresa j\xE1 existe \u2014 falta ligar esta pessoa a ela",
31222
+ "crm.linkCompany.create": "Cadastrar",
31223
+ "crm.linkCompany.link": "Vincular",
31224
+ "crm.linkCompany.done": "{{name}} vinculada",
31225
+ "crm.linkCompany.failed": "N\xE3o deu para vincular a empresa",
30003
31226
  "crm.card.groupTitle": "Grupo econ\xF4mico",
30004
31227
  "crm.card.groupCompanies": "{{count}} CNPJs",
30005
31228
  "crm.card.takeOver": "Assumir este lead",
@@ -30052,6 +31275,9 @@ var ptBR = {
30052
31275
  "crm.quoteDetail.unitPrice": "Pre\xE7o Unit\xE1rio",
30053
31276
  "crm.quoteDetail.validUntil": "V\xE1lido At\xE9",
30054
31277
  "crm.quoteDetail.viewInvoice": "Ver Fatura",
31278
+ "crm.itemType.service": "Servi\xE7o",
31279
+ "crm.itemType.product": "Produto",
31280
+ "crm.itemType.other": "Outro",
30055
31281
  "crm.quoteForm.addFirstItem": "Adicione seu primeiro item",
30056
31282
  "crm.quoteForm.addItem": "Adicionar Item",
30057
31283
  "crm.quoteForm.cancel": "Cancelar",
@@ -30082,6 +31308,7 @@ var ptBR = {
30082
31308
  "crm.quoteForm.saving": "Salvando...",
30083
31309
  "crm.quoteForm.searchClient": "Buscar cliente...",
30084
31310
  "crm.quoteForm.addAsLead": "Adicionar como lead",
31311
+ "crm.quoteForm.selectClientFirst": "Selecione o cliente antes de adicionar itens.",
30085
31312
  "crm.quoteForm.selectItemType": "Selecione o tipo de item:",
30086
31313
  "crm.quoteForm.statusApproved": "Aprovado",
30087
31314
  "crm.quoteForm.statusDraft": "Rascunho",
@@ -30090,6 +31317,9 @@ var ptBR = {
30090
31317
  "crm.quoteForm.statusSent": "Enviado",
30091
31318
  "crm.quoteForm.total": "Total",
30092
31319
  "crm.quoteForm.unitPrice": "Pre\xE7o Unit\xE1rio",
31320
+ "crm.quoteForm.validCustom": "Personalizado",
31321
+ "crm.quoteForm.validOneWeek": "1 semana",
31322
+ "crm.quoteForm.validThirtyDays": "30 dias",
30093
31323
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
30094
31324
  "crm.quotes.amount": "Valor",
30095
31325
  "crm.quotes.archive": "Arquivar",
@@ -30933,8 +32163,17 @@ function registerCrmTimelineSource() {
30933
32163
  }
30934
32164
  });
30935
32165
  }
30936
-
30937
- // src/views/customerEntity.ts
32166
+ var PJ_LABELS = {
32167
+ name: "Raz\xE3o Social",
32168
+ socialName: "Nome Fantasia",
32169
+ dateOfBirth: "Funda\xE7\xE3o",
32170
+ documentNumber: "CNPJ",
32171
+ rg: "Inscri\xE7\xE3o Estadual",
32172
+ profession: "Ramo de Atua\xE7\xE3o"
32173
+ };
32174
+ var isPJ = (v) => v.personType === "pessoa_juridica";
32175
+ var pjLabel = (key) => (v) => isPJ(v) ? PJ_LABELS[key] : void 0;
32176
+ var onlyPF = (v) => !isPJ(v);
30938
32177
  function buildCrmCustomerEntity(name, namePlural, kind = "customer") {
30939
32178
  return {
30940
32179
  name,
@@ -30946,37 +32185,136 @@ function buildCrmCustomerEntity(name, namePlural, kind = "customer") {
30946
32185
  subtitleField: "documentNumber",
30947
32186
  defaultSort: "name",
30948
32187
  formColumns: 2,
32188
+ facets: [activeFacet({ active: "Ativos", inactive: "Inativos", all: "Todos" })],
30949
32189
  fieldGroups: [
32190
+ { id: "identity", label: "Dados pessoais", columns: 2 },
30950
32191
  { id: "contact", label: "Contato", columns: 2 },
30951
- { id: "record", label: "Situa\xE7\xE3o", columns: 1, column: "side" }
32192
+ { id: "where", label: "Endere\xE7o", columns: 1 },
32193
+ { id: "origin", label: "Como chegou", columns: 2 },
32194
+ { ...RECORD_GROUP }
30952
32195
  ],
30953
32196
  fields: [
30954
- { key: "name", label: "Nome", type: "text", required: true, searchable: true, showInTable: true, group: "contact" },
30955
- // CPF only. Um CNPJ identifica uma EMPRESA, não a identidade de uma
30956
- // pessoa (plugin-crm 014 §3): 45% dos leads reais dividem CNPJ com
30957
- // alguém, então um CNPJ numa linha de pessoa ou colide em
30958
- // `people_tenant_document_uidx` ou vira uma segunda identidade da casa
30959
- // que o CRM já conhece. Cliente pessoa jurídica se cria em Empresas.
30960
- // No fornecedor o documento costuma ser CNPJ, e rotulá-lo "CPF" faz o
30961
- // operador deixar o campo vazio — a nota chega com o CNPJ impresso e não
30962
- // tem onde entrar. Do lado do cliente a regra continua: um CNPJ numa
30963
- // linha de pessoa é uma segunda identidade da casa que o CRM já conhece,
30964
- // e cliente pessoa jurídica se cria em Empresas.
30965
- { key: "documentNumber", label: kind === "supplier" ? "CNPJ / CPF" : "CPF", type: "text", searchable: true, showInTable: true, group: "contact" },
30966
- { key: "phone", label: "Telefone", type: "phone", searchable: true, showInTable: true, group: "contact" },
30967
- { key: "email", label: "E-mail", type: "email", searchable: true, showInTable: false, group: "contact" },
30968
- { key: "isActive", label: "Ativo", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true, group: "record" },
30969
- { key: "notes", label: "Observa\xE7\xF5es", type: "textarea", showInTable: false, group: "record" }
32197
+ {
32198
+ key: "personType",
32199
+ label: "Tipo",
32200
+ type: "segmented",
32201
+ defaultValue: "pessoa_fisica",
32202
+ group: "identity",
32203
+ span: 2,
32204
+ options: [
32205
+ { value: "pessoa_fisica", label: "Pessoa f\xEDsica" },
32206
+ { value: "pessoa_juridica", label: "Pessoa jur\xEDdica" }
32207
+ ]
32208
+ },
32209
+ { key: "name", label: "Nome", labelWhen: pjLabel("name"), type: "text", required: true, searchable: true, showInTable: true, group: "identity", span: 2 },
32210
+ { key: "socialName", label: "Nome Social", labelWhen: pjLabel("socialName"), type: "text", showInTable: false, group: "identity", span: 2 },
32211
+ // CPF only para pessoa FÍSICA. Um CNPJ numa linha de pessoa física ou
32212
+ // colide em `people_tenant_document_uidx` ou vira uma segunda identidade
32213
+ // da casa — por isso o tipo vem antes, e é ele que decide o rótulo.
32214
+ { key: "documentNumber", label: kind === "supplier" ? "CNPJ / CPF" : "CPF", labelWhen: pjLabel("documentNumber"), type: "text", searchable: true, showInTable: true, group: "identity" },
32215
+ { key: "rg", label: "Documento", labelWhen: pjLabel("rg"), type: "text", showInTable: false, group: "identity" },
32216
+ { key: "dateOfBirth", label: "Nascimento", labelWhen: pjLabel("dateOfBirth"), type: "date", showInTable: false, group: "identity" },
32217
+ { key: "profession", label: "Profiss\xE3o", labelWhen: pjLabel("profession"), type: "text", showInTable: false, group: "identity" },
32218
+ // Os sete que o V1 esconde em PJ. Uma empresa não tem sexo, estado civil,
32219
+ // escolaridade nem naturalidade — perguntar é convidar a preencher o que
32220
+ // ninguém vai ler.
32221
+ {
32222
+ key: "gender",
32223
+ label: "Sexo",
32224
+ type: "select",
32225
+ showInTable: false,
32226
+ group: "identity",
32227
+ visibleWhen: onlyPF,
32228
+ options: [
32229
+ { value: "masculino", label: "Masculino" },
32230
+ { value: "feminino", label: "Feminino" },
32231
+ { value: "outro", label: "Outro" }
32232
+ ]
32233
+ },
32234
+ {
32235
+ key: "maritalStatus",
32236
+ label: "Estado Civil",
32237
+ type: "select",
32238
+ showInTable: false,
32239
+ group: "identity",
32240
+ visibleWhen: onlyPF,
32241
+ options: [
32242
+ { value: "solteiro", label: "Solteiro(a)" },
32243
+ { value: "casado", label: "Casado(a)" },
32244
+ { value: "divorciado", label: "Divorciado(a)" },
32245
+ { value: "viuvo", label: "Vi\xFAvo(a)" }
32246
+ ]
32247
+ },
32248
+ {
32249
+ key: "education",
32250
+ label: "Escolaridade",
32251
+ type: "select",
32252
+ showInTable: false,
32253
+ group: "identity",
32254
+ visibleWhen: onlyPF,
32255
+ options: [
32256
+ { value: "fundamental", label: "Fundamental" },
32257
+ { value: "medio", label: "M\xE9dio" },
32258
+ { value: "superior", label: "Superior" },
32259
+ { value: "pos", label: "P\xF3s-gradua\xE7\xE3o" }
32260
+ ]
32261
+ },
32262
+ { key: "nationality", label: "Naturalidade", type: "text", showInTable: false, group: "identity", visibleWhen: onlyPF },
32263
+ ...crmContactChannels(),
32264
+ { key: "address", label: "Endere\xE7o", type: "address", showInTable: false, showInDetail: false, group: "where" },
32265
+ // COMO CHEGOU. A origem é catálogo (o cadastro de Origens); a indicação é
32266
+ // quem trouxe, em texto — no V1 ela vira obrigatória quando a origem
32267
+ // escolhida pede pessoa (`origins.requires_person`).
32268
+ {
32269
+ key: "originId",
32270
+ label: "Origem",
32271
+ type: "relation",
32272
+ showInTable: false,
32273
+ group: "origin",
32274
+ relation: { table: "categories", labelField: "name", filter: { kind: "origin" } }
32275
+ },
32276
+ { key: "referral", label: "Indica\xE7\xE3o", type: "text", showInTable: false, group: "origin" },
32277
+ ...recordRailFields({ tagsTable: "people", activeLabel: "Ativo" }),
32278
+ // AVISOS não é observação: é o que a recepção precisa ver ANTES de
32279
+ // atender («não pode níquel», «paga sempre no cartão da mãe»). No V1 ele
32280
+ // tem campo próprio, e misturá-lo com as observações é perdê-lo.
32281
+ { key: "warnings", label: "Avisos e Pend\xEAncias", type: "textarea", showInTable: false, group: "record", span: 2 }
30970
32282
  ],
30971
32283
  data: {
30972
32284
  table: "people",
30973
32285
  tenantScoped: true,
30974
32286
  archetype: "person",
30975
32287
  archetypeKind: kind,
32288
+ customFields: [
32289
+ "personType",
32290
+ "socialName",
32291
+ "rg",
32292
+ "profession",
32293
+ "gender",
32294
+ "maritalStatus",
32295
+ "education",
32296
+ "nationality",
32297
+ "originId",
32298
+ "referral",
32299
+ "warnings",
32300
+ ...CRM_CONTACT_CUSTOM
32301
+ ],
30976
32302
  searchColumns: ["name", "email", "phone", "document_number"]
30977
32303
  }
30978
32304
  };
30979
32305
  }
32306
+ function crmContactChannels() {
32307
+ return [
32308
+ { key: "phone", label: "Telefone", type: "phone", showInTable: true, searchable: true, group: "contact" },
32309
+ { key: "mobile", label: "Celular", type: "phone", showInTable: true, group: "contact" },
32310
+ { key: "email", label: "E-mail", type: "email", showInTable: true, searchable: true, group: "contact", span: 2 }
32311
+ // Desligados: seis caixas de contato onde a resposta costuma ser um número
32312
+ // e um e-mail. As chaves continuam em `customFields` para o que já foi
32313
+ // gravado não virar lixo no jsonb.
32314
+ // { key: 'phone2', ... }, { key: 'mobile2', ... }, { key: 'email2', ... }
32315
+ ];
32316
+ }
32317
+ var CRM_CONTACT_CUSTOM = ["mobile", "phone2", "mobile2", "email2"];
30980
32318
  var VOCABULARY = {
30981
32319
  education: { one: "Aluno", many: "Alunos" },
30982
32320
  health: { one: "Paciente", many: "Pacientes" }