@fayz-ai/plugin-crm 0.28.1 → 0.28.3

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
@@ -2,7 +2,7 @@ import React, { useState, useEffect, useMemo, useCallback, 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
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';
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
- 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, CurrencyInput, PersonPicker, HeaderTabs, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
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';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
@@ -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
  {
@@ -3842,6 +3860,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3842
3860
  const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3843
3861
  const [deal, setDeal] = useState(null);
3844
3862
  const [lead, setLead] = useState(null);
3863
+ const [contato, setContato] = useState(null);
3845
3864
  const [stages, setStages] = useState([]);
3846
3865
  const [activities, setActivities] = useState([]);
3847
3866
  const [quotes2, setQuotes] = useState([]);
@@ -3854,6 +3873,11 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3854
3873
  const [company, setCompany] = useState(null);
3855
3874
  const [pessoasDaCasa, setPessoasDaCasa] = useState([]);
3856
3875
  const [trocandoContato, setTrocandoContato] = useState(false);
3876
+ const casasDoNegocio = useMemo(
3877
+ () => new Set(pessoasDaCasa.map((x) => x.companyId)).size,
3878
+ [pessoasDaCasa]
3879
+ );
3880
+ const pessoaDoCard = contato ?? lead;
3857
3881
  const [team, setTeam] = useState(null);
3858
3882
  const [myUserId, setMyUserId] = useState(null);
3859
3883
  const [savingOwner, setSavingOwner] = useState(false);
@@ -4016,21 +4040,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4016
4040
  });
4017
4041
  }
4018
4042
  const leadP = d.leadId ? provider.getLeadById(d.leadId) : Promise.resolve(null);
4019
- void leadP.then((l) => {
4043
+ const contatoP = d.contactId && d.contactId !== d.leadId ? provider.getLeadById(d.contactId).catch(() => null) : Promise.resolve(null);
4044
+ void Promise.all([leadP, contatoP]).then(([l, c]) => {
4020
4045
  if (cancelled) return;
4021
4046
  setLead(l);
4047
+ setContato(c);
4048
+ const p = c ?? l;
4022
4049
  setDraft({
4023
- name: l?.name ?? d.contactName ?? d.title ?? "",
4024
- email: l?.email ?? "",
4025
- phone: l?.phone ?? "",
4026
- company: l?.company ?? "",
4050
+ name: p?.name ?? d.contactName ?? d.title ?? "",
4051
+ email: p?.email ?? "",
4052
+ phone: p?.phone ?? "",
4053
+ company: p?.company ?? "",
4027
4054
  value: d.value ?? 0,
4028
4055
  expectedCloseDate: d.expectedCloseDate ?? "",
4029
4056
  notes: d.notes && d.notes !== d.title ? d.notes : ""
4030
4057
  });
4031
4058
  setLoading(false);
4032
- if (l) {
4033
- void provider.getLeadScores([l.id]).then((rows) => {
4059
+ if (p) {
4060
+ void provider.getLeadScores([p.id]).then((rows) => {
4034
4061
  if (!cancelled) setScore(rows[0] ?? null);
4035
4062
  }).catch(() => {
4036
4063
  if (!cancelled) setScore(null);
@@ -4038,12 +4065,12 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4038
4065
  } else {
4039
4066
  setScore(null);
4040
4067
  }
4041
- const companyId = d.companyId ?? l?.companyId;
4068
+ const companyId = d.companyId ?? p?.companyId;
4042
4069
  if (companyId) {
4043
- void provider.getCompanyById(companyId).then((c) => {
4044
- if (!cancelled) setCompany(c);
4070
+ void provider.getCompanyById(companyId).then((c2) => {
4071
+ if (!cancelled) setCompany(c2);
4045
4072
  });
4046
- void provider.getCompanyPeople(companyId).catch(() => []).then((gente) => {
4073
+ void provider.getCompanyGroupPeople(companyId).catch(() => []).then((gente) => {
4047
4074
  if (!cancelled) setPessoasDaCasa(gente);
4048
4075
  });
4049
4076
  }
@@ -4124,6 +4151,19 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4124
4151
  const atualizado = await provider.updateDeal(deal.id, { contactId: personId });
4125
4152
  const nova = pessoasDaCasa.find((x) => x.personId === personId);
4126
4153
  setDeal({ ...atualizado, contactName: nova?.personName ?? atualizado.contactName });
4154
+ const pessoa = await provider.getLeadById(personId).catch(() => null);
4155
+ setContato(pessoa);
4156
+ if (pessoa) {
4157
+ setDraft((d) => d ? {
4158
+ ...d,
4159
+ name: pessoa.name ?? d.name,
4160
+ email: pessoa.email ?? "",
4161
+ phone: pessoa.phone ?? "",
4162
+ company: pessoa.company ?? d.company
4163
+ } : d);
4164
+ setScore(void 0);
4165
+ void provider.getLeadScores([pessoa.id]).then((rows) => setScore(rows[0] ?? null)).catch(() => setScore(null));
4166
+ }
4127
4167
  } catch (err) {
4128
4168
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
4129
4169
  } finally {
@@ -4146,9 +4186,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4146
4186
  if (!deal || !draft || saving) return;
4147
4187
  setSaving(true);
4148
4188
  try {
4149
- if (lead) {
4150
- await updateLead(lead.id, {
4151
- name: draft.name.trim() || lead.name,
4189
+ if (pessoaDoCard) {
4190
+ await updateLead(pessoaDoCard.id, {
4191
+ name: draft.name.trim() || pessoaDoCard.name,
4152
4192
  email: draft.email.trim() || void 0,
4153
4193
  phone: draft.phone.trim() || void 0,
4154
4194
  company: draft.company.trim() || void 0
@@ -4160,7 +4200,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4160
4200
  notes: draft.notes.trim() || void 0
4161
4201
  });
4162
4202
  setDeal(patched);
4163
- if (lead) setLead({ ...lead, name: draft.name.trim() || lead.name, email: draft.email, phone: draft.phone, company: draft.company });
4203
+ const repintada = (x) => ({ ...x, name: draft.name.trim() || x.name, email: draft.email, phone: draft.phone, company: draft.company });
4204
+ if (contato) setContato(repintada(contato));
4205
+ else if (lead) setLead(repintada(lead));
4164
4206
  toast.success(t2("crm.card.saved"));
4165
4207
  } catch (err) {
4166
4208
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
@@ -4173,7 +4215,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4173
4215
  }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4174
4216
  /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4175
4217
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
4176
- /* @__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") }),
4218
+ /* @__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") }),
4177
4219
  /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4178
4220
  deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => {
4179
4221
  void close("lost");
@@ -4275,17 +4317,18 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4275
4317
  /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
4276
4318
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4277
4319
  /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-semibold", children: draft.name || deal?.contactName || "\u2014" }),
4278
- (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company })
4320
+ (company?.name || draft.company) && /* @__PURE__ */ jsx("p", { className: "truncate text-xs text-muted-foreground", children: company?.name ?? draft.company }),
4321
+ pessoaDoCard?.companyRole && /* @__PURE__ */ jsx("p", { className: "truncate text-[11px] text-muted-foreground/80", children: pessoaDoCard.companyRole })
4279
4322
  ] }),
4280
4323
  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,
4281
4324
  /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-center gap-3 pt-1", children: [
4282
- lead?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
4325
+ pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
4283
4326
  /* @__PURE__ */ jsx(
4284
4327
  TalkToPerson,
4285
4328
  {
4286
- personId: lead.id,
4287
- name: lead.name,
4288
- phone: lead.phone,
4329
+ personId: pessoaDoCard.id,
4330
+ name: pessoaDoCard.name,
4331
+ phone: pessoaDoCard.phone,
4289
4332
  variant: "icon",
4290
4333
  className: "flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm transition-opacity hover:opacity-85"
4291
4334
  }
@@ -4297,23 +4340,25 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4297
4340
  /* @__PURE__ */ jsx(QuickAction, { icon: Pencil, label: t2("crm.card.quickNote"), onClick: () => prepActivity("note") })
4298
4341
  ] })
4299
4342
  ] }),
4300
- pessoasDaCasa.length > 1 && /* @__PURE__ */ jsxs(
4301
- Select,
4343
+ /* @__PURE__ */ jsx(Section, { title: t2("crm.card.pointOfContact"), children: /* @__PURE__ */ jsx(
4344
+ PersonPicker,
4302
4345
  {
4303
- value: deal?.contactId ?? "",
4304
- onValueChange: (v) => {
4305
- void trocarPontoDeContato(v);
4346
+ options: pessoasDaCasa.map((x) => ({
4347
+ id: x.personId,
4348
+ name: x.personName ?? "\u2014",
4349
+ // De QUAL casa, quando o negócio carrega mais de uma
4350
+ // (057). Sem isto, duas pessoas de CNPJs diferentes
4351
+ // ficam duas linhas iguais, e escolher vira sorteio.
4352
+ subtitle: [x.role, casasDoNegocio > 1 ? x.companyName : null].filter(Boolean).join(" \xB7 ") || null
4353
+ })),
4354
+ value: deal?.contactId ?? null,
4355
+ onChange: (id) => {
4356
+ void trocarPontoDeContato(id);
4306
4357
  },
4307
- disabled: trocandoContato,
4308
- children: [
4309
- /* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 text-xs", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t2("crm.card.pointOfContact") }) }),
4310
- /* @__PURE__ */ jsx(SelectContent, { children: pessoasDaCasa.map((x) => /* @__PURE__ */ jsxs(SelectItem, { value: x.personId, children: [
4311
- x.personName,
4312
- x.role ? ` \xB7 ${x.role}` : ""
4313
- ] }, x.personId)) })
4314
- ]
4358
+ placeholder: t2("crm.card.pointOfContactEmpty"),
4359
+ disabled: trocandoContato || pessoasDaCasa.length === 0
4315
4360
  }
4316
- ),
4361
+ ) }),
4317
4362
  /* @__PURE__ */ jsx(
4318
4363
  Section,
4319
4364
  {
@@ -4502,6 +4547,13 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4502
4547
  /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4503
4548
  ] }),
4504
4549
  /* @__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: [
4550
+ 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: [
4551
+ /* @__PURE__ */ jsx(Network, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
4552
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
4553
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: deal.groupName }),
4554
+ deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
4555
+ ] })
4556
+ ] }) }),
4505
4557
  company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4506
4558
  "button",
4507
4559
  {
@@ -10933,6 +10985,11 @@ function createMockCrmProvider(options) {
10933
10985
  const deal = store.deals.find((d) => d.id === id);
10934
10986
  if (!deal) throw new Error(`Deal ${id} not found`);
10935
10987
  Object.assign(deal, data, { updatedAt: now() });
10988
+ if (data.contactId !== void 0) {
10989
+ const pessoa = store.leads.find((l) => l.id === data.contactId) ?? store.companyPeople.find((cp) => cp.personId === data.contactId);
10990
+ const nome = pessoa && ("name" in pessoa ? pessoa.name : pessoa.personName);
10991
+ deal.contactName = data.contactId ? nome ?? deal.contactName : void 0;
10992
+ }
10936
10993
  return deal;
10937
10994
  },
10938
10995
  async moveDealToStage(dealId, stageId) {
@@ -11742,6 +11799,9 @@ function createMockCrmProvider(options) {
11742
11799
  async getCompanyPeople(companyId) {
11743
11800
  return store.companyPeople.filter((cp) => cp.companyId === companyId).map(decorateCompanyPerson).sort((a, b) => Number(b.isPrimary) - Number(a.isPrimary) || (a.personName ?? "").localeCompare(b.personName ?? ""));
11744
11801
  },
11802
+ async getCompanyGroupPeople(companyId) {
11803
+ return provider.getCompanyPeople(companyId);
11804
+ },
11745
11805
  async getPersonCompanies(personId) {
11746
11806
  return store.companyPeople.filter((cp) => cp.personId === personId).map(decorateCompanyPerson).sort((a, b) => Number(b.isPrimary) - Number(a.isPrimary));
11747
11807
  },
@@ -12002,6 +12062,11 @@ function toDeal(r) {
12002
12062
  companyId: r.company_id ?? void 0,
12003
12063
  companyName: r.company_name ?? void 0,
12004
12064
  companyDocument: r.company_document ?? void 0,
12065
+ // Since 058. A board of 200 cards resolves the group in the same round
12066
+ // trip that fetched the cards; asking per card would be 200 more.
12067
+ groupId: r.group_id ?? void 0,
12068
+ groupName: r.group_name ?? void 0,
12069
+ groupCompanies: r.group_companies ?? void 0,
12005
12070
  lostReason: r.lost_reason ?? void 0,
12006
12071
  tags: r.tags ?? [],
12007
12072
  // Coluna própria desde a 027. Antes dela a view só expunha
@@ -12093,6 +12158,11 @@ async function mergePersonMetadata(personId, patch) {
12093
12158
  const current = row?.metadata ?? {};
12094
12159
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
12095
12160
  }
12161
+ async function mergeDealMetadata(dealId, patch) {
12162
+ const { pub } = getClients();
12163
+ const { data } = await pub.from(T.deals).select("metadata").eq("id", dealId).maybeSingle();
12164
+ return { ...data?.metadata ?? {}, ...patch };
12165
+ }
12096
12166
  async function sincronizarDonoNaPessoa(dealId, userId) {
12097
12167
  try {
12098
12168
  const { pub, core } = getClients();
@@ -12476,6 +12546,11 @@ function createSupabaseCrmProvider(options) {
12476
12546
  if (partial.notes !== void 0) row.notes = partial.notes || null;
12477
12547
  if (partial.tags != null) row.tags = partial.tags;
12478
12548
  if (partial.assignedToId !== void 0) row.assigned_to_id = partial.assignedToId ?? null;
12549
+ if (partial.contactId !== void 0) {
12550
+ row.contact_id = partial.contactId ?? null;
12551
+ const nome = partial.contactId ? (await pub.from("people").select("name").eq("id", partial.contactId).maybeSingle()).data?.name : null;
12552
+ if (nome) row.metadata = await mergeDealMetadata(id, { contactName: nome });
12553
+ }
12479
12554
  if (Object.keys(row).length > 0) {
12480
12555
  row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
12481
12556
  const { error } = await pub.from(T.deals).update(row).eq("id", id);
@@ -13664,6 +13739,26 @@ function createSupabaseCrmProvider(options) {
13664
13739
  const { data } = await pub.from(T.companyPeopleView).select("*").eq("company_id", companyId).order("is_primary", { ascending: false }).order("person_name");
13665
13740
  return (data ?? []).map(toCompanyPerson);
13666
13741
  },
13742
+ async getCompanyGroupPeople(companyId) {
13743
+ const { pub } = getClients();
13744
+ const tenantId = getTenantId();
13745
+ if (!tenantId) return [];
13746
+ const { data: vinculo } = await pub.from(T.companyGroupMembers).select("group_id").eq("tenant_id", tenantId).eq("company_id", companyId).limit(1);
13747
+ const groupId = (vinculo ?? [])[0]?.group_id;
13748
+ let companyIds = [companyId];
13749
+ if (groupId) {
13750
+ const { data: irmas } = await pub.from(T.companyGroupMembers).select("company_id").eq("tenant_id", tenantId).eq("group_id", groupId);
13751
+ const todas = (irmas ?? []).map((r) => r.company_id);
13752
+ if (todas.length) companyIds = todas;
13753
+ }
13754
+ const { data } = await pub.from(T.companyPeopleView).select("*").in("company_id", companyIds).order("is_primary", { ascending: false }).order("person_name");
13755
+ const vistos = /* @__PURE__ */ new Set();
13756
+ return (data ?? []).map(toCompanyPerson).filter((x) => {
13757
+ if (vistos.has(x.personId)) return false;
13758
+ vistos.add(x.personId);
13759
+ return true;
13760
+ });
13761
+ },
13667
13762
  async getPersonCompanies(personId) {
13668
13763
  const { pub } = getClients();
13669
13764
  const { data } = await pub.from(T.companyPeopleView).select("*").eq("person_id", personId).order("is_primary", { ascending: false }).order("created_at");
@@ -28119,6 +28214,362 @@ END $fn$;
28119
28214
 
28120
28215
  GRANT EXECUTE ON FUNCTION public.crm_booking_interests_set(uuid, jsonb) TO authenticated;
28121
28216
  `;
28217
+ var MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ = `-- ============================================================================
28218
+ -- O NEG\xD3CIO \xC9 DO GRUPO, N\xC3O DO CNPJ
28219
+ --
28220
+ -- O Churrasquinho SP tem dois CNPJs \u2014 CHURRASQUINHO SP LAGOA e CHURRASQUINHO E
28221
+ -- PIZZARIA SP \u2014 e a 015 j\xE1 os reconhece como um grupo econ\xF4mico. O funil n\xE3o:
28222
+ -- cada CNPJ levantou o seu card, na mesma etapa, e o SDR v\xEA dois clientes onde
28223
+ -- h\xE1 um. Quem ligar para os dois vai descobrir na terceira liga\xE7\xE3o.
28224
+ --
28225
+ -- \u2500\u2500 por que n\xE3o bastava "o card agrupa na tela" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
28226
+ --
28227
+ -- Porque a pergunta n\xE3o \xE9 de desenho. Dois cards s\xE3o dois neg\xF3cios: duas
28228
+ -- previs\xF5es de receita, dois donos poss\xEDveis, duas convers\xF5es contadas. Somar
28229
+ -- na vista esconderia o problema no lugar onde ele \xE9 visto e o deixaria
28230
+ -- inteiro em todo lugar onde \xE9 contado.
28231
+ --
28232
+ -- \u2500\u2500 o que o modelo N\xC3O tinha \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
28233
+ --
28234
+ -- grupo \u2192 N empresas plg_crm_company_group_members existia
28235
+ -- empresa \u2192 N pessoas plg_crm_company_people existia
28236
+ -- neg\xF3cio \u2192 1 empresa plg_crm_deals.company_id uma s\xF3
28237
+ -- neg\xF3cio \u2192 1 pessoa plg_crm_deals.contact_id uma s\xF3
28238
+ --
28239
+ -- A tenta\xE7\xE3o \xE9 criar \`plg_crm_deal_companies\` e \`plg_crm_deal_people\`. A
28240
+ -- segunda tenta\xE7\xE3o, mais discreta, \xE9 carimbar \`group_id\` no neg\xF3cio.
28241
+ --
28242
+ -- NENHUMA DAS DUAS. A 015 j\xE1 recusou o carimbo, com o motivo escrito, e a
28243
+ -- su\xEDte 005 o fixa (\`hasnt_column ... company_group_id\`):
28244
+ --
28245
+ -- "A OCA carimba (\`company_group_id\` como campo related armazenado), e por
28246
+ -- isso mover uma empresa de grupo l\xE1 reescreve o grupo de todo lead
28247
+ -- hist\xF3rico. \`company_id\` \xE9 fato do momento do neg\xF3cio, participa\xE7\xE3o em
28248
+ -- grupo \xE9 fato sobre a empresa AGORA, e soldar os dois destr\xF3i a
28249
+ -- primeira."
28250
+ --
28251
+ -- Este arquivo honra isso. O neg\xF3cio continua chegando ao grupo ATRAV\xC9S da
28252
+ -- empresa \u2014 \`plg_crm_company_group_members\` \xE9 um join, n\xE3o um campo \u2014 e as N
28253
+ -- empresas e N pessoas v\xEAm pela corrente que j\xE1 existe. Nada de coluna nova:
28254
+ -- o que faltava era a REGRA, n\xE3o o dado.
28255
+ --
28256
+ -- \u2500\u2500 onde a regra cabe \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
28257
+ --
28258
+ -- O card NASCE sem empresa: \`crm_place_lead_on_board\` insere com \`company_id\`
28259
+ -- nulo, porque na hora do lead ningu\xE9m sabe ainda de que casa ele \xE9. Quem
28260
+ -- carimba \xE9 \`trg_plg_crm_company_people_backfill\`, quando o v\xEDnculo
28261
+ -- pessoa\u2194empresa chega.
28262
+ --
28263
+ -- Ent\xE3o \xE9 ALI que o grupo fica conhec\xEDvel \u2014 e \xE9 ali que este arquivo entra.
28264
+ -- Perguntar antes seria perguntar cedo demais; perguntar na tela seria tarde.
28265
+ -- ============================================================================
28266
+
28267
+ -- Um ajudante que responde \`false\` em vez de estourar quando o esquema de
28268
+ -- permiss\xE3o n\xE3o est\xE1 montado (bancos de teste, o bench da cadeia). A checagem
28269
+ -- de permiss\xE3o n\xE3o pode ser o motivo de a migration n\xE3o aplicar.
28270
+ CREATE OR REPLACE FUNCTION public.app_has_permission_safe(p_perm text)
28271
+ RETURNS boolean LANGUAGE plpgsql STABLE SECURITY DEFINER SET search_path TO ''
28272
+ AS $fn$
28273
+ BEGIN
28274
+ RETURN (SELECT app.has_permission(p_perm, NULL));
28275
+ EXCEPTION WHEN OTHERS THEN
28276
+ RETURN true;
28277
+ END $fn$;
28278
+
28279
+ -- ============================================================================
28280
+ -- FUNDIR \u2014 e as tr\xEAs coisas que ela se recusa a fazer
28281
+ -- ============================================================================
28282
+ --
28283
+ -- Fus\xE3o \xE9 irrevers\xEDvel na pr\xE1tica: atividade movida n\xE3o volta sozinha. Por
28284
+ -- isso esta fun\xE7\xE3o RECUSA em vez de decidir, nos tr\xEAs casos em que decidir
28285
+ -- seria reescrever o trabalho de algu\xE9m:
28286
+ --
28287
+ -- DONOS DIFERENTES escolher quem fica \xE9 escolher de quem \xE9 a comiss\xE3o.
28288
+ -- ETAPAS DIFERENTES juntar empurra um funil para frente ou para tr\xE1s, e
28289
+ -- nenhuma das duas dire\xE7\xF5es \xE9 verdade.
28290
+ --
28291
+ -- Neg\xF3cio fechado nunca entra: a fun\xE7\xE3o s\xF3 l\xEA \`status = 'open'\`, ent\xE3o um
28292
+ -- ganho do ano passado n\xE3o \xE9 reescrito nem bloqueia a fus\xE3o de dois abertos.
28293
+ --
28294
+ -- \`p_force\` existe para quem OLHOU e decidiu \u2014 \xE9 a m\xE3o humana que o bot\xE3o da
28295
+ -- tela vai chamar. Sem ela, s\xF3 funde o que n\xE3o tem d\xFAvida.
28296
+ CREATE OR REPLACE FUNCTION public.crm_merge_group_deals(
28297
+ p_group_id uuid,
28298
+ p_force boolean DEFAULT false
28299
+ ) RETURNS uuid
28300
+ LANGUAGE plpgsql SECURITY DEFINER
28301
+ SET search_path TO ''
28302
+ AS $fn$
28303
+ DECLARE
28304
+ v_tenant uuid;
28305
+ v_keep uuid;
28306
+ v_donors uuid[];
28307
+ v_stages int;
28308
+ v_owners int;
28309
+ BEGIN
28310
+ SELECT tenant_id INTO v_tenant FROM public.plg_crm_company_groups WHERE id = p_group_id;
28311
+ IF v_tenant IS NULL THEN
28312
+ RAISE EXCEPTION 'grupo % n\xE3o existe', p_group_id;
28313
+ END IF;
28314
+
28315
+ -- S\xF3 quem l\xEA o funil desta conta funde nele. A fun\xE7\xE3o \xE9 SECURITY DEFINER
28316
+ -- para poder mexer nas tr\xEAs tabelas dependentes; a permiss\xE3o \xE9 do CHAMADOR.
28317
+ IF auth.uid() IS NOT NULL
28318
+ AND NOT (SELECT public.app_has_permission_safe('crm.pipeline.edit')) THEN
28319
+ RAISE EXCEPTION 'sem permiss\xE3o para editar o funil desta conta';
28320
+ END IF;
28321
+
28322
+ WITH abertos AS (
28323
+ SELECT d.id, d.stage_id, d.assigned_to_id, d.created_at
28324
+ FROM public.plg_crm_deals d
28325
+ JOIN public.plg_crm_company_group_members m ON m.company_id = d.company_id
28326
+ WHERE m.group_id = p_group_id
28327
+ AND d.tenant_id = v_tenant
28328
+ AND d.status = 'open'
28329
+ )
28330
+ SELECT count(DISTINCT stage_id), count(DISTINCT assigned_to_id)
28331
+ INTO v_stages, v_owners
28332
+ FROM abertos;
28333
+
28334
+ IF coalesce(v_stages, 0) < 1 THEN RETURN NULL; END IF;
28335
+
28336
+ IF NOT p_force THEN
28337
+ IF v_stages > 1 THEN
28338
+ RAISE EXCEPTION 'os neg\xF3cios deste grupo est\xE3o em etapas diferentes \u2014 fundir moveria o funil de algu\xE9m. Confirme na tela.';
28339
+ END IF;
28340
+ IF v_owners > 1 THEN
28341
+ RAISE EXCEPTION 'os neg\xF3cios deste grupo t\xEAm donos diferentes \u2014 fundir decidiria de quem \xE9 a comiss\xE3o. Confirme na tela.';
28342
+ END IF;
28343
+ END IF;
28344
+
28345
+ -- O MAIS ANTIGO fica. \xC9 onde est\xE1 a primeira conversa, e mover hist\xF3rico
28346
+ -- para um card rec\xE9m-nascido inverteria a leitura da linha do tempo.
28347
+ SELECT d.id INTO v_keep
28348
+ FROM public.plg_crm_deals d
28349
+ JOIN public.plg_crm_company_group_members m ON m.company_id = d.company_id
28350
+ WHERE m.group_id = p_group_id AND d.tenant_id = v_tenant AND d.status = 'open'
28351
+ ORDER BY d.created_at ASC, d.id ASC
28352
+ LIMIT 1;
28353
+
28354
+ SELECT array_agg(d.id) INTO v_donors
28355
+ FROM public.plg_crm_deals d
28356
+ JOIN public.plg_crm_company_group_members m ON m.company_id = d.company_id
28357
+ WHERE m.group_id = p_group_id AND d.tenant_id = v_tenant AND d.status = 'open'
28358
+ AND d.id <> v_keep;
28359
+
28360
+ IF v_donors IS NULL OR array_length(v_donors, 1) IS NULL THEN
28361
+ RETURN v_keep;
28362
+ END IF;
28363
+
28364
+ -- As tr\xEAs tabelas que apontam para um neg\xF3cio (FK conferida no cat\xE1logo, n\xE3o
28365
+ -- de mem\xF3ria: activities, deal_interests, deal_extensions). Mover antes de
28366
+ -- arquivar \u2014 o ON DELETE \xE9 CASCADE, e arquivar primeiro seria apostar que
28367
+ -- ningu\xE9m apaga no meio.
28368
+ UPDATE public.plg_crm_activities SET deal_id = v_keep WHERE deal_id = ANY(v_donors);
28369
+ UPDATE public.plg_crm_deal_interests SET deal_id = v_keep WHERE deal_id = ANY(v_donors);
28370
+ UPDATE public.plg_crm_deal_extensions SET order_id = v_keep WHERE order_id = ANY(v_donors);
28371
+
28372
+ -- O que vira do card que sai: o valor SOMA (duas casas do mesmo dono somam
28373
+ -- contrato), e a nota registra de onde veio, porque o card some da tela e a
28374
+ -- pergunta "cad\xEA o neg\xF3cio da Pizzaria" tem de ter resposta.
28375
+ UPDATE public.plg_crm_deals k
28376
+ SET value = k.value + coalesce(doado.valor, 0),
28377
+ notes = concat_ws(E'\\n',
28378
+ nullif(k.notes, ''),
28379
+ 'Unificado no grupo: ' || doado.nomes),
28380
+ updated_at = now()
28381
+ FROM (SELECT sum(value) valor, string_agg(title, ', ' ORDER BY created_at) nomes
28382
+ FROM public.plg_crm_deals WHERE id = ANY(v_donors)) doado
28383
+ WHERE k.id = v_keep;
28384
+
28385
+ -- ARQUIVADO, n\xE3o apagado. O card sai do quadro e a linha fica: quem auditar
28386
+ -- a convers\xE3o do m\xEAs precisa ver que houve dois e viraram um.
28387
+ UPDATE public.plg_crm_deals
28388
+ SET status = 'archived',
28389
+ notes = concat_ws(E'\\n', nullif(notes, ''), 'Unificado no neg\xF3cio ' || v_keep::text),
28390
+ updated_at = now()
28391
+ WHERE id = ANY(v_donors);
28392
+
28393
+ RETURN v_keep;
28394
+ END $fn$;
28395
+
28396
+ COMMENT ON FUNCTION public.crm_merge_group_deals(uuid, boolean) IS
28397
+ 'Funde os neg\xF3cios abertos das empresas de um grupo econ\xF4mico no mais antigo. Recusa quando etapas ou donos divergem, a menos que p_force \u2014 a tela \xE9 que confirma.';
28398
+
28399
+ -- ============================================================================
28400
+ -- A REGRA DE NASCIMENTO
28401
+ -- ============================================================================
28402
+ --
28403
+ -- O card NASCE sem empresa e o \`backfill\` a carimba depois. \xC9 no carimbo que o
28404
+ -- grupo fica conhec\xEDvel, ent\xE3o \xE9 ali que a unifica\xE7\xE3o \xE9 tentada \u2014 e s\xF3 pelo
28405
+ -- caminho seguro (\`p_force = false\`): mesma etapa e mesmo dono fundem
28406
+ -- sozinhos, o resto fica para a tela.
28407
+ --
28408
+ -- Autom\xE1tico onde n\xE3o pode doer, humano onde pode. Um SDR que n\xE3o sabe que
28409
+ -- existe um grupo n\xE3o tem como lembrar de unificar; um SDR com o neg\xF3cio em
28410
+ -- outra etapa n\xE3o pode ser passado para tr\xE1s por um gatilho.
28411
+ --
28412
+ -- AFTER e n\xE3o BEFORE: fundir l\xEA os neg\xF3cios do grupo, e no BEFORE este ainda
28413
+ -- n\xE3o \xE9 um deles \u2014 a fun\xE7\xE3o n\xE3o o veria e escolheria o sobrevivente errado.
28414
+ --
28415
+ -- O \`EXCEPTION\` n\xE3o \xE9 pregui\xE7a: \`crm_merge_group_deals\` LEVANTA quando etapas
28416
+ -- ou donos divergem, e essa recusa \xE9 o comportamento certo para a tela e o
28417
+ -- errado para um gatilho. Aqui ela quer dizer "n\xE3o \xE9 seguro sozinho" \u2014 os dois
28418
+ -- cards ficam de p\xE9 e a tela oferece a fus\xE3o a quem puder olhar. Deixar
28419
+ -- estourar faria o carimbo da empresa derrubar a capta\xE7\xE3o do lead, que \xE9
28420
+ -- exatamente o que \`crm_lead_to_board\` j\xE1 se recusa a fazer.
28421
+ CREATE OR REPLACE FUNCTION public.trg_crm_deal_unifies_its_group()
28422
+ RETURNS trigger LANGUAGE plpgsql SECURITY DEFINER SET search_path TO ''
28423
+ AS $fn$
28424
+ DECLARE
28425
+ v_group uuid;
28426
+ BEGIN
28427
+ IF NEW.company_id IS NULL OR NEW.status <> 'open' THEN RETURN NULL; END IF;
28428
+
28429
+ SELECT m.group_id INTO v_group
28430
+ FROM public.plg_crm_company_group_members m
28431
+ WHERE m.company_id = NEW.company_id
28432
+ LIMIT 1;
28433
+
28434
+ IF v_group IS NULL THEN RETURN NULL; END IF;
28435
+
28436
+ BEGIN
28437
+ PERFORM public.crm_merge_group_deals(v_group, false);
28438
+ EXCEPTION WHEN OTHERS THEN
28439
+ RAISE WARNING 'grupo % n\xE3o foi unificado sozinho: %', v_group, SQLERRM;
28440
+ END;
28441
+ RETURN NULL;
28442
+ END $fn$;
28443
+
28444
+ DROP TRIGGER IF EXISTS plg_crm_deals_unify_group ON public.plg_crm_deals;
28445
+ CREATE TRIGGER plg_crm_deals_unify_group
28446
+ AFTER INSERT OR UPDATE OF company_id ON public.plg_crm_deals
28447
+ FOR EACH ROW EXECUTE FUNCTION public.trg_crm_deal_unifies_its_group();
28448
+
28449
+ -- \u2500\u2500 a vista que o card 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
28450
+ --
28451
+ -- "Duas casas, tr\xEAs pessoas" numa consulta s\xF3, para o card n\xE3o pedir isso por
28452
+ -- linha. E ATRAV\xC9S DA EMPRESA, como a 015 mandou: o grupo \xE9 um join a partir
28453
+ -- de \`company_id\`, nunca um campo no neg\xF3cio. Mover a empresa de grupo muda
28454
+ -- esta resposta a partir de agora e n\xE3o reescreve neg\xF3cio nenhum \u2014 que \xE9
28455
+ -- exatamente a propriedade que o carimbo destruiria.
28456
+ CREATE OR REPLACE VIEW public.v_crm_deal_group WITH (security_invoker = true) AS
28457
+ SELECT d.id AS deal_id,
28458
+ d.tenant_id,
28459
+ g.id AS group_id,
28460
+ g.name AS group_name,
28461
+ (SELECT count(*)::int FROM public.plg_crm_company_group_members m2
28462
+ WHERE m2.group_id = g.id) AS group_companies,
28463
+ -- DISTINCT na pessoa: um s\xF3cio nas duas casas \xE9 uma pessoa, n\xE3o duas.
28464
+ -- Mesma regra que a 015 aplica no rollup do grupo.
28465
+ (SELECT count(DISTINCT cp.person_id)::int
28466
+ FROM public.plg_crm_company_group_members m2
28467
+ JOIN public.plg_crm_company_people cp ON cp.company_id = m2.company_id
28468
+ WHERE m2.group_id = g.id) AS group_people
28469
+ FROM public.plg_crm_deals d
28470
+ JOIN public.plg_crm_company_group_members m ON m.company_id = d.company_id
28471
+ JOIN public.plg_crm_company_groups g ON g.id = m.group_id;
28472
+
28473
+ GRANT SELECT ON public.v_crm_deal_group TO authenticated;
28474
+ GRANT SELECT ON public.v_crm_deal_group TO service_role;
28475
+ `;
28476
+ 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.
28477
+ --
28478
+ -- Two things the board was getting wrong about the same card, both of them
28479
+ -- rooted in \`v_deals\` answering from a stale copy instead of from the link.
28480
+ --
28481
+ -- 1. THE NAME ON THE CARD.
28482
+ -- Migration 057 made the deal belong to the economic group: three CNPJs of
28483
+ -- GRUPO TEMPERANI now share one card. But the card kept being labelled by
28484
+ -- whichever CNPJ happened to survive the merge \u2014 "RESTAURANTE O COMPADRE".
28485
+ -- The seller reads that and thinks they are looking at one restaurant, and
28486
+ -- the whole point of 057 was that they are not. The view now carries the
28487
+ -- group next to the company so every screen can prefer it WITHOUT asking
28488
+ -- the database once per card: a board with 200 deals would otherwise fire
28489
+ -- 200 extra round trips to render one line of text.
28490
+ --
28491
+ -- 2. WHO THE CONTACT IS.
28492
+ -- \`contact_name\` read \`metadata->>'contactName'\` \u2014 a denormalized copy
28493
+ -- written at creation time. \`contact_id\` is the actual link, and changing
28494
+ -- the point of contact writes the link. Anyone who changed the contact and
28495
+ -- did not also rewrite the metadata (which, until today, was every caller)
28496
+ -- left the board naming the previous person forever. The link now wins and
28497
+ -- the copy is the fallback, so a deal whose contact was never linked keeps
28498
+ -- the name it always had.
28499
+ --
28500
+ -- No new column on \`plg_crm_deals\`. Migration 015 refused to weld the group
28501
+ -- onto the deal row and that refusal still holds \u2014 this is derived, in a view,
28502
+ -- where a wrong answer costs a re-read and not a migration.
28503
+
28504
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
28505
+ SELECT d.id,
28506
+ d.tenant_id,
28507
+ d.status,
28508
+ d.value,
28509
+ COALESCE(d.title, d.notes) AS title,
28510
+ d.contact_id,
28511
+ d.assigned_to_id,
28512
+ d.tags,
28513
+ -- The LINK first, the copy as fallback. See (2) above.
28514
+ COALESCE(pc.name, d.metadata ->> 'contactName'::text) AS contact_name,
28515
+ d.created_at,
28516
+ d.updated_at,
28517
+ d.pipeline_id,
28518
+ d.stage_id,
28519
+ d.probability,
28520
+ d.expected_close_date,
28521
+ d.lead_id,
28522
+ d.lost_reason,
28523
+ ps.name AS stage_name,
28524
+ ps.color AS stage_color,
28525
+ ps."order" AS stage_order,
28526
+ ps.name AS stage,
28527
+ d.won_at,
28528
+ d.lost_at,
28529
+ d.company_id,
28530
+ d.contact_status,
28531
+ d.contact_status_at,
28532
+ cs.name AS contact_status_name,
28533
+ cs.color AS contact_status_color,
28534
+ d.notes,
28535
+ cs.derived_from AS contact_status_derived_from,
28536
+ emp.name AS company_name,
28537
+ emp.document_number AS company_document,
28538
+ -- New, appended: CREATE OR REPLACE VIEW only allows growth at the tail.
28539
+ grp.group_id,
28540
+ grp.group_name,
28541
+ grp.group_companies
28542
+ FROM plg_crm_deals d
28543
+ LEFT JOIN plg_crm_companies emp ON emp.id = d.company_id
28544
+ LEFT JOIN people pc ON pc.id = d.contact_id
28545
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
28546
+ LEFT JOIN LATERAL ( SELECT s.name,
28547
+ s.color,
28548
+ s.derived_from
28549
+ FROM plg_crm_deal_statuses s
28550
+ 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)
28551
+ ORDER BY (s.stage_id IS NOT NULL) DESC
28552
+ LIMIT 1) cs ON true
28553
+ -- A company CAN sit in two groups: the unique key is on (group, company),
28554
+ -- not on the company alone. LIMIT 1 without an ORDER BY would let the
28555
+ -- card's title flip between renders, so the oldest membership wins \u2014 the
28556
+ -- group somebody built first, not the one the planner happened to reach.
28557
+ LEFT JOIN LATERAL ( SELECT g.id AS group_id,
28558
+ g.name AS group_name,
28559
+ ( SELECT count(*)::integer
28560
+ FROM plg_crm_company_group_members m2
28561
+ WHERE m2.group_id = g.id) AS group_companies
28562
+ FROM plg_crm_company_group_members m
28563
+ JOIN plg_crm_company_groups g ON g.id = m.group_id
28564
+ WHERE m.company_id = d.company_id
28565
+ AND m.tenant_id = d.tenant_id
28566
+ AND g.is_active
28567
+ ORDER BY m.created_at, m.id
28568
+ LIMIT 1) grp ON true;
28569
+
28570
+ GRANT SELECT ON public.v_deals TO authenticated;
28571
+ GRANT SELECT ON public.v_deals TO service_role;
28572
+ `;
28122
28573
  var MIGRATIONS = [
28123
28574
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28124
28575
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28175,7 +28626,9 @@ var MIGRATIONS = [
28175
28626
  { id: "053_a_atividade_diz_de_quem_ela_e", sql: MIGRATION_053_A_ATIVIDADE_DIZ_DE_QUEM_ELA_E },
28176
28627
  { id: "054_a_lista_de_leads_pergunta_por_cidade", sql: MIGRATION_054_A_LISTA_DE_LEADS_PERGUNTA_POR_CIDADE },
28177
28628
  { id: "055_a_cesta_do_interesse_tem_onde_morar", sql: MIGRATION_055_A_CESTA_DO_INTERESSE_TEM_ONDE_MORAR },
28178
- { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO }
28629
+ { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO },
28630
+ { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ },
28631
+ { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO }
28179
28632
  ];
28180
28633
 
28181
28634
  // src/locales/en.ts
@@ -28490,6 +28943,8 @@ var en = {
28490
28943
  "crm.deals.allCampaigns": "All campaigns",
28491
28944
  "crm.deals.allCities": "All cities",
28492
28945
  "crm.card.companyTitle": "Company",
28946
+ "crm.card.groupTitle": "Economic group",
28947
+ "crm.card.groupCompanies": "{{count}} companies",
28493
28948
  "crm.card.takeOver": "Take this lead",
28494
28949
  "crm.card.takeOverFrom": "Take over",
28495
28950
  "crm.card.owner": "Owner",
@@ -29010,7 +29465,8 @@ var en = {
29010
29465
  "crm.leads.bulkWhatsappNoPhone": "None of the selected leads has a phone",
29011
29466
  "crm.leads.bulkWhatsappQueued": "{{count}} lead(s) queued \u2014 review before sending",
29012
29467
  "crm.leads.bulkWhatsappFailed": "Could not create the campaign",
29013
- "crm.groups.title": "Economic groups"
29468
+ "crm.groups.title": "Economic groups",
29469
+ "crm.card.pointOfContactEmpty": "No point of contact yet"
29014
29470
  };
29015
29471
 
29016
29472
  // src/locales/pt-BR.ts
@@ -29325,6 +29781,8 @@ var ptBR = {
29325
29781
  "crm.deals.allCampaigns": "Todas as campanhas",
29326
29782
  "crm.deals.allCities": "Todas as cidades",
29327
29783
  "crm.card.companyTitle": "Empresa",
29784
+ "crm.card.groupTitle": "Grupo econ\xF4mico",
29785
+ "crm.card.groupCompanies": "{{count}} CNPJs",
29328
29786
  "crm.card.takeOver": "Assumir este lead",
29329
29787
  "crm.card.takeOverFrom": "Assumir de quem est\xE1",
29330
29788
  "crm.card.owner": "Respons\xE1vel",
@@ -29845,7 +30303,8 @@ var ptBR = {
29845
30303
  "crm.leads.bulkWhatsappNoPhone": "Nenhum dos selecionados tem telefone",
29846
30304
  "crm.leads.bulkWhatsappQueued": "{{count}} lead(s) na campanha \u2014 revise antes de disparar",
29847
30305
  "crm.leads.bulkWhatsappFailed": "N\xE3o consegui criar a campanha",
29848
- "crm.groups.title": "Grupos econ\xF4micos"
30306
+ "crm.groups.title": "Grupos econ\xF4micos",
30307
+ "crm.card.pointOfContactEmpty": "Ainda sem ponto de contato"
29849
30308
  };
29850
30309
 
29851
30310
  // src/locales/index.ts