@fayz-ai/plugin-crm 0.29.1 → 0.29.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.
@@ -0,0 +1,31 @@
1
+ import React from 'react';
2
+ /**
3
+ * A empresa que alguém DIGITOU, mas que não é empresa nenhuma ainda.
4
+ *
5
+ * Um lead de feira chega com o nome da casa escrito à mão num campo de texto —
6
+ * `people.metadata.company`. É o dado mais importante do card e o único que o
7
+ * sistema não sabia usar: sem uma linha em `plg_crm_companies` e sem o vínculo
8
+ * em `plg_crm_company_people`, o negócio nasce sem `company_id`, a manchete do
9
+ * funil cai no nome da PESSOA e o painel Empresa não aparece — o nome fica na
10
+ * tela como texto morto, sem levar a lugar nenhum.
11
+ *
12
+ * Medido em 2026-09-28 nesta base: 27 leads assim, 26 negócios abertos por
13
+ * baixo deles. Não é um caso de borda, é um quarto do funil.
14
+ *
15
+ * O gesto é UM clique porque o dado já está lá. Quem escreveu "AELA BURGER" no
16
+ * crachá já decidiu o nome; pedir um formulário aqui é pedir que digite de novo
17
+ * o que acabou de ler na tela. Se já existir uma casa com esse nome a gente
18
+ * VINCULA em vez de criar uma segunda — duplicata de empresa é o defeito que
19
+ * este botão existiria para causar se fosse ingênuo.
20
+ *
21
+ * Some assim que o vínculo existe. O `trg_plg_crm_deals_stamp_company` carimba
22
+ * o negócio a partir do vínculo, então não há nada a fazer do lado do card.
23
+ */
24
+ export declare function LinkCompanyPrompt({ personId, companyText, onLinked }: {
25
+ /** A pessoa a ligar — o lead ou o contato do card. */
26
+ personId: string;
27
+ /** O que está escrito no cadastro. Sem isto não há o que oferecer. */
28
+ companyText?: string | null;
29
+ onLinked?: (companyId: string) => void;
30
+ }): React.JSX.Element | null;
31
+ //# sourceMappingURL=LinkCompanyPrompt.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"LinkCompanyPrompt.d.ts","sourceRoot":"","sources":["../../src/components/LinkCompanyPrompt.tsx"],"names":[],"mappings":"AAAA,OAAO,KAA8B,MAAM,OAAO,CAAA;AAMlD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,iBAAiB,CAAC,EAAE,QAAQ,EAAE,WAAW,EAAE,QAAQ,EAAE,EAAE;IACrE,sDAAsD;IACtD,QAAQ,EAAE,MAAM,CAAA;IAChB,sEAAsE;IACtE,WAAW,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC3B,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,IAAI,CAAA;CACvC,4BAgEA"}
@@ -28,7 +28,7 @@ export declare const T: {
28
28
  readonly people: "people";
29
29
  readonly personMerges: "person_merges";
30
30
  readonly companies: "plg_crm_companies";
31
- readonly companiesView: "v_crm_companies";
31
+ readonly companiesView: "v_crm_companies_enriched";
32
32
  readonly companyPeople: "plg_crm_company_people";
33
33
  readonly companyPeopleView: "v_crm_company_people";
34
34
  readonly personPhones: "plg_crm_person_phones";
@@ -1 +1 @@
1
- {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAwDJ,CAAA"}
1
+ {"version":3,"file":"tables.d.ts","sourceRoot":"","sources":["../../src/data/tables.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA0DJ,CAAA"}
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
2
  import { tl, useTranslation, getSupabaseClientOptional, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
3
  import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, usePluginOnboardingGate, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
4
- import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, Building2, CircleDot, User, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, 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, PersonPicker, CurrencyInput, HeaderTabs, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
4
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, Building2, CircleDot, User, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, SlidersHorizontal, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
5
+ import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, PageViewBar, ViewTabs, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, PageHeaderActions, FilterChip, MultiSelect, FilterMenu, FilterMenuRow, PersonAvatar, ListView, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, PersonPicker, CurrencyInput, HeaderTabs, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
@@ -3221,7 +3221,9 @@ var T = {
3221
3221
  companies: "plg_crm_companies",
3222
3222
  // The read model: the table plus people_count, open_deals, won_value and how
3223
3223
  // many siblings share the CNPJ root. Reads go here, writes to `companies`.
3224
- companiesView: "v_crm_companies",
3224
+ // A enriquecida (059). A 013 continua dona de `v_crm_companies`, que não pode
3225
+ // crescer sem quebrar o replay da cadeia — o porquê está escrito na 059.
3226
+ companiesView: "v_crm_companies_enriched",
3225
3227
  companyPeople: "plg_crm_company_people",
3226
3228
  companyPeopleView: "v_crm_company_people",
3227
3229
  personPhones: "plg_crm_person_phones",
@@ -3760,6 +3762,68 @@ function buildCrmRegistries(activityTypes) {
3760
3762
  } : registry
3761
3763
  );
3762
3764
  }
3765
+ function LinkCompanyPrompt({ personId, companyText, onLinked }) {
3766
+ const t2 = useTranslation();
3767
+ const provider = useCrmProvider();
3768
+ const saveCompany = useCrmStore((s) => s.saveCompany);
3769
+ const [existente, setExistente] = useState(null);
3770
+ const [ligando, setLigando] = useState(false);
3771
+ const nome = companyText?.trim();
3772
+ useEffect(() => {
3773
+ if (!nome) {
3774
+ setExistente(null);
3775
+ return;
3776
+ }
3777
+ let vivo = true;
3778
+ provider.searchCompanies(nome, 5).then((rs) => {
3779
+ if (!vivo) return;
3780
+ const exato = rs.find((r) => r.name.trim().toLowerCase() === nome.toLowerCase());
3781
+ setExistente(exato ? { id: exato.id, name: exato.name } : null);
3782
+ }).catch(() => {
3783
+ if (vivo) setExistente(null);
3784
+ });
3785
+ return () => {
3786
+ vivo = false;
3787
+ };
3788
+ }, [provider, nome]);
3789
+ if (!nome) return null;
3790
+ async function vincular() {
3791
+ if (!nome || ligando) return;
3792
+ setLigando(true);
3793
+ try {
3794
+ const companyId = existente?.id ?? (await saveCompany({ name: nome })).id;
3795
+ await provider.linkCompanyPerson({ companyId, personId, isPrimary: true });
3796
+ toast.success(t2("crm.linkCompany.done", { name: nome }));
3797
+ onLinked?.(companyId);
3798
+ } catch (err) {
3799
+ toast.error(t2("crm.linkCompany.failed"), { description: err?.message });
3800
+ } finally {
3801
+ setLigando(false);
3802
+ }
3803
+ }
3804
+ return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-card border border-dashed bg-muted/20 px-3 py-3", children: [
3805
+ /* @__PURE__ */ jsx(Building2, { className: "h-4 w-4 shrink-0 text-muted-foreground" }),
3806
+ /* @__PURE__ */ jsxs("span", { className: "min-w-0 flex-1", children: [
3807
+ /* @__PURE__ */ jsx("span", { className: "block truncate text-sm font-medium", children: nome }),
3808
+ /* @__PURE__ */ jsx("span", { className: "block text-[11px] text-muted-foreground", children: t2(existente ? "crm.linkCompany.hintExisting" : "crm.linkCompany.hintNew") })
3809
+ ] }),
3810
+ /* @__PURE__ */ jsxs(
3811
+ "button",
3812
+ {
3813
+ type: "button",
3814
+ onClick: () => {
3815
+ void vincular();
3816
+ },
3817
+ disabled: ligando,
3818
+ className: "inline-flex shrink-0 items-center gap-1.5 rounded-button bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-button transition-opacity hover:opacity-90 disabled:opacity-60",
3819
+ children: [
3820
+ ligando ? /* @__PURE__ */ jsx(Loader2, { className: "h-3 w-3 animate-spin" }) : /* @__PURE__ */ jsx(Plus, { className: "h-3 w-3" }),
3821
+ t2(existente ? "crm.linkCompany.link" : "crm.linkCompany.create")
3822
+ ]
3823
+ }
3824
+ )
3825
+ ] });
3826
+ }
3763
3827
  var STYLE = {
3764
3828
  hot: { icon: Flame, cls: "bg-destructive-soft text-destructive-soft-foreground" },
3765
3829
  warm: { icon: Sun, cls: "bg-warning-soft text-warning-soft-foreground" },
@@ -4623,6 +4687,16 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
4623
4687
  deal.groupCompanies ? /* @__PURE__ */ jsx("span", { className: "block truncate text-[11px] text-muted-foreground", children: t2("crm.card.groupCompanies", { count: String(deal.groupCompanies) }) }) : null
4624
4688
  ] })
4625
4689
  ] }) }),
4690
+ !company && pessoaDoCard?.id && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsx(
4691
+ LinkCompanyPrompt,
4692
+ {
4693
+ personId: pessoaDoCard.id,
4694
+ companyText: pessoaDoCard.company ?? draft.company,
4695
+ onLinked: () => {
4696
+ void provider.getLiveDealById(dealId).then((d) => d && setDeal(d));
4697
+ }
4698
+ }
4699
+ ) }),
4626
4700
  company && /* @__PURE__ */ jsx(Section, { title: t2("crm.card.companyTitle"), children: /* @__PURE__ */ jsxs(
4627
4701
  "button",
4628
4702
  {
@@ -5848,18 +5922,22 @@ function useQuoteColumns(currency, onEditQuote, onArchive) {
5848
5922
  children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
5849
5923
  }
5850
5924
  ),
5851
- onArchive && /* @__PURE__ */ jsx(
5852
- "button",
5853
- {
5854
- onClick: (e) => {
5855
- e.stopPropagation();
5856
- onArchive(row.original.id);
5857
- },
5858
- className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground transition-colors",
5859
- title: t2("crm.quotes.archive"),
5860
- children: /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" })
5861
- }
5862
- )
5925
+ onArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
5926
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
5927
+ "button",
5928
+ {
5929
+ onClick: (e) => e.stopPropagation(),
5930
+ "aria-label": t2("crm.quotes.moreActions"),
5931
+ className: "inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",
5932
+ children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-3.5 w-3.5" })
5933
+ }
5934
+ ) }),
5935
+ /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => onArchive(row.original.id), children: [
5936
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
5937
+ " ",
5938
+ t2("crm.quotes.archive")
5939
+ ] }) })
5940
+ ] })
5863
5941
  ] })
5864
5942
  });
5865
5943
  }
@@ -5876,9 +5954,8 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
5876
5954
  useEffect(() => {
5877
5955
  fetchQuotes({});
5878
5956
  }, []);
5879
- const columns = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
5880
- void archiveQuote(id);
5881
- } : void 0);
5957
+ const [alvoArquivo, setAlvoArquivo] = useState(null);
5958
+ const columns = useQuoteColumns(currency, onEditQuote, canArchive ? setAlvoArquivo : void 0);
5882
5959
  const exportRows = useCallback(() => {
5883
5960
  exportCSV(
5884
5961
  [
@@ -5933,6 +6010,21 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
5933
6010
  )
5934
6011
  ] })
5935
6012
  }
6013
+ ),
6014
+ /* @__PURE__ */ jsx(
6015
+ ConfirmDialog,
6016
+ {
6017
+ open: alvoArquivo !== null,
6018
+ onCancel: () => setAlvoArquivo(null),
6019
+ variant: "destructive",
6020
+ title: t2("crm.quotes.archiveTitle"),
6021
+ description: t2("crm.quotes.archiveDescription"),
6022
+ confirmLabel: t2("crm.quotes.archive"),
6023
+ onConfirm: async () => {
6024
+ if (alvoArquivo) await archiveQuote(alvoArquivo);
6025
+ setAlvoArquivo(null);
6026
+ }
6027
+ }
5936
6028
  )
5937
6029
  ] });
5938
6030
  }
@@ -7049,7 +7141,9 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7049
7141
  const archiveLead = useCrmStore((s) => s.archiveLead);
7050
7142
  const canArchive = useCanArchive();
7051
7143
  const [archiving, setArchiving] = useState(false);
7144
+ const [confirmandoArquivo, setConfirmandoArquivo] = useState(false);
7052
7145
  const [lead, setLead] = useState(null);
7146
+ const [recarga, setRecarga] = useState(0);
7053
7147
  useRecordVisit(lead ? {
7054
7148
  id: lead.id,
7055
7149
  kind: "lead",
@@ -7093,7 +7187,7 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7093
7187
  }
7094
7188
  setLoading(false);
7095
7189
  });
7096
- }, [leadId]);
7190
+ }, [leadId, recarga]);
7097
7191
  if (loading) {
7098
7192
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
7099
7193
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leadDetail.loading"), parentLabel: t2("crm.leads.title"), onBack }),
@@ -7152,23 +7246,22 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7152
7246
  }
7153
7247
  ),
7154
7248
  /* @__PURE__ */ jsx(TalkToPerson, { personId: leadId, name: lead.name, phone: lead.phone }),
7155
- canArchive && /* @__PURE__ */ jsxs(
7156
- "button",
7157
- {
7158
- onClick: () => {
7159
- setArchiving(true);
7160
- archiveLead(leadId).then(onBack).catch(() => setArchiving(false));
7161
- },
7162
- disabled: archiving,
7163
- title: t2("crm.leadDetail.archive"),
7164
- className: "inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted hover:text-foreground bg-card shadow-button active:shadow-button-inset transition-colors disabled:opacity-60",
7165
- children: [
7166
- /* @__PURE__ */ jsx(Archive, { className: "h-3 w-3" }),
7167
- " ",
7168
- t2("crm.leadDetail.archive")
7169
- ]
7170
- }
7171
- ),
7249
+ canArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
7250
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
7251
+ "button",
7252
+ {
7253
+ "aria-label": t2("crm.leadDetail.moreActions"),
7254
+ disabled: archiving,
7255
+ className: "inline-flex h-[30px] w-[30px] items-center justify-center rounded-lg border bg-card text-muted-foreground shadow-button transition-colors hover:bg-muted hover:text-foreground disabled:opacity-60",
7256
+ children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" })
7257
+ }
7258
+ ) }),
7259
+ /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setConfirmandoArquivo(true), children: [
7260
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
7261
+ " ",
7262
+ t2("crm.leadDetail.archive")
7263
+ ] }) })
7264
+ ] }),
7172
7265
  onCreateQuote && lead.status !== "converted" && lead.status !== "lost" && /* @__PURE__ */ jsxs(
7173
7266
  "button",
7174
7267
  {
@@ -7215,12 +7308,21 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7215
7308
  ] })
7216
7309
  ]
7217
7310
  }
7218
- ) : (
7311
+ ) : lead.company ? (
7219
7312
  /* Sem vínculo ainda: mostra o texto livre que veio da
7220
- importação. Trocar um pelo outro apagaria a única coisa
7221
- que 297 leads importados têm. */
7222
- lead.company
7223
- )
7313
+ importação — e OFERECE transformá-lo em cadastro. Trocar
7314
+ um pelo outro apagaria a única coisa que 297 leads
7315
+ importados têm; deixá-lo como texto morto era o que fazia
7316
+ o card do funil cair no nome da pessoa. */
7317
+ /* @__PURE__ */ jsx(
7318
+ LinkCompanyPrompt,
7319
+ {
7320
+ personId: leadId,
7321
+ companyText: lead.company,
7322
+ onLinked: () => setRecarga((n) => n + 1)
7323
+ }
7324
+ )
7325
+ ) : null
7224
7326
  }
7225
7327
  ) }),
7226
7328
  lead.credentialCompany && lead.credentialCompany.trim().toLowerCase() !== (lead.companyName ?? "").trim().toLowerCase() && /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
@@ -7380,7 +7482,28 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
7380
7482
  lead.notes && /* @__PURE__ */ jsxs("div", { children: [
7381
7483
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.notes") }),
7382
7484
  /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm px-5 py-4", children: /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground whitespace-pre-wrap", children: lead.notes }) })
7383
- ] })
7485
+ ] }),
7486
+ /* @__PURE__ */ jsx(
7487
+ ConfirmDialog,
7488
+ {
7489
+ open: confirmandoArquivo,
7490
+ onCancel: () => setConfirmandoArquivo(false),
7491
+ variant: "destructive",
7492
+ title: t2("crm.leadDetail.archiveTitle"),
7493
+ description: t2("crm.leadDetail.archiveDescription"),
7494
+ confirmLabel: t2("crm.leadDetail.archive"),
7495
+ onConfirm: async () => {
7496
+ setArchiving(true);
7497
+ try {
7498
+ await archiveLead(leadId);
7499
+ setConfirmandoArquivo(false);
7500
+ onBack?.();
7501
+ } catch {
7502
+ setArchiving(false);
7503
+ }
7504
+ }
7505
+ }
7506
+ )
7384
7507
  ] });
7385
7508
  }
7386
7509
  var buildColumns2 = (t2) => [
@@ -8022,6 +8145,11 @@ function CompanyDetailView({
8022
8145
  const [unlinkTarget, setUnlinkTarget] = useState(null);
8023
8146
  const [archiving, setArchiving] = useState(false);
8024
8147
  const [linking, setLinking] = useState(false);
8148
+ const negocioDoFunil = useMemo(() => {
8149
+ const abertos = deals.filter((d) => d.status === "open");
8150
+ if (abertos.length === 0) return null;
8151
+ return abertos.reduce((a, b) => (b.updatedAt ?? b.createdAt ?? "") > (a.updatedAt ?? a.createdAt ?? "") ? b : a);
8152
+ }, [deals]);
8025
8153
  const load = useCallback(async () => {
8026
8154
  setLoading(true);
8027
8155
  try {
@@ -8063,26 +8191,42 @@ function CompanyDetailView({
8063
8191
  /* @__PURE__ */ jsx("h2", { className: "text-lg font-semibold text-foreground", children: company.name }),
8064
8192
  company.legalName && company.legalName !== company.name && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: company.legalName })
8065
8193
  ] }),
8066
- /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
8067
- /* @__PURE__ */ jsx(
8194
+ /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2", children: [
8195
+ negocioDoFunil && onOpenDeal && /* @__PURE__ */ jsxs(
8068
8196
  "button",
8069
8197
  {
8070
- onClick: () => onEdit?.(company.id),
8071
- className: "rounded-button border bg-card px-3 py-1.5 text-xs font-medium shadow-button hover:bg-muted",
8072
- children: t2("common.edit")
8198
+ onClick: () => onOpenDeal(negocioDoFunil.id),
8199
+ className: "inline-flex items-center gap-1.5 rounded-button bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-button transition-opacity hover:opacity-90",
8200
+ children: [
8201
+ /* @__PURE__ */ jsx(Filter, { className: "h-3 w-3" }),
8202
+ " ",
8203
+ t2("crm.companyDetail.openInPipeline")
8204
+ ]
8073
8205
  }
8074
8206
  ),
8075
- canArchive && /* @__PURE__ */ jsxs(
8207
+ /* @__PURE__ */ jsx(
8076
8208
  "button",
8077
8209
  {
8078
- onClick: () => setArchiving(true),
8210
+ onClick: () => onEdit?.(company.id),
8079
8211
  className: "rounded-button border bg-card px-3 py-1.5 text-xs font-medium shadow-button hover:bg-muted",
8080
- children: [
8081
- /* @__PURE__ */ jsx(Archive, { className: "inline h-3 w-3 mr-1" }),
8082
- t2("crm.companies.archive")
8083
- ]
8212
+ children: t2("common.edit")
8084
8213
  }
8085
- )
8214
+ ),
8215
+ canArchive && /* @__PURE__ */ jsxs(Dropdown, { children: [
8216
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
8217
+ "button",
8218
+ {
8219
+ "aria-label": t2("crm.companyDetail.moreActions"),
8220
+ className: "inline-flex h-[30px] w-[30px] items-center justify-center rounded-button border bg-card text-muted-foreground shadow-button transition-colors hover:bg-muted hover:text-foreground",
8221
+ children: /* @__PURE__ */ jsx(MoreHorizontal, { className: "h-4 w-4" })
8222
+ }
8223
+ ) }),
8224
+ /* @__PURE__ */ jsx(DropdownContent, { align: "end", children: /* @__PURE__ */ jsxs(DropdownItem, { onSelect: () => setArchiving(true), children: [
8225
+ /* @__PURE__ */ jsx(Archive, { className: "h-3.5 w-3.5" }),
8226
+ " ",
8227
+ t2("crm.companies.archive")
8228
+ ] }) })
8229
+ ] })
8086
8230
  ] })
8087
8231
  ] }),
8088
8232
  /* @__PURE__ */ jsxs("div", { children: [
@@ -28624,6 +28768,83 @@ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
28624
28768
  GRANT SELECT ON public.v_deals TO authenticated;
28625
28769
  GRANT SELECT ON public.v_deals TO service_role;
28626
28770
  `;
28771
+ var MIGRATION_059_A_EMPRESA_MOSTRA_O_INSTAGRAM_QUE_ELA_GUARDA = `-- 059 \u2014 The company screen shows the Instagram it already stores.
28772
+ --
28773
+ -- \`plg_crm_companies.instagram\` is written by the edit form, and the plugin
28774
+ -- ships \`instagramUrl\`/\`normalizeInstagram\` to render it \u2014 but the read model
28775
+ -- never carried it, so every screen painted a dash beside a filled column.
28776
+ -- Measured on 2026-09-28 with VILA PAULIST\xC2NIA: \`instagram = 'vilapaulistania'\`
28777
+ -- in the table, "\u2014" on the screen. Write-only data.
28778
+ --
28779
+ -- \u2500\u2500 Why a NEW NAME and not a wider \`v_crm_companies\` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
28780
+ --
28781
+ -- Because the chain is replayed, and 013 owns that name.
28782
+ --
28783
+ -- Widening it with CREATE OR REPLACE applies fine ONCE. On the second pass of
28784
+ -- the chain, 013 runs again \u2014 before this file \u2014 and recreates the view from
28785
+ -- its own narrower column list, over a view that is now wider. Postgres refuses
28786
+ -- outright: \xABcannot drop columns from view\xBB. The bench caught exactly that, and
28787
+ -- no amount of dropping HERE fixes it, because 013 runs first.
28788
+ --
28789
+ -- Editing 013 is not the answer either: it is applied, its checksum is in
28790
+ -- \`public._migrations\`, and the ledger treats a changed checksum as a hard stop.
28791
+ --
28792
+ -- So the enriched read model gets its own name and 013 keeps owning its own,
28793
+ -- untouched and replay-safe. This is the same move the inventory chain already
28794
+ -- made for \`v_inventory_consumption_audit\`, and for the same reason.
28795
+ --
28796
+ -- \`v_crm_companies\` is left in place: it costs nothing, and anything still
28797
+ -- pointing at it keeps working rather than breaking on deploy order.
28798
+
28799
+ CREATE OR REPLACE VIEW public.v_crm_companies_enriched WITH (security_invoker = true) AS
28800
+ SELECT c.id,
28801
+ c.tenant_id,
28802
+ c.name,
28803
+ c.legal_name,
28804
+ c.document_number,
28805
+ c.document_kind,
28806
+ c.document_root,
28807
+ c.document_valid,
28808
+ c.email,
28809
+ c.phone,
28810
+ c.website,
28811
+ c.address,
28812
+ c.city,
28813
+ c.state,
28814
+ c.country,
28815
+ c.postal_code,
28816
+ c.tags,
28817
+ c.notes,
28818
+ c.metadata,
28819
+ c.custom_fields,
28820
+ c.owner_id,
28821
+ c.is_active,
28822
+ c.created_at,
28823
+ c.updated_at,
28824
+ COALESCE(p.people_count, 0) AS people_count,
28825
+ COALESCE(d.open_deals, 0) AS open_deals,
28826
+ COALESCE(d.won_value, 0::numeric) AS won_value,
28827
+ CASE
28828
+ WHEN c.document_root IS NULL THEN 0
28829
+ ELSE COALESCE(g.group_size, 1) - 1
28830
+ END AS group_siblings,
28831
+ c.instagram
28832
+ FROM plg_crm_companies c
28833
+ LEFT JOIN LATERAL ( SELECT count(*)::integer AS people_count
28834
+ FROM plg_crm_company_people cp
28835
+ JOIN people pe ON pe.id = cp.person_id
28836
+ WHERE cp.company_id = c.id) p ON true
28837
+ LEFT JOIN LATERAL ( SELECT count(*) FILTER (WHERE dl.status = 'open'::text)::integer AS open_deals,
28838
+ COALESCE(sum(dl.value) FILTER (WHERE dl.status = 'won'::text), 0::numeric) AS won_value
28839
+ FROM plg_crm_deals dl
28840
+ WHERE dl.company_id = c.id) d ON true
28841
+ LEFT JOIN LATERAL ( SELECT count(*)::integer AS group_size
28842
+ FROM plg_crm_companies s
28843
+ WHERE s.tenant_id = c.tenant_id AND s.document_root = c.document_root) g ON true;
28844
+
28845
+ GRANT SELECT ON public.v_crm_companies_enriched TO authenticated;
28846
+ GRANT SELECT ON public.v_crm_companies_enriched TO service_role;
28847
+ `;
28627
28848
  var MIGRATIONS = [
28628
28849
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
28629
28850
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -28682,7 +28903,8 @@ var MIGRATIONS = [
28682
28903
  { id: "055_a_cesta_do_interesse_tem_onde_morar", sql: MIGRATION_055_A_CESTA_DO_INTERESSE_TEM_ONDE_MORAR },
28683
28904
  { id: "056_o_interesse_entra_pelo_agendamento", sql: MIGRATION_056_O_INTERESSE_ENTRA_PELO_AGENDAMENTO },
28684
28905
  { id: "057_o_negocio_e_do_grupo_nao_do_cnpj", sql: MIGRATION_057_O_NEGOCIO_E_DO_GRUPO_NAO_DO_CNPJ },
28685
- { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO }
28906
+ { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO },
28907
+ { id: "059_a_empresa_mostra_o_instagram_que_ela_guarda", sql: MIGRATION_059_A_EMPRESA_MOSTRA_O_INSTAGRAM_QUE_ELA_GUARDA }
28686
28908
  ];
28687
28909
 
28688
28910
  // src/locales/en.ts
@@ -28751,6 +28973,9 @@ var en = {
28751
28973
  "crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
28752
28974
  "crm.leadDetail.assignedTo": "Assigned to",
28753
28975
  "crm.leadDetail.archive": "Archive",
28976
+ "crm.leadDetail.archiveTitle": "Archive this lead?",
28977
+ "crm.leadDetail.archiveDescription": "It leaves the lists and the pipeline, and its history is kept. The deal linked to it is not archived with it.",
28978
+ "crm.leadDetail.moreActions": "More actions",
28754
28979
  "crm.leadDetail.backToList": "Back to list",
28755
28980
  "crm.leadDetail.formAnswers": "Form answers",
28756
28981
  "crm.leadDetail.attachments": "Attachments",
@@ -29004,6 +29229,12 @@ var en = {
29004
29229
  "crm.deals.allCampaigns": "All campaigns",
29005
29230
  "crm.deals.allCities": "All cities",
29006
29231
  "crm.card.companyTitle": "Company",
29232
+ "crm.linkCompany.hintNew": "Written on the record, but not a company here yet",
29233
+ "crm.linkCompany.hintExisting": "This company already exists \u2014 this person is not linked to it",
29234
+ "crm.linkCompany.create": "Create",
29235
+ "crm.linkCompany.link": "Link",
29236
+ "crm.linkCompany.done": "{{name}} linked",
29237
+ "crm.linkCompany.failed": "Could not link the company",
29007
29238
  "crm.card.groupTitle": "Economic group",
29008
29239
  "crm.card.groupCompanies": "{{count}} companies",
29009
29240
  "crm.card.takeOver": "Take this lead",
@@ -29097,6 +29328,9 @@ var en = {
29097
29328
  "crm.quoteForm.validUntil": "Valid Until",
29098
29329
  "crm.quotes.amount": "Amount",
29099
29330
  "crm.quotes.archive": "Archive",
29331
+ "crm.quotes.archiveTitle": "Archive this quote?",
29332
+ "crm.quotes.archiveDescription": "It leaves the list and its history is kept. The deal and the lead linked to it do not change.",
29333
+ "crm.quotes.moreActions": "More actions",
29100
29334
  "crm.quotes.contact": "Contact",
29101
29335
  "crm.quotes.createFirst": "Create your first quote",
29102
29336
  "crm.quotes.date": "Date",
@@ -29192,6 +29426,8 @@ var en = {
29192
29426
  "crm.companies.noCompanies": "No companies yet",
29193
29427
  "crm.companies.createFirst": "Add the first one",
29194
29428
  "crm.companies.archive": "Archive",
29429
+ "crm.companyDetail.openInPipeline": "View in pipeline",
29430
+ "crm.companyDetail.moreActions": "More actions",
29195
29431
  "crm.companies.archiveTitle": "Archive company?",
29196
29432
  "crm.companies.archiveDescription": "It leaves the list and keeps its history. Deals already stamped with it are untouched.",
29197
29433
  "crm.companyDetail.link": "Link contact",
@@ -29596,6 +29832,9 @@ var ptBR = {
29596
29832
  "crm.dealSidebar.viewLeadProfile": "Ver Perfil Completo do Lead",
29597
29833
  "crm.leadDetail.assignedTo": "Atribu\xEDdo a",
29598
29834
  "crm.leadDetail.archive": "Arquivar",
29835
+ "crm.leadDetail.archiveTitle": "Arquivar este lead?",
29836
+ "crm.leadDetail.archiveDescription": "Sai das listas e do funil, e o hist\xF3rico fica guardado. O neg\xF3cio ligado a ele n\xE3o \xE9 arquivado junto.",
29837
+ "crm.leadDetail.moreActions": "Mais a\xE7\xF5es",
29599
29838
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
29600
29839
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
29601
29840
  "crm.leadDetail.attachments": "Anexos",
@@ -29849,6 +30088,12 @@ var ptBR = {
29849
30088
  "crm.deals.allCampaigns": "Todas as campanhas",
29850
30089
  "crm.deals.allCities": "Todas as cidades",
29851
30090
  "crm.card.companyTitle": "Empresa",
30091
+ "crm.linkCompany.hintNew": "Escrito no cadastro, mas ainda n\xE3o \xE9 uma empresa aqui",
30092
+ "crm.linkCompany.hintExisting": "Esta empresa j\xE1 existe \u2014 falta ligar esta pessoa a ela",
30093
+ "crm.linkCompany.create": "Cadastrar",
30094
+ "crm.linkCompany.link": "Vincular",
30095
+ "crm.linkCompany.done": "{{name}} vinculada",
30096
+ "crm.linkCompany.failed": "N\xE3o deu para vincular a empresa",
29852
30097
  "crm.card.groupTitle": "Grupo econ\xF4mico",
29853
30098
  "crm.card.groupCompanies": "{{count}} CNPJs",
29854
30099
  "crm.card.takeOver": "Assumir este lead",
@@ -29942,6 +30187,9 @@ var ptBR = {
29942
30187
  "crm.quoteForm.validUntil": "V\xE1lido At\xE9",
29943
30188
  "crm.quotes.amount": "Valor",
29944
30189
  "crm.quotes.archive": "Arquivar",
30190
+ "crm.quotes.archiveTitle": "Arquivar este or\xE7amento?",
30191
+ "crm.quotes.archiveDescription": "Sai da lista e o hist\xF3rico fica guardado. O neg\xF3cio e o lead ligados a ele n\xE3o mudam.",
30192
+ "crm.quotes.moreActions": "Mais a\xE7\xF5es",
29945
30193
  "crm.quotes.contact": "Contato",
29946
30194
  "crm.quotes.createFirst": "Crie seu primeiro or\xE7amento",
29947
30195
  "crm.quotes.date": "Data",
@@ -30037,6 +30285,8 @@ var ptBR = {
30037
30285
  "crm.companies.noCompanies": "Nenhuma empresa ainda",
30038
30286
  "crm.companies.createFirst": "Cadastrar a primeira",
30039
30287
  "crm.companies.archive": "Arquivar",
30288
+ "crm.companyDetail.openInPipeline": "Ver no funil",
30289
+ "crm.companyDetail.moreActions": "Mais a\xE7\xF5es",
30040
30290
  "crm.companies.archiveTitle": "Arquivar empresa?",
30041
30291
  "crm.companies.archiveDescription": "Sai da lista e mant\xE9m o hist\xF3rico. Neg\xF3cios j\xE1 carimbados com ela n\xE3o mudam.",
30042
30292
  "crm.companyDetail.link": "Vincular contato",