@fayz-ai/plugin-crm 0.28.2 → 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.
@@ -1 +1 @@
1
- {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA2K9C,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE;IAC9C,UAAU,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACxE,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAmuClB"}
1
+ {"version":3,"file":"mock.d.ts","sourceRoot":"","sources":["../../src/data/mock.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA2K9C,wBAAgB,qBAAqB,CAAC,OAAO,CAAC,EAAE;IAC9C,UAAU,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IACxE,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CA6uClB"}
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAsT9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CA67ElB"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AAkV9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAk9ElB"}
package/dist/index.js CHANGED
@@ -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([]);
@@ -3858,6 +3877,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3858
3877
  () => new Set(pessoasDaCasa.map((x) => x.companyId)).size,
3859
3878
  [pessoasDaCasa]
3860
3879
  );
3880
+ const pessoaDoCard = contato ?? lead;
3861
3881
  const [team, setTeam] = useState(null);
3862
3882
  const [myUserId, setMyUserId] = useState(null);
3863
3883
  const [savingOwner, setSavingOwner] = useState(false);
@@ -4020,21 +4040,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4020
4040
  });
4021
4041
  }
4022
4042
  const leadP = d.leadId ? provider.getLeadById(d.leadId) : Promise.resolve(null);
4023
- 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]) => {
4024
4045
  if (cancelled) return;
4025
4046
  setLead(l);
4047
+ setContato(c);
4048
+ const p = c ?? l;
4026
4049
  setDraft({
4027
- name: l?.name ?? d.contactName ?? d.title ?? "",
4028
- email: l?.email ?? "",
4029
- phone: l?.phone ?? "",
4030
- company: l?.company ?? "",
4050
+ name: p?.name ?? d.contactName ?? d.title ?? "",
4051
+ email: p?.email ?? "",
4052
+ phone: p?.phone ?? "",
4053
+ company: p?.company ?? "",
4031
4054
  value: d.value ?? 0,
4032
4055
  expectedCloseDate: d.expectedCloseDate ?? "",
4033
4056
  notes: d.notes && d.notes !== d.title ? d.notes : ""
4034
4057
  });
4035
4058
  setLoading(false);
4036
- if (l) {
4037
- void provider.getLeadScores([l.id]).then((rows) => {
4059
+ if (p) {
4060
+ void provider.getLeadScores([p.id]).then((rows) => {
4038
4061
  if (!cancelled) setScore(rows[0] ?? null);
4039
4062
  }).catch(() => {
4040
4063
  if (!cancelled) setScore(null);
@@ -4042,10 +4065,10 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4042
4065
  } else {
4043
4066
  setScore(null);
4044
4067
  }
4045
- const companyId = d.companyId ?? l?.companyId;
4068
+ const companyId = d.companyId ?? p?.companyId;
4046
4069
  if (companyId) {
4047
- void provider.getCompanyById(companyId).then((c) => {
4048
- if (!cancelled) setCompany(c);
4070
+ void provider.getCompanyById(companyId).then((c2) => {
4071
+ if (!cancelled) setCompany(c2);
4049
4072
  });
4050
4073
  void provider.getCompanyGroupPeople(companyId).catch(() => []).then((gente) => {
4051
4074
  if (!cancelled) setPessoasDaCasa(gente);
@@ -4128,6 +4151,19 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4128
4151
  const atualizado = await provider.updateDeal(deal.id, { contactId: personId });
4129
4152
  const nova = pessoasDaCasa.find((x) => x.personId === personId);
4130
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
+ }
4131
4167
  } catch (err) {
4132
4168
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
4133
4169
  } finally {
@@ -4150,9 +4186,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4150
4186
  if (!deal || !draft || saving) return;
4151
4187
  setSaving(true);
4152
4188
  try {
4153
- if (lead) {
4154
- await updateLead(lead.id, {
4155
- name: draft.name.trim() || lead.name,
4189
+ if (pessoaDoCard) {
4190
+ await updateLead(pessoaDoCard.id, {
4191
+ name: draft.name.trim() || pessoaDoCard.name,
4156
4192
  email: draft.email.trim() || void 0,
4157
4193
  phone: draft.phone.trim() || void 0,
4158
4194
  company: draft.company.trim() || void 0
@@ -4164,7 +4200,9 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4164
4200
  notes: draft.notes.trim() || void 0
4165
4201
  });
4166
4202
  setDeal(patched);
4167
- 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));
4168
4206
  toast.success(t2("crm.card.saved"));
4169
4207
  } catch (err) {
4170
4208
  toast.error(t2("crm.card.saveFailed"), { description: err?.message });
@@ -4177,7 +4215,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4177
4215
  }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
4178
4216
  /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-col items-stretch gap-2 border-b px-5 py-3", children: [
4179
4217
  /* @__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") }),
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") }),
4181
4219
  /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
4182
4220
  deal?.status === "open" ? /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "ghost", disabled: closing, onClick: () => {
4183
4221
  void close("lost");
@@ -4279,17 +4317,18 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4279
4317
  /* @__PURE__ */ jsx(PersonAvatar, { name: draft.name || deal?.contactName || "?", size: "md", className: "h-14 w-14 text-lg" }),
4280
4318
  /* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
4281
4319
  /* @__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 })
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 })
4283
4322
  ] }),
4284
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,
4285
4324
  /* @__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: [
4325
+ pessoaDoCard?.id && /* @__PURE__ */ jsxs("span", { className: "flex flex-col items-center gap-1", onClickCapture: () => prepActivity("whatsapp"), children: [
4287
4326
  /* @__PURE__ */ jsx(
4288
4327
  TalkToPerson,
4289
4328
  {
4290
- personId: lead.id,
4291
- name: lead.name,
4292
- phone: lead.phone,
4329
+ personId: pessoaDoCard.id,
4330
+ name: pessoaDoCard.name,
4331
+ phone: pessoaDoCard.phone,
4293
4332
  variant: "icon",
4294
4333
  className: "flex h-9 w-9 items-center justify-center rounded-full text-white shadow-sm transition-opacity hover:opacity-85"
4295
4334
  }
@@ -4508,6 +4547,13 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4508
4547
  /* @__PURE__ */ jsx(ActivityTimeline, { activities: shownActivities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
4509
4548
  ] }),
4510
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
+ ] }) }),
4511
4557
  company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4512
4558
  "button",
4513
4559
  {
@@ -10939,6 +10985,11 @@ function createMockCrmProvider(options) {
10939
10985
  const deal = store.deals.find((d) => d.id === id);
10940
10986
  if (!deal) throw new Error(`Deal ${id} not found`);
10941
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
+ }
10942
10993
  return deal;
10943
10994
  },
10944
10995
  async moveDealToStage(dealId, stageId) {
@@ -12011,6 +12062,11 @@ function toDeal(r) {
12011
12062
  companyId: r.company_id ?? void 0,
12012
12063
  companyName: r.company_name ?? void 0,
12013
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,
12014
12070
  lostReason: r.lost_reason ?? void 0,
12015
12071
  tags: r.tags ?? [],
12016
12072
  // Coluna própria desde a 027. Antes dela a view só expunha
@@ -12102,6 +12158,11 @@ async function mergePersonMetadata(personId, patch) {
12102
12158
  const current = row?.metadata ?? {};
12103
12159
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
12104
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
+ }
12105
12166
  async function sincronizarDonoNaPessoa(dealId, userId) {
12106
12167
  try {
12107
12168
  const { pub, core } = getClients();
@@ -12485,6 +12546,11 @@ function createSupabaseCrmProvider(options) {
12485
12546
  if (partial.notes !== void 0) row.notes = partial.notes || null;
12486
12547
  if (partial.tags != null) row.tags = partial.tags;
12487
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
+ }
12488
12554
  if (Object.keys(row).length > 0) {
12489
12555
  row.updated_at = (/* @__PURE__ */ new Date()).toISOString();
12490
12556
  const { error } = await pub.from(T.deals).update(row).eq("id", id);
@@ -28407,6 +28473,103 @@ CREATE OR REPLACE VIEW public.v_crm_deal_group WITH (security_invoker = true) AS
28407
28473
  GRANT SELECT ON public.v_crm_deal_group TO authenticated;
28408
28474
  GRANT SELECT ON public.v_crm_deal_group TO service_role;
28409
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
+ `;
28410
28573
  var MIGRATIONS = [
28411
28574
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28412
28575
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28464,7 +28627,8 @@ var MIGRATIONS = [
28464
28627
  { id: "054_a_lista_de_leads_pergunta_por_cidade", sql: MIGRATION_054_A_LISTA_DE_LEADS_PERGUNTA_POR_CIDADE },
28465
28628
  { id: "055_a_cesta_do_interesse_tem_onde_morar", sql: MIGRATION_055_A_CESTA_DO_INTERESSE_TEM_ONDE_MORAR },
28466
28629
  { 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 }
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 }
28468
28632
  ];
28469
28633
 
28470
28634
  // src/locales/en.ts
@@ -28779,6 +28943,8 @@ var en = {
28779
28943
  "crm.deals.allCampaigns": "All campaigns",
28780
28944
  "crm.deals.allCities": "All cities",
28781
28945
  "crm.card.companyTitle": "Company",
28946
+ "crm.card.groupTitle": "Economic group",
28947
+ "crm.card.groupCompanies": "{{count}} companies",
28782
28948
  "crm.card.takeOver": "Take this lead",
28783
28949
  "crm.card.takeOverFrom": "Take over",
28784
28950
  "crm.card.owner": "Owner",
@@ -29615,6 +29781,8 @@ var ptBR = {
29615
29781
  "crm.deals.allCampaigns": "Todas as campanhas",
29616
29782
  "crm.deals.allCities": "Todas as cidades",
29617
29783
  "crm.card.companyTitle": "Empresa",
29784
+ "crm.card.groupTitle": "Grupo econ\xF4mico",
29785
+ "crm.card.groupCompanies": "{{count}} CNPJs",
29618
29786
  "crm.card.takeOver": "Assumir este lead",
29619
29787
  "crm.card.takeOverFrom": "Assumir de quem est\xE1",
29620
29788
  "crm.card.owner": "Respons\xE1vel",