@fayz-ai/plugin-crm 0.26.0 → 0.27.1

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
@@ -1011,7 +1011,7 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
1011
1011
  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"}`,
1012
1012
  children: [
1013
1013
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
1014
- /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium", children: deal.contactName || deal.companyName || deal.title }),
1014
+ /* @__PURE__ */ jsx("p", { className: "truncate text-sm font-medium", children: deal.companyName || deal.contactName || deal.title }),
1015
1015
  saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin text-muted-foreground shrink-0" }),
1016
1016
  !saving && onArchive && /* @__PURE__ */ jsx(
1017
1017
  "button",
@@ -1028,8 +1028,14 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
1028
1028
  ] }),
1029
1029
  (() => {
1030
1030
  const partes = [
1031
- deal.contactName && deal.companyName ? deal.companyName : null,
1032
- deal.title && deal.title !== (deal.contactName || deal.companyName) ? deal.title : null,
1031
+ // O PONTO DE CONTATO, quando a manchete ja e a empresa. Invertido em
1032
+ // relacao ao que era: antes a empresa e que descia para ca.
1033
+ deal.companyName && deal.contactName ? deal.contactName : null,
1034
+ // O título só quando ele DIZ outra coisa. Hoje ele é o nome da
1035
+ // pessoa em quase todos os 316 negócios — herança de quando o
1036
+ // negócio era da pessoa —, e repeti-lo ao lado do ponto de contato
1037
+ // dava "Victor Brandes · Victor Brandes" no card.
1038
+ deal.title && deal.title !== deal.companyName && deal.title !== deal.contactName ? deal.title : null,
1033
1039
  deal.contactCity || null
1034
1040
  ].filter(Boolean);
1035
1041
  if (!partes.length) return null;
@@ -2358,7 +2364,7 @@ var TYPE_ICONS = {
2358
2364
  deal_archived: Archive,
2359
2365
  quote_archived: Archive
2360
2366
  };
2361
- function ActivityTimeline({ activities, loading, locale }) {
2367
+ function ActivityTimeline({ activities, loading, locale, contactName }) {
2362
2368
  const t2 = useTranslation();
2363
2369
  const messages = useActivityAutomations();
2364
2370
  if (loading) {
@@ -2383,7 +2389,13 @@ function ActivityTimeline({ activities, loading, locale }) {
2383
2389
  ] }),
2384
2390
  /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1 pt-0.5", children: [
2385
2391
  /* @__PURE__ */ jsxs("div", { className: "flex items-baseline gap-2", children: [
2386
- /* @__PURE__ */ jsx("p", { className: "min-w-0 flex-1 truncate text-xs font-medium leading-5", children: a.title }),
2392
+ /* @__PURE__ */ jsxs("p", { className: "min-w-0 flex-1 truncate text-xs font-medium leading-5", children: [
2393
+ a.title,
2394
+ a.contactName && a.contactName !== contactName && /* @__PURE__ */ jsxs("span", { className: "ml-1.5 font-normal text-muted-foreground", children: [
2395
+ "\xB7 ",
2396
+ a.contactName
2397
+ ] })
2398
+ ] }),
2387
2399
  a.completedAt && /* @__PURE__ */ jsx(Check, { className: "h-3 w-3 shrink-0 text-success" }),
2388
2400
  /* @__PURE__ */ jsx(AutomationBolt, { activityType: a.activityType, messages }),
2389
2401
  /* @__PURE__ */ jsx("time", { className: "shrink-0 text-[10px] tabular-nums text-muted-foreground/70", children: formatRelativeTime(a.createdAt, locale) })
@@ -3149,6 +3161,49 @@ function LogActivityButton({ target, onLogged }) {
3149
3161
  ] }) })
3150
3162
  ] });
3151
3163
  }
3164
+ function useCanTalk() {
3165
+ const runtime = usePluginRuntimeOptional();
3166
+ return Boolean(runtime?.activePlugins.some((p) => p.id === "conversations"));
3167
+ }
3168
+ function href(personId, name, phone) {
3169
+ return `/conversations?personId=${encodeURIComponent(personId)}&name=${encodeURIComponent(name)}&handle=${encodeURIComponent(phone)}&channel=whatsapp`;
3170
+ }
3171
+ function TalkToPerson({ personId, name, phone, variant = "button", className }) {
3172
+ const t2 = useTranslation();
3173
+ const canTalk = useCanTalk();
3174
+ if (!canTalk || !phone) return null;
3175
+ const label2 = t2("crm.leadDetail.whatsapp");
3176
+ const go = (e) => {
3177
+ e.stopPropagation();
3178
+ e.preventDefault();
3179
+ adminNavigateTo(href(personId, name ?? "", phone));
3180
+ };
3181
+ if (variant === "icon") {
3182
+ return /* @__PURE__ */ jsx(
3183
+ "button",
3184
+ {
3185
+ onClick: go,
3186
+ title: label2,
3187
+ "aria-label": label2,
3188
+ className: className ?? "inline-flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
3189
+ children: /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5" })
3190
+ }
3191
+ );
3192
+ }
3193
+ return /* @__PURE__ */ jsxs(
3194
+ "button",
3195
+ {
3196
+ onClick: go,
3197
+ title: label2,
3198
+ className: className ?? "inline-flex items-center gap-1.5 rounded-lg border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-button transition-colors hover:bg-muted hover:text-foreground active:shadow-button-inset",
3199
+ children: [
3200
+ /* @__PURE__ */ jsx(MessageCircle, { className: "h-3 w-3" }),
3201
+ " ",
3202
+ label2
3203
+ ]
3204
+ }
3205
+ );
3206
+ }
3152
3207
  function Section({ title, action, children }) {
3153
3208
  return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3154
3209
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
@@ -3213,6 +3268,8 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3213
3268
  const [closing, setClosing] = useState(false);
3214
3269
  const [draft, setDraft] = useState(null);
3215
3270
  const [company, setCompany] = useState(null);
3271
+ const [pessoasDaCasa, setPessoasDaCasa] = useState([]);
3272
+ const [trocandoContato, setTrocandoContato] = useState(false);
3216
3273
  const [team, setTeam] = useState(null);
3217
3274
  const [myUserId, setMyUserId] = useState(null);
3218
3275
  const [savingOwner, setSavingOwner] = useState(false);
@@ -3228,7 +3285,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3228
3285
  setActivities([]);
3229
3286
  setQuotes([]);
3230
3287
  setDraft(null);
3231
- void provider.getDealById(dealId).then(async (d) => {
3288
+ void provider.getLiveDealById(dealId).then(async (d) => {
3232
3289
  if (cancelled) return;
3233
3290
  setDeal(d);
3234
3291
  let l = null;
@@ -3252,6 +3309,8 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3252
3309
  if (companyId) {
3253
3310
  const c = await provider.getCompanyById(companyId);
3254
3311
  if (!cancelled) setCompany(c);
3312
+ const gente = await provider.getCompanyPeople(companyId).catch(() => []);
3313
+ if (!cancelled) setPessoasDaCasa(gente);
3255
3314
  }
3256
3315
  if (!cancelled) setLoading(false);
3257
3316
  });
@@ -3320,6 +3379,19 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3320
3379
  setClosing(false);
3321
3380
  }
3322
3381
  }
3382
+ async function trocarPontoDeContato(personId) {
3383
+ if (!deal || trocandoContato) return;
3384
+ setTrocandoContato(true);
3385
+ try {
3386
+ const atualizado = await provider.updateDeal(deal.id, { contactId: personId });
3387
+ const nova = pessoasDaCasa.find((x) => x.personId === personId);
3388
+ setDeal({ ...atualizado, contactName: nova?.personName ?? atualizado.contactName });
3389
+ } catch (err) {
3390
+ toast.error(t2("crm.card.saveFailed"), { description: err?.message });
3391
+ } finally {
3392
+ setTrocandoContato(false);
3393
+ }
3394
+ }
3323
3395
  async function changeOwner(userId) {
3324
3396
  if (!deal || savingOwner) return;
3325
3397
  setSavingOwner(true);
@@ -3462,31 +3534,55 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3462
3534
  /* @__PURE__ */ jsx("div", { className: "h-64 animate-pulse rounded-lg bg-muted/40" })
3463
3535
  ] }) : /* @__PURE__ */ jsxs("div", { className: "grid gap-0 lg:grid-cols-2", children: [
3464
3536
  /* @__PURE__ */ jsxs("div", { className: "space-y-5 border-b p-5 lg:border-b-0 lg:border-r", children: [
3465
- /* @__PURE__ */ jsxs(Section, { title: t2("crm.card.record"), children: [
3466
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
3467
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.name"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }) }) }),
3468
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.phone"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.phone, onChange: (e) => setDraft({ ...draft, phone: e.target.value }) }) }),
3469
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.email"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", type: "email", value: draft.email, onChange: (e) => setDraft({ ...draft, email: e.target.value }) }) }),
3470
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.company"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.company, onChange: (e) => setDraft({ ...draft, company: e.target.value }) }) }),
3471
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.value"), children: /* @__PURE__ */ jsx(CurrencyInput, { value: draft.value, onChange: (v) => setDraft({ ...draft, value: v ?? 0 }) }) }),
3472
- /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.expectedClose"), children: /* @__PURE__ */ jsx(DatePicker, { value: draft.expectedCloseDate, onChange: (v) => setDraft({ ...draft, expectedCloseDate: v }) }) })
3473
- ] }),
3474
- /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.notes"), children: /* @__PURE__ */ jsx(
3475
- "textarea",
3476
- {
3477
- rows: 3,
3478
- value: draft.notes,
3479
- onChange: (e) => setDraft({ ...draft, notes: e.target.value }),
3480
- className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
3481
- }
3482
- ) }),
3483
- /* @__PURE__ */ jsxs(Button, { className: "w-full", onClick: () => {
3484
- void save();
3485
- }, disabled: saving, children: [
3486
- saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
3487
- t2("crm.card.save")
3488
- ] })
3489
- ] }),
3537
+ /* @__PURE__ */ jsxs(
3538
+ Section,
3539
+ {
3540
+ title: t2("crm.card.pointOfContact"),
3541
+ action: lead?.id ? /* @__PURE__ */ jsx(TalkToPerson, { personId: lead.id, name: lead.name, phone: lead.phone, variant: "icon" }) : void 0,
3542
+ children: [
3543
+ pessoasDaCasa.length > 1 && /* @__PURE__ */ jsx("div", { className: "mb-3", children: /* @__PURE__ */ jsxs(
3544
+ Select,
3545
+ {
3546
+ value: deal?.contactId ?? "",
3547
+ onValueChange: (v) => {
3548
+ void trocarPontoDeContato(v);
3549
+ },
3550
+ disabled: trocandoContato,
3551
+ children: [
3552
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: t2("crm.card.pointOfContact") }) }),
3553
+ /* @__PURE__ */ jsx(SelectContent, { children: pessoasDaCasa.map((x) => /* @__PURE__ */ jsxs(SelectItem, { value: x.personId, children: [
3554
+ x.personName,
3555
+ x.role ? ` \xB7 ${x.role}` : ""
3556
+ ] }, x.personId)) })
3557
+ ]
3558
+ }
3559
+ ) }),
3560
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
3561
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.name"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.name, onChange: (e) => setDraft({ ...draft, name: e.target.value }) }) }),
3562
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.phone"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.phone, onChange: (e) => setDraft({ ...draft, phone: e.target.value }) }) }),
3563
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.email"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", type: "email", value: draft.email, onChange: (e) => setDraft({ ...draft, email: e.target.value }) }) }),
3564
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.company"), children: /* @__PURE__ */ jsx(Input, { className: "h-9", value: draft.company, onChange: (e) => setDraft({ ...draft, company: e.target.value }) }) }),
3565
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.value"), children: /* @__PURE__ */ jsx(CurrencyInput, { value: draft.value, onChange: (v) => setDraft({ ...draft, value: v ?? 0 }) }) }),
3566
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.dealSidebar.expectedClose"), children: /* @__PURE__ */ jsx(DatePicker, { value: draft.expectedCloseDate, onChange: (v) => setDraft({ ...draft, expectedCloseDate: v }) }) })
3567
+ ] }),
3568
+ /* @__PURE__ */ jsx(Field, { label: t2("crm.leadDetail.notes"), children: /* @__PURE__ */ jsx(
3569
+ "textarea",
3570
+ {
3571
+ rows: 3,
3572
+ value: draft.notes,
3573
+ onChange: (e) => setDraft({ ...draft, notes: e.target.value }),
3574
+ className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-ring"
3575
+ }
3576
+ ) }),
3577
+ /* @__PURE__ */ jsxs(Button, { className: "w-full", onClick: () => {
3578
+ void save();
3579
+ }, disabled: saving, children: [
3580
+ saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
3581
+ t2("crm.card.save")
3582
+ ] })
3583
+ ]
3584
+ }
3585
+ ),
3490
3586
  company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
3491
3587
  "button",
3492
3588
  {
@@ -3594,7 +3690,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3594
3690
  onLogged: (activity) => setActivities((prev) => [activity, ...prev])
3595
3691
  }
3596
3692
  ),
3597
- children: /* @__PURE__ */ jsx(ActivityTimeline, { activities, loading: activitiesLoading, locale: currency.locale })
3693
+ children: /* @__PURE__ */ jsx(ActivityTimeline, { activities, loading: activitiesLoading, locale: currency.locale, contactName: deal?.contactName })
3598
3694
  }
3599
3695
  ) })
3600
3696
  ] }) })
@@ -3724,49 +3820,6 @@ function LeadStatusBadge({ status, className }) {
3724
3820
  }
3725
3821
  );
3726
3822
  }
3727
- function useCanTalk() {
3728
- const runtime = usePluginRuntimeOptional();
3729
- return Boolean(runtime?.activePlugins.some((p) => p.id === "conversations"));
3730
- }
3731
- function href(personId, name, phone) {
3732
- return `/conversations?personId=${encodeURIComponent(personId)}&name=${encodeURIComponent(name)}&handle=${encodeURIComponent(phone)}&channel=whatsapp`;
3733
- }
3734
- function TalkToPerson({ personId, name, phone, variant = "button", className }) {
3735
- const t2 = useTranslation();
3736
- const canTalk = useCanTalk();
3737
- if (!canTalk || !phone) return null;
3738
- const label2 = t2("crm.leadDetail.whatsapp");
3739
- const go = (e) => {
3740
- e.stopPropagation();
3741
- e.preventDefault();
3742
- adminNavigateTo(href(personId, name ?? "", phone));
3743
- };
3744
- if (variant === "icon") {
3745
- return /* @__PURE__ */ jsx(
3746
- "button",
3747
- {
3748
- onClick: go,
3749
- title: label2,
3750
- "aria-label": label2,
3751
- className: className ?? "inline-flex h-7 w-7 items-center justify-center rounded-lg text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
3752
- children: /* @__PURE__ */ jsx(MessageCircle, { className: "h-3.5 w-3.5" })
3753
- }
3754
- );
3755
- }
3756
- return /* @__PURE__ */ jsxs(
3757
- "button",
3758
- {
3759
- onClick: go,
3760
- title: label2,
3761
- className: className ?? "inline-flex items-center gap-1.5 rounded-lg border bg-card px-3 py-1.5 text-xs font-medium text-muted-foreground shadow-button transition-colors hover:bg-muted hover:text-foreground active:shadow-button-inset",
3762
- children: [
3763
- /* @__PURE__ */ jsx(MessageCircle, { className: "h-3 w-3" }),
3764
- " ",
3765
- label2
3766
- ]
3767
- }
3768
- );
3769
- }
3770
3823
  function topAnswerKeys(leads2, limit = 3) {
3771
3824
  const count = /* @__PURE__ */ new Map();
3772
3825
  for (const lead of leads2) {
@@ -5559,7 +5612,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5559
5612
  provider.getLeadById(leadId).then(async (l) => {
5560
5613
  setLead(l);
5561
5614
  if (l) {
5562
- const d = await provider.getDealByLeadId(leadId);
5615
+ const d = await provider.getPipelineCardForLead(leadId);
5563
5616
  setDeal(d);
5564
5617
  if (d) {
5565
5618
  const q = await provider.getQuotesByDealId(d.id);
@@ -5753,6 +5806,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5753
5806
  }
5754
5807
  )
5755
5808
  ] }),
5809
+ deal.contactId && deal.contactId !== leadId && /* @__PURE__ */ jsx("p", { className: "mb-2 rounded-card border border-dashed bg-muted/30 px-3 py-2 text-[11px] text-muted-foreground", children: t2("crm.leadDetail.notThePointOfContact").replace("{company}", deal.companyName ?? t2("crm.leadDetail.thisCompany")).replace("{contact}", deal.contactName ?? "\u2014") }),
5756
5810
  /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
5757
5811
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.stage"), value: deal.stageName ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
5758
5812
  deal.stageColor && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: deal.stageColor } }),
@@ -9641,7 +9695,45 @@ function createMockCrmProvider(options) {
9641
9695
  return store.quotes.filter((q) => q.dealId === dealId);
9642
9696
  },
9643
9697
  async getDealByLeadId(leadId) {
9644
- return store.deals.find((d) => d.leadId === leadId) ?? null;
9698
+ const dela = store.deals.filter((d) => d.leadId === leadId);
9699
+ return dela.find((d) => d.status === "open") ?? dela[0] ?? null;
9700
+ },
9701
+ async seguirFusao(inicio, jaVistos = []) {
9702
+ const vistos = new Set(jaVistos);
9703
+ let alvo = inicio;
9704
+ while (alvo && !vistos.has(alvo)) {
9705
+ vistos.add(alvo);
9706
+ const linha = store.deals.find((d) => d.id === alvo);
9707
+ if (!linha) return null;
9708
+ if (linha.status === "open") return linha.id;
9709
+ alvo = linha.metadata?.merged_into;
9710
+ }
9711
+ return null;
9712
+ },
9713
+ async getLiveDealById(dealId) {
9714
+ const linha = store.deals.find((d) => d.id === dealId);
9715
+ if (!linha) return null;
9716
+ const fundidoEm = linha.metadata?.merged_into;
9717
+ const destino = fundidoEm ? await provider.seguirFusao(fundidoEm, [dealId]) : null;
9718
+ return (destino ? store.deals.find((d) => d.id === destino) : linha) ?? linha;
9719
+ },
9720
+ async getPipelineCardForLead(leadId) {
9721
+ const dela = store.deals.filter((d) => d.leadId === leadId);
9722
+ const aberto = dela.find((d) => d.status === "open");
9723
+ if (aberto) return aberto;
9724
+ const vistos = new Set(dela.map((d) => d.id));
9725
+ let alvo = dela.find((d) => d.metadata?.merged_into)?.["metadata"];
9726
+ alvo = alvo?.merged_into;
9727
+ while (alvo && !vistos.has(alvo)) {
9728
+ vistos.add(alvo);
9729
+ const linha = store.deals.find((d) => d.id === alvo);
9730
+ if (!linha) break;
9731
+ if (linha.status === "open") return linha;
9732
+ alvo = linha.metadata?.merged_into;
9733
+ }
9734
+ const empresaId = dela.find((d) => d.companyId)?.companyId;
9735
+ if (!empresaId) return null;
9736
+ return store.deals.find((d) => d.companyId === empresaId && d.status === "open") ?? null;
9645
9737
  },
9646
9738
  // --- Pesquisas de avaliação (memória; some ao recarregar, como o resto do mock) ---
9647
9739
  async getSurveys() {
@@ -10419,7 +10511,7 @@ function snakeToCamel(obj) {
10419
10511
  return result;
10420
10512
  }
10421
10513
  var DEALS_POR_ETAPA = 100;
10422
- var BUSCA_NO_QUADRO = ["title", "contact_name", "notes", "lost_reason", "stage_name", "contact_status_name"];
10514
+ var BUSCA_NO_QUADRO = ["title", "contact_name", "company_name", "notes", "lost_reason", "stage_name", "contact_status_name"];
10423
10515
  async function callBacklog(limit, dryRun) {
10424
10516
  const supabase = getSupabaseClientOptional();
10425
10517
  if (!supabase) throw new Error("Supabase not initialized");
@@ -11329,11 +11421,92 @@ function createSupabaseCrmProvider(options) {
11329
11421
  updatedAt: r.updated_at
11330
11422
  }));
11331
11423
  },
11424
+ /**
11425
+ * Walk `metadata.merged_into` to the card that is still on the board.
11426
+ *
11427
+ * Transitive because a second merge points the first survivor at a third
11428
+ * card. `vistos` is not defensive decoration: a merge that ever pointed two
11429
+ * cards at each other would spin this loop forever, and a hung page is
11430
+ * worse than a wrong one.
11431
+ *
11432
+ * Returns the id of the first OPEN card found, or null — a trail that ends
11433
+ * in something archived is not an answer worth showing.
11434
+ */
11435
+ async seguirFusao(inicio, jaVistos = []) {
11436
+ const { pub } = getClients();
11437
+ const vistos = new Set(jaVistos);
11438
+ let alvo = inicio;
11439
+ while (alvo && !vistos.has(alvo)) {
11440
+ vistos.add(alvo);
11441
+ const { data } = await pub.from(T.deals).select("id, status, metadata").eq("id", alvo).limit(1);
11442
+ const linha = (data ?? [])[0];
11443
+ if (!linha) return null;
11444
+ if (linha.status === "open") return linha.id;
11445
+ alvo = linha.metadata?.merged_into;
11446
+ }
11447
+ return null;
11448
+ },
11449
+ /**
11450
+ * The deal behind an id, with a merged one redirected to its survivor.
11451
+ *
11452
+ * Only a MERGED card redirects. A card archived by hand is a card someone
11453
+ * chose to take off the board, and opening it should show it — the rule is
11454
+ * `metadata.merged_into`, not `status`.
11455
+ *
11456
+ * This is the belt to `getPipelineCardForLead`'s braces: that one fixes the
11457
+ * link, this one fixes the bookmark, the pasted URL and every link written
11458
+ * before the merge happened.
11459
+ */
11460
+ async getLiveDealById(dealId) {
11461
+ const { pub } = getClients();
11462
+ const { data } = await pub.from(T.deals).select("id, status, metadata").eq("id", dealId).limit(1);
11463
+ const linha = (data ?? [])[0];
11464
+ if (!linha) return provider.getDealById(dealId);
11465
+ const destino = linha.metadata?.merged_into ? await provider.seguirFusao(linha.metadata.merged_into, [dealId]) : null;
11466
+ return provider.getDealById(destino ?? dealId);
11467
+ },
11332
11468
  async getDealByLeadId(leadId) {
11333
11469
  const { pub } = getClients();
11334
- const { data } = await pub.from(T.deals).select("id").eq("lead_id", leadId).limit(1);
11335
- if (!data || data.length === 0) return null;
11336
- return provider.getDealById(data[0].id);
11470
+ const { data } = await pub.from(T.deals).select("id, status, created_at").eq("lead_id", leadId).order("created_at", { ascending: false });
11471
+ const rows = data ?? [];
11472
+ if (rows.length === 0) return null;
11473
+ return provider.getDealById((rows.find((r) => r.status === "open") ?? rows[0]).id);
11474
+ },
11475
+ /**
11476
+ * The card this person opens in the funnel — the house's, not hers.
11477
+ *
11478
+ * The bug this closes: opening SAO JORDÃO from Rosany's page showed a card
11479
+ * with a "Perdido" badge, no stage row and no way to move it. It was her
11480
+ * own deal, `archived`, `merged_into` the live one — a row that exists in
11481
+ * the table and not on the board.
11482
+ *
11483
+ * Three steps, in this order:
11484
+ *
11485
+ * 1. her own OPEN deal — someone who was never merged still has one, and
11486
+ * it is the right answer;
11487
+ * 2. the merge trail: `metadata.merged_into` on her archived deal, walked
11488
+ * to the survivor. Transitive because a second merge points the first
11489
+ * survivor at a third card, and bounded because a cycle would
11490
+ * otherwise hang the page;
11491
+ * 3. the company's open card, for a lead whose own deal was deleted
11492
+ * rather than merged, or who never had one.
11493
+ */
11494
+ async getPipelineCardForLead(leadId) {
11495
+ const { pub } = getClients();
11496
+ const { data } = await pub.from(T.deals).select("id, status, metadata, company_id, created_at").eq("lead_id", leadId).order("created_at", { ascending: false });
11497
+ const rows = data ?? [];
11498
+ const aberto = rows.find((r) => r.status === "open");
11499
+ if (aberto) return provider.getDealById(aberto.id);
11500
+ const sobrevivente = await provider.seguirFusao(
11501
+ rows.find((r) => r.metadata?.merged_into)?.metadata?.merged_into,
11502
+ rows.map((r) => r.id)
11503
+ );
11504
+ if (sobrevivente) return provider.getDealById(sobrevivente);
11505
+ const empresaId = rows.find((r) => r.company_id)?.company_id ?? (await provider.getLeadById(leadId))?.companyId;
11506
+ if (!empresaId) return null;
11507
+ const { data: daCasa } = await pub.from(T.deals).select("id").eq("company_id", empresaId).eq("status", "open").order("created_at", { ascending: true }).limit(1);
11508
+ const linha = (daCasa ?? [])[0];
11509
+ return linha ? provider.getDealById(linha.id) : null;
11337
11510
  },
11338
11511
  // --- Summary ---
11339
11512
  // --- Pesquisas de avaliação ---
@@ -25663,6 +25836,206 @@ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25663
25836
 
25664
25837
  GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25665
25838
  `;
25839
+ var MIGRATION_052_O_NEGOCIO_DIZ_DE_QUE_CASA_ELE_E = `-- ---------------------------------------------------------------------------
25840
+ -- 052_o_negocio_diz_de_que_casa_ele_e.sql
25841
+ --
25842
+ -- \u2500\u2500 o buraco \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25843
+ --
25844
+ -- O card do funil mostrava o nome da PESSOA mesmo quando o neg\xF3cio tinha
25845
+ -- empresa ligada. A causa n\xE3o era a tela: \`v_deals\` exp\xF5e \`company_id\` e nunca
25846
+ -- exp\xF4s \`company_name\`, e o mapeador do cliente l\xEA \`r.company_name\` \u2014 que
25847
+ -- voltava indefinido em todas as 316 linhas.
25848
+ --
25849
+ -- Ent\xE3o \`deal.companyName\` era sempre vazio, a tela ca\xEDa no nome da pessoa, e
25850
+ -- nada em lugar nenhum indicava que faltava um dado. Um \`undefined\` silencioso
25851
+ -- atravessando quatro camadas.
25852
+ --
25853
+ -- \u2500\u2500 por que aqui e n\xE3o uma segunda consulta na tela \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25854
+ --
25855
+ -- O quadro carrega centenas de cards de uma vez. Buscar a empresa card a card
25856
+ -- seriam centenas de idas ao servidor para preencher uma linha de texto; o
25857
+ -- JOIN custa uma vez, do lado onde o \xEDndice j\xE1 existe.
25858
+ --
25859
+ -- Vem tamb\xE9m o \`document_number\`: quem agrupa casas por raiz de CNPJ precisa
25860
+ -- dele no card, e uma segunda migration para acrescentar uma coluna irm\xE3 seria
25861
+ -- a mesma view derrubada duas vezes.
25862
+ --
25863
+ -- \u2500\u2500 e o dependente volta junto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25864
+ --
25865
+ -- \`plg_crm_rep_deals\` l\xEA desta view, e \`DROP ... CASCADE\` a levaria embora.
25866
+ -- Isso j\xE1 aconteceu com a \`v_leads\`: um script a derrubou, o dependente foi
25867
+ -- junto, e a lista de leads ficou VAZIA em produ\xE7\xE3o at\xE9 algu\xE9m reclamar.
25868
+ --
25869
+ -- Recriar na MESMA migration \xE9 o que torna a troca at\xF4mica: ou as duas voltam,
25870
+ -- ou nenhuma cai.
25871
+ --
25872
+ -- Idempotente e replay-safe: a view \xE9 DERRUBADA antes de criada.
25873
+ -- ---------------------------------------------------------------------------
25874
+
25875
+ DROP VIEW IF EXISTS public.v_deals CASCADE;
25876
+ CREATE VIEW public.v_deals WITH (security_invoker = true) AS
25877
+ SELECT d.id,
25878
+ d.tenant_id,
25879
+ d.status,
25880
+ d.value,
25881
+ COALESCE(d.title, d.notes) AS title,
25882
+ d.contact_id,
25883
+ d.assigned_to_id,
25884
+ d.tags,
25885
+ d.metadata ->> 'contactName'::text AS contact_name,
25886
+ d.created_at,
25887
+ d.updated_at,
25888
+ d.pipeline_id,
25889
+ d.stage_id,
25890
+ d.probability,
25891
+ d.expected_close_date,
25892
+ d.lead_id,
25893
+ d.lost_reason,
25894
+ ps.name AS stage_name,
25895
+ ps.color AS stage_color,
25896
+ ps."order" AS stage_order,
25897
+ ps.name AS stage,
25898
+ d.won_at,
25899
+ d.lost_at,
25900
+ d.company_id,
25901
+ d.contact_status,
25902
+ d.contact_status_at,
25903
+ cs.name AS contact_status_name,
25904
+ cs.color AS contact_status_color,
25905
+ d.notes,
25906
+ cs.derived_from AS contact_status_derived_from,
25907
+ -- 052: o NOME da empresa do neg\xF3cio.
25908
+ --
25909
+ -- \`company_id\` estava aqui desde sempre, o nome n\xE3o \u2014 e o mapeador do
25910
+ -- cliente lia \`r.company_name\`, que voltava indefinido em toda linha. O
25911
+ -- card do funil tinha \`deal.companyName\` sempre vazio e ca\xEDa no nome da
25912
+ -- pessoa, sem nada indicando que faltava um dado.
25913
+ emp.name AS company_name,
25914
+ emp.document_number AS company_document
25915
+ FROM plg_crm_deals d
25916
+ LEFT JOIN plg_crm_companies emp ON emp.id = d.company_id
25917
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
25918
+ LEFT JOIN LATERAL ( SELECT s.name,
25919
+ s.color,
25920
+ s.derived_from
25921
+ FROM plg_crm_deal_statuses s
25922
+ 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)
25923
+ ORDER BY (s.stage_id IS NOT NULL) DESC
25924
+ LIMIT 1) cs ON true;
25925
+
25926
+ GRANT SELECT ON public.v_deals TO authenticated, service_role;
25927
+
25928
+ -- O dependente, recriado a partir do que estava no ar.
25929
+ CREATE VIEW public.plg_crm_rep_deals WITH (security_invoker = true) AS
25930
+ SELECT id AS deal_id,
25931
+ tenant_id,
25932
+ created_at,
25933
+ title,
25934
+ contact_name,
25935
+ status,
25936
+ pipeline_id,
25937
+ COALESCE(NULLIF(stage_name, ''::text), 'Sem etapa'::text) AS stage_name,
25938
+ assigned_to_id,
25939
+ expected_close_date,
25940
+ lost_reason,
25941
+ COALESCE(value, 0::numeric) AS value,
25942
+ 1 AS deals,
25943
+ CASE
25944
+ WHEN status = 'won'::text THEN COALESCE(value, 0::numeric)
25945
+ ELSE 0::numeric
25946
+ END AS won_value,
25947
+ CASE
25948
+ WHEN status = 'open'::text THEN COALESCE(value, 0::numeric)
25949
+ ELSE 0::numeric
25950
+ END AS open_value,
25951
+ CASE
25952
+ WHEN status = 'won'::text THEN 1
25953
+ ELSE 0
25954
+ END AS is_won,
25955
+ CASE
25956
+ WHEN status = 'lost'::text THEN 1
25957
+ ELSE 0
25958
+ END AS is_lost,
25959
+ CASE
25960
+ WHEN status = 'open'::text THEN 1
25961
+ ELSE 0
25962
+ END AS is_open
25963
+ FROM v_deals d
25964
+ WHERE status <> 'archived'::text;
25965
+
25966
+ GRANT SELECT ON public.plg_crm_rep_deals TO authenticated, service_role;
25967
+ `;
25968
+ var MIGRATION_053_A_ATIVIDADE_DIZ_DE_QUEM_ELA_E = `-- ---------------------------------------------------------------------------
25969
+ -- 053_a_atividade_diz_de_quem_ela_e.sql
25970
+ --
25971
+ -- \u2500\u2500 o buraco \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25972
+ --
25973
+ -- A linha do tempo do card da KEETA mostra OITO linhas id\xEAnticas:
25974
+ --
25975
+ -- Contato presencial na feira
25976
+ -- Sal\xE3o Abrasel \u2014 o crach\xE1 foi lido no estande e o contato entrou na base.
25977
+ --
25978
+ -- Parece duplica\xE7\xE3o e n\xE3o \xE9: s\xE3o oito pessoas distintas \u2014 Vitor, Victor Piva,
25979
+ -- Natan, Jonathan, Marco Antonio, julia, Larissa e Fabio \u2014, cada uma com o
25980
+ -- crach\xE1 lido no estande. Oito eventos reais.
25981
+ --
25982
+ -- O texto nunca precisou dizer de quem era porque cada card era de UMA pessoa:
25983
+ -- o nome estava no t\xEDtulo do card. Quando os cards viraram um por casa, a
25984
+ -- informa\xE7\xE3o que tornava cada linha distinta ficou de fora, e o hist\xF3rico
25985
+ -- passou a parecer defeito.
25986
+ --
25987
+ -- \u2500\u2500 por que preencher em vez de juntar na leitura \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25988
+ --
25989
+ -- \`contact_name\` j\xE1 existe na tabela e est\xE1 preenchido em 18 de 382 linhas.
25990
+ -- \`lead_id\` est\xE1 em 370. O nome sempre esteve alcan\xE7\xE1vel; ningu\xE9m o copiou.
25991
+ --
25992
+ -- Um JOIN na leitura resolveria a tela e deixaria a coluna mentindo \u2014 e a
25993
+ -- pr\xF3xima tela a ler a tabela cairia no mesmo vazio. Preencher conserta a
25994
+ -- origem, e o gatilho abaixo impede que volte a acontecer.
25995
+ --
25996
+ -- \u2500\u2500 por que um gatilho, e n\xE3o s\xF3 o backfill \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25997
+ --
25998
+ -- Quem grava atividade hoje s\xE3o cinco caminhos diferentes (webhook, campanha,
25999
+ -- tela, importa\xE7\xE3o, automa\xE7\xE3o). Exigir que todos lembrem de copiar o nome \xE9
26000
+ -- garantir que um deles n\xE3o vai lembrar. O banco preenche quando falta.
26001
+ --
26002
+ -- Idempotente e replay-safe.
26003
+ -- ---------------------------------------------------------------------------
26004
+
26005
+ CREATE OR REPLACE FUNCTION public.plg_crm_atividade_nomeia_a_pessoa()
26006
+ RETURNS trigger
26007
+ LANGUAGE plpgsql
26008
+ SECURITY DEFINER
26009
+ SET search_path = ''
26010
+ AS $$
26011
+ BEGIN
26012
+ -- S\xF3 quando FALTA. Um nome escrito \xE0 m\xE3o \u2014 "a recepcionista", "o s\xF3cio que
26013
+ -- atendeu" \u2014 vale mais que o cadastro e n\xE3o deve ser sobrescrito.
26014
+ IF NEW.contact_name IS NULL OR btrim(NEW.contact_name) = '' THEN
26015
+ SELECT p.name INTO NEW.contact_name
26016
+ FROM public.people p
26017
+ WHERE p.id = coalesce(NEW.contact_id, NEW.lead_id);
26018
+ END IF;
26019
+ RETURN NEW;
26020
+ END $$;
26021
+
26022
+ REVOKE ALL ON FUNCTION public.plg_crm_atividade_nomeia_a_pessoa() FROM public, anon, authenticated;
26023
+
26024
+ DROP TRIGGER IF EXISTS plg_crm_atividade_nomeia_a_pessoa ON public.plg_crm_activities;
26025
+ CREATE TRIGGER plg_crm_atividade_nomeia_a_pessoa
26026
+ BEFORE INSERT OR UPDATE OF contact_id, lead_id ON public.plg_crm_activities
26027
+ FOR EACH ROW EXECUTE FUNCTION public.plg_crm_atividade_nomeia_a_pessoa();
26028
+
26029
+ -- O passado, que \xE9 o que est\xE1 na tela agora.
26030
+ UPDATE public.plg_crm_activities a
26031
+ SET contact_name = p.name
26032
+ FROM public.people p
26033
+ WHERE p.id = coalesce(a.contact_id, a.lead_id)
26034
+ AND (a.contact_name IS NULL OR btrim(a.contact_name) = '');
26035
+
26036
+ COMMENT ON COLUMN public.plg_crm_activities.contact_name IS
26037
+ 'De QUEM \xE9 a atividade. Redundante com \`lead_id\` de prop\xF3sito: quando os cards passaram a ser por empresa, oito visitas de oito pessoas viraram oito linhas id\xEAnticas na tela (053).';
26038
+ `;
25666
26039
  var MIGRATIONS = [
25667
26040
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
25668
26041
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -25714,7 +26087,9 @@ var MIGRATIONS = [
25714
26087
  { id: "048_a_empresa_tambem_tem_um_arroba", sql: MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA },
25715
26088
  { id: "049_o_arroba_chega_ate_a_lista", sql: MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA },
25716
26089
  { id: "050_a_reuniao_e_uma_especie_declarada", sql: MIGRATION_050_A_REUNIAO_E_UMA_ESPECIE_DECLARADA },
25717
- { id: "051_o_cracha_e_o_telefone_recusado_aparecem", sql: MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM }
26090
+ { id: "051_o_cracha_e_o_telefone_recusado_aparecem", sql: MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM },
26091
+ { id: "052_o_negocio_diz_de_que_casa_ele_e", sql: MIGRATION_052_O_NEGOCIO_DIZ_DE_QUE_CASA_ELE_E },
26092
+ { id: "053_a_atividade_diz_de_quem_ela_e", sql: MIGRATION_053_A_ATIVIDADE_DIZ_DE_QUEM_ELA_E }
25718
26093
  ];
25719
26094
 
25720
26095
  // src/locales/en.ts
@@ -25822,6 +26197,8 @@ var en = {
25822
26197
  "crm.leads.filters.clear": "Clear",
25823
26198
  "crm.leadDetail.pipeline": "Pipeline",
25824
26199
  "crm.leadDetail.openDeal": "Open in pipeline",
26200
+ "crm.leadDetail.notThePointOfContact": "The pipeline has one card per company. This one opens on {company}, with {contact} as the point of contact \u2014 you can change it there.",
26201
+ "crm.leadDetail.thisCompany": "this company",
25825
26202
  "crm.leadDetail.probability": "Probability",
25826
26203
  "crm.leadDetail.quotes": "Quotes",
25827
26204
  "crm.leadDetail.source": "Source",
@@ -25960,6 +26337,7 @@ var en = {
25960
26337
  "crm.segments.field.lastEngagedAt": "Last sign of life",
25961
26338
  "crm.segments.field.ordersCount": "Purchases",
25962
26339
  "crm.segments.field.totalSpent": "Total spent",
26340
+ "crm.card.pointOfContact": "Point of contact",
25963
26341
  "crm.card.record": "Record",
25964
26342
  "crm.card.timeline": "Timeline",
25965
26343
  "crm.card.save": "Save record",
@@ -26619,6 +26997,8 @@ var ptBR = {
26619
26997
  "crm.leads.filters.clear": "Limpar",
26620
26998
  "crm.leadDetail.pipeline": "Pipeline",
26621
26999
  "crm.leadDetail.openDeal": "Abrir no funil",
27000
+ "crm.leadDetail.notThePointOfContact": "O funil tem um card por casa. Este abre em {company}, com {contact} como ponto de contato \u2014 voc\xEA pode trocar por l\xE1.",
27001
+ "crm.leadDetail.thisCompany": "esta empresa",
26622
27002
  "crm.leadDetail.probability": "Probabilidade",
26623
27003
  "crm.leadDetail.quotes": "Or\xE7amentos",
26624
27004
  "crm.leadDetail.source": "Origem",
@@ -26757,6 +27137,7 @@ var ptBR = {
26757
27137
  "crm.segments.field.lastEngagedAt": "\xDAltimo sinal de vida",
26758
27138
  "crm.segments.field.ordersCount": "N\xBA de compras",
26759
27139
  "crm.segments.field.totalSpent": "Total gasto",
27140
+ "crm.card.pointOfContact": "Ponto de contato",
26760
27141
  "crm.card.record": "Ficha de cadastro",
26761
27142
  "crm.card.timeline": "Linha do tempo",
26762
27143
  "crm.card.save": "Salvar cadastro",