@fayz-ai/plugin-crm 0.28.2 → 0.29.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.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
1
+ import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
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, 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';
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
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, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, MoreHorizontal, 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, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, 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';
@@ -952,6 +952,14 @@ function dealMatches(deal, query, tagDefs) {
952
952
  ];
953
953
  return haystack.some((v) => v && fold(v).includes(text));
954
954
  }
955
+
956
+ // src/lib/deal-headline.ts
957
+ function dealHeadline(deal) {
958
+ return deal.groupName || deal.companyName || deal.contactName || deal.title || "";
959
+ }
960
+ function dealHouseLine(deal) {
961
+ return deal.groupName && deal.companyName ? deal.companyName : null;
962
+ }
955
963
  async function loadTeam() {
956
964
  const supabase = getSupabaseClientOptional();
957
965
  if (!supabase) return [];
@@ -1170,11 +1178,15 @@ function DealCard({ deal, saving, currency, tagDefs, temperature, risk, display,
1170
1178
  className: `group rounded-card border bg-card p-3 transition-shadow ${saving ? "opacity-70" : "hover:shadow-sm cursor-grab active:cursor-grabbing active:opacity-70"}`,
1171
1179
  children: [
1172
1180
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
1173
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium", children: deal.companyName || deal.contactName || deal.title }),
1181
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium", children: dealHeadline(deal) }),
1174
1182
  saving ? /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" }) : /* @__PURE__ */ jsx(OwnerControl, { ownerId: deal.assignedToId, team, onAssign })
1175
1183
  ] }),
1176
1184
  (() => {
1177
1185
  const partes = [
1186
+ // WHICH HOUSE, when the headline is the group. "GRUPO TEMPERANI"
1187
+ // alone does not tell you which of the three CNPJs this conversation
1188
+ // came in through, and that is the one the seller dials.
1189
+ dealHouseLine(deal),
1178
1190
  // O PONTO DE CONTATO, quando a manchete ja e a empresa. Invertido em
1179
1191
  // relacao ao que era: antes a empresa e que descia para ca.
1180
1192
  deal.companyName && deal.contactName ? deal.contactName : null,
@@ -1182,7 +1194,7 @@ function DealCard({ deal, saving, currency, tagDefs, temperature, risk, display,
1182
1194
  // pessoa em quase todos os 316 negócios — herança de quando o
1183
1195
  // negócio era da pessoa —, e repeti-lo ao lado do ponto de contato
1184
1196
  // dava "Victor Brandes · Victor Brandes" no card.
1185
- deal.title && deal.title !== deal.companyName && deal.title !== deal.contactName ? deal.title : null,
1197
+ deal.title && deal.title !== deal.companyName && deal.title !== deal.contactName && deal.title !== deal.groupName ? deal.title : null,
1186
1198
  deal.contactCity || null
1187
1199
  ].filter(Boolean);
1188
1200
  if (!partes.length) return null;
@@ -2179,9 +2191,15 @@ function DealListView({ onOpenDeal }) {
2179
2191
  // esta coluna nada na lista diz que são a mesma casa.
2180
2192
  accessorKey: "companyName",
2181
2193
  header: t2("crm.card.companyTitle"),
2182
- cell: ({ row }) => row.original.companyName ? /* @__PURE__ */ jsxs("span", { className: "inline-flex max-w-[14rem] items-center gap-1.5 text-xs", children: [
2183
- /* @__PURE__ */ jsx(Building2, { className: "h-3 w-3 shrink-0 text-muted-foreground" }),
2184
- /* @__PURE__ */ jsx("span", { className: "truncate", title: row.original.companyDocument ?? void 0, children: row.original.companyName })
2194
+ cell: ({ row }) => row.original.companyName ? /* @__PURE__ */ jsxs("div", { className: "min-w-0 max-w-[14rem]", children: [
2195
+ /* @__PURE__ */ jsxs("span", { className: "inline-flex w-full items-center gap-1.5 text-xs", children: [
2196
+ /* @__PURE__ */ jsx(Building2, { className: "h-3 w-3 shrink-0 text-muted-foreground" }),
2197
+ /* @__PURE__ */ jsx("span", { className: "truncate", title: row.original.companyDocument ?? void 0, children: row.original.companyName })
2198
+ ] }),
2199
+ row.original.groupName && /* @__PURE__ */ jsxs("span", { className: "mt-0.5 inline-flex w-full items-center gap-1.5 text-[11px] text-muted-foreground", children: [
2200
+ /* @__PURE__ */ jsx(Network, { className: "h-3 w-3 shrink-0" }),
2201
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: row.original.groupName })
2202
+ ] })
2185
2203
  ] }) : /* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: "\u2014" })
2186
2204
  },
2187
2205
  {
@@ -3082,22 +3100,22 @@ function ActivityTimeline({ activities, loading, locale, contactName }) {
3082
3100
  /* @__PURE__ */ jsx("span", { className: "relative flex h-6 w-6 items-center justify-center rounded-full border bg-card", children: /* @__PURE__ */ jsx(Icon, { className: "h-3 w-3 text-muted-foreground" }) })
3083
3101
  ] }),
3084
3102
  /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 pt-0.5", children: [
3085
- /* @__PURE__ */ jsxs("div", { className: "flex items-baseline gap-2", children: [
3086
- /* @__PURE__ */ jsxs("p", { className: "min-w-0 flex-1 break-words text-xs font-medium leading-5", children: [
3103
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-[minmax(0,1fr)_auto_auto] items-center gap-2", children: [
3104
+ /* @__PURE__ */ jsxs("p", { className: "min-w-0 break-words text-xs font-medium leading-5", children: [
3087
3105
  a.title,
3088
- a.createdByName && /* @__PURE__ */ jsxs("span", { className: "ml-1.5 inline-flex items-center gap-1 align-middle font-normal text-muted-foreground", children: [
3089
- "\xB7 ",
3090
- /* @__PURE__ */ jsx(PersonAvatar, { name: a.createdByName, size: "xs" }),
3091
- " ",
3092
- a.createdByName
3093
- ] }),
3094
3106
  a.contactName && a.contactName !== contactName && /* @__PURE__ */ jsxs("span", { className: "ml-1.5 font-normal text-muted-foreground/70", children: [
3095
3107
  "\xB7 ",
3096
3108
  a.contactName
3097
3109
  ] })
3098
3110
  ] }),
3099
- a.completedAt && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 shrink-0 text-success" }),
3100
- /* @__PURE__ */ jsx(AutomationBolt, { activityType: a.activityType, messages }),
3111
+ /* @__PURE__ */ jsxs("div", { className: "flex min-w-[5.5rem] items-center justify-end gap-1.5", children: [
3112
+ a.completedAt && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 shrink-0 text-success" }),
3113
+ /* @__PURE__ */ jsx(AutomationBolt, { activityType: a.activityType, messages }),
3114
+ a.createdByName && /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center justify-end gap-1 text-xs font-normal text-muted-foreground", children: [
3115
+ /* @__PURE__ */ jsx(PersonAvatar, { name: a.createdByName, size: "xs" }),
3116
+ /* @__PURE__ */ jsx("span", { className: "max-w-20 truncate", children: a.createdByName })
3117
+ ] })
3118
+ ] }),
3101
3119
  /* @__PURE__ */ jsx("time", { className: "shrink-0 text-[10px] tabular-nums text-muted-foreground/70", children: formatRelativeTime(a.createdAt, locale) })
3102
3120
  ] }),
3103
3121
  a.description && /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-[11px] leading-snug text-muted-foreground", children: a.description })
@@ -3765,6 +3783,57 @@ function TemperatureBadge({ score, size = "sm", className }) {
3765
3783
  }
3766
3784
  );
3767
3785
  }
3786
+ function toLocalDate(value) {
3787
+ const year = value.getFullYear();
3788
+ const month = String(value.getMonth() + 1).padStart(2, "0");
3789
+ const day = String(value.getDate()).padStart(2, "0");
3790
+ return `${year}-${month}-${day}`;
3791
+ }
3792
+ function addDaysToDate(value, days) {
3793
+ const result = new Date(value.getFullYear(), value.getMonth(), value.getDate());
3794
+ result.setDate(result.getDate() + days);
3795
+ return toLocalDate(result);
3796
+ }
3797
+ function addMonthsToDate(value, months) {
3798
+ const day = value.getDate();
3799
+ const result = new Date(value.getFullYear(), value.getMonth() + months, 1);
3800
+ const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
3801
+ result.setDate(Math.min(day, lastDay));
3802
+ return toLocalDate(result);
3803
+ }
3804
+ function defaultFutureContactDate(now2 = /* @__PURE__ */ new Date()) {
3805
+ return addMonthsToDate(now2, 1);
3806
+ }
3807
+ function FutureContactPicker({ value, onChange, required = false }) {
3808
+ const t2 = useTranslation();
3809
+ const today2 = /* @__PURE__ */ new Date();
3810
+ const presets = [
3811
+ { label: t2("crm.followUp.inSevenDays"), value: addDaysToDate(today2, 7) },
3812
+ { label: t2("crm.followUp.inOneMonth"), value: addMonthsToDate(today2, 1) },
3813
+ { label: t2("crm.followUp.inThreeMonths"), value: addMonthsToDate(today2, 3) }
3814
+ ];
3815
+ return /* @__PURE__ */ jsxs("div", { className: "w-full space-y-2 rounded-lg border border-amber-300/70 bg-amber-50/60 p-2.5 dark:border-amber-700/60 dark:bg-amber-950/20", children: [
3816
+ /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-1.5 text-xs font-medium text-foreground", children: [
3817
+ /* @__PURE__ */ jsx(CalendarClock, { className: "h-3.5 w-3.5 text-amber-600" }),
3818
+ t2("crm.followUp.futureContact"),
3819
+ required ? " *" : ""
3820
+ ] }),
3821
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: presets.map((preset) => /* @__PURE__ */ jsx(
3822
+ Button,
3823
+ {
3824
+ type: "button",
3825
+ size: "sm",
3826
+ variant: value === preset.value ? "default" : "outline",
3827
+ className: "h-7 px-2 text-[11px]",
3828
+ onClick: () => onChange(preset.value),
3829
+ children: preset.label
3830
+ },
3831
+ preset.value
3832
+ )) }),
3833
+ /* @__PURE__ */ jsx(DatePicker, { value, onChange }),
3834
+ required && !value && /* @__PURE__ */ jsx("p", { className: "text-[11px] text-destructive", children: t2("crm.followUp.futureRequired") })
3835
+ ] });
3836
+ }
3768
3837
  function Section({ title, action, children }) {
3769
3838
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3770
3839
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
@@ -3842,6 +3911,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3842
3911
  const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3843
3912
  const [deal, setDeal] = useState(null);
3844
3913
  const [lead, setLead] = useState(null);
3914
+ const [contato, setContato] = useState(null);
3845
3915
  const [stages, setStages] = useState([]);
3846
3916
  const [activities, setActivities] = useState([]);
3847
3917
  const [quotes2, setQuotes] = useState([]);
@@ -3858,6 +3928,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3858
3928
  () => new Set(pessoasDaCasa.map((x) => x.companyId)).size,
3859
3929
  [pessoasDaCasa]
3860
3930
  );
3931
+ const pessoaDoCard = contato ?? lead;
3861
3932
  const [team, setTeam] = useState(null);
3862
3933
  const [myUserId, setMyUserId] = useState(null);
3863
3934
  const [savingOwner, setSavingOwner] = useState(false);
@@ -3910,6 +3981,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3910
3981
  const [ctype, setCtype] = useState("whatsapp");
3911
3982
  const [cnote, setCnote] = useState("");
3912
3983
  const [coutcome, setCoutcome] = useState("connected");
3984
+ const [cfutureDate, setCfutureDate] = useState("");
3913
3985
  const [cdue, setCdue] = useState(() => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10));
3914
3986
  const [csaving, setCsaving] = useState(false);
3915
3987
  const composerRef = useRef(null);
@@ -3967,6 +4039,8 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3967
4039
  }, [activities, timelineTab, CONTACT_TYPES2]);
3968
4040
  async function logFromComposer() {
3969
4041
  if (csaving) return;
4042
+ const needsFutureContact = CONTACT_TYPES2.has(ctype) && coutcome === "not_now";
4043
+ if (needsFutureContact && !cfutureDate) return;
3970
4044
  const body = cnote.trim();
3971
4045
  if (!body && (ctype === "note" || ctype === "task")) return;
3972
4046
  setCsaving(true);
@@ -3978,14 +4052,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3978
4052
  leadId: deal?.leadId,
3979
4053
  contactId: deal?.contactId,
3980
4054
  activityType: ctype,
3981
- outcome: CONTACT_TYPES2.has(ctype) ? coutcome : void 0,
3982
- title: firstLine ? firstLine.slice(0, 120) : typeLabel,
3983
- description: body && firstLine !== body ? body : void 0,
4055
+ outcome: CONTACT_TYPES2.has(ctype) && coutcome !== "not_now" ? coutcome : void 0,
4056
+ title: coutcome === "not_now" ? t2("crm.outcome.not_now") : firstLine ? firstLine.slice(0, 120) : typeLabel,
4057
+ description: coutcome === "not_now" ? body || void 0 : body && firstLine !== body ? body : void 0,
3984
4058
  dueDate: ctype === "task" ? cdue : void 0
3985
4059
  });
3986
- setActivities((prev) => [logged, ...prev]);
4060
+ const futureTask = needsFutureContact ? await createActivity({
4061
+ dealId,
4062
+ leadId: deal?.leadId,
4063
+ contactId: deal?.contactId,
4064
+ activityType: "task",
4065
+ title: t2("crm.followUp.futureTaskTitle"),
4066
+ dueDate: cfutureDate,
4067
+ assignedToId: deal?.assignedToId
4068
+ }) : void 0;
4069
+ setActivities((prev) => futureTask ? [futureTask, logged, ...prev] : [logged, ...prev]);
3987
4070
  setCnote("");
3988
4071
  setCoutcome("connected");
4072
+ setCfutureDate("");
3989
4073
  setComposerOpen(false);
3990
4074
  setTimeout(() => {
3991
4075
  void provider.getLiveDealById(dealId).then((d) => {
@@ -4020,21 +4104,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4020
4104
  });
4021
4105
  }
4022
4106
  const leadP = d.leadId ? provider.getLeadById(d.leadId) : Promise.resolve(null);
4023
- void leadP.then((l) => {
4107
+ const contatoP = d.contactId && d.contactId !== d.leadId ? provider.getLeadById(d.contactId).catch(() => null) : Promise.resolve(null);
4108
+ void Promise.all([leadP, contatoP]).then(([l, c]) => {
4024
4109
  if (cancelled) return;
4025
4110
  setLead(l);
4111
+ setContato(c);
4112
+ const p = c ?? l;
4026
4113
  setDraft({
4027
- name: l?.name ?? d.contactName ?? d.title ?? "",
4028
- email: l?.email ?? "",
4029
- phone: l?.phone ?? "",
4030
- company: l?.company ?? "",
4114
+ name: p?.name ?? d.contactName ?? d.title ?? "",
4115
+ email: p?.email ?? "",
4116
+ phone: p?.phone ?? "",
4117
+ company: p?.company ?? "",
4031
4118
  value: d.value ?? 0,
4032
4119
  expectedCloseDate: d.expectedCloseDate ?? "",
4033
4120
  notes: d.notes && d.notes !== d.title ? d.notes : ""
4034
4121
  });
4035
4122
  setLoading(false);
4036
- if (l) {
4037
- void provider.getLeadScores([l.id]).then((rows) => {
4123
+ if (p) {
4124
+ void provider.getLeadScores([p.id]).then((rows) => {
4038
4125
  if (!cancelled) setScore(rows[0] ?? null);
4039
4126
  }).catch(() => {
4040
4127
  if (!cancelled) setScore(null);
@@ -4042,10 +4129,10 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4042
4129
  } else {
4043
4130
  setScore(null);
4044
4131
  }
4045
- const companyId = d.companyId ?? l?.companyId;
4132
+ const companyId = d.companyId ?? p?.companyId;
4046
4133
  if (companyId) {
4047
- void provider.getCompanyById(companyId).then((c) => {
4048
- if (!cancelled) setCompany(c);
4134
+ void provider.getCompanyById(companyId).then((c2) => {
4135
+ if (!cancelled) setCompany(c2);
4049
4136
  });
4050
4137
  void provider.getCompanyGroupPeople(companyId).catch(() => []).then((gente) => {
4051
4138
  if (!cancelled) setPessoasDaCasa(gente);
@@ -4128,6 +4215,19 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4128
4215
  const atualizado = await provider.updateDeal(deal.id, { contactId: personId });
4129
4216
  const nova = pessoasDaCasa.find((x) => x.personId === personId);
4130
4217
  setDeal({ ...atualizado, contactName: nova?.personName ?? atualizado.contactName });
4218
+ const pessoa = await provider.getLeadById(personId).catch(() => null);
4219
+ setContato(pessoa);
4220
+ if (pessoa) {
4221
+ setDraft((d) => d ? {
4222
+ ...d,
4223
+ name: pessoa.name ?? d.name,
4224
+ email: pessoa.email ?? "",
4225
+ phone: pessoa.phone ?? "",
4226
+ company: pessoa.company ?? d.company
4227
+ } : d);
4228
+ setScore(void 0);
4229
+ void provider.getLeadScores([pessoa.id]).then((rows) => setScore(rows[0] ?? null)).catch(() => setScore(null));
4230
+ }
4131
4231
  } catch (err) {
4132
4232
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
4133
4233
  } finally {
@@ -4150,9 +4250,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4150
4250
  if (!deal || !draft || saving) return;
4151
4251
  setSaving(true);
4152
4252
  try {
4153
- if (lead) {
4154
- await updateLead(lead.id, {
4155
- name: draft.name.trim() || lead.name,
4253
+ if (pessoaDoCard) {
4254
+ await updateLead(pessoaDoCard.id, {
4255
+ name: draft.name.trim() || pessoaDoCard.name,
4156
4256
  email: draft.email.trim() || void 0,
4157
4257
  phone: draft.phone.trim() || void 0,
4158
4258
  company: draft.company.trim() || void 0
@@ -4164,7 +4264,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4164
4264
  notes: draft.notes.trim() || void 0
4165
4265
  });
4166
4266
  setDeal(patched);
4167
- if (lead) setLead({ ...lead, name: draft.name.trim() || lead.name, email: draft.email, phone: draft.phone, company: draft.company });
4267
+ const repintada = (x) => ({ ...x, name: draft.name.trim() || x.name, email: draft.email, phone: draft.phone, company: draft.company });
4268
+ if (contato) setContato(repintada(contato));
4269
+ else if (lead) setLead(repintada(lead));
4168
4270
  toast.success(t2("crm.card.saved"));
4169
4271
  } catch (err) {
4170
4272
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
@@ -4177,7 +4279,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4177
4279
  }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4178
4280
  /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4179
4281
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
4180
- /* @__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?.companyName || deal?.title || t2("crm.dealSidebar.deal") }),
4282
+ /* @__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") }),
4181
4283
  /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4182
4284
  deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => {
4183
4285
  void close("lost");
@@ -4279,17 +4381,18 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4279
4381
  /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
4280
4382
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4281
4383
  /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: draft.name || deal?.contactName || "\u2014" }),
4282
- (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company })
4384
+ (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company }),
4385
+ pessoaDoCard?.companyRole && /* @__PURE__ */ jsx("p", { className: "truncate text-[11px] text-muted-foreground/80", children: pessoaDoCard.companyRole })
4283
4386
  ] }),
4284
4387
  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,
4285
4388
  /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-center gap-3 pt-1", children: [
4286
- lead?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
4389
+ pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
4287
4390
  /* @__PURE__ */ jsx(
4288
4391
  TalkToPerson,
4289
4392
  {
4290
- personId: lead.id,
4291
- name: lead.name,
4292
- phone: lead.phone,
4393
+ personId: pessoaDoCard.id,
4394
+ name: pessoaDoCard.name,
4395
+ phone: pessoaDoCard.phone,
4293
4396
  variant: "icon",
4294
4397
  className: "flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm transition-opacity hover:opacity-85"
4295
4398
  }
@@ -4481,9 +4584,13 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4481
4584
  }
4482
4585
  ),
4483
4586
  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
4484
- CONTACT_TYPES2.has(ctype) && /* @__PURE__ */ jsxs(Select, { value: coutcome, onValueChange: (v) => setCoutcome(v), children: [
4587
+ CONTACT_TYPES2.has(ctype) && /* @__PURE__ */ jsxs(Select, { value: coutcome, onValueChange: (v) => {
4588
+ const nextOutcome = v;
4589
+ setCoutcome(nextOutcome);
4590
+ if (nextOutcome === "not_now" && !cfutureDate) setCfutureDate(defaultFutureContactDate());
4591
+ }, children: [
4485
4592
  /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-auto min-w-[10rem] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
4486
- /* @__PURE__ */ jsx(SelectContent, { children: ["connected", "no_answer", "left_message", "replied", "scheduled"].map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o, children: t2(`crm.outcome.${o}`) }, o)) })
4593
+ /* @__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)) })
4487
4594
  ] }),
4488
4595
  ctype === "task" && /* @__PURE__ */ jsx(
4489
4596
  "input",
@@ -4494,11 +4601,12 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4494
4601
  className: "h-8 rounded-lg border bg-background px-2 text-xs outline-none focus:ring-2 focus:ring-ring"
4495
4602
  }
4496
4603
  ),
4604
+ CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && /* @__PURE__ */ jsx(FutureContactPicker, { value: cfutureDate, onChange: setCfutureDate, required: true }),
4497
4605
  /* @__PURE__ */ jsxs("div", { className: "ml-auto flex items-center gap-1.5", children: [
4498
4606
  /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => setComposerOpen(false), children: t2("crm.card.cancelEdit") }),
4499
4607
  /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => {
4500
4608
  void logFromComposer();
4501
- }, disabled: csaving, children: [
4609
+ }, disabled: csaving || CONTACT_TYPES2.has(ctype) && coutcome === "not_now" && !cfutureDate, children: [
4502
4610
  csaving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }),
4503
4611
  t2("crm.followUp.save")
4504
4612
  ] })
@@ -4508,6 +4616,13 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4508
4616
  /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4509
4617
  ] }),
4510
4618
  /* @__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: [
4619
+ 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: [
4620
+ /* @__PURE__ */ jsx(Network, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4621
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4622
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: deal.groupName }),
4623
+ deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
4624
+ ] })
4625
+ ] }) }),
4511
4626
  company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4512
4627
  "button",
4513
4628
  {
@@ -6767,7 +6882,7 @@ function LeadQualification({ lead }) {
6767
6882
  }
6768
6883
  var PREFERRED_ORDER = ["whatsapp", "call", "visit", "email", "meeting", "note"];
6769
6884
  var CONTACT_TYPES = /* @__PURE__ */ new Set(["whatsapp", "call", "visit", "email", "meeting"]);
6770
- var OUTCOMES = ["connected", "no_answer", "left_message", "replied", "scheduled"];
6885
+ var OUTCOMES = ["connected", "no_answer", "left_message", "replied", "scheduled", "not_now"];
6771
6886
  function LogActivityButton({ target, onLogged }) {
6772
6887
  const t2 = useTranslation();
6773
6888
  const provider = useCrmProvider();
@@ -6803,6 +6918,7 @@ function LogActivityButton({ target, onLogged }) {
6803
6918
  const asksOutcome = CONTACT_TYPES.has(type);
6804
6919
  async function submit() {
6805
6920
  if (saving) return;
6921
+ if (asksOutcome && outcome === "not_now" && !nextDate) return;
6806
6922
  const body = note.trim();
6807
6923
  setSaving(true);
6808
6924
  try {
@@ -6810,17 +6926,17 @@ function LogActivityButton({ target, onLogged }) {
6810
6926
  const logged = await createActivity({
6811
6927
  ...target,
6812
6928
  activityType: type,
6813
- outcome: asksOutcome ? outcome : void 0,
6929
+ outcome: asksOutcome && outcome !== "not_now" ? outcome : void 0,
6814
6930
  // O título é a primeira linha do relato — é o que a linha do tempo
6815
6931
  // mostra em negrito. Sem relato, o tipo já diz o que aconteceu.
6816
- title: firstLine ? firstLine.slice(0, 120) : typeLabel,
6817
- description: body && firstLine !== body ? body : void 0
6932
+ title: outcome === "not_now" ? t2("crm.outcome.not_now") : firstLine ? firstLine.slice(0, 120) : typeLabel,
6933
+ description: outcome === "not_now" ? body || void 0 : body && firstLine !== body ? body : void 0
6818
6934
  });
6819
6935
  if (nextDate) {
6820
6936
  await createActivity({
6821
6937
  ...target,
6822
6938
  activityType: "task",
6823
- title: t2("crm.followUp.defaultNextTitle", { type: typeLabel }),
6939
+ title: asksOutcome && outcome === "not_now" ? t2("crm.followUp.futureTaskTitle") : t2("crm.followUp.defaultNextTitle", { type: typeLabel }),
6824
6940
  dueDate: nextDate
6825
6941
  });
6826
6942
  }
@@ -6853,7 +6969,11 @@ function LogActivityButton({ target, onLogged }) {
6853
6969
  ] }) }, opt.value);
6854
6970
  }) })
6855
6971
  ] }),
6856
- asksOutcome && /* @__PURE__ */ jsxs(Select, { value: outcome, onValueChange: (v) => setOutcome(v), children: [
6972
+ asksOutcome && /* @__PURE__ */ jsxs(Select, { value: outcome, onValueChange: (v) => {
6973
+ const nextOutcome = v;
6974
+ setOutcome(nextOutcome);
6975
+ if (nextOutcome === "not_now" && !nextDate) setNextDate(defaultFutureContactDate());
6976
+ }, children: [
6857
6977
  /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9 text-sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
6858
6978
  /* @__PURE__ */ jsx(SelectContent, { children: OUTCOMES.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o, children: t2(`crm.outcome.${o}`) }, o)) })
6859
6979
  ] }),
@@ -6891,16 +7011,12 @@ function LogActivityButton({ target, onLogged }) {
6891
7011
  }
6892
7012
  )
6893
7013
  ] }),
6894
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
6895
- /* @__PURE__ */ jsx(CalendarClock, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
6896
- /* @__PURE__ */ jsx(DatePicker, { value: nextDate, onChange: setNextDate }),
6897
- /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: t2("crm.followUp.nextStepShort") })
6898
- ] }),
7014
+ /* @__PURE__ */ jsx(FutureContactPicker, { value: nextDate, onChange: setNextDate, required: asksOutcome && outcome === "not_now" }),
6899
7015
  /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2 pt-0.5", children: [
6900
7016
  /* @__PURE__ */ jsx(Button, { size: "sm", variant: "ghost", onClick: () => setOpen(false), children: t2("common.cancel") }),
6901
7017
  /* @__PURE__ */ jsxs(Button, { size: "sm", onClick: () => {
6902
7018
  void submit();
6903
- }, disabled: saving, children: [
7019
+ }, disabled: saving || asksOutcome && outcome === "not_now" && !nextDate, children: [
6904
7020
  saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
6905
7021
  t2("crm.followUp.save")
6906
7022
  ] })
@@ -9926,24 +10042,11 @@ function CrmPage({ config, provider, store, registries }) {
9926
10042
  "distribution-board": 0,
9927
10043
  settings: 1
9928
10044
  }, "dashboard");
9929
- const [onboardingComplete, setOnboardingComplete] = useState(() => {
9930
- try {
9931
- return localStorage.getItem("saas-core:crm-onboarded") === "true";
9932
- } catch {
9933
- return false;
9934
- }
9935
- });
9936
- useEffect(() => {
9937
- if (onboardingComplete) return;
9938
- let cancelled = false;
9939
- void provider.getLeads({ pageSize: 1 }).then((res) => {
9940
- if (!cancelled && res.total > 0) setOnboardingComplete(true);
9941
- }).catch(() => {
9942
- });
9943
- return () => {
9944
- cancelled = true;
9945
- };
9946
- }, [onboardingComplete, provider]);
10045
+ const checkExistingData = useCallback(
10046
+ async () => (await provider.getLeads({ pageSize: 1 })).total > 0,
10047
+ [provider]
10048
+ );
10049
+ const onboarding = usePluginOnboardingGate("saas-core:crm-onboarded", checkExistingData);
9947
10050
  const isSettings = view === "settings";
9948
10051
  const isSummary = view === "dashboard";
9949
10052
  const leadsFamilyTab = view === "leads-list" || view === "leads-new" ? "leads" : view === "companies-list" || view === "companies-new" ? "companies" : view === "company-groups" ? "groups" : null;
@@ -9959,14 +10062,11 @@ function CrmPage({ config, provider, store, registries }) {
9959
10062
  ...config.modules.quotes ? [{ id: "new-quote", label: t2("crm.quickActions.newQuote"), icon: "FileText", description: t2("crm.quickActions.newQuoteDesc"), action: () => navigate("quotes-new") }] : [],
9960
10063
  ...config.modules.activities ? [{ id: "log-activity", label: t2("crm.quickActions.logActivity"), icon: "MessageCircle", description: t2("crm.quickActions.logActivityDesc"), action: () => navigate("activities") }] : []
9961
10064
  ], [config.modules]);
9962
- if (!onboardingComplete && isSummary) {
9963
- return /* @__PURE__ */ jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsx(CrmOnboarding, { onComplete: () => {
9964
- setOnboardingComplete(true);
9965
- try {
9966
- localStorage.setItem("saas-core:crm-onboarded", "true");
9967
- } catch {
9968
- }
9969
- } }) });
10065
+ if (isSummary && onboarding.status === "checking") {
10066
+ return /* @__PURE__ */ jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsx(PluginOnboardingGateSkeleton, {}) });
10067
+ }
10068
+ if (isSummary && onboarding.status === "needed") {
10069
+ return /* @__PURE__ */ jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsx(CrmOnboarding, { onComplete: onboarding.complete }) });
9970
10070
  }
9971
10071
  if (isSettings && registries && registries.length > 0) {
9972
10072
  return /* @__PURE__ */ jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsx(PageTransition, { transitionKey: "settings", direction, children: /* @__PURE__ */ jsxs("div", { style: { padding: "24px", display: "flex", flexDirection: "column", gap: "20px" }, children: [
@@ -10939,6 +11039,11 @@ function createMockCrmProvider(options) {
10939
11039
  const deal = store.deals.find((d) => d.id === id);
10940
11040
  if (!deal) throw new Error(`Deal ${id} not found`);
10941
11041
  Object.assign(deal, data, { updatedAt: now() });
11042
+ if (data.contactId !== void 0) {
11043
+ const pessoa = store.leads.find((l) => l.id === data.contactId) ?? store.companyPeople.find((cp) => cp.personId === data.contactId);
11044
+ const nome = pessoa && ("name" in pessoa ? pessoa.name : pessoa.personName);
11045
+ deal.contactName = data.contactId ? nome ?? deal.contactName : void 0;
11046
+ }
10942
11047
  return deal;
10943
11048
  },
10944
11049
  async moveDealToStage(dealId, stageId) {
@@ -12011,6 +12116,11 @@ function toDeal(r) {
12011
12116
  companyId: r.company_id ?? void 0,
12012
12117
  companyName: r.company_name ?? void 0,
12013
12118
  companyDocument: r.company_document ?? void 0,
12119
+ // Since 058. A board of 200 cards resolves the group in the same round
12120
+ // trip that fetched the cards; asking per card would be 200 more.
12121
+ groupId: r.group_id ?? void 0,
12122
+ groupName: r.group_name ?? void 0,
12123
+ groupCompanies: r.group_companies ?? void 0,
12014
12124
  lostReason: r.lost_reason ?? void 0,
12015
12125
  tags: r.tags ?? [],
12016
12126
  // Coluna própria desde a 027. Antes dela a view só expunha
@@ -12102,6 +12212,11 @@ async function mergePersonMetadata(personId, patch) {
12102
12212
  const current = row?.metadata ?? {};
12103
12213
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
12104
12214
  }
12215
+ async function mergeDealMetadata(dealId, patch) {
12216
+ const { pub } = getClients();
12217
+ const { data } = await pub.from(T.deals).select("metadata").eq("id", dealId).maybeSingle();
12218
+ return { ...data?.metadata ?? {}, ...patch };
12219
+ }
12105
12220
  async function sincronizarDonoNaPessoa(dealId, userId) {
12106
12221
  try {
12107
12222
  const { pub, core } = getClients();
@@ -12485,6 +12600,11 @@ function createSupabaseCrmProvider(options) {
12485
12600
  if (partial.notes !== void 0) row.notes = partial.notes || null;
12486
12601
  if (partial.tags != null) row.tags = partial.tags;
12487
12602
  if (partial.assignedToId !== void 0) row.assigned_to_id = partial.assignedToId ?? null;
12603
+ if (partial.contactId !== void 0) {
12604
+ row.contact_id = partial.contactId ?? null;
12605
+ const nome = partial.contactId ? (await pub.from("people").select("name").eq("id", partial.contactId).maybeSingle()).data?.name : null;
12606
+ if (nome) row.metadata = await mergeDealMetadata(id, { contactName: nome });
12607
+ }
12488
12608
  if (Object.keys(row).length > 0) {
12489
12609
  row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
12490
12610
  const { error } = await pub.from(T.deals).update(row).eq("id", id);
@@ -28407,6 +28527,103 @@ CREATE OR REPLACE VIEW public.v_crm_deal_group WITH (security_invoker = true) AS
28407
28527
  GRANT SELECT ON public.v_crm_deal_group TO authenticated;
28408
28528
  GRANT SELECT ON public.v_crm_deal_group TO service_role;
28409
28529
  `;
28530
+ var MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO = `-- 058 \u2014 The card says the GROUP's name, and says who the contact IS.
28531
+ --
28532
+ -- Two things the board was getting wrong about the same card, both of them
28533
+ -- rooted in \`v_deals\` answering from a stale copy instead of from the link.
28534
+ --
28535
+ -- 1. THE NAME ON THE CARD.
28536
+ -- Migration 057 made the deal belong to the economic group: three CNPJs of
28537
+ -- GRUPO TEMPERANI now share one card. But the card kept being labelled by
28538
+ -- whichever CNPJ happened to survive the merge \u2014 "RESTAURANTE O COMPADRE".
28539
+ -- The seller reads that and thinks they are looking at one restaurant, and
28540
+ -- the whole point of 057 was that they are not. The view now carries the
28541
+ -- group next to the company so every screen can prefer it WITHOUT asking
28542
+ -- the database once per card: a board with 200 deals would otherwise fire
28543
+ -- 200 extra round trips to render one line of text.
28544
+ --
28545
+ -- 2. WHO THE CONTACT IS.
28546
+ -- \`contact_name\` read \`metadata->>'contactName'\` \u2014 a denormalized copy
28547
+ -- written at creation time. \`contact_id\` is the actual link, and changing
28548
+ -- the point of contact writes the link. Anyone who changed the contact and
28549
+ -- did not also rewrite the metadata (which, until today, was every caller)
28550
+ -- left the board naming the previous person forever. The link now wins and
28551
+ -- the copy is the fallback, so a deal whose contact was never linked keeps
28552
+ -- the name it always had.
28553
+ --
28554
+ -- No new column on \`plg_crm_deals\`. Migration 015 refused to weld the group
28555
+ -- onto the deal row and that refusal still holds \u2014 this is derived, in a view,
28556
+ -- where a wrong answer costs a re-read and not a migration.
28557
+
28558
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
28559
+ SELECT d.id,
28560
+ d.tenant_id,
28561
+ d.status,
28562
+ d.value,
28563
+ COALESCE(d.title, d.notes) AS title,
28564
+ d.contact_id,
28565
+ d.assigned_to_id,
28566
+ d.tags,
28567
+ -- The LINK first, the copy as fallback. See (2) above.
28568
+ COALESCE(pc.name, d.metadata ->> 'contactName'::text) AS contact_name,
28569
+ d.created_at,
28570
+ d.updated_at,
28571
+ d.pipeline_id,
28572
+ d.stage_id,
28573
+ d.probability,
28574
+ d.expected_close_date,
28575
+ d.lead_id,
28576
+ d.lost_reason,
28577
+ ps.name AS stage_name,
28578
+ ps.color AS stage_color,
28579
+ ps."order" AS stage_order,
28580
+ ps.name AS stage,
28581
+ d.won_at,
28582
+ d.lost_at,
28583
+ d.company_id,
28584
+ d.contact_status,
28585
+ d.contact_status_at,
28586
+ cs.name AS contact_status_name,
28587
+ cs.color AS contact_status_color,
28588
+ d.notes,
28589
+ cs.derived_from AS contact_status_derived_from,
28590
+ emp.name AS company_name,
28591
+ emp.document_number AS company_document,
28592
+ -- New, appended: CREATE OR REPLACE VIEW only allows growth at the tail.
28593
+ grp.group_id,
28594
+ grp.group_name,
28595
+ grp.group_companies
28596
+ FROM plg_crm_deals d
28597
+ LEFT JOIN plg_crm_companies emp ON emp.id = d.company_id
28598
+ LEFT JOIN people pc ON pc.id = d.contact_id
28599
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
28600
+ LEFT JOIN LATERAL ( SELECT s.name,
28601
+ s.color,
28602
+ s.derived_from
28603
+ FROM plg_crm_deal_statuses s
28604
+ WHERE s.tenant_id = d.tenant_id AND s.key = d.contact_status AND (s.stage_id IS NULL OR s.stage_id = d.stage_id)
28605
+ ORDER BY (s.stage_id IS NOT NULL) DESC
28606
+ LIMIT 1) cs ON true
28607
+ -- A company CAN sit in two groups: the unique key is on (group, company),
28608
+ -- not on the company alone. LIMIT 1 without an ORDER BY would let the
28609
+ -- card's title flip between renders, so the oldest membership wins \u2014 the
28610
+ -- group somebody built first, not the one the planner happened to reach.
28611
+ LEFT JOIN LATERAL ( SELECT g.id AS group_id,
28612
+ g.name AS group_name,
28613
+ ( SELECT count(*)::integer
28614
+ FROM plg_crm_company_group_members m2
28615
+ WHERE m2.group_id = g.id) AS group_companies
28616
+ FROM plg_crm_company_group_members m
28617
+ JOIN plg_crm_company_groups g ON g.id = m.group_id
28618
+ WHERE m.company_id = d.company_id
28619
+ AND m.tenant_id = d.tenant_id
28620
+ AND g.is_active
28621
+ ORDER BY m.created_at, m.id
28622
+ LIMIT 1) grp ON true;
28623
+
28624
+ GRANT SELECT ON public.v_deals TO authenticated;
28625
+ GRANT SELECT ON public.v_deals TO service_role;
28626
+ `;
28410
28627
  var MIGRATIONS = [
28411
28628
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28412
28629
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28464,7 +28681,8 @@ var MIGRATIONS = [
28464
28681
  { id: "054_a_lista_de_leads_pergunta_por_cidade", sql: MIGRATION_054_A_LISTA_DE_LEADS_PERGUNTA_POR_CIDADE },
28465
28682
  { id: "055_a_cesta_do_interesse_tem_onde_morar", sql: MIGRATION_055_A_CESTA_DO_INTERESSE_TEM_ONDE_MORAR },
28466
28683
  { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO },
28467
- { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ }
28684
+ { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ },
28685
+ { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO }
28468
28686
  ];
28469
28687
 
28470
28688
  // src/locales/en.ts
@@ -28727,6 +28945,12 @@ var en = {
28727
28945
  "crm.followUp.nextStep": "Next step",
28728
28946
  "crm.followUp.nextTitlePlaceholder": "What to do (e.g. call back)",
28729
28947
  "crm.followUp.defaultNextTitle": "Follow up ({{type}})",
28948
+ "crm.followUp.futureContact": "Contact again in",
28949
+ "crm.followUp.inSevenDays": "7 days",
28950
+ "crm.followUp.inOneMonth": "1 month",
28951
+ "crm.followUp.inThreeMonths": "3 months",
28952
+ "crm.followUp.futureRequired": "Choose when to contact them again.",
28953
+ "crm.followUp.futureTaskTitle": "Contact again",
28730
28954
  "crm.nav.dashboard": "Dashboard",
28731
28955
  "crm.nav.new": "New",
28732
28956
  "crm.nav.list": "List",
@@ -28761,6 +28985,7 @@ var en = {
28761
28985
  "crm.outcome.left_message": "Left a message",
28762
28986
  "crm.outcome.replied": "They replied",
28763
28987
  "crm.outcome.scheduled": "Got it scheduled",
28988
+ "crm.outcome.not_now": "Not interested right now",
28764
28989
  "crm.card.statusIsDerived": "Computed from the timeline \u2014 nobody sets this by hand.",
28765
28990
  "crm.deals.colStatus": "Status",
28766
28991
  "crm.card.markWon": "Won",
@@ -28779,6 +29004,8 @@ var en = {
28779
29004
  "crm.deals.allCampaigns": "All campaigns",
28780
29005
  "crm.deals.allCities": "All cities",
28781
29006
  "crm.card.companyTitle": "Company",
29007
+ "crm.card.groupTitle": "Economic group",
29008
+ "crm.card.groupCompanies": "{{count}} companies",
28782
29009
  "crm.card.takeOver": "Take this lead",
28783
29010
  "crm.card.takeOverFrom": "Take over",
28784
29011
  "crm.card.owner": "Owner",
@@ -29563,6 +29790,12 @@ var ptBR = {
29563
29790
  "crm.followUp.nextStep": "Pr\xF3ximo passo",
29564
29791
  "crm.followUp.nextTitlePlaceholder": "O que fazer (ex.: retornar a liga\xE7\xE3o)",
29565
29792
  "crm.followUp.defaultNextTitle": "Retornar o contato ({{type}})",
29793
+ "crm.followUp.futureContact": "Retomar contato em",
29794
+ "crm.followUp.inSevenDays": "7 dias",
29795
+ "crm.followUp.inOneMonth": "1 m\xEAs",
29796
+ "crm.followUp.inThreeMonths": "3 meses",
29797
+ "crm.followUp.futureRequired": "Escolha quando retomar o contato.",
29798
+ "crm.followUp.futureTaskTitle": "Retomar contato",
29566
29799
  "crm.nav.dashboard": "Painel",
29567
29800
  "crm.nav.new": "Novo",
29568
29801
  "crm.nav.list": "Lista",
@@ -29597,6 +29830,7 @@ var ptBR = {
29597
29830
  "crm.outcome.left_message": "Deixei recado",
29598
29831
  "crm.outcome.replied": "A pessoa respondeu",
29599
29832
  "crm.outcome.scheduled": "Ficou agendado",
29833
+ "crm.outcome.not_now": "N\xE3o tem interesse agora",
29600
29834
  "crm.card.statusIsDerived": "Calculado a partir da linha do tempo \u2014 ningu\xE9m escolhe este status \xE0 m\xE3o.",
29601
29835
  "crm.deals.colStatus": "Status",
29602
29836
  "crm.card.markWon": "Ganho",
@@ -29615,6 +29849,8 @@ var ptBR = {
29615
29849
  "crm.deals.allCampaigns": "Todas as campanhas",
29616
29850
  "crm.deals.allCities": "Todas as cidades",
29617
29851
  "crm.card.companyTitle": "Empresa",
29852
+ "crm.card.groupTitle": "Grupo econ\xF4mico",
29853
+ "crm.card.groupCompanies": "{{count}} CNPJs",
29618
29854
  "crm.card.takeOver": "Assumir este lead",
29619
29855
  "crm.card.takeOverFrom": "Assumir de quem est\xE1",
29620
29856
  "crm.card.owner": "Respons\xE1vel",