@fayz-ai/plugin-crm 0.23.0 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import React, { useState, useEffect, useMemo, useCallback, useRef } from 'react';
2
2
  import { tl, useTranslation, getSupabaseClientOptional, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
- import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
3
+ import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
4
4
  import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, User, Building2, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, CalendarDays, Clipboard, DollarSign, ThumbsUp } from 'lucide-react';
5
5
  import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, SegmentedControl, PageHeaderActions, FilterChip, MultiSelect, ListView, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, CurrencyInput, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -1501,13 +1501,13 @@ function DealListView({ onOpenDeal }) {
1501
1501
  const stages = useCrmStore((s) => s.stages);
1502
1502
  const tagDefs = useCrmStore((s) => s.tagDefs);
1503
1503
  const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
1504
- const [search, setSearch] = useState("");
1504
+ const [search, setSearch] = usePersistedState("crm.deals.search", "");
1505
1505
  const [stage, setStage] = useState();
1506
1506
  const [status, setStatus] = useState();
1507
1507
  const [cohort, setCohort] = useState();
1508
1508
  const [city, setCity] = useState();
1509
1509
  const [companyName, setCompanyName] = useState();
1510
- const [page, setPage] = useState(1);
1510
+ const [page, setPage] = usePersistedState("crm.deals.page", 1);
1511
1511
  const [segmentOpen, setSegmentOpen] = useState(false);
1512
1512
  const [tag, setTag] = useState();
1513
1513
  useEffect(() => {
@@ -1659,7 +1659,8 @@ function DealListView({ onOpenDeal }) {
1659
1659
  cohort && t2("crm.deals.cohort"),
1660
1660
  companyName && t2("crm.card.companyTitle")
1661
1661
  ].filter(Boolean);
1662
- return /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
1662
+ const ancoraRolagem = useScrollMemory("crm.deals");
1663
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-3", children: [
1663
1664
  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center justify-between gap-2", children: [
1664
1665
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.deals.summary", { count: String(rows.length), value: formatCurrency(total, currency) }) }),
1665
1666
  /* @__PURE__ */ jsx(
@@ -3909,15 +3910,15 @@ function LeadListView({ onNew, onEdit }) {
3909
3910
  const fetchLeads = useCrmStore((s) => s.fetchLeads);
3910
3911
  const updateLead = useCrmStore((s) => s.updateLead);
3911
3912
  const refreshLeads = useCrmStore((s) => s.refreshLeads);
3912
- const [search, setSearch] = useState("");
3913
- const [statusFilter, setStatusFilter] = useState([]);
3914
- const [sourceFilter, setSourceFilter] = useState();
3915
- const [tagFilter, setTagFilter] = useState([]);
3913
+ const [search, setSearch] = usePersistedState("crm.leads.search", "");
3914
+ const [statusFilter, setStatusFilter] = usePersistedState("crm.leads.status", []);
3915
+ const [sourceFilter, setSourceFilter] = usePersistedState("crm.leads.source", void 0);
3916
+ const [tagFilter, setTagFilter] = usePersistedState("crm.leads.tags", []);
3916
3917
  const [team, setTeam] = useState(null);
3917
3918
  const [myUserId, setMyUserId] = useState(null);
3918
- const [ownerFilter, setOwnerFilter] = useState();
3919
- const [reachFilter, setReachFilter] = useState();
3920
- const [companyFilter, setCompanyFilter] = useState();
3919
+ const [ownerFilter, setOwnerFilter] = usePersistedState("crm.leads.owner", void 0);
3920
+ const [reachFilter, setReachFilter] = usePersistedState("crm.leads.reach", void 0);
3921
+ const [companyFilter, setCompanyFilter] = usePersistedState("crm.leads.company", void 0);
3921
3922
  const leadSources = useCrmStore((s) => s.leadSources);
3922
3923
  const fetchLeadSources = useCrmStore((s) => s.fetchLeadSources);
3923
3924
  const tagDefs = useCrmStore((s) => s.tagDefs);
@@ -3928,7 +3929,7 @@ function LeadListView({ onNew, onEdit }) {
3928
3929
  }, []);
3929
3930
  const [archiveTarget, setArchiveTarget] = useState(null);
3930
3931
  const [bulkBusy, setBulkBusy] = useState(false);
3931
- const [page, setPage] = useState(1);
3932
+ const [page, setPage] = usePersistedState("crm.leads.page", 1);
3932
3933
  const PAGE_SIZE2 = 50;
3933
3934
  const [scores, setScores] = useState(/* @__PURE__ */ new Map());
3934
3935
  useEffect(() => {
@@ -4218,7 +4219,8 @@ function LeadListView({ onNew, onEdit }) {
4218
4219
  }
4219
4220
  )
4220
4221
  ] });
4221
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4222
+ const ancoraRolagem = useScrollMemory("crm.leads");
4223
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
4222
4224
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
4223
4225
  /* @__PURE__ */ jsx(
4224
4226
  ListView,
@@ -4284,6 +4286,20 @@ function LeadListView({ onNew, onEdit }) {
4284
4286
  )
4285
4287
  ] });
4286
4288
  }
4289
+
4290
+ // src/lib/instagram.ts
4291
+ function normalizeInstagram(raw) {
4292
+ const v = String(raw ?? "").trim();
4293
+ if (!v) return void 0;
4294
+ const url = v.match(/(?:https?:\/\/)?(?:www\.)?instagram\.com\/([^/?#\s]+)/i);
4295
+ const handle = (url ? url[1] : v).replace(/^@+/, "").replace(/\/+$/, "").trim();
4296
+ return /^[A-Za-z0-9._]{1,30}$/.test(handle) ? handle : v;
4297
+ }
4298
+ function instagramUrl(handle) {
4299
+ const h = normalizeInstagram(handle);
4300
+ if (!h || !/^[A-Za-z0-9._]{1,30}$/.test(h)) return void 0;
4301
+ return `https://instagram.com/${h}`;
4302
+ }
4287
4303
  function LeadFormView({ onSaved }) {
4288
4304
  const t2 = useTranslation();
4289
4305
  const createLead = useCrmStore((s) => s.createLead);
@@ -4294,6 +4310,7 @@ function LeadFormView({ onSaved }) {
4294
4310
  const [name, setName] = useState("");
4295
4311
  const [email, setEmail] = useState("");
4296
4312
  const [phone, setPhone] = useState("");
4313
+ const [instagram, setInstagram] = useState("");
4297
4314
  const [company, setCompany] = useState("");
4298
4315
  const [notes, setNotes] = useState("");
4299
4316
  const [sourceId, setSourceId] = useState("");
@@ -4328,6 +4345,9 @@ function LeadFormView({ onSaved }) {
4328
4345
  name,
4329
4346
  email: email || void 0,
4330
4347
  phone: phone || void 0,
4348
+ // Normaliza na ESCRITA: `@casa`, `casa` e a URL inteira viram o mesmo
4349
+ // handle, senão a mesma casa aparece como quatro contatos ao cruzar.
4350
+ instagram: normalizeInstagram(instagram),
4331
4351
  company: company || void 0,
4332
4352
  notes: notes || void 0,
4333
4353
  sourceId: source?.id,
@@ -4368,6 +4388,10 @@ function LeadFormView({ onSaved }) {
4368
4388
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.phone") }),
4369
4389
  /* @__PURE__ */ jsx(Input, { type: "tel", className: "mt-1", value: phone, onChange: (e) => setPhone(e.target.value), placeholder: t2("crm.leadForm.phonePlaceholder") })
4370
4390
  ] }),
4391
+ /* @__PURE__ */ jsxs("div", { children: [
4392
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.instagram") }),
4393
+ /* @__PURE__ */ jsx(Input, { className: "mt-1", value: instagram, onChange: (e) => setInstagram(e.target.value), placeholder: t2("crm.leadForm.instagramPlaceholder") })
4394
+ ] }),
4371
4395
  /* @__PURE__ */ jsxs("div", { children: [
4372
4396
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
4373
4397
  /* @__PURE__ */ jsx("textarea", { value: notes, onChange: (e) => setNotes(e.target.value), rows: 2, placeholder: t2("crm.leadForm.notesPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" })
@@ -4492,7 +4516,8 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
4492
4516
  );
4493
4517
  toast.success(t2("crud.export.toastSuccess", { count: String(quotes2.length) }));
4494
4518
  }, [quotes2, currency, t2]);
4495
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4519
+ const ancoraRolagem = useScrollMemory("crm.quotes");
4520
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
4496
4521
  /* @__PURE__ */ jsx(
4497
4522
  SubpageHeader,
4498
4523
  {
@@ -5511,6 +5536,15 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5511
5536
  const canArchive = useCanArchive();
5512
5537
  const [archiving, setArchiving] = useState(false);
5513
5538
  const [lead, setLead] = useState(null);
5539
+ useRecordVisit(lead ? {
5540
+ id: lead.id,
5541
+ kind: "lead",
5542
+ kindLabel: t2("crm.leads.title"),
5543
+ label: lead.name,
5544
+ subtitle: lead.company || lead.email || void 0,
5545
+ archetype: "person",
5546
+ archetypeKind: "lead"
5547
+ } : null);
5514
5548
  const [deal, setDeal] = useState(null);
5515
5549
  const [quotes2, setQuotes] = useState([]);
5516
5550
  const [loading, setLoading] = useState(true);
@@ -5615,7 +5649,10 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5615
5649
  FieldRow,
5616
5650
  {
5617
5651
  label: t2("crm.leadDetail.phone"),
5618
- value: lead.phone ? /* @__PURE__ */ jsx(PhoneLink, { phone: lead.phone, className: "text-primary" }) : null
5652
+ value: lead.phone ? /* @__PURE__ */ jsx(PhoneLink, { phone: lead.phone, className: "text-primary" }) : lead.phoneRaw ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
5653
+ /* @__PURE__ */ jsx("span", { className: "tabular-nums", children: lead.phoneRaw }),
5654
+ /* @__PURE__ */ jsx("span", { className: "rounded-full bg-warning/10 px-1.5 py-0.5 text-[10px] font-medium text-warning", children: t2("crm.leadDetail.phoneUnverified") })
5655
+ ] }) : null
5619
5656
  }
5620
5657
  ) }),
5621
5658
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
@@ -5643,6 +5680,32 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5643
5680
  )
5644
5681
  }
5645
5682
  ) }),
5683
+ 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(
5684
+ FieldRow,
5685
+ {
5686
+ label: t2("crm.leadDetail.credentialCompany"),
5687
+ value: /* @__PURE__ */ jsx("span", { children: lead.credentialCompany })
5688
+ }
5689
+ ) }),
5690
+ /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
5691
+ FieldRow,
5692
+ {
5693
+ label: t2("crm.leadDetail.instagram"),
5694
+ value: lead.instagram ? instagramUrl(lead.instagram) ? /* @__PURE__ */ jsxs(
5695
+ "a",
5696
+ {
5697
+ href: instagramUrl(lead.instagram),
5698
+ target: "_blank",
5699
+ rel: "noreferrer",
5700
+ className: "text-primary hover:underline",
5701
+ children: [
5702
+ "@",
5703
+ normalizeInstagram(lead.instagram)
5704
+ ]
5705
+ }
5706
+ ) : /* @__PURE__ */ jsx("span", { children: lead.instagram }) : null
5707
+ }
5708
+ ) }),
5646
5709
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.source"), value: lead.sourceName }) })
5647
5710
  ] }) })
5648
5711
  ] }),
@@ -5817,7 +5880,7 @@ function CompanyListView({ onNew, onEdit }) {
5817
5880
  const companiesLoading = useCrmStore((s) => s.companiesLoading);
5818
5881
  const fetchCompanies = useCrmStore((s) => s.fetchCompanies);
5819
5882
  const archiveCompany = useCrmStore((s) => s.archiveCompany);
5820
- const [search, setSearch] = useState("");
5883
+ const [search, setSearch] = usePersistedState("crm.companies.search", "");
5821
5884
  const [archiveTarget, setArchiveTarget] = useState(null);
5822
5885
  const [bulkBusy, setBulkBusy] = useState(false);
5823
5886
  const columns = useMemo(() => buildColumns2(t2), [t2]);
@@ -5843,7 +5906,8 @@ function CompanyListView({ onNew, onEdit }) {
5843
5906
  { key: "state", label: t2("crm.companyForm.state") },
5844
5907
  { key: "peopleCount", label: t2("crm.companies.peopleCol") }
5845
5908
  ], companies, "empresas.csv");
5846
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
5909
+ const ancoraRolagem = useScrollMemory("crm.companies");
5910
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
5847
5911
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.companies.title") }),
5848
5912
  /* @__PURE__ */ jsx(
5849
5913
  ListView,
@@ -5901,6 +5965,7 @@ function CompanyFormView({ companyId, onSaved }) {
5901
5965
  const [email, setEmail] = useState("");
5902
5966
  const [phone, setPhone] = useState("");
5903
5967
  const [website, setWebsite] = useState("");
5968
+ const [instagram, setInstagram] = useState("");
5904
5969
  const [city, setCity] = useState("");
5905
5970
  const [state, setState] = useState("");
5906
5971
  const [notes, setNotes] = useState("");
@@ -5917,6 +5982,7 @@ function CompanyFormView({ companyId, onSaved }) {
5917
5982
  setEmail(c.email ?? "");
5918
5983
  setPhone(c.phone ?? "");
5919
5984
  setWebsite(c.website ?? "");
5985
+ setInstagram(c.instagram ?? "");
5920
5986
  setCity(c.city ?? "");
5921
5987
  setState(c.state ?? "");
5922
5988
  setNotes(c.notes ?? "");
@@ -5953,6 +6019,8 @@ function CompanyFormView({ companyId, onSaved }) {
5953
6019
  email: email.trim() || void 0,
5954
6020
  phone: phone.trim() || void 0,
5955
6021
  website: website.trim() || void 0,
6022
+ // Normaliza na escrita — ver lib/instagram.
6023
+ instagram: normalizeInstagram(instagram),
5956
6024
  city: city.trim() || void 0,
5957
6025
  state: state.trim() || void 0,
5958
6026
  notes: notes.trim() || void 0
@@ -6027,9 +6095,24 @@ function CompanyFormView({ companyId, onSaved }) {
6027
6095
  /* @__PURE__ */ jsx("input", { type: "tel", value: phone, onChange: (e) => setPhone(e.target.value), className: inputClass })
6028
6096
  ] })
6029
6097
  ] }),
6030
- /* @__PURE__ */ jsxs("div", { children: [
6031
- /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.website") }),
6032
- /* @__PURE__ */ jsx("input", { type: "text", value: website, onChange: (e) => setWebsite(e.target.value), className: inputClass })
6098
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-2 gap-3", children: [
6099
+ /* @__PURE__ */ jsxs("div", { children: [
6100
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.website") }),
6101
+ /* @__PURE__ */ jsx("input", { type: "text", value: website, onChange: (e) => setWebsite(e.target.value), className: inputClass })
6102
+ ] }),
6103
+ /* @__PURE__ */ jsxs("div", { children: [
6104
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.companyForm.instagram") }),
6105
+ /* @__PURE__ */ jsx(
6106
+ "input",
6107
+ {
6108
+ type: "text",
6109
+ value: instagram,
6110
+ onChange: (e) => setInstagram(e.target.value),
6111
+ placeholder: "@casa",
6112
+ className: inputClass
6113
+ }
6114
+ )
6115
+ ] })
6033
6116
  ] }),
6034
6117
  /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-3", children: [
6035
6118
  /* @__PURE__ */ jsxs("div", { className: "col-span-2", children: [
@@ -6227,7 +6310,8 @@ function CompanyDetailView({
6227
6310
  onBack,
6228
6311
  onEdit,
6229
6312
  onOpenLead,
6230
- onOpenCompany
6313
+ onOpenCompany,
6314
+ onOpenDeal
6231
6315
  }) {
6232
6316
  const t2 = useTranslation();
6233
6317
  const { currency } = useCrmConfig();
@@ -6236,6 +6320,16 @@ function CompanyDetailView({
6236
6320
  const archiveCompany = useCrmStore((s) => s.archiveCompany);
6237
6321
  const unlinkCompanyPerson = useCrmStore((s) => s.unlinkCompanyPerson);
6238
6322
  const [company, setCompany] = useState(null);
6323
+ useRecordVisit(company ? {
6324
+ id: company.id,
6325
+ kind: "company",
6326
+ kindLabel: t2("crm.companies.title"),
6327
+ label: company.name || company.legalName || "",
6328
+ // Só quando DIZ outra coisa. A razão social costuma ser igual ao nome
6329
+ // fantasia, e um subtítulo que repete o título é ruído.
6330
+ subtitle: company.legalName && company.legalName !== company.name ? company.legalName : void 0,
6331
+ archetype: "company"
6332
+ } : null);
6239
6333
  const [receita, setReceita] = useState(null);
6240
6334
  const [people, setPeople] = useState([]);
6241
6335
  const [deals, setDeals] = useState([]);
@@ -6251,11 +6345,11 @@ function CompanyDetailView({
6251
6345
  provider.getCompanyPeople(companyId),
6252
6346
  // Todos os negócios da casa, não só os abertos: o histórico é metade do
6253
6347
  // que faz uma ficha de empresa valer alguma coisa.
6254
- provider.getDeals({ pageSize: 200 })
6348
+ provider.getDeals({ companyId, pageSize: 200 })
6255
6349
  ]);
6256
6350
  setCompany(c);
6257
6351
  setPeople(p);
6258
- setDeals(d.data.filter((x) => x.companyId === companyId));
6352
+ setDeals(d.data);
6259
6353
  } finally {
6260
6354
  setLoading(false);
6261
6355
  }
@@ -6339,6 +6433,25 @@ function CompanyDetailView({
6339
6433
  label: t2("crm.companyDetail.location"),
6340
6434
  value: [company.city, company.state].filter(Boolean).join(" / ") || null
6341
6435
  }
6436
+ ) }),
6437
+ /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
6438
+ FieldRow2,
6439
+ {
6440
+ label: t2("crm.companyDetail.instagram"),
6441
+ value: company.instagram ? instagramUrl(company.instagram) ? /* @__PURE__ */ jsxs(
6442
+ "a",
6443
+ {
6444
+ href: instagramUrl(company.instagram),
6445
+ target: "_blank",
6446
+ rel: "noreferrer",
6447
+ className: "text-primary hover:underline",
6448
+ children: [
6449
+ "@",
6450
+ normalizeInstagram(company.instagram)
6451
+ ]
6452
+ }
6453
+ ) : /* @__PURE__ */ jsx("span", { children: company.instagram }) : null
6454
+ }
6342
6455
  ) })
6343
6456
  ] }) })
6344
6457
  ] }),
@@ -6439,17 +6552,30 @@ function CompanyDetailView({
6439
6552
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.companyDetail.deals") }),
6440
6553
  /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card shadow-sm divide-y", children: [
6441
6554
  deals.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-5 py-4 text-sm text-muted-foreground", children: t2("crm.companyDetail.noDeals") }),
6442
- deals.map((d) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 px-5 py-3", children: [
6443
- /* @__PURE__ */ jsxs("span", { className: "flex flex-col", children: [
6444
- /* @__PURE__ */ jsx("span", { className: "text-sm", children: d.title }),
6445
- /* @__PURE__ */ jsxs("span", { className: "text-[11px] text-muted-foreground", children: [
6446
- d.stageName,
6447
- " \xB7 ",
6448
- formatRelativeTime(d.createdAt)
6449
- ] })
6450
- ] }),
6451
- /* @__PURE__ */ jsx("span", { className: "text-sm tabular-nums", children: formatCurrency(d.value, currency) })
6452
- ] }, d.id))
6555
+ deals.map((d) => {
6556
+ const conteudo = /* @__PURE__ */ jsxs(Fragment, { children: [
6557
+ /* @__PURE__ */ jsxs("span", { className: "flex flex-col text-left", children: [
6558
+ /* @__PURE__ */ jsx("span", { className: "text-sm", children: d.title }),
6559
+ /* @__PURE__ */ jsxs("span", { className: "text-[11px] text-muted-foreground", children: [
6560
+ d.stageName,
6561
+ " \xB7 ",
6562
+ formatRelativeTime(d.createdAt)
6563
+ ] })
6564
+ ] }),
6565
+ /* @__PURE__ */ jsx("span", { className: "text-sm tabular-nums", children: formatCurrency(d.value, currency) })
6566
+ ] });
6567
+ const classe = "flex w-full items-center justify-between gap-3 px-5 py-3";
6568
+ return onOpenDeal ? /* @__PURE__ */ jsx(
6569
+ "button",
6570
+ {
6571
+ type: "button",
6572
+ onClick: () => onOpenDeal(d.id),
6573
+ className: `${classe} text-left transition-colors hover:bg-muted/40`,
6574
+ children: conteudo
6575
+ },
6576
+ d.id
6577
+ ) : /* @__PURE__ */ jsx("div", { className: classe, children: conteudo }, d.id);
6578
+ })
6453
6579
  ] })
6454
6580
  ] }),
6455
6581
  /* @__PURE__ */ jsx(
@@ -6759,7 +6885,7 @@ function ActivityListView({ onOpenLead, onOpenQuote, onOpenDeal } = {}) {
6759
6885
  const activities = useCrmStore((s) => s.activities);
6760
6886
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
6761
6887
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
6762
- const [typeFilter, setTypeFilter] = useState(null);
6888
+ const [typeFilter, setTypeFilter] = usePersistedState("crm.activities.type", null);
6763
6889
  const [showCompleted, setShowCompleted] = useState(null);
6764
6890
  const eventsFilter = typeFilter === "events";
6765
6891
  useEffect(() => {
@@ -6789,7 +6915,8 @@ function ActivityListView({ onOpenLead, onOpenQuote, onOpenDeal } = {}) {
6789
6915
  );
6790
6916
  toast.success(t2("crud.export.toastSuccess", { count: String(filtered.length) }));
6791
6917
  }, [filtered, t2]);
6792
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
6918
+ const ancoraRolagem = useScrollMemory("crm.activities");
6919
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
6793
6920
  /* @__PURE__ */ jsx(
6794
6921
  SubpageHeader,
6795
6922
  {
@@ -8318,7 +8445,8 @@ function CrmPage({ config, provider, store, registries }) {
8318
8445
  onBack: () => navigate("companies-list"),
8319
8446
  onEdit: (cid) => navigate(`companies-edit:${cid}`),
8320
8447
  onOpenLead: (lid) => navigate(`leads-detail:${lid}`),
8321
- onOpenCompany: (cid) => navigate(`companies-detail:${cid}`)
8448
+ onOpenCompany: (cid) => navigate(`companies-detail:${cid}`),
8449
+ onOpenDeal: (did) => navigate(`pipeline-detail:${did}`, `/sales/pipeline/${did}`)
8322
8450
  }
8323
8451
  ) },
8324
8452
  { id: "surveys", render: () => /* @__PURE__ */ jsx(SurveysView, {}) },
@@ -9119,6 +9247,9 @@ function createMockCrmProvider(options) {
9119
9247
  let results = [...store.deals];
9120
9248
  if (query.pipelineId) results = results.filter((d) => d.pipelineId === query.pipelineId);
9121
9249
  if (query.stageId) results = results.filter((d) => d.stageId === query.stageId);
9250
+ if (query.companyId) results = results.filter((d) => d.companyId === query.companyId);
9251
+ if (query.assignedToId === "none") results = results.filter((d) => !d.assignedToId);
9252
+ else if (query.assignedToId) results = results.filter((d) => d.assignedToId === query.assignedToId);
9122
9253
  if (query.status) {
9123
9254
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
9124
9255
  results = results.filter((d) => statuses.includes(d.status));
@@ -10160,6 +10291,7 @@ function toCompany(r) {
10160
10291
  email: r.email ?? void 0,
10161
10292
  phone: r.phone ?? void 0,
10162
10293
  website: r.website ?? void 0,
10294
+ instagram: r.instagram ?? void 0,
10163
10295
  address: r.address ?? void 0,
10164
10296
  city: r.city ?? void 0,
10165
10297
  state: r.state ?? void 0,
@@ -10314,6 +10446,21 @@ async function mergePersonMetadata(personId, patch) {
10314
10446
  const current = row?.metadata ?? {};
10315
10447
  await core.from("people").update({ metadata: { ...current, ...patch } }).eq("id", personId);
10316
10448
  }
10449
+ async function sincronizarDonoNaPessoa(dealId, userId) {
10450
+ try {
10451
+ const { pub, core } = getClients();
10452
+ const { data: negocio } = await pub.from(T.deals).select("lead_id, contact_id").eq("id", dealId).maybeSingle();
10453
+ const pessoaId = negocio?.lead_id ?? negocio?.contact_id;
10454
+ if (!pessoaId) return;
10455
+ const { data: pessoa } = await core.from("people").select("metadata").eq("id", pessoaId).maybeSingle();
10456
+ const metadata = { ...pessoa?.metadata ?? {} };
10457
+ if (userId) metadata.assignedToId = userId;
10458
+ else delete metadata.assignedToId;
10459
+ await core.from("people").update({ metadata }).eq("id", pessoaId);
10460
+ } catch (e) {
10461
+ console.error("[crm] o negocio mudou de dono, a pessoa nao:", e);
10462
+ }
10463
+ }
10317
10464
  function createSupabaseCrmProvider(options) {
10318
10465
  async function logEvent(input) {
10319
10466
  try {
@@ -10420,10 +10567,13 @@ function createSupabaseCrmProvider(options) {
10420
10567
  name: r.name,
10421
10568
  email: r.email,
10422
10569
  phone: r.phone,
10570
+ instagram: r.instagram ?? void 0,
10423
10571
  company: r.company,
10424
10572
  companyId: r.company_id ?? void 0,
10425
10573
  companyName: r.company_name ?? void 0,
10426
10574
  companyRole: r.company_role ?? void 0,
10575
+ credentialCompany: r.credential_company ?? void 0,
10576
+ phoneRaw: r.phone_raw ?? void 0,
10427
10577
  sourceId: r.source_id,
10428
10578
  sourceName: r.source_name,
10429
10579
  status: r.lead_status ?? "new",
@@ -10456,6 +10606,7 @@ function createSupabaseCrmProvider(options) {
10456
10606
  name: r.name,
10457
10607
  email: r.email,
10458
10608
  phone: r.phone,
10609
+ instagram: r.instagram ?? void 0,
10459
10610
  company: r.company,
10460
10611
  companyId: r.company_id ?? void 0,
10461
10612
  companyName: r.company_name ?? void 0,
@@ -10489,6 +10640,7 @@ function createSupabaseCrmProvider(options) {
10489
10640
  name: input.name,
10490
10641
  email: input.email,
10491
10642
  phone: input.phone,
10643
+ instagram: input.instagram || null,
10492
10644
  notes: input.notes,
10493
10645
  tags: input.tags ?? [],
10494
10646
  is_active: true,
@@ -10556,6 +10708,9 @@ function createSupabaseCrmProvider(options) {
10556
10708
  }
10557
10709
  if (query.pipelineId) qb = qb.eq("pipeline_id", query.pipelineId);
10558
10710
  if (query.stageId) qb = qb.eq("stage_id", query.stageId);
10711
+ if (query.companyId) qb = qb.eq("company_id", query.companyId);
10712
+ if (query.assignedToId === "none") qb = qb.is("assigned_to_id", null);
10713
+ else if (query.assignedToId) qb = qb.eq("assigned_to_id", query.assignedToId);
10559
10714
  const page = query.page ?? 1;
10560
10715
  const pageSize = query.pageSize ?? 50;
10561
10716
  qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
@@ -10672,6 +10827,9 @@ function createSupabaseCrmProvider(options) {
10672
10827
  const { error } = await pub.from(T.deals).update(row).eq("id", id);
10673
10828
  if (error) throw new Error(error.message);
10674
10829
  }
10830
+ if (partial.assignedToId !== void 0) {
10831
+ await sincronizarDonoNaPessoa(id, partial.assignedToId ?? null);
10832
+ }
10675
10833
  return await provider.getDealById(id);
10676
10834
  },
10677
10835
  async moveDealToStage(dealId, stageId) {
@@ -12032,9 +12190,17 @@ function createSupabaseCrmProvider(options) {
12032
12190
  const { pub } = getClients();
12033
12191
  const tenantId = getTenantId();
12034
12192
  if (!tenantId) throw new Error("no tenant");
12035
- const { data: group, error } = await pub.from(T.companyGroups).insert({ tenant_id: tenantId, name, document_root: documentRoot2 ?? null, is_active: true }).select("id").single();
12036
- if (error) throw new Error(error.message);
12037
- const { error: e2 } = await pub.from(T.companyGroupMembers).insert(
12193
+ let group = null;
12194
+ if (documentRoot2) {
12195
+ const { data: existente } = await pub.from(T.companyGroups).select("id").eq("tenant_id", tenantId).eq("document_root", documentRoot2).maybeSingle();
12196
+ if (existente) group = existente;
12197
+ }
12198
+ if (!group) {
12199
+ const { data: criado, error } = await pub.from(T.companyGroups).insert({ tenant_id: tenantId, name, document_root: documentRoot2 ?? null, is_active: true }).select("id").single();
12200
+ if (error) throw new Error(error.message);
12201
+ group = criado;
12202
+ }
12203
+ const { error: e2 } = await pub.from(T.companyGroupMembers).upsert(
12038
12204
  companyIds.map((cid) => ({
12039
12205
  tenant_id: tenantId,
12040
12206
  group_id: group.id,
@@ -12050,7 +12216,8 @@ function createSupabaseCrmProvider(options) {
12050
12216
  // `plg_crm_company_group_members_source_check` na cara de quem
12051
12217
  // clicava. O banco é quem define este vocabulário.
12052
12218
  source: documentRoot2 ? "document_root" : "manual"
12053
- }))
12219
+ })),
12220
+ { onConflict: "group_id,company_id", ignoreDuplicates: true }
12054
12221
  );
12055
12222
  if (e2) throw new Error(e2.message);
12056
12223
  return group.id;
@@ -25227,6 +25394,269 @@ CREATE OR REPLACE VIEW public.v_leads WITH (security_invoker = true) AS
25227
25394
  FROM plg_crm_deals d
25228
25395
  WHERE d.status = 'open'::text AND d.contact_id IS NOT NULL));
25229
25396
  `;
25397
+ var MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA = `-- ---------------------------------------------------------------------------
25398
+ -- 048_a_empresa_tambem_tem_um_arroba.sql
25399
+ --
25400
+ -- O par da 117 do lado da empresa. A pessoa ganhou \`instagram\` na espinha; a
25401
+ -- empresa ganha aqui, porque \`plg_crm_companies\` \xE9 tabela deste plugin.
25402
+ --
25403
+ -- E na empresa ele vale ainda mais do que na pessoa: num restaurante o perfil
25404
+ -- da CASA \xE9 o que tem os posts, o p\xFAblico e a prova de que ela existe \u2014 muitas
25405
+ -- vezes \xE9 a \xFAnica presen\xE7a digital que h\xE1. \`website\` est\xE1 vazio em quase toda
25406
+ -- a base da feira; o Instagram n\xE3o.
25407
+ --
25408
+ -- Mesmo racioc\xEDnio da 117 quanto \xE0 forma: texto simples, sem CHECK. Quem digita
25409
+ -- escreve \`@casa\`, \`casa\`, \`instagram.com/casa\`. Recusar tr\xEAs dessas formas faz
25410
+ -- o vendedor parar de preencher, que \xE9 o \xFAnico jeito de este campo falhar.
25411
+ -- ---------------------------------------------------------------------------
25412
+
25413
+ ALTER TABLE public.plg_crm_companies
25414
+ ADD COLUMN IF NOT EXISTS instagram text;
25415
+
25416
+ COMMENT ON COLUMN public.plg_crm_companies.instagram IS
25417
+ 'O @ da casa, preenchido \xE0 m\xE3o. Costuma ser a \xFAnica presen\xE7a digital que existe \u2014 \`website\` est\xE1 vazio em quase toda a base (048).';
25418
+ `;
25419
+ var MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA = `-- ---------------------------------------------------------------------------
25420
+ -- 049_o_arroba_chega_ate_a_lista.sql
25421
+ --
25422
+ -- A 117 criou \`people.instagram\` e a 048 o da empresa. A lista de leads n\xE3o l\xEA
25423
+ -- \`people\` \u2014 l\xEA \`v_crm_leads\` \u2014, e coluna nova numa tabela n\xE3o aparece sozinha
25424
+ -- numa view: ela tem de ser dita.
25425
+ --
25426
+ -- \u2500\u2500 e N\xC3O se diz na \`v_leads\` \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
25427
+ --
25428
+ -- A primeira vers\xE3o desta migration alargava \`v_leads\` e deixava \`v_crm_leads\`
25429
+ -- herdar por \`l.*\`. Parecia o caminho curto e quebrou o db-from-zero:
25430
+ --
25431
+ -- 023_o_contato_diz_de_que_empresa_ele_e.sql \u2026 FAILED
25432
+ -- ERROR: cannot drop columns from view
25433
+ --
25434
+ -- A 023 cria a \`v_leads\` com \`CREATE OR REPLACE\` e colunas NOMEADAS, sem DROP
25435
+ -- antes. No replay ela roda de novo \u2014 agora sobre a view j\xE1 alargada \u2014 e o
25436
+ -- Postgres recusa, porque a lista dela \xE9 menor. Ou seja: quem alarga a
25437
+ -- \`v_leads\` quebra a migration que a criou.
25438
+ --
25439
+ -- A \`v_crm_leads\` n\xE3o tem esse problema: a 013 a DERRUBA antes de criar. \xC9 por
25440
+ -- isso que o alargamento mora aqui, e a coluna vem da tabela e n\xE3o da view
25441
+ -- intermedi\xE1ria.
25442
+ --
25443
+ -- \u2500\u2500 a defini\xE7\xE3o vem do banco \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
25444
+ --
25445
+ -- Como na 047: esta view foi alargada por migrations posteriores \xE0 que a criou,
25446
+ -- e reescrev\xEA-la a partir da origem devolveria a forma antiga.
25447
+ -- ---------------------------------------------------------------------------
25448
+
25449
+ DROP VIEW IF EXISTS public.v_crm_leads;
25450
+ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25451
+ SELECT l.id,
25452
+ l.tenant_id,
25453
+ l.name,
25454
+ l.email,
25455
+ l.phone,
25456
+ l.notes,
25457
+ l.tags,
25458
+ l.is_active,
25459
+ l.company,
25460
+ l.source_id,
25461
+ l.source_name,
25462
+ l.lead_status,
25463
+ l.lead_value,
25464
+ l.assigned_to_id,
25465
+ l.created_at,
25466
+ l.updated_at,
25467
+ l.form_id,
25468
+ l.custom_fields,
25469
+ l.utm,
25470
+ l.status,
25471
+ l.attachments,
25472
+ cp.company_id,
25473
+ cp.role AS company_role,
25474
+ c.name AS company_name,
25475
+ c.legal_name AS company_legal_name,
25476
+ c.document_number AS company_document,
25477
+ -- 049: o @ vem direto de \`people\`, e N\xC3O de \`v_leads\`.
25478
+ --
25479
+ -- A \`v_leads\` \xE9 criada pela 023 com \`CREATE OR REPLACE\` e colunas
25480
+ -- nomeadas, sem DROP antes. Acrescentar uma coluna l\xE1 faz o REPLAY da
25481
+ -- 023 falhar com \`cannot drop columns from view\` \u2014 ela roda de novo, com
25482
+ -- a lista antiga, sobre a view j\xE1 alargada. Foi o que o db-from-zero
25483
+ -- pegou.
25484
+ --
25485
+ -- Esta view n\xE3o tem esse problema: a 013 a derruba antes de criar. Ent\xE3o
25486
+ -- o lugar certo de alargar \xE9 aqui, e a fonte \xE9 a tabela.
25487
+ pess.instagram
25488
+ FROM v_leads l
25489
+ LEFT JOIN people pess ON pess.id = l.id
25490
+ LEFT JOIN LATERAL ( SELECT x.company_id,
25491
+ x.role
25492
+ FROM plg_crm_company_people x
25493
+ WHERE x.person_id = l.id
25494
+ ORDER BY x.is_primary DESC, x.created_at
25495
+ LIMIT 1) cp ON true
25496
+ LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
25497
+
25498
+ GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25499
+ `;
25500
+ var MIGRATION_050_A_REUNIAO_E_UMA_ESPECIE_DECLARADA = `-- ---------------------------------------------------------------------------
25501
+ -- 050_a_reuniao_e_uma_especie_declarada.sql
25502
+ --
25503
+ -- \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
25504
+ --
25505
+ -- Marcar uma reuni\xE3o falhava com:
25506
+ --
25507
+ -- order_create: meeting is not a registered order kind
25508
+ -- HINT: public.order_kinds is the vocabulary; a plugin declares its own species.
25509
+ --
25510
+ -- O tipo de compromisso "Reuni\xE3o" foi declarado no APP (\`bookingTypes\`), e o
25511
+ -- app \xE9 quem decide o que a tela oferece. Mas \`kind\` n\xE3o \xE9 r\xF3tulo de tela: \xE9
25512
+ -- esp\xE9cie, e esp\xE9cie tem registro com chave estrangeira atr\xE1s. Um tipo que a
25513
+ -- tela oferece e o banco n\xE3o conhece \xE9 um bot\xE3o que s\xF3 falha no fim.
25514
+ --
25515
+ -- \u2500\u2500 por que DUAS tabelas \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
25516
+ --
25517
+ -- \`agenda_booking_create\` grava em duas: o COMPROMISSO (\`appointments.kind\` \u2192
25518
+ -- \`appointment_kinds\`) e a VENDA que ele carrega (\`orders.kind\` \u2192
25519
+ -- \`order_kinds\`). Na agenda o compromisso \xC9 um pedido \u2014 \xE9 o que faz uma
25520
+ -- consulta virar fatura sem ningu\xE9m redigitar nada.
25521
+ --
25522
+ -- Registrar s\xF3 numa das duas \xE9 exatamente o estado em que isto estava: a
25523
+ -- esp\xE9cie existia para o compromisso e n\xE3o para a venda, ent\xE3o a primeira
25524
+ -- metade da transa\xE7\xE3o passava e a segunda derrubava tudo.
25525
+ --
25526
+ -- \u2500\u2500 por que uma migration, e n\xE3o um INSERT \xE0 m\xE3o \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25527
+ --
25528
+ -- Foi \xE0 m\xE3o que a \`appointment_kinds\` ganhou \`meeting\` \u2014 em produ\xE7\xE3o, no meio
25529
+ -- de uma sess\xE3o, sem arquivo. O cluster ficou certo e a corrente ficou errada:
25530
+ -- quem constru\xEDsse do zero teria a tela oferecendo "Reuni\xE3o" e o banco sem
25531
+ -- saber o que \xE9. Isto p\xF5e as duas no mesmo lugar, de onde saem juntas.
25532
+ --
25533
+ -- \u2500\u2500 por que no CRM e n\xE3o na agenda \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
25534
+ --
25535
+ -- Reuni\xE3o comercial \xE9 vocabul\xE1rio de quem vende. \`plugin-agenda\` serve sal\xE3o e
25536
+ -- cl\xEDnica, e nenhum dos dois marca "reuni\xE3o" \u2014 declarar ali obrigaria as duas
25537
+ -- verticais a carregar uma esp\xE9cie que n\xE3o usam. \xC9 a mesma raz\xE3o pela qual o
25538
+ -- \`appointment_kinds.meeting\` j\xE1 nasceu com \`plugin = 'crm'\`.
25539
+ --
25540
+ -- \u2500\u2500 os status \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
25541
+ --
25542
+ -- Copiados de \`appointment\`, a esp\xE9cie irm\xE3, e n\xE3o inventados: quem escolhe
25543
+ -- "Ganho" numa reuni\xE3o espera o mesmo vocabul\xE1rio de estados que j\xE1 usa no
25544
+ -- resto da agenda, e um conjunto pr\xF3prio faria a mesma tela dizer coisas
25545
+ -- diferentes dependendo da aba.
25546
+ --
25547
+ -- Idempotente e replay-safe.
25548
+ -- ---------------------------------------------------------------------------
25549
+
25550
+ -- A esp\xE9cie do COMPROMISSO.
25551
+ INSERT INTO public.appointment_kinds (kind, plugin, description, statuses, transitions)
25552
+ VALUES (
25553
+ 'meeting',
25554
+ 'crm',
25555
+ 'Uma reuni\xE3o comercial (demo, discovery): compromisso sem servi\xE7o a entregar, com pessoas na sala em vez de um executor.',
25556
+ ARRAY['scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show']::text[],
25557
+ '{"*": ["*"], "no_show": [], "cancelled": []}'::jsonb
25558
+ )
25559
+ ON CONFLICT (kind) DO NOTHING;
25560
+
25561
+ -- A esp\xE9cie da VENDA que o compromisso carrega. \xC9 esta que faltava.
25562
+ INSERT INTO public.order_kinds (kind, plugin, description, statuses, transitions)
25563
+ VALUES (
25564
+ 'meeting',
25565
+ 'crm',
25566
+ 'O documento comercial de uma reuni\xE3o (CRM). Nasce sem linhas e sem valor \u2014 a reuni\xE3o n\xE3o entrega servi\xE7o \u2014, mas existe porque na agenda o compromisso \xC9 um pedido.',
25567
+ ARRAY['scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid', 'waiting']::text[],
25568
+ '{"*": ["*"], "paid": [], "no_show": [], "cancelled": []}'::jsonb
25569
+ )
25570
+ ON CONFLICT (kind) DO NOTHING;
25571
+
25572
+ COMMENT ON TABLE public.order_kinds IS
25573
+ 'O vocabul\xE1rio de esp\xE9cies de pedido. Um \`kind\` que a tela oferece e esta tabela n\xE3o conhece \xE9 um bot\xE3o que s\xF3 falha no fim (050).';
25574
+ `;
25575
+ var MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM = `-- ---------------------------------------------------------------------------
25576
+ -- 051_o_cracha_e_o_telefone_recusado_aparecem.sql
25577
+ --
25578
+ -- \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
25579
+ --
25580
+ -- A importa\xE7\xE3o do Sal\xE3o Abrasel guardou duas coisas no \`metadata\` da pessoa e
25581
+ -- nenhuma tela as l\xEA:
25582
+ --
25583
+ -- \`credential_company\` o NOME DA EMPRESA NA CREDENCIAL
25584
+ -- \`phone_raw\` o telefone que a valida\xE7\xE3o recusou
25585
+ --
25586
+ -- Em 27 dos 297 leads o crach\xE1 nomeia um estabelecimento DIFERENTE da empresa
25587
+ -- ligada, porque o v\xEDnculo foi feito pelo CNPJ declarado e o CNPJ nem sempre \xE9
25588
+ -- o do lugar que a pessoa toca \u2014 duas s\xF3cias do "Tata gastro bar" digitaram o
25589
+ -- CNPJ da Abrasel-GO, a associa\xE7\xE3o a que pertencem, e ficaram ligadas a ela.
25590
+ --
25591
+ -- E quatro telefones foram recusados de prop\xF3sito (dois com c\xF3digo de pa\xEDs
25592
+ -- estrangeiro, dois com um d\xEDgito a mais). A decis\xE3o est\xE1 certa: telefone
25593
+ -- errado no CRM \xE9 pior que nenhum. Guardar o valor cru e N\xC3O mostr\xE1-lo \xE9 que
25594
+ -- n\xE3o est\xE1 \u2014 a tela diz "\u2014" enquanto o dado existe no banco.
25595
+ --
25596
+ -- \u2500\u2500 por que na view e n\xE3o numa tabela nova \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
25597
+ --
25598
+ -- Os dois j\xE1 existem, escritos pela importa\xE7\xE3o. Isto n\xE3o cria dado: abre a
25599
+ -- porta para o que est\xE1 atr\xE1s dela. \xC9 o mesmo movimento da 049 com o @.
25600
+ --
25601
+ -- Idempotente e replay-safe: a 013 DERRUBA esta view antes de cri\xE1-la, ent\xE3o
25602
+ -- alarg\xE1-la aqui n\xE3o quebra o replay dela \u2014 que foi exatamente o erro que a
25603
+ -- primeira vers\xE3o da 049 cometeu com a \`v_leads\`.
25604
+ -- ---------------------------------------------------------------------------
25605
+
25606
+ DROP VIEW IF EXISTS public.v_crm_leads;
25607
+ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25608
+ SELECT l.id,
25609
+ l.tenant_id,
25610
+ l.name,
25611
+ l.email,
25612
+ l.phone,
25613
+ l.notes,
25614
+ l.tags,
25615
+ l.is_active,
25616
+ l.company,
25617
+ l.source_id,
25618
+ l.source_name,
25619
+ l.lead_status,
25620
+ l.lead_value,
25621
+ l.assigned_to_id,
25622
+ l.created_at,
25623
+ l.updated_at,
25624
+ l.form_id,
25625
+ l.custom_fields,
25626
+ l.utm,
25627
+ l.status,
25628
+ l.attachments,
25629
+ cp.company_id,
25630
+ cp.role AS company_role,
25631
+ c.name AS company_name,
25632
+ c.legal_name AS company_legal_name,
25633
+ c.document_number AS company_document,
25634
+ pess.instagram,
25635
+ -- 051: o que a planilha trouxe e a tela n\xE3o mostrava.
25636
+ --
25637
+ -- \`credential_company\` \xE9 o NOME DA EMPRESA NA CREDENCIAL \u2014 o que a pessoa
25638
+ -- escreveu no crach\xE1, que \xE9 o estabelecimento que ela toca. Em 27 casos
25639
+ -- ele diverge do CNPJ declarado, e o CNPJ \xE9 o que virou v\xEDnculo: duas
25640
+ -- s\xF3cias do Tata gastro bar ficaram ligadas \xE0 Abrasel-GO porque foi esse
25641
+ -- o CNPJ que digitaram.
25642
+ --
25643
+ -- \`phone_raw\` \xE9 o telefone que a importa\xE7\xE3o RECUSOU por n\xE3o virar n\xFAmero
25644
+ -- v\xE1lido. Guard\xE1-lo e n\xE3o mostr\xE1-lo \xE9 o pior dos dois mundos: a tela diz
25645
+ -- "\u2014" enquanto o dado est\xE1 no banco.
25646
+ pess.metadata ->> 'credential_company'::text AS credential_company,
25647
+ pess.metadata ->> 'phone_raw'::text AS phone_raw
25648
+ FROM v_leads l
25649
+ LEFT JOIN people pess ON pess.id = l.id
25650
+ LEFT JOIN LATERAL ( SELECT x.company_id,
25651
+ x.role
25652
+ FROM plg_crm_company_people x
25653
+ WHERE x.person_id = l.id
25654
+ ORDER BY x.is_primary DESC, x.created_at
25655
+ LIMIT 1) cp ON true
25656
+ LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
25657
+
25658
+ GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25659
+ `;
25230
25660
  var MIGRATIONS = [
25231
25661
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
25232
25662
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -25274,7 +25704,11 @@ var MIGRATIONS = [
25274
25704
  { id: "044_o_status_nao_e_um_acontecimento", sql: MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO },
25275
25705
  { id: "045_contato_feito_e_contato_que_alguem_fez", sql: MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ },
25276
25706
  { id: "046_a_pastilha_do_card_so_fala_quando_tem_o_que_dizer", sql: MIGRATION_046_A_PASTILHA_DO_CARD_SO_FALA_QUANDO_TEM_O_QUE_DIZER },
25277
- { id: "047_o_dono_do_lead_tem_um_lugar_so", sql: MIGRATION_047_O_DONO_DO_LEAD_TEM_UM_LUGAR_SO }
25707
+ { id: "047_o_dono_do_lead_tem_um_lugar_so", sql: MIGRATION_047_O_DONO_DO_LEAD_TEM_UM_LUGAR_SO },
25708
+ { id: "048_a_empresa_tambem_tem_um_arroba", sql: MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA },
25709
+ { id: "049_o_arroba_chega_ate_a_lista", sql: MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA },
25710
+ { id: "050_a_reuniao_e_uma_especie_declarada", sql: MIGRATION_050_A_REUNIAO_E_UMA_ESPECIE_DECLARADA },
25711
+ { id: "051_o_cracha_e_o_telefone_recusado_aparecem", sql: MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM }
25278
25712
  ];
25279
25713
 
25280
25714
  // src/locales/en.ts
@@ -25345,6 +25779,8 @@ var en = {
25345
25779
  "crm.leadDetail.backToList": "Back to list",
25346
25780
  "crm.leadDetail.formAnswers": "Form answers",
25347
25781
  "crm.leadDetail.attachments": "Attachments",
25782
+ "crm.leadDetail.credentialCompany": "Company on badge",
25783
+ "crm.leadDetail.phoneUnverified": "unverified",
25348
25784
  "crm.leadDetail.company": "Company",
25349
25785
  "crm.leadDetail.contactInfo": "Contact Information",
25350
25786
  "crm.leadDetail.createQuote": "Create Quote",
@@ -25396,6 +25832,11 @@ var en = {
25396
25832
  "crm.leadForm.namePlaceholder": "Contact name",
25397
25833
  "crm.leadForm.notes": "Notes",
25398
25834
  "crm.leadForm.notesPlaceholder": "Additional notes...",
25835
+ "crm.leadForm.instagram": "Instagram",
25836
+ "crm.leadForm.instagramPlaceholder": "@handle or link",
25837
+ "crm.leadDetail.instagram": "Instagram",
25838
+ "crm.companyForm.instagram": "Instagram",
25839
+ "crm.companyDetail.instagram": "Instagram",
25399
25840
  "crm.leadForm.phone": "Phone",
25400
25841
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
25401
25842
  "crm.leadForm.source": "Source",
@@ -26135,6 +26576,8 @@ var ptBR = {
26135
26576
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
26136
26577
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
26137
26578
  "crm.leadDetail.attachments": "Anexos",
26579
+ "crm.leadDetail.credentialCompany": "Empresa no crach\xE1",
26580
+ "crm.leadDetail.phoneUnverified": "n\xE3o validado",
26138
26581
  "crm.leadDetail.company": "Empresa",
26139
26582
  "crm.leadDetail.contactInfo": "Informa\xE7\xF5es de Contato",
26140
26583
  "crm.leadDetail.createQuote": "Criar Or\xE7amento",
@@ -26186,6 +26629,11 @@ var ptBR = {
26186
26629
  "crm.leadForm.namePlaceholder": "Nome do contato",
26187
26630
  "crm.leadForm.notes": "Observa\xE7\xF5es",
26188
26631
  "crm.leadForm.notesPlaceholder": "Observa\xE7\xF5es adicionais...",
26632
+ "crm.leadForm.instagram": "Instagram",
26633
+ "crm.leadForm.instagramPlaceholder": "@perfil ou link",
26634
+ "crm.leadDetail.instagram": "Instagram",
26635
+ "crm.companyForm.instagram": "Instagram",
26636
+ "crm.companyDetail.instagram": "Instagram",
26189
26637
  "crm.leadForm.phone": "Telefone",
26190
26638
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
26191
26639
  "crm.leadForm.source": "Origem",