@fayz-ai/plugin-crm 0.29.3 → 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 (38) hide show
  1. package/dist/components/LostReasonDialog.d.ts +19 -0
  2. package/dist/components/LostReasonDialog.d.ts.map +1 -0
  3. package/dist/data/mock.d.ts.map +1 -1
  4. package/dist/data/registries.d.ts.map +1 -1
  5. package/dist/data/supabase.d.ts.map +1 -1
  6. package/dist/data/tables.d.ts +3 -0
  7. package/dist/data/tables.d.ts.map +1 -1
  8. package/dist/data/types.d.ts +3 -1
  9. package/dist/data/types.d.ts.map +1 -1
  10. package/dist/index.js +1850 -606
  11. package/dist/index.js.map +1 -1
  12. package/dist/lib/board-filter.d.ts +43 -0
  13. package/dist/lib/board-filter.d.ts.map +1 -0
  14. package/dist/lib/lost-reasons.d.ts +18 -0
  15. package/dist/lib/lost-reasons.d.ts.map +1 -0
  16. package/dist/lib/pipeline-agent-surface.d.ts +36 -0
  17. package/dist/lib/pipeline-agent-surface.d.ts.map +1 -0
  18. package/dist/lib/pipeline-scope.d.ts +19 -0
  19. package/dist/lib/pipeline-scope.d.ts.map +1 -0
  20. package/dist/locales/en.d.ts.map +1 -1
  21. package/dist/locales/pt-BR.d.ts.map +1 -1
  22. package/dist/migrations/index.d.ts +2 -0
  23. package/dist/migrations/index.d.ts.map +1 -1
  24. package/dist/store.d.ts +7 -1
  25. package/dist/store.d.ts.map +1 -1
  26. package/dist/types.d.ts +10 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/dist/views/DealCardModal.d.ts +13 -2
  29. package/dist/views/DealCardModal.d.ts.map +1 -1
  30. package/dist/views/DealFunnelView.d.ts.map +1 -1
  31. package/dist/views/DealListView.d.ts.map +1 -1
  32. package/dist/views/DealsView.d.ts.map +1 -1
  33. package/dist/views/LeadListView.d.ts.map +1 -1
  34. package/dist/views/PipelineView.d.ts +12 -1
  35. package/dist/views/PipelineView.d.ts.map +1 -1
  36. package/dist/views/QuoteFormView.d.ts.map +1 -1
  37. package/dist/views/customerEntity.d.ts.map +1 -1
  38. 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",
@@ -3961,7 +4560,7 @@ function CopyDocument({ document: doc, label: label2 }) {
3961
4560
  }
3962
4561
  );
3963
4562
  }
3964
- function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewCompany, onCreateQuote, seed }) {
4563
+ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewCompany, onCreateQuote, seed, pendingStage, onPendingResolved }) {
3965
4564
  const t2 = useTranslation();
3966
4565
  const provider = useCrmProvider();
3967
4566
  const { currency } = useCrmConfig();
@@ -3971,6 +4570,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3971
4570
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
3972
4571
  const patchBoardDeal = useCrmStore((s) => s.patchBoardDeal);
3973
4572
  const removeBoardDeal = useCrmStore((s) => s.removeBoardDeal);
4573
+ const refreshBoard = useCrmStore((s) => s.refreshBoard);
3974
4574
  const tagDefs = useCrmStore((s) => s.tagDefs);
3975
4575
  const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3976
4576
  const [deal, setDeal] = useState(null);
@@ -3984,6 +4584,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3984
4584
  const [movingStage, setMovingStage] = useState(false);
3985
4585
  const [saving, setSaving] = useState(false);
3986
4586
  const [closing, setClosing] = useState(false);
4587
+ const [askingLost, setAskingLost] = useState(false);
3987
4588
  const [draft, setDraft] = useState(null);
3988
4589
  const [company, setCompany] = useState(null);
3989
4590
  const [pessoasDaCasa, setPessoasDaCasa] = useState([]);
@@ -4060,6 +4661,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4060
4661
  const id = requestAnimationFrame(() => composerRef.current?.focus());
4061
4662
  return () => cancelAnimationFrame(id);
4062
4663
  }, [composerOpen]);
4664
+ useEffect(() => {
4665
+ if (open && pendingStage) setComposerOpen(true);
4666
+ }, [open, pendingStage?.id]);
4063
4667
  useEffect(() => {
4064
4668
  if (!seed || seed.id !== dealId) return;
4065
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);
@@ -4131,6 +4735,11 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4131
4735
  assignedToId: deal?.assignedToId
4132
4736
  }) : void 0;
4133
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
+ }
4134
4743
  setCnote("");
4135
4744
  setCoutcome("connected");
4136
4745
  setCfutureDate("");
@@ -4249,20 +4858,18 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4249
4858
  setMovingStage(false);
4250
4859
  }
4251
4860
  }
4252
- async function close(outcome) {
4861
+ async function close(outcome, reason) {
4253
4862
  if (!deal || closing) return;
4254
- let reason;
4255
- if (outcome === "lost") {
4256
- const answer = window.prompt(t2("crm.card.lostReasonPrompt"));
4257
- if (answer === null) return;
4258
- reason = answer.trim() || void 0;
4259
- }
4260
4863
  setClosing(true);
4261
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);
4262
4867
  const patched = await provider.updateDeal(deal.id, { status: outcome, lostReason: reason });
4263
4868
  setDeal(patched);
4264
- if (outcome === "lost") removeBoardDeal(deal.id);
4265
- 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" });
4266
4873
  const refreshed = await provider.getActivities({ dealId });
4267
4874
  setActivities(refreshed.data);
4268
4875
  toast.success(t2(outcome === "won" ? "crm.card.markedWon" : "crm.card.markedLost"));
@@ -4338,424 +4945,460 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4338
4945
  setSaving(false);
4339
4946
  }
4340
4947
  }
4341
- return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (o) => {
4342
- if (!o) onClose();
4343
- }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4344
- /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4345
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
4346
- /* @__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") }),
4347
- /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4348
- deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => {
4349
- void close("lost");
4350
- }, children: [
4351
- /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4352
- " ",
4353
- t2("crm.card.markLost")
4354
- ] }) : deal ? /* @__PURE__ */ jsxs(
4355
- "span",
4356
- {
4357
- 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"),
4358
- title: deal.lostReason ?? void 0,
4359
- children: [
4360
- deal.status === "won" ? /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3" }) : /* @__PURE__ */ jsx(ThumbsDown, { className: "h-3 w-3" }),
4361
- t2(deal.status === "won" ? "crm.card.won" : "crm.card.lost"),
4362
- deal.lostReason && /* @__PURE__ */ jsxs("span", { className: "font-normal opacity-80", children: [
4363
- "\xB7 ",
4364
- 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")
4365
4994
  ] })
4366
- ]
4367
- }
4368
- ) : null,
4369
- deal && (onCreateQuote || onViewLead || canArchive) && /* @__PURE__ */ jsxs(Dropdown, { children: [
4370
- /* @__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" }) }) }),
4371
- /* @__PURE__ */ jsxs(DropdownContent, { align: "end", children: [
4372
- onCreateQuote && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onCreateQuote(lead.id), children: [
4373
- /* @__PURE__ */ jsx(FileText, { className: "h-3.5 w-3.5" }),
4374
- " ",
4375
- t2("crm.leadDetail.createQuote")
4376
- ] }),
4377
- onViewLead && lead && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onViewLead(lead.id), children: [
4378
- /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5" }),
4379
- " ",
4380
- t2("crm.dealSidebar.viewLeadProfile")
4381
- ] }),
4382
- canArchive && /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => {
4383
- void archiveDeal(deal.id).then(onClose);
4384
- }, children: [
4385
- /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
4386
- " ",
4387
- t2("crm.pipeline.archive")
4388
4995
  ] })
4389
4996
  ] })
4390
4997
  ] })
4391
- ] })
4392
- ] }),
4393
- deal?.status === "open" && (journeyStages.length > 0 ? /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5", children: [
4394
- journeyStages.map((s) => {
4395
- const active = s.id === deal?.stageId;
4396
- return /* @__PURE__ */ jsxs(
4397
- "button",
4398
- {
4399
- type: "button",
4400
- disabled: movingStage,
4401
- onClick: () => {
4402
- 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
+ ]
4403
5016
  },
4404
- "aria-pressed": active,
4405
- 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"),
4406
- children: [
4407
- /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: s.color } }),
4408
- s.name
4409
- ]
4410
- },
4411
- s.id
4412
- );
4413
- }),
4414
- movingStage && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin text-muted-foreground" }),
4415
- /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", disabled: closing, onClick: () => {
4416
- void close("won");
4417
- }, children: [
4418
- /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3 text-success" }),
4419
- " ",
4420
- t2("crm.card.markWon")
4421
- ] })
4422
- ] }) : /* @__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)) }))
4423
- ] }),
4424
- /* @__PURE__ */ jsx(ModalBody, { className: wide ? "overflow-hidden p-0" : "sm:max-h-[70vh] overflow-y-auto p-0", children: loading || !draft ? (
4425
- // O esqueleto tem a MESMA silhueta das três colunas — carregar não
4426
- // pode trocar o desenho da tela no meio.
4427
- /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
4428
- /* @__PURE__ */ jsxs("div", { className: "space-y-4 p-5", style: wide ? { width: "18rem" } : void 0, children: [
4429
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2", children: [
4430
- /* @__PURE__ */ jsx("div", { className: "h-14 w-14 animate-pulse rounded-full bg-muted/40" }),
4431
- /* @__PURE__ */ jsx("div", { className: "h-4 w-32 animate-pulse rounded bg-muted/40" }),
4432
- /* @__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))
4433
5041
  ] }),
4434
- [1, 2, 3, 4].map((i) => /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/30" }, i))
4435
- ] }),
4436
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
4437
- /* @__PURE__ */ jsx("div", { className: "h-10 animate-pulse rounded-lg bg-muted/40" }),
4438
- [1, 2, 3].map((i) => /* @__PURE__ */ jsx("div", { className: "h-14 animate-pulse rounded-lg bg-muted/30" }, i))
4439
- ] }),
4440
- 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)) })
4441
- ] })
4442
- ) : /* @__PURE__ */ jsxs("div", { className: "flex", style: wide ? { height: "70vh" } : { flexDirection: "column" }, children: [
4443
- /* @__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: [
4444
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2 text-center", children: [
4445
- /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
4446
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4447
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: draft.name || deal?.contactName || "\u2014" }),
4448
- (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company }),
4449
- 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))
4450
5045
  ] }),
4451
- 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,
4452
- /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-center gap-3 pt-1", children: [
4453
- pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
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
+ ] })
5076
+ ] }),
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: [
4454
5155
  /* @__PURE__ */ jsx(
4455
- TalkToPerson,
5156
+ PersonPicker,
4456
5157
  {
4457
- personId: pessoaDoCard.id,
4458
- name: pessoaDoCard.name,
4459
- phone: pessoaDoCard.phone,
4460
- variant: "icon",
4461
- 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
4462
5170
  }
4463
5171
  ),
4464
- /* @__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
+ ] })
4465
5196
  ] }),
4466
- /* @__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 }),
4467
- /* @__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 }),
4468
- /* @__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
+ ] })
4469
5204
  ] })
4470
5205
  ] }),
4471
- /* @__PURE__ */ jsx(Section, { title: t2("crm.card.pointOfContact"), children: /* @__PURE__ */ jsx(
4472
- PersonPicker,
4473
- {
4474
- options: pessoasDaCasa.map((x) => ({
4475
- id: x.personId,
4476
- name: x.personName ?? "\u2014",
4477
- // De QUAL casa, quando o negócio carrega mais de uma
4478
- // (057). Sem isto, duas pessoas de CNPJs diferentes
4479
- // ficam duas linhas iguais, e escolher vira sorteio.
4480
- subtitle: [x.role, casasDoNegocio > 1 ? x.companyName : null].filter(Boolean).join(" \xB7 ") || null
4481
- })),
4482
- value: deal?.contactId ?? null,
4483
- onChange: (id) => {
4484
- void trocarPontoDeContato(id);
4485
- },
4486
- placeholder: t2("crm.card.pointOfContactEmpty"),
4487
- disabled: trocandoContato || pessoasDaCasa.length === 0
4488
- }
4489
- ) }),
4490
- /* @__PURE__ */ jsx(
4491
- Section,
4492
- {
4493
- title: t2("crm.card.about"),
4494
- 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(
4495
5210
  "button",
4496
5211
  {
4497
5212
  type: "button",
4498
- onClick: () => setEditing((e) => !e),
4499
- title: t2("crm.card.edit"),
4500
- className: "rounded p-1 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
4501
- children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
4502
- }
4503
- ),
4504
- children: !editing ? /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
4505
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.phone"), value: draft.phone }),
4506
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.email"), value: draft.email }),
4507
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.value"), value: draft.value ? formatCurrency(draft.value, currency) : void 0 }),
4508
- /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.dealSidebar.expectedClose"), value: draft.expectedCloseDate }),
4509
- draft.notes && /* @__PURE__ */ jsx(InfoRow, { label: t2("crm.leadDetail.notes"), value: /* @__PURE__ */ jsx("span", { className: "whitespace-pre-wrap text-xs", children: draft.notes }) })
4510
- ] }) : /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
4511
- /* @__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 }) }) }),
4512
- /* @__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 }) }) }),
4513
- /* @__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 }) }) }),
4514
- !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 }) }) }),
4515
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.value"), children: /* @__PURE__ */ jsx(CurrencyInput, { value: draft.value, onChange: (v) => setDraft({ ...draft, value: v ?? 0 }) }) }),
4516
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.expectedClose"), children: /* @__PURE__ */ jsx(DatePicker, { value: draft.expectedCloseDate, onChange: (v) => setDraft({ ...draft, expectedCloseDate: v }) }) }),
4517
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.notes"), children: /* @__PURE__ */ jsx(
4518
- "textarea",
4519
- {
4520
- rows: 3,
4521
- value: draft.notes,
4522
- onChange: (e) => setDraft({ ...draft, notes: e.target.value }),
4523
- className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
4524
- }
4525
- ) }),
4526
- /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
4527
- /* @__PURE__ */ jsxs(Button, { className: "flex-1", onClick: () => {
4528
- void save().then(() => setEditing(false));
4529
- }, disabled: saving, children: [
4530
- saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
4531
- t2("crm.card.save")
4532
- ] }),
4533
- /* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: () => setEditing(false), children: t2("crm.card.cancelEdit") })
4534
- ] })
4535
- ] })
4536
- }
4537
- ),
4538
- /* @__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 ? (
4539
- // Lista vazia aqui quase sempre é falta de `members.read`, e
4540
- // não uma casa sem equipe. Dizer "ninguém" seria mentir.
4541
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
4542
- ) : (
4543
- // Uma linha só: quem é o dono (PersonPicker, com o retrato
4544
- // — o rosto é o que distingue duas Anas em meio segundo) e,
4545
- // ao lado, o ASSUMIR de um clique. Pegar a fila é o gesto
4546
- // mais repetido do dia de prospecção; o botão some quando o
4547
- // negócio já é de quem olha.
4548
- /* @__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) }),
4549
5223
  /* @__PURE__ */ jsx(
4550
- PersonPicker,
4551
- {
4552
- className: "min-w-0 flex-1",
4553
- options: team.map((m) => ({ id: m.userId, name: m.name })),
4554
- value: deal?.assignedToId ?? null,
4555
- onChange: (id) => {
4556
- void changeOwner(id);
4557
- },
4558
- placeholder: t2("crm.card.noOwner"),
4559
- clearable: true,
4560
- onClear: () => {
4561
- void changeOwner(void 0);
4562
- },
4563
- disabled: savingOwner
4564
- }
4565
- ),
4566
- myUserId && deal?.assignedToId !== myUserId && /* @__PURE__ */ jsxs(
4567
5224
  "button",
4568
5225
  {
4569
- onClick: () => {
4570
- void changeOwner(myUserId);
4571
- },
4572
- disabled: savingOwner,
4573
- 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",
4574
- children: [
4575
- /* @__PURE__ */ jsx(UserCheck, { className: "h-3.5 w-3.5" }),
4576
- deal?.assignedToId ? t2("crm.card.takeOverFrom") : t2("crm.card.takeOver")
4577
- ]
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")
4578
5230
  }
4579
5231
  )
4580
- ] })
4581
- ) }),
4582
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-5 gap-y-1 text-[11px] text-muted-foreground", children: [
4583
- /* @__PURE__ */ jsxs("span", { children: [
4584
- t2("crm.dealSidebar.probability"),
4585
- ": ",
4586
- /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
4587
- deal?.probability ?? 0,
4588
- "%"
4589
- ] })
4590
5232
  ] }),
4591
- deal?.createdAt && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1", children: [
4592
- /* @__PURE__ */ jsx(Clock, { className: "h-3 w-3" }),
4593
- formatDateTime(deal.createdAt, currency.locale),
4594
- " (",
4595
- formatRelativeTime(deal.createdAt, currency.locale),
4596
- ")"
4597
- ] })
4598
- ] })
4599
- ] }),
4600
- /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 space-y-3 p-5" + (wide ? " min-h-0 overflow-y-auto" : ""), children: [
4601
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
4602
- /* @__PURE__ */ jsx("h3", { className: "text-[11px] font-semibold uppercase tracking-wider text-muted-foreground", children: t2("crm.card.timeline") }),
4603
- /* @__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(
4604
5234
  "button",
4605
5235
  {
4606
5236
  type: "button",
4607
- onClick: () => setTimelineTab(v),
4608
- 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"),
4609
- children: label2
4610
- },
4611
- v
4612
- )) })
4613
- ] }),
4614
- !composerOpen ? /* @__PURE__ */ jsx(
4615
- "button",
4616
- {
4617
- type: "button",
4618
- onClick: () => prepActivity(ctype),
4619
- 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",
4620
- children: t2("crm.followUp.placeholder")
4621
- }
4622
- ) : /* @__PURE__ */ jsxs("div", { className: "space-y-2 rounded-card border bg-card p-3 shadow-sm", children: [
4623
- /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1", children: orderedTypes.map((tp) => /* @__PURE__ */ jsx(
4624
- "button",
4625
- {
4626
- type: "button",
4627
- onClick: () => setCtype(tp.value),
4628
- 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"),
4629
- children: tp.label
4630
- },
4631
- tp.value
4632
- )) }),
4633
- /* @__PURE__ */ jsx(
4634
- "textarea",
4635
- {
4636
- ref: composerRef,
4637
- rows: 2,
4638
- value: cnote,
4639
- onChange: (e) => setCnote(e.target.value),
4640
- onKeyDown: (e) => {
4641
- if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
4642
- e.preventDefault();
4643
- void logFromComposer();
4644
- }
4645
- },
4646
- placeholder: t2("crm.followUp.placeholder"),
4647
- 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")
4648
5240
  }
4649
- ),
4650
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
4651
- CONTACT_TYPES2.has(ctype) && /* @__PURE__ */ jsxs(Select, { value: coutcome, onValueChange: (v) => {
4652
- const nextOutcome = v;
4653
- setCoutcome(nextOutcome);
4654
- if (nextOutcome === "not_now" && !cfutureDate) setCfutureDate(defaultFutureContactDate());
4655
- }, children: [
4656
- /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-auto min-w-[10rem] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
4657
- /* @__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)) })
4658
- ] }),
4659
- ctype === "task" && /* @__PURE__ */ jsx(
4660
- "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",
4661
5244
  {
4662
- type: "date",
4663
- value: cdue,
4664
- onChange: (e) => setCdue(e.target.value),
4665
- 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"
4666
5267
  }
4667
5268
  ),
4668
- CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && /* @__PURE__ */ jsx(FutureContactPicker, { value: cfutureDate, onChange: setCfutureDate, required: true }),
4669
- /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-1.5", children: [
4670
- /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => setComposerOpen(false), children: t2("crm.card.cancelEdit") }),
4671
- /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => {
4672
- void logFromComposer();
4673
- }, disabled: csaving || CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && !cfutureDate, children: [
4674
- csaving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }),
4675
- 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
+ ] })
4676
5307
  ] })
4677
5308
  ] })
4678
- ] })
5309
+ ] }),
5310
+ /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4679
5311
  ] }),
4680
- /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4681
- ] }),
4682
- /* @__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: [
4683
- 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: [
4684
- /* @__PURE__ */ jsx(Network, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4685
- /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4686
- /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: deal.groupName }),
4687
- deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
4688
- ] })
4689
- ] }) }),
4690
- !company && pessoaDoCard?.id && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsx(
4691
- LinkCompanyPrompt,
4692
- {
4693
- personId: pessoaDoCard.id,
4694
- companyText: pessoaDoCard.company ?? draft.company,
4695
- onLinked: () => {
4696
- void provider.getLiveDealById(dealId).then((d) => d && setDeal(d));
4697
- }
4698
- }
4699
- ) }),
4700
- company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4701
- "button",
4702
- {
4703
- type: "button",
4704
- onClick: () => onViewCompany?.(company.id),
4705
- disabled: !onViewCompany,
4706
- 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",
4707
- children: [
4708
- /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4709
- /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4710
- /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: company.name }),
4711
- /* @__PURE__ */ jsxs("span", { className: "block truncate text-[11px] text-muted-foreground", children: [
4712
- company.documentNumber ? `CNPJ ${formatDocument(company.documentNumber)}` : t2("crm.card.noDocument"),
4713
- company.peopleCount ? ` \xB7 ${t2("crm.card.peopleCount", { count: String(company.peopleCount) })}` : ""
4714
- ] })
4715
- ] }),
4716
- company.documentNumber && /* @__PURE__ */ jsx(CopyDocument, { document: company.documentNumber, label: t2("crm.card.copyDocument") }),
4717
- onViewCompany && /* @__PURE__ */ jsx(ArrowRight, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" })
4718
- ]
4719
- }
4720
- ) }),
4721
- /* @__PURE__ */ jsx(
4722
- Section,
4723
- {
4724
- title: t2("crm.dealSidebar.quotes"),
4725
- action: onCreateQuote && lead ? /* @__PURE__ */ jsx(
4726
- "button",
4727
- {
4728
- type: "button",
4729
- onClick: () => onCreateQuote(lead.id),
4730
- className: "text-[11px] font-medium text-primary hover:underline",
4731
- 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));
4732
5327
  }
4733
- ) : void 0,
4734
- 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(
4735
- "div",
4736
- {
4737
- onClick: () => onViewQuote?.(q.id),
4738
- className: "flex cursor-pointer items-center justify-between px-3 py-2.5 transition-colors hover:bg-muted/20",
4739
- children: [
4740
- /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4741
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: q.quoteNumber }),
4742
- /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: q.quoteDate })
4743
- ] }),
4744
- /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", onClick: (e) => e.stopPropagation(), children: [
4745
- /* @__PURE__ */ jsx("span", { className: "text-sm font-semibold", children: formatCurrency(q.totalAmount, currency) }),
4746
- /* @__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) })}` : ""
4747
5344
  ] })
4748
- ]
4749
- },
4750
- q.id
4751
- )) })
4752
- }
4753
- ),
4754
- 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" }) }),
4755
- /* @__PURE__ */ jsx(FormAnswers, { lead })
4756
- ] })
4757
- ] }) })
4758
- ] }) });
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
+ ] });
4759
5402
  }
4760
5403
 
4761
5404
  // src/lib/instagram.ts
@@ -4938,6 +5581,7 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
4938
5581
  } catch {
4939
5582
  }
4940
5583
  };
5584
+ const [pendingStage, setPendingStage] = useState(null);
4941
5585
  const [novoLead, setNovoLead] = useState(false);
4942
5586
  const refreshBoard = useCrmStore((s) => s.refreshBoard);
4943
5587
  const addLead = onAddLead ? () => setNovoLead(true) : void 0;
@@ -5016,7 +5660,19 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
5016
5660
  p.id
5017
5661
  );
5018
5662
  }) }),
5019
- 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
+ ),
5020
5676
  mode === "list" && /* @__PURE__ */ jsxs(Fragment, { children: [
5021
5677
  /* @__PURE__ */ jsxs(PageViewBar, { children: [
5022
5678
  /* @__PURE__ */ jsx("div", { className: "min-w-0", children: modeControl }),
@@ -5057,7 +5713,15 @@ function DealsView({ openDealId, onOpenDeal, onCloseDeal, onViewLead, onViewQuot
5057
5713
  dealId: openId ?? "",
5058
5714
  open: !!openId,
5059
5715
  seed: seedDeal,
5060
- onClose: closeCard,
5716
+ pendingStage,
5717
+ onPendingResolved: (moved) => {
5718
+ setPendingStage(null);
5719
+ if (!moved) closeCard();
5720
+ },
5721
+ onClose: () => {
5722
+ setPendingStage(null);
5723
+ closeCard();
5724
+ },
5061
5725
  onViewLead,
5062
5726
  onViewQuote,
5063
5727
  onViewCompany,
@@ -5392,46 +6056,7 @@ function LeadListView({ onNew, onEdit }) {
5392
6056
  });
5393
6057
  }
5394
6058
  }));
5395
- const whatsappAction = {
5396
- id: "whatsapp-campaign",
5397
- label: t2("crm.leads.bulkWhatsapp"),
5398
- icon: Send,
5399
- disabled: bulkBusy,
5400
- onSelect: async (rows) => {
5401
- const comFone = rows.filter((l) => (l.phone ?? "").replace(/\D/g, "").length >= 10);
5402
- if (comFone.length === 0) {
5403
- toast.error(t2("crm.leads.bulkWhatsappNoPhone"));
5404
- return;
5405
- }
5406
- try {
5407
- const sb = getSupabaseClientOptional();
5408
- if (!sb) throw new Error(t2("crm.leads.bulkWhatsappFailed"));
5409
- const tenantId = getActiveTenantId();
5410
- const nome = `Leads \xB7 ${(/* @__PURE__ */ new Date()).toLocaleDateString()} \xB7 ${comFone.length}`;
5411
- const { data: camp, error: e1 } = await sb.from("plg_conversations_campaigns").insert({ tenant_id: tenantId, name: nome, status: "draft" }).select("id").single();
5412
- if (e1) throw new Error(e1.message);
5413
- const alvos = comFone.map((l) => ({
5414
- tenant_id: tenantId,
5415
- campaign_id: camp.id,
5416
- phone_e164: (l.phone ?? "").replace(/\D/g, ""),
5417
- person_id: l.id
5418
- }));
5419
- for (let i = 0; i < alvos.length; i += 200) {
5420
- const { error: e2 } = await sb.from("plg_conversations_campaign_targets").upsert(alvos.slice(i, i + 200), {
5421
- onConflict: "campaign_id,phone_e164,rotation",
5422
- ignoreDuplicates: true
5423
- });
5424
- if (e2) throw new Error(e2.message);
5425
- }
5426
- toast.success(t2("crm.leads.bulkWhatsappQueued", { count: String(comFone.length) }));
5427
- window.location.hash = "#/conversations/campaigns";
5428
- } catch (e) {
5429
- toast.error(e?.message ?? t2("crm.leads.bulkWhatsappFailed"));
5430
- }
5431
- }
5432
- };
5433
6059
  return [
5434
- whatsappAction,
5435
6060
  ...statusActions,
5436
6061
  ...can("sales", "delete") ? [{
5437
6062
  id: "archive",
@@ -6035,6 +6660,19 @@ var STATUSES = [
6035
6660
  { value: "rejected", labelKey: "crm.quoteForm.statusRejected", color: "bg-destructive-soft text-destructive-soft-foreground border border-destructive/30 dark:border-destructive/30" },
6036
6661
  { value: "expired", labelKey: "crm.quoteForm.statusExpired", color: "bg-muted text-muted-foreground border" }
6037
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
+ }
6038
6676
  var fid = 1;
6039
6677
  function nextId() {
6040
6678
  return `qi${fid++}`;
@@ -6043,7 +6681,15 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6043
6681
  const t2 = useTranslation();
6044
6682
  const config = useCrmConfig();
6045
6683
  const provider = useCrmProvider();
6046
- 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);
6047
6693
  const createQuote = useCrmStore((s) => s.createQuote);
6048
6694
  const updateQuote = useCrmStore((s) => s.updateQuote);
6049
6695
  const guardQuotes = useLimitGuard("quotes");
@@ -6059,6 +6705,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6059
6705
  d.setDate(d.getDate() + 30);
6060
6706
  return d.toISOString().slice(0, 10);
6061
6707
  });
6708
+ const [validityDays, setValidityDays] = useState(30);
6062
6709
  const [currentStatus, setCurrentStatus] = useState("draft");
6063
6710
  const [paymentConditions, setPaymentConditions] = useState("");
6064
6711
  const [observations, setObservations] = useState("");
@@ -6076,6 +6723,8 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6076
6723
  setLinkedDealId(q.dealId ?? "");
6077
6724
  setQuoteDate(q.quoteDate);
6078
6725
  setValidUntil(q.validUntil);
6726
+ const span = daysBetween2(q.quoteDate, q.validUntil);
6727
+ setValidityDays(VALIDITY_PRESETS.some((pr) => pr.days === span) ? span : null);
6079
6728
  setCurrentStatus(q.status);
6080
6729
  setPaymentConditions(q.paymentConditions ?? "");
6081
6730
  setObservations(q.observations ?? "");
@@ -6104,7 +6753,24 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6104
6753
  setLoadingExisting(false);
6105
6754
  });
6106
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
+ }
6107
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
+ }
6108
6774
  function addItemOfKind(kind) {
6109
6775
  const newItem = { _id: nextId(), itemKind: kind, description: "", quantity: 1, unitPrice: 0, discount: 0 };
6110
6776
  setItems([...items, newItem]);
@@ -6184,40 +6850,73 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6184
6850
  });
6185
6851
  if (loadingExisting) return /* @__PURE__ */ jsx(OrderFormSkeleton, { parentLabel: t2("crm.quotes.title"), onBack: () => onSaved?.() });
6186
6852
  const money2 = (v) => formatCurrency(v, currency);
6187
- const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6188
- /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.client"), children: /* @__PURE__ */ jsx(
6189
- SearchSelect,
6190
- {
6191
- value: contactId,
6192
- displayValue: contactName,
6193
- onChange: (id, opt) => {
6194
- setContactId(id);
6195
- setContactName(opt?.label ?? "");
6196
- },
6197
- onSearch: async (q) => {
6198
- if (!config.contactLookup) return [];
6199
- const results = await config.contactLookup.search(q);
6200
- return results.map((r) => ({ id: r.id, label: r.label, subtitle: r.subtitle, group: r.group, data: r }));
6201
- },
6202
- required: true,
6203
- placeholder: t2("crm.quoteForm.searchClient"),
6204
- allowCreate: true,
6205
- createLabel: t2("crm.quoteForm.addAsLead"),
6206
- onCreate: async (name) => {
6207
- const lead = await provider.createLead({ name });
6208
- setContactId(lead.id);
6209
- setContactName(lead.name);
6210
- }
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);
6211
6876
  }
6212
- ) }),
6877
+ }
6878
+ ) });
6879
+ const sideSections = /* @__PURE__ */ jsxs(Fragment, { children: [
6213
6880
  /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.quoteDetails"), children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
6214
6881
  /* @__PURE__ */ jsxs("div", { children: [
6215
6882
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.quoteDate") }),
6216
- /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: setQuoteDate, className: "mt-1" })
6883
+ /* @__PURE__ */ jsx(DatePicker, { value: quoteDate, onChange: changeQuoteDate, className: "mt-1" })
6217
6884
  ] }),
6218
6885
  /* @__PURE__ */ jsxs("div", { children: [
6219
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.quoteForm.validUntil") }),
6220
- /* @__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
+ ] })
6221
6920
  ] })
6222
6921
  ] }) }),
6223
6922
  /* @__PURE__ */ jsx(OrderFormBlock, { title: t2("crm.quoteForm.paymentConditions"), children: /* @__PURE__ */ jsx(
@@ -6241,7 +6940,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6241
6940
  }
6242
6941
  ) })
6243
6942
  ] });
6244
- return /* @__PURE__ */ jsx(
6943
+ return /* @__PURE__ */ jsxs(
6245
6944
  OrderFormView,
6246
6945
  {
6247
6946
  sideSections,
@@ -6256,60 +6955,65 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6256
6955
  },
6257
6956
  s.value
6258
6957
  )) }),
6259
- children: /* @__PURE__ */ jsx(
6260
- OrderFormItemsCard,
6261
- {
6262
- label: t2("crm.quoteForm.quoteItems"),
6263
- addLabel: t2("crm.quoteForm.addItem"),
6264
- onAdd: () => setAddingItem(true),
6265
- count: items.length,
6266
- countLabel: t2("crm.quoteForm.itemCount", { count: String(items.length) }),
6267
- totalLabel: t2("crm.quoteForm.total"),
6268
- total: money2(totalAmount),
6269
- emptyLabel: t2("crm.quoteForm.noItems"),
6270
- emptyActionLabel: t2("crm.quoteForm.addFirstItem"),
6271
- header: addingItem && /* @__PURE__ */ jsx(
6272
- OrderFormAddItemStep,
6273
- {
6274
- itemTypes,
6275
- onSelect: addItemOfKind,
6276
- onCancel: () => setAddingItem(false),
6277
- label: t2("crm.quoteForm.selectItemType"),
6278
- cancelLabel: t2("crm.quoteForm.cancel")
6279
- }
6280
- ),
6281
- children: items.map((item, i) => /* @__PURE__ */ jsx(
6282
- OrderFormItemRow,
6283
- {
6284
- index: i,
6285
- itemKind: item.itemKind,
6286
- description: item.description,
6287
- quantity: item.quantity,
6288
- unitPrice: item.unitPrice,
6289
- discount: item.discount,
6290
- itemTypes,
6291
- currency,
6292
- formatMoney: money2,
6293
- expanded: expandedItemId === item._id,
6294
- onToggle: () => setExpandedItemId(expandedItemId === item._id ? null : item._id),
6295
- onChange: (patch) => updateItem(item._id, patch),
6296
- onRemove: () => removeItem(item._id),
6297
- entityLookups: config.entityLookups,
6298
- labels: {
6299
- item: t2("crm.quoteForm.description"),
6300
- description: t2("crm.quoteForm.description"),
6301
- descriptionPlaceholder: t2("crm.quoteForm.itemDescriptionPlaceholder"),
6302
- noDescription: t2("crm.quoteForm.noDescription"),
6303
- qty: t2("crm.quoteForm.qty"),
6304
- unitPrice: t2("crm.quoteForm.unitPrice"),
6305
- discount: t2("crm.quoteForm.discount"),
6306
- 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")
6307
6982
  }
6308
- },
6309
- item._id
6310
- ))
6311
- }
6312
- )
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
+ ]
6313
7017
  }
6314
7018
  );
6315
7019
  }
@@ -11136,7 +11840,8 @@ function createMockCrmProvider(options) {
11136
11840
  const map = /* @__PURE__ */ new Map();
11137
11841
  const totals = /* @__PURE__ */ new Map();
11138
11842
  for (const stage of stages) {
11139
- 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));
11140
11845
  totals.set(stage.id, todos.length);
11141
11846
  map.set(stage.id, todos.slice(0, limits?.[stage.id] ?? MOCK_DEALS_POR_ETAPA));
11142
11847
  }
@@ -12079,10 +12784,10 @@ function createMockCrmProvider(options) {
12079
12784
  if (!key) return [];
12080
12785
  return store.personPhones.filter((p) => p.phoneKey === key);
12081
12786
  },
12082
- async getFunnel(pipelineId) {
12787
+ async getFunnel(pipelineId, filter) {
12083
12788
  const stages = store.stages.filter((s) => s.pipelineId === pipelineId && !s.isLost).sort((a, b) => a.order - b.order);
12084
12789
  return stages.map((stage) => {
12085
- 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));
12086
12791
  return {
12087
12792
  stageId: stage.id,
12088
12793
  stageName: stage.name,
@@ -12179,6 +12884,26 @@ var t;
12179
12884
  function getCrmTenantId() {
12180
12885
  return t;
12181
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
+ }
12182
12907
 
12183
12908
  // src/data/supabase.ts
12184
12909
  function orTerm(raw) {
@@ -12428,8 +13153,17 @@ function createSupabaseCrmProvider(options) {
12428
13153
  const { pub } = getClients();
12429
13154
  const tenantId = getTenantId();
12430
13155
  if (!tenantId) return [];
12431
- const { data } = await pub.from(T.pipelines).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("is_default", { ascending: false }).order("name");
12432
- 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 });
12433
13167
  },
12434
13168
  async getPipelineStages(pipelineId) {
12435
13169
  const { pub } = getClients();
@@ -12646,8 +13380,9 @@ function createSupabaseCrmProvider(options) {
12646
13380
  async getDealsByStage(pipelineId, filter, knownStages, limits) {
12647
13381
  const { pub } = getClients();
12648
13382
  const stages = knownStages ?? await provider.getPipelineStages(pipelineId);
12649
- const montar = async (stageId) => {
12650
- 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)");
12651
13386
  if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
12652
13387
  if (filter?.search) {
12653
13388
  const t2 = filter.search.replace(/[(),]/g, " ").trim();
@@ -12661,11 +13396,11 @@ function createSupabaseCrmProvider(options) {
12661
13396
  if (filter?.createdTo) qb = qb.lte("created_at", filter.createdTo);
12662
13397
  if (filter?.assignedToId === "none") qb = qb.is("assigned_to_id", null);
12663
13398
  else if (filter?.assignedToId) qb = qb.eq("assigned_to_id", filter.assignedToId);
12664
- const teto = limits?.[stageId] ?? DEALS_POR_ETAPA;
13399
+ const teto = limits?.[stage.id] ?? DEALS_POR_ETAPA;
12665
13400
  const { data: data2, count } = await qb.order("updated_at", { ascending: false }).limit(teto);
12666
- return { stageId, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
13401
+ return { stageId: stage.id, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
12667
13402
  };
12668
- const porEtapa = await Promise.all(stages.map((s) => montar(s.id)));
13403
+ const porEtapa = await Promise.all(stages.map((s) => montar(s)));
12669
13404
  const totals = new Map(porEtapa.map((r) => [r.stageId, r.total]));
12670
13405
  const data = porEtapa.flatMap((r) => r.rows);
12671
13406
  const deals = (data ?? []).map(toDeal);
@@ -14016,10 +14751,13 @@ function createSupabaseCrmProvider(options) {
14016
14751
  const { data } = await pub.from(T.personPhones).select("*").eq("phone_key", key);
14017
14752
  return (data ?? []).map((r) => snakeToCamel(r));
14018
14753
  },
14019
- async getFunnel(pipelineId) {
14754
+ async getFunnel(pipelineId, filter) {
14020
14755
  const { pub } = getClients();
14021
14756
  const stages = await provider.getPipelineStages(pipelineId);
14022
- 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
+ });
14023
14761
  if (error) throw new Error(error.message);
14024
14762
  const porEtapa = /* @__PURE__ */ new Map();
14025
14763
  for (const r of data ?? []) {
@@ -14372,6 +15110,7 @@ function createCrmStore(provider) {
14372
15110
  stages: [],
14373
15111
  activePipelineId: null,
14374
15112
  pipelinesLoading: true,
15113
+ stagesPipelineId: null,
14375
15114
  leads: [],
14376
15115
  leadsTotal: 0,
14377
15116
  leadsLoading: false,
@@ -14465,16 +15204,17 @@ function createCrmStore(provider) {
14465
15204
  set({ pipelines });
14466
15205
  return;
14467
15206
  }
14468
- set({ pipelines, stages, activePipelineId: active });
15207
+ set({ pipelines, stages, stagesPipelineId: active, activePipelineId: active });
14469
15208
  });
14470
15209
  } finally {
14471
15210
  set({ pipelinesLoading: false });
14472
15211
  }
14473
15212
  },
14474
15213
  async selectPipeline(pipelineId) {
14475
- if (get().activePipelineId === pipelineId) return;
15214
+ const { activePipelineId, stagesPipelineId } = get();
15215
+ if (activePipelineId === pipelineId && stagesPipelineId === pipelineId) return;
14476
15216
  const stages = await provider.getPipelineStages(pipelineId);
14477
- 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: {} });
14478
15218
  },
14479
15219
  async fetchTagDefs() {
14480
15220
  return dedup(sid + "crm:tag-defs", async () => {
@@ -14500,9 +15240,9 @@ function createCrmStore(provider) {
14500
15240
  set({ summary, summaryLoading: false });
14501
15241
  });
14502
15242
  },
14503
- async fetchFunnel(pipelineId) {
14504
- return dedup(sid + "crm:funnel:" + pipelineId, async () => {
14505
- 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);
14506
15246
  set({ funnel });
14507
15247
  });
14508
15248
  },
@@ -14852,7 +15592,11 @@ function createCrmStore(provider) {
14852
15592
  stageId,
14853
15593
  stageName: alvo?.name ?? movido.stageName,
14854
15594
  stageColor: alvo?.color ?? movido.stageColor,
14855
- 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
14856
15600
  };
14857
15601
  novo.set(stageId, [atualizado, ...novo.get(stageId) ?? []]);
14858
15602
  totais.set(stageId, (totais.get(stageId) ?? 0) + 1);
@@ -28845,6 +29589,304 @@ SELECT c.id,
28845
29589
  GRANT SELECT ON public.v_crm_companies_enriched TO authenticated;
28846
29590
  GRANT SELECT ON public.v_crm_companies_enriched TO service_role;
28847
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
+ `;
28848
29890
  var MIGRATIONS = [
28849
29891
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28850
29892
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28904,7 +29946,9 @@ var MIGRATIONS = [
28904
29946
  { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO },
28905
29947
  { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ },
28906
29948
  { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO },
28907
- { 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 }
28908
29952
  ];
28909
29953
 
28910
29954
  // src/locales/en.ts
@@ -29127,6 +30171,26 @@ var en = {
29127
30171
  "crm.rota.count": "{{count}} in the rota",
29128
30172
  "crm.pipeline.pickFunnel": "Pick a funnel",
29129
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",
29130
30194
  "crm.pipeline.loadMore": "Show {n} more",
29131
30195
  "crm.pipeline.noDeals": "No deals",
29132
30196
  "crm.pipeline.addLead": "Add lead",
@@ -29220,6 +30284,25 @@ var en = {
29220
30284
  "crm.card.markedWon": "Deal marked won",
29221
30285
  "crm.card.markedLost": "Deal marked lost",
29222
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",
29223
30306
  "crm.deals.colCity": "City",
29224
30307
  "crm.deals.cohort": "Cohort",
29225
30308
  "crm.deals.campaign": "Campaign",
@@ -29287,6 +30370,9 @@ var en = {
29287
30370
  "crm.quoteDetail.unitPrice": "Unit Price",
29288
30371
  "crm.quoteDetail.validUntil": "Valid Until",
29289
30372
  "crm.quoteDetail.viewInvoice": "View Invoice",
30373
+ "crm.itemType.service": "Service",
30374
+ "crm.itemType.product": "Product",
30375
+ "crm.itemType.other": "Other",
29290
30376
  "crm.quoteForm.addFirstItem": "Add your first item",
29291
30377
  "crm.quoteForm.addItem": "Add Item",
29292
30378
  "crm.quoteForm.cancel": "Cancel",
@@ -29317,6 +30403,7 @@ var en = {
29317
30403
  "crm.quoteForm.saving": "Saving...",
29318
30404
  "crm.quoteForm.searchClient": "Search client...",
29319
30405
  "crm.quoteForm.addAsLead": "Add as lead",
30406
+ "crm.quoteForm.selectClientFirst": "Select the client before adding items.",
29320
30407
  "crm.quoteForm.selectItemType": "Select item type:",
29321
30408
  "crm.quoteForm.statusApproved": "Approved",
29322
30409
  "crm.quoteForm.statusDraft": "Draft",
@@ -29325,6 +30412,9 @@ var en = {
29325
30412
  "crm.quoteForm.statusSent": "Sent",
29326
30413
  "crm.quoteForm.total": "Total",
29327
30414
  "crm.quoteForm.unitPrice": "Unit Price",
30415
+ "crm.quoteForm.validCustom": "Custom",
30416
+ "crm.quoteForm.validOneWeek": "1 week",
30417
+ "crm.quoteForm.validThirtyDays": "30 days",
29328
30418
  "crm.quoteForm.validUntil": "Valid Until",
29329
30419
  "crm.quotes.amount": "Amount",
29330
30420
  "crm.quotes.archive": "Archive",
@@ -29986,6 +31076,26 @@ var ptBR = {
29986
31076
  "crm.rota.count": "{{count}} na rota",
29987
31077
  "crm.pipeline.pickFunnel": "Escolher funil",
29988
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",
29989
31099
  "crm.pipeline.loadMore": "Ver mais {n}",
29990
31100
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
29991
31101
  "crm.pipeline.addLead": "Adicionar lead",
@@ -30079,6 +31189,25 @@ var ptBR = {
30079
31189
  "crm.card.markedWon": "Neg\xF3cio marcado como ganho",
30080
31190
  "crm.card.markedLost": "Neg\xF3cio marcado como perdido",
30081
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",
30082
31211
  "crm.deals.colCity": "Cidade",
30083
31212
  "crm.deals.cohort": "Safra",
30084
31213
  "crm.deals.campaign": "Campanha",
@@ -30146,6 +31275,9 @@ var ptBR = {
30146
31275
  "crm.quoteDetail.unitPrice": "Pre\xE7o Unit\xE1rio",
30147
31276
  "crm.quoteDetail.validUntil": "V\xE1lido At\xE9",
30148
31277
  "crm.quoteDetail.viewInvoice": "Ver Fatura",
31278
+ "crm.itemType.service": "Servi\xE7o",
31279
+ "crm.itemType.product": "Produto",
31280
+ "crm.itemType.other": "Outro",
30149
31281
  "crm.quoteForm.addFirstItem": "Adicione seu primeiro item",
30150
31282
  "crm.quoteForm.addItem": "Adicionar Item",
30151
31283
  "crm.quoteForm.cancel": "Cancelar",
@@ -30176,6 +31308,7 @@ var ptBR = {
30176
31308
  "crm.quoteForm.saving": "Salvando...",
30177
31309
  "crm.quoteForm.searchClient": "Buscar cliente...",
30178
31310
  "crm.quoteForm.addAsLead": "Adicionar como lead",
31311
+ "crm.quoteForm.selectClientFirst": "Selecione o cliente antes de adicionar itens.",
30179
31312
  "crm.quoteForm.selectItemType": "Selecione o tipo de item:",
30180
31313
  "crm.quoteForm.statusApproved": "Aprovado",
30181
31314
  "crm.quoteForm.statusDraft": "Rascunho",
@@ -30184,6 +31317,9 @@ var ptBR = {
30184
31317
  "crm.quoteForm.statusSent": "Enviado",
30185
31318
  "crm.quoteForm.total": "Total",
30186
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",
30187
31323
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
30188
31324
  "crm.quotes.amount": "Valor",
30189
31325
  "crm.quotes.archive": "Arquivar",
@@ -31027,8 +32163,17 @@ function registerCrmTimelineSource() {
31027
32163
  }
31028
32164
  });
31029
32165
  }
31030
-
31031
- // 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);
31032
32177
  function buildCrmCustomerEntity(name, namePlural, kind = "customer") {
31033
32178
  return {
31034
32179
  name,
@@ -31040,37 +32185,136 @@ function buildCrmCustomerEntity(name, namePlural, kind = "customer") {
31040
32185
  subtitleField: "documentNumber",
31041
32186
  defaultSort: "name",
31042
32187
  formColumns: 2,
32188
+ facets: [activeFacet({ active: "Ativos", inactive: "Inativos", all: "Todos" })],
31043
32189
  fieldGroups: [
32190
+ { id: "identity", label: "Dados pessoais", columns: 2 },
31044
32191
  { id: "contact", label: "Contato", columns: 2 },
31045
- { 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 }
31046
32195
  ],
31047
32196
  fields: [
31048
- { key: "name", label: "Nome", type: "text", required: true, searchable: true, showInTable: true, group: "contact" },
31049
- // CPF only. Um CNPJ identifica uma EMPRESA, não a identidade de uma
31050
- // pessoa (plugin-crm 014 §3): 45% dos leads reais dividem CNPJ com
31051
- // alguém, então um CNPJ numa linha de pessoa ou colide em
31052
- // `people_tenant_document_uidx` ou vira uma segunda identidade da casa
31053
- // que o CRM já conhece. Cliente pessoa jurídica se cria em Empresas.
31054
- // No fornecedor o documento costuma ser CNPJ, e rotulá-lo "CPF" faz o
31055
- // operador deixar o campo vazio — a nota chega com o CNPJ impresso e não
31056
- // tem onde entrar. Do lado do cliente a regra continua: um CNPJ numa
31057
- // linha de pessoa é uma segunda identidade da casa que o CRM já conhece,
31058
- // e cliente pessoa jurídica se cria em Empresas.
31059
- { key: "documentNumber", label: kind === "supplier" ? "CNPJ / CPF" : "CPF", type: "text", searchable: true, showInTable: true, group: "contact" },
31060
- { key: "phone", label: "Telefone", type: "phone", searchable: true, showInTable: true, group: "contact" },
31061
- { key: "email", label: "E-mail", type: "email", searchable: true, showInTable: false, group: "contact" },
31062
- { key: "isActive", label: "Ativo", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true, group: "record" },
31063
- { 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 }
31064
32282
  ],
31065
32283
  data: {
31066
32284
  table: "people",
31067
32285
  tenantScoped: true,
31068
32286
  archetype: "person",
31069
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
+ ],
31070
32302
  searchColumns: ["name", "email", "phone", "document_number"]
31071
32303
  }
31072
32304
  };
31073
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"];
31074
32318
  var VOCABULARY = {
31075
32319
  education: { one: "Aluno", many: "Alunos" },
31076
32320
  health: { one: "Paciente", many: "Pacientes" }