@fayz-ai/plugin-crm 0.31.3 → 0.31.5

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,7 +1,8 @@
1
- import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
1
+ import * as React from 'react';
2
+ import React__default, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
2
3
  import { tl, useTranslation, getSupabaseClientOptional, getActiveUnitId, RECORD_GROUP, recordRailFields, activeFacet, registerTranslations, registerMessageDefaults, createSafeDataProvider, getActiveTenantId, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, getCurrentLocale, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
3
- import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, usePluginOnboardingGate, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, useCatalogedItemTypes, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, createArchetypeLookup, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, AskAIButton, KanbanBoard, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker, useAgentSurface } 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, CircleDashed, Search, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, ThumbsDown, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CheckCircle2, SlidersHorizontal, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
4
+ import { createPluginContext, useUnitBootstrap, useUnitStore, createCrudPage, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, usePluginOnboardingGate, PluginOnboardingGateSkeleton, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePersistedState, useScrollMemory, useLimitGuard, useCatalogedItemTypes, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, createArchetypeLookup, formatCurrency, useRecordVisit, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, RightRailPage, AskAIButton, KanbanBoard, useUnitFilter, invalidateLimit, useAccessOptional, useOrganizationStore, getRailPage, ContactPicker, useAgentSurface } from '@fayz-ai/admin';
5
+ 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, Briefcase, CircleDot, User, Download, CircleDashed, Search, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, MoreHorizontal, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Building2, Fingerprint, Link2, Star, MessageSquareQuote, UserRound, CalendarDays, ThumbsDown, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Paperclip, ImageOff, CircleAlert, CheckCircle2, SlidersHorizontal, ExternalLink, Clipboard, DollarSign, ThumbsUp, UserRoundPlus } from 'lucide-react';
5
6
  import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, 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, FilterPanel, FilterPanelField, RequiredFilter, Card, DataTable, Dropdown, DropdownTrigger, DropdownContent, DropdownItem, PhoneLink, SheetBody, SheetFooter, ComingSoon, DashboardCanvas, ModalDescription, PageViewBar, PersonPicker, CurrencyInput, HeaderTabs, Popover, PopoverTrigger, PopoverContent, getLucideIcon, DictateButton, DropdownLabel, DropdownSeparator, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
7
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
8
  import { createPortal } from 'react-dom';
@@ -190,13 +191,13 @@ var KINDS = [
190
191
  ];
191
192
  function GroupRow({ g, onOpen, open, members, roll, onEdit, onAdd, onRemove, onDelete, search }) {
192
193
  const { currency } = useCrmConfig();
193
- const [editing, setEditing] = React.useState(false);
194
- const [draftName, setDraftName] = React.useState(g.name);
195
- const [draftKind, setDraftKind] = React.useState(g.kind ?? "economic_group");
196
- const [term, setTerm] = React.useState("");
197
- const [hits, setHits] = React.useState([]);
198
- const [busy, setBusy] = React.useState(false);
199
- React.useEffect(() => {
194
+ const [editing, setEditing] = React__default.useState(false);
195
+ const [draftName, setDraftName] = React__default.useState(g.name);
196
+ const [draftKind, setDraftKind] = React__default.useState(g.kind ?? "economic_group");
197
+ const [term, setTerm] = React__default.useState("");
198
+ const [hits, setHits] = React__default.useState([]);
199
+ const [busy, setBusy] = React__default.useState(false);
200
+ React__default.useEffect(() => {
200
201
  if (term.trim().length < 2) {
201
202
  setHits([]);
202
203
  return;
@@ -387,16 +388,16 @@ function GroupRow({ g, onOpen, open, members, roll, onEdit, onAdd, onRemove, onD
387
388
  }
388
389
  function CompanyGroupsView() {
389
390
  const provider = useCrmProvider();
390
- const [groups, setGroups] = React.useState(null);
391
- const [candidates, setCandidates] = React.useState([]);
392
- const [openId, setOpenId] = React.useState(null);
393
- const [members, setMembers] = React.useState({});
394
- const [rollups, setRollups] = React.useState({});
395
- const [names, setNames] = React.useState({});
396
- const [busy, setBusy] = React.useState(null);
397
- const [novoAberto, setNovoAberto] = React.useState(false);
398
- const [novoNome, setNovoNome] = React.useState("");
399
- const [criando, setCriando] = React.useState(false);
391
+ const [groups, setGroups] = React__default.useState(null);
392
+ const [candidates, setCandidates] = React__default.useState([]);
393
+ const [openId, setOpenId] = React__default.useState(null);
394
+ const [members, setMembers] = React__default.useState({});
395
+ const [rollups, setRollups] = React__default.useState({});
396
+ const [names, setNames] = React__default.useState({});
397
+ const [busy, setBusy] = React__default.useState(null);
398
+ const [novoAberto, setNovoAberto] = React__default.useState(false);
399
+ const [novoNome, setNovoNome] = React__default.useState("");
400
+ const [criando, setCriando] = React__default.useState(false);
400
401
  async function criarGrupo() {
401
402
  const nome = novoNome.trim();
402
403
  if (!nome || criando) return;
@@ -413,7 +414,7 @@ function CompanyGroupsView() {
413
414
  setCriando(false);
414
415
  }
415
416
  }
416
- const load = React.useCallback(async () => {
417
+ const load = React__default.useCallback(async () => {
417
418
  try {
418
419
  const [g, c, r] = await Promise.all([
419
420
  provider.getCompanyGroups(),
@@ -428,7 +429,7 @@ function CompanyGroupsView() {
428
429
  setGroups([]);
429
430
  }
430
431
  }, [provider]);
431
- React.useEffect(() => {
432
+ React__default.useEffect(() => {
432
433
  void load();
433
434
  }, [load]);
434
435
  async function toggle(id) {
@@ -599,9 +600,9 @@ function CompanyGroupsView() {
599
600
  function EngagementLadderSettings() {
600
601
  const t2 = useTranslation();
601
602
  const provider = useCrmProvider();
602
- const [cfg, setCfg] = React.useState(null);
603
- const [saving, setSaving] = React.useState(false);
604
- React.useEffect(() => {
603
+ const [cfg, setCfg] = React__default.useState(null);
604
+ const [saving, setSaving] = React__default.useState(false);
605
+ React__default.useEffect(() => {
605
606
  let alive = true;
606
607
  provider.getEngagementSummary().then((d) => {
607
608
  if (alive) setCfg(d.settings);
@@ -655,9 +656,9 @@ function EngagementLadderSettings() {
655
656
  function LeadScoreWeights() {
656
657
  const t2 = useTranslation();
657
658
  const provider = useCrmProvider();
658
- const [rows, setRows] = React.useState(null);
659
- const [saving, setSaving] = React.useState(null);
660
- React.useEffect(() => {
659
+ const [rows, setRows] = React__default.useState(null);
660
+ const [saving, setSaving] = React__default.useState(null);
661
+ React__default.useEffect(() => {
661
662
  let alive = true;
662
663
  provider.getLeadScoreWeights().then((d) => {
663
664
  if (alive) setRows(d);
@@ -929,6 +930,45 @@ function LostReasonDialog({
929
930
  ] })
930
931
  ] }) });
931
932
  }
933
+ function useCrmUnitFilter() {
934
+ return useUnitFilter({ scope: "global" });
935
+ }
936
+ var ROW = "flex w-full items-center gap-2 rounded-button px-2 py-1.5 text-left text-xs transition-colors hover:bg-muted";
937
+ function UnitPicker({ filter: f }) {
938
+ const [open, setOpen] = React.useState(false);
939
+ if (!f.visible) return null;
940
+ const current = f.value ? f.options.find((u) => u.id === f.value)?.name ?? f.allLabel : f.allLabel;
941
+ const pick = (id) => {
942
+ f.setValue(id);
943
+ setOpen(false);
944
+ };
945
+ return /* @__PURE__ */ jsxs(Dropdown, { open, onOpenChange: setOpen, children: [
946
+ /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
947
+ "button",
948
+ {
949
+ type: "button",
950
+ title: f.label,
951
+ className: "inline-flex h-8 shrink-0 items-center gap-1.5 rounded-full border bg-card px-3 text-xs font-medium text-foreground shadow-button transition-colors hover:bg-muted",
952
+ children: [
953
+ /* @__PURE__ */ jsx(Building2, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
954
+ /* @__PURE__ */ jsx("span", { className: "max-w-[10rem] truncate", children: current }),
955
+ /* @__PURE__ */ jsx(ChevronDown, { className: "h-3 w-3 shrink-0 opacity-60" })
956
+ ]
957
+ }
958
+ ) }),
959
+ /* @__PURE__ */ jsxs(DropdownContent, { align: "end", className: "w-56 p-1", children: [
960
+ /* @__PURE__ */ jsxs("button", { className: ROW, onClick: () => pick(void 0), children: [
961
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: f.allLabel }),
962
+ !f.value && /* @__PURE__ */ jsx(Check, { className: "ml-auto h-3 w-3 shrink-0" })
963
+ ] }),
964
+ /* @__PURE__ */ jsx("div", { className: "my-1 border-t" }),
965
+ /* @__PURE__ */ jsx("div", { className: "max-h-64 overflow-y-auto", children: f.options.map((u) => /* @__PURE__ */ jsxs("button", { className: ROW, onClick: () => pick(u.id), children: [
966
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: u.name }),
967
+ f.value === u.id && /* @__PURE__ */ jsx(Check, { className: "ml-auto h-3 w-3 shrink-0" })
968
+ ] }, u.id)) })
969
+ ] })
970
+ ] });
971
+ }
932
972
 
933
973
  // src/lib/relative-time.ts
934
974
  var MINUTE = 60;
@@ -1412,7 +1452,7 @@ function usePipelineAgentSurface(deps) {
1412
1452
  }
1413
1453
  var CHIP_ROW = "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs transition-colors hover:bg-muted";
1414
1454
  function BoardFilterChip({ trigger, onClear, clearLabel, closeOnSelect, children }) {
1415
- const [open, setOpen] = React.useState(false);
1455
+ const [open, setOpen] = React__default.useState(false);
1416
1456
  return /* @__PURE__ */ jsxs(Dropdown, { open, onOpenChange: setOpen, children: [
1417
1457
  /* @__PURE__ */ jsx(DropdownTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
1418
1458
  "button",
@@ -1860,6 +1900,7 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, onStageIntent })
1860
1900
  void loadMyUserId().then(setMyUserId);
1861
1901
  }, []);
1862
1902
  const effectiveOwner = ownerFilter === "__me__" ? myUserId ?? void 0 : ownerFilter;
1903
+ const unitFilter = useCrmUnitFilter();
1863
1904
  const [temps, setTemps] = useState(/* @__PURE__ */ new Map());
1864
1905
  const [channels, setChannels] = useState(/* @__PURE__ */ new Map());
1865
1906
  const [period, setPeriod] = usePersistedState("crm.board.period", "all");
@@ -2198,6 +2239,7 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings, onStageIntent })
2198
2239
  })
2199
2240
  }
2200
2241
  ),
2242
+ /* @__PURE__ */ jsx(UnitPicker, { filter: unitFilter }),
2201
2243
  /* @__PURE__ */ jsx(
2202
2244
  FilterMenu,
2203
2245
  {
@@ -2774,6 +2816,7 @@ function DealListView({ onOpenDeal }) {
2774
2816
  cohort && t2("crm.deals.cohort"),
2775
2817
  companyName && t2("crm.card.companyTitle")
2776
2818
  ].filter(Boolean);
2819
+ const unitFilter = useCrmUnitFilter();
2777
2820
  const filtrosAtivos = (stage ? 1 : 0) + (status ? 1 : 0) + (cohort ? 1 : 0) + (outcome !== "open" ? 1 : 0) + (city ? 1 : 0) + (companyName ? 1 : 0) + (tags.length ? 1 : 0) + (owner ? 1 : 0);
2778
2821
  const limparFiltros = () => {
2779
2822
  setStage(void 0);
@@ -2894,6 +2937,7 @@ function DealListView({ onOpenDeal }) {
2894
2937
  )
2895
2938
  ] }),
2896
2939
  /* @__PURE__ */ jsxs("div", { className: "ml-auto flex shrink-0 flex-nowrap items-center justify-end gap-1.5 md:flex-wrap", children: [
2940
+ /* @__PURE__ */ jsx(UnitPicker, { filter: unitFilter }),
2897
2941
  stage && /* @__PURE__ */ jsx(
2898
2942
  FilterChip,
2899
2943
  {
@@ -3964,11 +4008,11 @@ var partnerEntity = {
3964
4008
  // escondido, e sem isto a coluna NOT NULL recebe null e o save volta 400.
3965
4009
  defaultValue: [],
3966
4010
  visibleWhen: (values) => values.allUnits === false,
3967
- renderInput: ({ value, onChange }) => React.createElement(PartnerUnitsInput, {
4011
+ renderInput: ({ value, onChange }) => React__default.createElement(PartnerUnitsInput, {
3968
4012
  value,
3969
4013
  onChange
3970
4014
  }),
3971
- renderCell: (value) => React.createElement(PartnerUnitsCell, { value })
4015
+ renderCell: (value) => React__default.createElement(PartnerUnitsCell, { value })
3972
4016
  },
3973
4017
  {
3974
4018
  key: "allowsOnlineBooking",
@@ -3977,7 +4021,7 @@ var partnerEntity = {
3977
4021
  showInTable: true,
3978
4022
  defaultValue: false,
3979
4023
  hint: "Members can book on their own from the public page.",
3980
- renderCell: (value) => React.createElement(PartnerOnlineBookingCell, { value })
4024
+ renderCell: (value) => React__default.createElement(PartnerOnlineBookingCell, { value })
3981
4025
  },
3982
4026
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
3983
4027
  ],
@@ -4208,11 +4252,11 @@ var assignmentRuleEntity = {
4208
4252
  defaultValue: [],
4209
4253
  showInTable: true,
4210
4254
  hint: "Who is offered a new lead, in order.",
4211
- renderInput: ({ value, onChange }) => React.createElement(AssigneeRotaInput, {
4255
+ renderInput: ({ value, onChange }) => React__default.createElement(AssigneeRotaInput, {
4212
4256
  value,
4213
4257
  onChange
4214
4258
  }),
4215
- renderCell: (value) => React.createElement(AssigneeRotaCell, { value })
4259
+ renderCell: (value) => React__default.createElement(AssigneeRotaCell, { value })
4216
4260
  },
4217
4261
  // Where the rotation currently is. Read-only: editing it by hand would skew
4218
4262
  // the next offer with nothing recording why.
@@ -4544,7 +4588,7 @@ function formatDocument(doc) {
4544
4588
  return doc;
4545
4589
  }
4546
4590
  function CopyDocument({ document: doc, label: label2 }) {
4547
- const [copied, setCopied] = React.useState(false);
4591
+ const [copied, setCopied] = React__default.useState(false);
4548
4592
  return /* @__PURE__ */ jsx(
4549
4593
  "button",
4550
4594
  {
@@ -5601,7 +5645,7 @@ function DealsView({ mode, onChangeMode, openDealId, onOpenDeal, onCloseDeal, on
5601
5645
  const refreshBoard = useCrmStore((s) => s.refreshBoard);
5602
5646
  const addLead = onAddLead ? (stageId) => setNovoLead({ stageId }) : void 0;
5603
5647
  const dealsByStage = useCrmStore((s) => s.dealsByStage);
5604
- const seedDeal = React.useMemo(() => {
5648
+ const seedDeal = React__default.useMemo(() => {
5605
5649
  if (!openId) return null;
5606
5650
  for (const lista of dealsByStage.values()) {
5607
5651
  const d = lista.find((x) => x.id === openId);
@@ -6324,6 +6368,7 @@ function LeadListView({ onNew, onEdit }) {
6324
6368
  }
6325
6369
  return vistos;
6326
6370
  }, [team, leads2]);
6371
+ const unitFilter = useCrmUnitFilter();
6327
6372
  const activeFilterCount = (statusFilter.length ? 1 : 0) + (sourceFilter ? 1 : 0) + (tagFilter.length ? 1 : 0) + (effectiveOwner ? 1 : 0) + (companyFilter ? 1 : 0) + (reachFilter ? 1 : 0) + (cityFilter ? 1 : 0);
6328
6373
  const clearFilters = () => {
6329
6374
  setStatusFilter([]);
@@ -6399,7 +6444,7 @@ function LeadListView({ onNew, onEdit }) {
6399
6444
  FilterChip,
6400
6445
  {
6401
6446
  label: t2("crm.leads.companyCol"),
6402
- icon: Building2,
6447
+ icon: Briefcase,
6403
6448
  allLabel: t2("crm.leads.filters.anyCompany"),
6404
6449
  options: [
6405
6450
  { value: "yes", label: t2("crm.leads.filters.withCompany") },
@@ -6570,9 +6615,12 @@ function LeadListView({ onNew, onEdit }) {
6570
6615
  ] })
6571
6616
  },
6572
6617
  {
6618
+ // Briefcase, not Building2: the unit field took the building icon the
6619
+ // rest of the product uses for a branch, and two identical icons in
6620
+ // one menu are two fields people confuse.
6573
6621
  id: "company",
6574
6622
  label: t2("crm.leads.companyCol"),
6575
- icon: Building2,
6623
+ icon: Briefcase,
6576
6624
  activeCount: companyFilter ? 1 : 0,
6577
6625
  render: (close) => /* @__PURE__ */ jsxs(Fragment, { children: [
6578
6626
  /* @__PURE__ */ jsx(FilterMenuRow, { active: !companyFilter, onClick: () => {
@@ -6637,7 +6685,10 @@ function LeadListView({ onNew, onEdit }) {
6637
6685
  search,
6638
6686
  onSearchChange: setSearch,
6639
6687
  filters: filtros,
6640
- filtersTrigger: filtersMenu,
6688
+ filtersTrigger: /* @__PURE__ */ jsxs(Fragment, { children: [
6689
+ /* @__PURE__ */ jsx(UnitPicker, { filter: unitFilter }),
6690
+ filtersMenu
6691
+ ] }),
6641
6692
  activeFilterCount,
6642
6693
  onClearFilters: activeFilterCount > 0 ? clearFilters : void 0,
6643
6694
  clearFiltersLabel: t2("crm.leads.filters.clear"),
@@ -6986,7 +7037,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
6986
7037
  const config = useCrmConfig();
6987
7038
  const provider = useCrmProvider();
6988
7039
  const { currency, itemTypes: declaredItemTypes } = config;
6989
- const translatedItemTypes = React.useMemo(
7040
+ const translatedItemTypes = React__default.useMemo(
6990
7041
  () => declaredItemTypes.map((tp) => {
6991
7042
  const traduzido = t2(`crm.itemType.${tp.value}`);
6992
7043
  return traduzido === `crm.itemType.${tp.value}` ? tp : { ...tp, label: traduzido };
@@ -7061,7 +7112,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
7061
7112
  setQuoteDate(iso);
7062
7113
  if (validityDays !== null) setValidUntil(addDays(iso, validityDays));
7063
7114
  }
7064
- const openCustomOnMount = React.useRef(false);
7115
+ const openCustomOnMount = React__default.useRef(false);
7065
7116
  function pickValidity(days) {
7066
7117
  openCustomOnMount.current = days === null && validityDays !== null;
7067
7118
  setValidityDays(days);
@@ -7138,7 +7189,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
7138
7189
  observations,
7139
7190
  items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
7140
7191
  };
7141
- const snapshot = React.useRef(null);
7192
+ const snapshot = React__default.useRef(null);
7142
7193
  useEffect(() => {
7143
7194
  if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
7144
7195
  }, [loadingExisting]);
@@ -8608,6 +8659,7 @@ function CompanyListView({ onNew, onEdit }) {
8608
8659
  pageSize: PAGE_SIZE2
8609
8660
  });
8610
8661
  }, [search, cityFilter, tagFilter, page]);
8662
+ const unitFilter = useCrmUnitFilter();
8611
8663
  const activeFilterCount = (cityFilter ? 1 : 0) + (tagFilter.length ? 1 : 0);
8612
8664
  const clearFilters = () => {
8613
8665
  setCityFilter(void 0);
@@ -8730,7 +8782,10 @@ function CompanyListView({ onNew, onEdit }) {
8730
8782
  search,
8731
8783
  onSearchChange: setSearch,
8732
8784
  filters: filtros,
8733
- filtersTrigger: filtersMenu,
8785
+ filtersTrigger: /* @__PURE__ */ jsxs(Fragment, { children: [
8786
+ /* @__PURE__ */ jsx(UnitPicker, { filter: unitFilter }),
8787
+ filtersMenu
8788
+ ] }),
8734
8789
  activeFilterCount,
8735
8790
  onClearFilters: activeFilterCount > 0 ? clearFilters : void 0,
8736
8791
  clearFiltersLabel: t2("crm.leads.filters.clear"),
@@ -8971,8 +9026,8 @@ function CompanyFormView({ companyId, onSaved }) {
8971
9026
  function CompanyGroupBadge({ companyId, onOpenCompany }) {
8972
9027
  const provider = useCrmProvider();
8973
9028
  const { currency } = useCrmConfig();
8974
- const [data, setData] = React.useState(null);
8975
- React.useEffect(() => {
9029
+ const [data, setData] = React__default.useState(null);
9030
+ React__default.useEffect(() => {
8976
9031
  let alive = true;
8977
9032
  provider.getGroupOfCompany(companyId).then((d) => {
8978
9033
  if (alive) setData(d);
@@ -10006,10 +10061,10 @@ function NetworkView() {
10006
10061
  const t2 = useTranslation();
10007
10062
  const provider = useCrmProvider();
10008
10063
  const { currency } = useCrmConfig();
10009
- const [days, setDays] = React.useState("90");
10010
- const [rows, setRows] = React.useState(null);
10011
- const [weights, setWeights] = React.useState({});
10012
- React.useEffect(() => {
10064
+ const [days, setDays] = React__default.useState("90");
10065
+ const [rows, setRows] = React__default.useState(null);
10066
+ const [weights, setWeights] = React__default.useState({});
10067
+ React__default.useEffect(() => {
10013
10068
  let alive = true;
10014
10069
  const to = (/* @__PURE__ */ new Date()).toISOString();
10015
10070
  const from = new Date(Date.now() - Number(days) * 864e5).toISOString();
@@ -10026,9 +10081,9 @@ function NetworkView() {
10026
10081
  alive = false;
10027
10082
  };
10028
10083
  }, [provider, days]);
10029
- const scored = React.useMemo(() => scoreUnits(rows ?? [], weights), [rows, weights]);
10084
+ const scored = React__default.useMemo(() => scoreUnits(rows ?? [], weights), [rows, weights]);
10030
10085
  const avg = networkScore(scored);
10031
- const ranked = React.useMemo(() => [...scored].sort((a, b) => b.revenue - a.revenue), [scored]);
10086
+ const ranked = React__default.useMemo(() => [...scored].sort((a, b) => b.revenue - a.revenue), [scored]);
10032
10087
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
10033
10088
  /* @__PURE__ */ jsx(
10034
10089
  SubpageHeader,
@@ -10209,11 +10264,11 @@ function SurveyScale({ type, value, onChange, readOnly, compact }) {
10209
10264
  ] });
10210
10265
  }
10211
10266
  function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, onSaved }) {
10212
- const [name, setName] = React.useState(survey?.name ?? "Pesquisa p\xF3s-atendimento");
10213
- const [isActive, setIsActive] = React.useState(survey?.isActive ?? true);
10214
- const [askOnCheckout, setAskOnCheckout] = React.useState(survey?.askOnCheckout ?? true);
10215
- const [thanks, setThanks] = React.useState(survey?.thankYouMessage ?? "");
10216
- const [questions, setQuestions] = React.useState(
10267
+ const [name, setName] = React__default.useState(survey?.name ?? "Pesquisa p\xF3s-atendimento");
10268
+ const [isActive, setIsActive] = React__default.useState(survey?.isActive ?? true);
10269
+ const [askOnCheckout, setAskOnCheckout] = React__default.useState(survey?.askOnCheckout ?? true);
10270
+ const [thanks, setThanks] = React__default.useState(survey?.thankYouMessage ?? "");
10271
+ const [questions, setQuestions] = React__default.useState(
10217
10272
  (survey?.questions ?? []).map((q) => ({
10218
10273
  id: q.id,
10219
10274
  text: q.text,
@@ -10223,8 +10278,8 @@ function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, on
10223
10278
  answered: answeredQuestionIds?.has(q.id)
10224
10279
  }))
10225
10280
  );
10226
- const [saving, setSaving] = React.useState(false);
10227
- const [error, setError] = React.useState(null);
10281
+ const [saving, setSaving] = React__default.useState(false);
10282
+ const [error, setError] = React__default.useState(null);
10228
10283
  function patch(i, changes) {
10229
10284
  setQuestions((qs) => qs.map((q, j) => j === i ? { ...q, ...changes } : q));
10230
10285
  }
@@ -10418,13 +10473,13 @@ function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, on
10418
10473
  }
10419
10474
  function SurveyCollectDialog({ survey, provider, contactLookup, onClose, onSaved }) {
10420
10475
  const unitId = useActiveUnitId();
10421
- const [contact, setContact] = React.useState(null);
10422
- const [answers, setAnswers] = React.useState(
10476
+ const [contact, setContact] = React__default.useState(null);
10477
+ const [answers, setAnswers] = React__default.useState(
10423
10478
  Object.fromEntries(survey.questions.map((q) => [q.id, { rating: null, comment: "" }]))
10424
10479
  );
10425
- const [saving, setSaving] = React.useState(false);
10426
- const [done, setDone] = React.useState(false);
10427
- const [error, setError] = React.useState(null);
10480
+ const [saving, setSaving] = React__default.useState(false);
10481
+ const [done, setDone] = React__default.useState(false);
10482
+ const [error, setError] = React__default.useState(null);
10428
10483
  function patch(id, changes) {
10429
10484
  setAnswers((a) => ({ ...a, [id]: { ...a[id], ...changes } }));
10430
10485
  }
@@ -10523,8 +10578,8 @@ function ResponseSkeleton() {
10523
10578
  ] }, i)) });
10524
10579
  }
10525
10580
  function SurveyResponsesRail({ survey, provider, onClose }) {
10526
- const [responses, setResponses] = React.useState(null);
10527
- React.useEffect(() => {
10581
+ const [responses, setResponses] = React__default.useState(null);
10582
+ React__default.useEffect(() => {
10528
10583
  let cancelled = false;
10529
10584
  setResponses(null);
10530
10585
  void provider.getSurveyResponses(survey.id).then((r) => {
@@ -10584,19 +10639,19 @@ function SurveysView() {
10584
10639
  const can = usePermissionOptional();
10585
10640
  const canEdit = can("sales", "edit");
10586
10641
  const canDelete = can("sales", "delete");
10587
- const [surveys, setSurveys] = React.useState(null);
10588
- const [stats, setStats] = React.useState({});
10589
- const [editing, setEditing] = React.useState(void 0);
10590
- const [collecting, setCollecting] = React.useState(null);
10591
- const [viewing, setViewing] = React.useState(null);
10592
- const [removing, setRemoving] = React.useState(null);
10593
- const [answeredIds, setAnsweredIds] = React.useState(/* @__PURE__ */ new Set());
10594
- const load = React.useCallback(async () => {
10642
+ const [surveys, setSurveys] = React__default.useState(null);
10643
+ const [stats, setStats] = React__default.useState({});
10644
+ const [editing, setEditing] = React__default.useState(void 0);
10645
+ const [collecting, setCollecting] = React__default.useState(null);
10646
+ const [viewing, setViewing] = React__default.useState(null);
10647
+ const [removing, setRemoving] = React__default.useState(null);
10648
+ const [answeredIds, setAnsweredIds] = React__default.useState(/* @__PURE__ */ new Set());
10649
+ const load = React__default.useCallback(async () => {
10595
10650
  const [list, st] = await Promise.all([provider.getSurveys(), provider.getSurveyStats()]);
10596
10651
  setSurveys(list);
10597
10652
  setStats(Object.fromEntries(st.map((s) => [s.surveyId, s])));
10598
10653
  }, [provider]);
10599
- React.useEffect(() => {
10654
+ React__default.useEffect(() => {
10600
10655
  void load();
10601
10656
  }, [load]);
10602
10657
  const askers = (surveys ?? []).filter((s) => s.isActive && s.askOnCheckout);
@@ -10872,12 +10927,12 @@ function DistributionView() {
10872
10927
  const t2 = useTranslation();
10873
10928
  const can = usePermissionOptional();
10874
10929
  const canDistribute = can("sales", "edit");
10875
- const [rota, setRota] = React.useState(void 0);
10876
- const [backlog, setBacklog] = React.useState(null);
10877
- const [offers, setOffers] = React.useState(null);
10878
- const [preview, setPreview] = React.useState(null);
10879
- const [busy, setBusy] = React.useState(false);
10880
- const load = React.useCallback(async () => {
10930
+ const [rota, setRota] = React__default.useState(void 0);
10931
+ const [backlog, setBacklog] = React__default.useState(null);
10932
+ const [offers, setOffers] = React__default.useState(null);
10933
+ const [preview, setPreview] = React__default.useState(null);
10934
+ const [busy, setBusy] = React__default.useState(false);
10935
+ const load = React__default.useCallback(async () => {
10881
10936
  const [r, b, o] = await Promise.all([
10882
10937
  provider.getRotaState().catch(() => null),
10883
10938
  provider.getLeadBacklog(500).catch(() => []),
@@ -10887,7 +10942,7 @@ function DistributionView() {
10887
10942
  setBacklog(b);
10888
10943
  setOffers(o);
10889
10944
  }, [provider]);
10890
- React.useEffect(() => {
10945
+ React__default.useEffect(() => {
10891
10946
  void load();
10892
10947
  }, [load]);
10893
10948
  async function askPreview() {
@@ -11007,11 +11062,11 @@ function DistributionView() {
11007
11062
  }
11008
11063
  function Countdown({ seconds }) {
11009
11064
  const t2 = useTranslation();
11010
- const [left, setLeft] = React.useState(seconds);
11011
- React.useEffect(() => {
11065
+ const [left, setLeft] = React__default.useState(seconds);
11066
+ React__default.useEffect(() => {
11012
11067
  setLeft(seconds);
11013
11068
  }, [seconds]);
11014
- React.useEffect(() => {
11069
+ React__default.useEffect(() => {
11015
11070
  if (left <= 0) return;
11016
11071
  const id = setInterval(() => setLeft((s2) => Math.max(0, s2 - 1)), 1e3);
11017
11072
  return () => clearInterval(id);
@@ -11027,16 +11082,16 @@ function Countdown({ seconds }) {
11027
11082
  function MyOffersView() {
11028
11083
  const provider = useCrmProvider();
11029
11084
  const t2 = useTranslation();
11030
- const [offers, setOffers] = React.useState(null);
11031
- const [busy, setBusy] = React.useState(null);
11032
- const load = React.useCallback(async () => {
11085
+ const [offers, setOffers] = React__default.useState(null);
11086
+ const [busy, setBusy] = React__default.useState(null);
11087
+ const load = React__default.useCallback(async () => {
11033
11088
  try {
11034
11089
  setOffers(await provider.getLeadOffers({ mine: true }));
11035
11090
  } catch {
11036
11091
  setOffers([]);
11037
11092
  }
11038
11093
  }, [provider]);
11039
- React.useEffect(() => {
11094
+ React__default.useEffect(() => {
11040
11095
  void load();
11041
11096
  const id = setInterval(() => {
11042
11097
  void load();
@@ -11528,7 +11583,7 @@ function PerformancePanel() {
11528
11583
  }
11529
11584
  function NpsKpi() {
11530
11585
  const provider = useCrmProvider();
11531
- const [stats, setStats] = React.useState(null);
11586
+ const [stats, setStats] = React__default.useState(null);
11532
11587
  useEffect(() => {
11533
11588
  let cancelled = false;
11534
11589
  void provider.getSurveyStats().then((s) => {
@@ -11562,8 +11617,8 @@ function NpsKpi() {
11562
11617
  }
11563
11618
  function useEngagement() {
11564
11619
  const provider = useCrmProvider();
11565
- const [data, setData] = React.useState(null);
11566
- React.useEffect(() => {
11620
+ const [data, setData] = React__default.useState(null);
11621
+ React__default.useEffect(() => {
11567
11622
  let alive = true;
11568
11623
  provider.getEngagementSummary().then((d) => {
11569
11624
  if (alive) setData(d);
@@ -11694,8 +11749,8 @@ function ActiveCustomersKpi() {
11694
11749
  function SourceConversionChart() {
11695
11750
  const t2 = useTranslation();
11696
11751
  const provider = useCrmProvider();
11697
- const [rows, setRows] = React.useState([]);
11698
- React.useEffect(() => {
11752
+ const [rows, setRows] = React__default.useState([]);
11753
+ React__default.useEffect(() => {
11699
11754
  let alive = true;
11700
11755
  provider.getSourceConversion(90).then((r) => {
11701
11756
  if (alive) setRows(r);
@@ -11723,8 +11778,8 @@ function SourceConversionChart() {
11723
11778
  function MonthlyTrendChart() {
11724
11779
  const t2 = useTranslation();
11725
11780
  const provider = useCrmProvider();
11726
- const [rows, setRows] = React.useState([]);
11727
- React.useEffect(() => {
11781
+ const [rows, setRows] = React__default.useState([]);
11782
+ React__default.useEffect(() => {
11728
11783
  let alive = true;
11729
11784
  provider.getMonthlySeries(6).then((r) => {
11730
11785
  if (alive) setRows(r);
@@ -13275,6 +13330,9 @@ async function fetchMyTeamId(tenantId, userId) {
13275
13330
  function orTerm(raw) {
13276
13331
  return raw.replace(/[,()]/g, " ").replace(/\s+/g, " ").trim();
13277
13332
  }
13333
+ function birthUnitId() {
13334
+ return getActiveUnitId() ?? null;
13335
+ }
13278
13336
  function toCompany(r) {
13279
13337
  return {
13280
13338
  id: r.id,
@@ -13363,6 +13421,7 @@ function toDeal(r) {
13363
13421
  // TÍTULO para cá: buscar na nota achava o que o título já achava, e nada
13364
13422
  // do que estava escrito na nota.
13365
13423
  notes: r.notes ?? void 0,
13424
+ unitId: r.unit_id ?? void 0,
13366
13425
  tenantId: r.tenant_id,
13367
13426
  createdAt: r.created_at,
13368
13427
  updatedAt: r.updated_at
@@ -13473,6 +13532,9 @@ function createSupabaseCrmProvider(options) {
13473
13532
  const { pub } = getClients();
13474
13533
  await pub.from(T.activities).insert({
13475
13534
  tenant_id: getTenantId(),
13535
+ // Same reason as createActivity: null here would show the event in
13536
+ // every branch.
13537
+ unit_id: birthUnitId(),
13476
13538
  deal_id: input.dealId ?? null,
13477
13539
  lead_id: input.leadId ?? null,
13478
13540
  contact_id: input.contactId ?? null,
@@ -13658,6 +13720,7 @@ function createSupabaseCrmProvider(options) {
13658
13720
  tenant_id: tenantId,
13659
13721
  kind: "lead",
13660
13722
  name: input.name,
13723
+ unit_id: birthUnitId(),
13661
13724
  email: input.email,
13662
13725
  phone: input.phone,
13663
13726
  instagram: input.instagram || null,
@@ -13784,6 +13847,7 @@ function createSupabaseCrmProvider(options) {
13784
13847
  const { data: row, error } = await pub.from(T.deals).insert({
13785
13848
  tenant_id: tenantId,
13786
13849
  status: "open",
13850
+ unit_id: birthUnitId(),
13787
13851
  title: input.title,
13788
13852
  value: input.value,
13789
13853
  currency: "BRL",
@@ -13988,6 +14052,10 @@ function createSupabaseCrmProvider(options) {
13988
14052
  tenant_id: tenantId,
13989
14053
  deal_id: input.dealId,
13990
14054
  lead_id: input.leadId,
14055
+ // Where the contact HAPPENED. 062 inherited it for existing rows from
14056
+ // the deal; from here it comes from where the person stood, which is
14057
+ // the same answer without the join.
14058
+ unit_id: birthUnitId(),
13991
14059
  contact_id: input.contactId,
13992
14060
  activity_type: input.activityType,
13993
14061
  title: input.title,
@@ -30270,6 +30338,283 @@ REVOKE ALL ON FUNCTION public.crm_funnel(uuid, jsonb) FROM public;
30270
30338
  GRANT EXECUTE ON FUNCTION public.crm_funnel(uuid, jsonb) TO authenticated;
30271
30339
  GRANT EXECUTE ON FUNCTION public.crm_funnel(uuid, jsonb) TO service_role;
30272
30340
  `;
30341
+ var MIGRATION_062_THE_WHOLE_CRM_SAYS_WHICH_UNIT_IT_IS = `-- ---------------------------------------------------------------------------
30342
+ -- 062_the_whole_crm_says_which_unit_it_is.sql
30343
+ --
30344
+ -- The CRM was the last module blind to units. Two brands selling out of one
30345
+ -- tenant shared a single board: 335 cards of one brand on the screen of
30346
+ -- whoever runs the other, with no way to say "only mine".
30347
+ --
30348
+ -- Most of the fence already existed and nobody had noticed: \`plg_crm_deals.
30349
+ -- unit_id\` and \`people.unit_id\` have carried a restrictive policy since 052 and
30350
+ -- the spine's 042, and \`app.has_unit\` narrows to \`app.current_unit_id()\`. Three
30351
+ -- things were missing, and each one hid the other two:
30352
+ --
30353
+ -- 1. the COLUMN on the two tables that lacked it \u2014 company and activity;
30354
+ -- 2. the column reaching the VIEWS, which is where the screens read: none of
30355
+ -- them returned \`unit_id\`, so the client had nothing to narrow by;
30356
+ -- 3. the row in \`scoped_resources\`, which is how the visibility screen and
30357
+ -- the generic CRUD learn that these rows carry a unit.
30358
+ --
30359
+ -- Activity stays OUT of \`scoped_resources\`, same call as 055: that registry
30360
+ -- serves the resource the visibility screen offers and wants \`owner_id\`. An
30361
+ -- activity has \`created_by\` \u2014 who logged it, not who owns it \u2014 and inherits its
30362
+ -- unit from the deal or lead it reports. Its fence is the policy below.
30363
+ --
30364
+ -- A company is born shared (\`unit_id\` null = the whole house) and every existing
30365
+ -- one stays that way. Deliberate, and the opposite of the unit's usual
30366
+ -- deny-by-default: the same restaurant chain is a customer of both brands, and
30367
+ -- pinning it to one branch would hide a book of business from the people
30368
+ -- working it.
30369
+ --
30370
+ -- Idempotent and replay-safe. Views grow by CREATE OR REPLACE with the new
30371
+ -- column LAST, which is what spares the CASCADE and recreating
30372
+ -- \`plg_crm_rep_deals\` by hand.
30373
+ -- ---------------------------------------------------------------------------
30374
+
30375
+ -- \u2500\u2500 the column \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
30376
+
30377
+ ALTER TABLE public.plg_crm_companies ADD COLUMN IF NOT EXISTS unit_id uuid;
30378
+ ALTER TABLE public.plg_crm_activities ADD COLUMN IF NOT EXISTS unit_id uuid;
30379
+
30380
+ -- SET NULL, not CASCADE: closing a branch must not delete its book of business
30381
+ -- or 551 logged calls. The row going back to shared is the acceptable worst
30382
+ -- case; losing the history is not.
30383
+ ALTER TABLE public.plg_crm_companies DROP CONSTRAINT IF EXISTS plg_crm_companies_unit_fk;
30384
+ ALTER TABLE public.plg_crm_companies
30385
+ ADD CONSTRAINT plg_crm_companies_unit_fk
30386
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
30387
+
30388
+ ALTER TABLE public.plg_crm_activities DROP CONSTRAINT IF EXISTS plg_crm_activities_unit_fk;
30389
+ ALTER TABLE public.plg_crm_activities
30390
+ ADD CONSTRAINT plg_crm_activities_unit_fk
30391
+ FOREIGN KEY (tenant_id, unit_id) REFERENCES app.units(tenant_id, id) ON DELETE SET NULL;
30392
+
30393
+ -- (tenant, unit) in the order the query asks: the policy filters the tenant
30394
+ -- first, and that prefix is what keeps the predicate out of a row-by-row loop.
30395
+ CREATE INDEX IF NOT EXISTS plg_crm_companies_unit_idx
30396
+ ON public.plg_crm_companies (tenant_id, unit_id);
30397
+ CREATE INDEX IF NOT EXISTS plg_crm_activities_unit_idx
30398
+ ON public.plg_crm_activities (tenant_id, unit_id);
30399
+
30400
+ -- \u2500\u2500 the activity inherits the unit of what it reports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
30401
+ --
30402
+ -- A loose activity (no deal, no lead) stays null: inventing its branch would
30403
+ -- hide somebody's phone call on a guess.
30404
+ UPDATE public.plg_crm_activities a
30405
+ SET unit_id = d.unit_id
30406
+ FROM public.plg_crm_deals d
30407
+ WHERE a.unit_id IS NULL AND a.deal_id = d.id AND d.unit_id IS NOT NULL;
30408
+
30409
+ UPDATE public.plg_crm_activities a
30410
+ SET unit_id = p.unit_id
30411
+ FROM public.people p
30412
+ WHERE a.unit_id IS NULL AND a.deal_id IS NULL
30413
+ AND a.lead_id = p.id AND p.unit_id IS NOT NULL;
30414
+
30415
+ -- \u2500\u2500 the fence \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
30416
+ --
30417
+ -- Same shape as the deal's policy (052): null passes, a unit asks
30418
+ -- \`app.has_unit\`. Additive \u2014 no row that was readable stops being readable.
30419
+ --
30420
+ -- The verb does not change here. Company stays on \`sales.read\`, activity stays
30421
+ -- on the tenant cut 012 wrote: widening permission and unit in one migration
30422
+ -- would be two changes with one test.
30423
+
30424
+ DROP POLICY IF EXISTS plg_crm_companies_authz_select ON public.plg_crm_companies;
30425
+ CREATE POLICY plg_crm_companies_authz_select ON public.plg_crm_companies
30426
+ FOR SELECT TO authenticated USING (
30427
+ tenant_id = (SELECT app.current_tenant_id())
30428
+ AND (unit_id IS NULL OR (SELECT app.has_unit(plg_crm_companies.unit_id)))
30429
+ AND (SELECT app.has_permission('sales.read', NULL::uuid)));
30430
+
30431
+ DROP POLICY IF EXISTS plg_crm_activities_select ON public.plg_crm_activities;
30432
+ CREATE POLICY plg_crm_activities_select ON public.plg_crm_activities
30433
+ FOR SELECT TO authenticated USING (
30434
+ tenant_id IN (SELECT user_tenant_ids())
30435
+ AND (unit_id IS NULL OR (SELECT app.has_unit(plg_crm_activities.unit_id))));
30436
+
30437
+ -- \u2500\u2500 the column reaches the view \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
30438
+ --
30439
+ -- Columns below are what 058 (v_deals), 054 (v_crm_leads) and 059
30440
+ -- (v_crm_companies_enriched) left, in the same order, plus \`unit_id\`.
30441
+
30442
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
30443
+ SELECT d.id,
30444
+ d.tenant_id,
30445
+ d.status,
30446
+ d.value,
30447
+ COALESCE(d.title, d.notes) AS title,
30448
+ d.contact_id,
30449
+ d.assigned_to_id,
30450
+ d.tags,
30451
+ COALESCE(pc.name, d.metadata ->> 'contactName'::text) AS contact_name,
30452
+ d.created_at,
30453
+ d.updated_at,
30454
+ d.pipeline_id,
30455
+ d.stage_id,
30456
+ d.probability,
30457
+ d.expected_close_date,
30458
+ d.lead_id,
30459
+ d.lost_reason,
30460
+ ps.name AS stage_name,
30461
+ ps.color AS stage_color,
30462
+ ps."order" AS stage_order,
30463
+ ps.name AS stage,
30464
+ d.won_at,
30465
+ d.lost_at,
30466
+ d.company_id,
30467
+ d.contact_status,
30468
+ d.contact_status_at,
30469
+ cs.name AS contact_status_name,
30470
+ cs.color AS contact_status_color,
30471
+ d.notes,
30472
+ cs.derived_from AS contact_status_derived_from,
30473
+ emp.name AS company_name,
30474
+ emp.document_number AS company_document,
30475
+ grp.group_id,
30476
+ grp.group_name,
30477
+ grp.group_companies,
30478
+ -- On the table since 052 and never here, so the board had no way to narrow
30479
+ -- without a second query per card.
30480
+ d.unit_id
30481
+ FROM plg_crm_deals d
30482
+ LEFT JOIN plg_crm_companies emp ON emp.id = d.company_id
30483
+ LEFT JOIN people pc ON pc.id = d.contact_id
30484
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
30485
+ LEFT JOIN LATERAL ( SELECT s.name,
30486
+ s.color,
30487
+ s.derived_from
30488
+ FROM plg_crm_deal_statuses s
30489
+ 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)
30490
+ ORDER BY (s.stage_id IS NOT NULL) DESC
30491
+ LIMIT 1) cs ON true
30492
+ LEFT JOIN LATERAL ( SELECT g.id AS group_id,
30493
+ g.name AS group_name,
30494
+ ( SELECT count(*)::integer AS count
30495
+ FROM plg_crm_company_group_members m2
30496
+ WHERE m2.group_id = g.id) AS group_companies
30497
+ FROM plg_crm_company_group_members m
30498
+ JOIN plg_crm_company_groups g ON g.id = m.group_id
30499
+ WHERE m.company_id = d.company_id AND m.tenant_id = d.tenant_id AND g.is_active
30500
+ ORDER BY m.created_at, m.id
30501
+ LIMIT 1) grp ON true;
30502
+
30503
+ GRANT SELECT ON public.v_deals TO authenticated, service_role;
30504
+
30505
+ CREATE OR REPLACE VIEW public.v_crm_leads WITH (security_invoker = true) AS
30506
+ SELECT l.id,
30507
+ l.tenant_id,
30508
+ l.name,
30509
+ l.email,
30510
+ l.phone,
30511
+ l.notes,
30512
+ l.tags,
30513
+ l.is_active,
30514
+ l.company,
30515
+ l.source_id,
30516
+ l.source_name,
30517
+ l.lead_status,
30518
+ l.lead_value,
30519
+ l.assigned_to_id,
30520
+ l.created_at,
30521
+ l.updated_at,
30522
+ l.form_id,
30523
+ l.custom_fields,
30524
+ l.utm,
30525
+ l.status,
30526
+ l.attachments,
30527
+ cp.company_id,
30528
+ cp.role AS company_role,
30529
+ c.name AS company_name,
30530
+ c.legal_name AS company_legal_name,
30531
+ c.document_number AS company_document,
30532
+ pess.instagram,
30533
+ pess.metadata ->> 'credential_company'::text AS credential_company,
30534
+ pess.metadata ->> 'phone_raw'::text AS phone_raw,
30535
+ pess.city,
30536
+ pess.state,
30537
+ -- From \`people\`, not \`v_leads\`: the spine's view does not expose it and is
30538
+ -- not this plugin's to widen \u2014 the reason 013 wrapped it instead.
30539
+ pess.unit_id
30540
+ FROM v_leads l
30541
+ LEFT JOIN people pess ON pess.id = l.id
30542
+ LEFT JOIN LATERAL ( SELECT x.company_id,
30543
+ x.role
30544
+ FROM plg_crm_company_people x
30545
+ WHERE x.person_id = l.id
30546
+ ORDER BY x.is_primary DESC, x.created_at
30547
+ LIMIT 1) cp ON true
30548
+ LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
30549
+
30550
+ GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
30551
+
30552
+ CREATE OR REPLACE VIEW public.v_crm_companies_enriched WITH (security_invoker = true) AS
30553
+ SELECT c.id,
30554
+ c.tenant_id,
30555
+ c.name,
30556
+ c.legal_name,
30557
+ c.document_number,
30558
+ c.document_kind,
30559
+ c.document_root,
30560
+ c.document_valid,
30561
+ c.email,
30562
+ c.phone,
30563
+ c.website,
30564
+ c.address,
30565
+ c.city,
30566
+ c.state,
30567
+ c.country,
30568
+ c.postal_code,
30569
+ c.tags,
30570
+ c.notes,
30571
+ c.metadata,
30572
+ c.custom_fields,
30573
+ c.owner_id,
30574
+ c.is_active,
30575
+ c.created_at,
30576
+ c.updated_at,
30577
+ COALESCE(p.people_count, 0) AS people_count,
30578
+ COALESCE(d.open_deals, 0) AS open_deals,
30579
+ COALESCE(d.won_value, 0::numeric) AS won_value,
30580
+ CASE
30581
+ WHEN c.document_root IS NULL THEN 0
30582
+ ELSE COALESCE(g.group_size, 1) - 1
30583
+ END AS group_siblings,
30584
+ c.instagram,
30585
+ c.unit_id
30586
+ FROM plg_crm_companies c
30587
+ LEFT JOIN LATERAL ( SELECT count(*)::integer AS people_count
30588
+ FROM plg_crm_company_people cp
30589
+ JOIN people pe ON pe.id = cp.person_id
30590
+ WHERE cp.company_id = c.id) p ON true
30591
+ LEFT JOIN LATERAL ( SELECT count(*) FILTER (WHERE dl.status = 'open'::text)::integer AS open_deals,
30592
+ COALESCE(sum(dl.value) FILTER (WHERE dl.status = 'won'::text), 0::numeric) AS won_value
30593
+ FROM plg_crm_deals dl
30594
+ WHERE dl.company_id = c.id) d ON true
30595
+ LEFT JOIN LATERAL ( SELECT count(*)::integer AS group_size
30596
+ FROM plg_crm_companies s
30597
+ WHERE s.tenant_id = c.tenant_id AND s.document_root = c.document_root) g ON true;
30598
+
30599
+ GRANT SELECT ON public.v_crm_companies_enriched TO authenticated, service_role;
30600
+
30601
+ -- \u2500\u2500 the row the visibility screen reads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
30602
+ --
30603
+ -- \`shareable\` on both: a book of business and a funnel cross branches on
30604
+ -- purpose. \`default_visibility\` is what the screen OFFERS on create \u2014 unit for
30605
+ -- the deal, which is born where somebody is selling; the whole tenant for the
30606
+ -- company, which is the same chain for both brands.
30607
+ INSERT INTO public.scoped_resources (resource_table, unit_column, owner_column, shareable, default_visibility, label)
30608
+ VALUES
30609
+ ('plg_crm_deals', 'unit_id', 'owner_id', true, 'unit', 'Neg\xF3cios'),
30610
+ ('plg_crm_companies', 'unit_id', 'owner_id', true, 'tenant', 'Empresas')
30611
+ ON CONFLICT (resource_table) DO UPDATE
30612
+ SET unit_column = EXCLUDED.unit_column,
30613
+ owner_column = EXCLUDED.owner_column,
30614
+ shareable = EXCLUDED.shareable,
30615
+ default_visibility = EXCLUDED.default_visibility,
30616
+ label = EXCLUDED.label;
30617
+ `;
30273
30618
  var MIGRATIONS = [
30274
30619
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
30275
30620
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -30331,7 +30676,8 @@ var MIGRATIONS = [
30331
30676
  { id: "058_o_card_diz_o_nome_do_grupo", sql: MIGRATION_058_O_CARD_DIZ_O_NOME_DO_GRUPO },
30332
30677
  { id: "059_a_empresa_mostra_o_instagram_que_ela_guarda", sql: MIGRATION_059_A_EMPRESA_MOSTRA_O_INSTAGRAM_QUE_ELA_GUARDA },
30333
30678
  { id: "060_o_funil_sabe_de_quem_ele_e", sql: MIGRATION_060_O_FUNIL_SABE_DE_QUEM_ELE_E },
30334
- { id: "061_a_conversao_respeita_o_filtro_do_quadro", sql: MIGRATION_061_A_CONVERSAO_RESPEITA_O_FILTRO_DO_QUADRO }
30679
+ { id: "061_a_conversao_respeita_o_filtro_do_quadro", sql: MIGRATION_061_A_CONVERSAO_RESPEITA_O_FILTRO_DO_QUADRO },
30680
+ { id: "062_the_whole_crm_says_which_unit_it_is", sql: MIGRATION_062_THE_WHOLE_CRM_SAYS_WHICH_UNIT_IT_IS }
30335
30681
  ];
30336
30682
 
30337
30683
  // src/locales/en.ts
@@ -32224,15 +32570,15 @@ var crmLocales = {
32224
32570
  var EMPTY_RULE = { column: "kind", op: "=", value: "lead" };
32225
32571
  function SegmentEditorDialog({ open, segment, provider, onClose, onSaved }) {
32226
32572
  const t2 = useTranslation();
32227
- const [name, setName] = React.useState("");
32228
- const [description, setDescription] = React.useState("");
32229
- const [isActive, setIsActive] = React.useState(true);
32230
- const [rules, setRules] = React.useState([EMPTY_RULE]);
32231
- const [saving, setSaving] = React.useState(false);
32232
- const [error, setError] = React.useState(null);
32233
- const [preview, setPreview] = React.useState(null);
32234
- const [previewing, setPreviewing] = React.useState(false);
32235
- React.useEffect(() => {
32573
+ const [name, setName] = React__default.useState("");
32574
+ const [description, setDescription] = React__default.useState("");
32575
+ const [isActive, setIsActive] = React__default.useState(true);
32576
+ const [rules, setRules] = React__default.useState([EMPTY_RULE]);
32577
+ const [saving, setSaving] = React__default.useState(false);
32578
+ const [error, setError] = React__default.useState(null);
32579
+ const [preview, setPreview] = React__default.useState(null);
32580
+ const [previewing, setPreviewing] = React__default.useState(false);
32581
+ React__default.useEffect(() => {
32236
32582
  if (!open) return;
32237
32583
  setName(segment?.name ?? "");
32238
32584
  setDescription(segment?.description ?? "");
@@ -32431,11 +32777,11 @@ function SegmentsView() {
32431
32777
  const can = usePermissionOptional();
32432
32778
  const canEdit = can("sales", "edit");
32433
32779
  const canDelete = can("sales", "delete");
32434
- const [segments, setSegments] = React.useState(null);
32435
- const [counts, setCounts] = React.useState({});
32436
- const [editing, setEditing] = React.useState(void 0);
32437
- const [removing, setRemoving] = React.useState(null);
32438
- const load = React.useCallback(async () => {
32780
+ const [segments, setSegments] = React__default.useState(null);
32781
+ const [counts, setCounts] = React__default.useState({});
32782
+ const [editing, setEditing] = React__default.useState(void 0);
32783
+ const [removing, setRemoving] = React__default.useState(null);
32784
+ const load = React__default.useCallback(async () => {
32439
32785
  const list = await provider.getSegments();
32440
32786
  setSegments(list);
32441
32787
  try {
@@ -32445,7 +32791,7 @@ function SegmentsView() {
32445
32791
  setCounts({});
32446
32792
  }
32447
32793
  }, [provider]);
32448
- React.useEffect(() => {
32794
+ React__default.useEffect(() => {
32449
32795
  void load();
32450
32796
  }, [load]);
32451
32797
  async function toggleActive(segment, next) {
@@ -32831,7 +33177,7 @@ function createCrmPlugin(options) {
32831
33177
  () => createMockCrmProvider({ activityTypes })
32832
33178
  );
32833
33179
  const store = createCrmStore(provider);
32834
- const PageComponent = () => React.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
33180
+ const PageComponent = () => React__default.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
32835
33181
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
32836
33182
  const vocab = customerVocabulary(options?.tenantVerticalId);
32837
33183
  const customerOne = config.labels.customersSingular ?? vocab.one;
@@ -33354,12 +33700,12 @@ function createCrmPlugin(options) {
33354
33700
  label: "Sales & CRM",
33355
33701
  icon: "Filter",
33356
33702
  component: (() => {
33357
- const Tab = () => React.createElement(
33703
+ const Tab = () => React__default.createElement(
33358
33704
  CrmContextProvider,
33359
33705
  { config, provider, store },
33360
- React.createElement(PluginSettingsPanel, {
33706
+ React__default.createElement(PluginSettingsPanel, {
33361
33707
  title: "Sales & CRM",
33362
- generalSettings: React.createElement(CrmGeneralSettings),
33708
+ generalSettings: React__default.createElement(CrmGeneralSettings),
33363
33709
  // Segmento é CADASTRO, e mora onde os outros moram. Etapas do
33364
33710
  // funil, origens, parcerias e tags já estão aqui; ter o recorte
33365
33711
  // fora, no rail de trabalho diário, era a inconsistência.
@@ -33367,7 +33713,7 @@ function createCrmPlugin(options) {
33367
33713
  id: "segments",
33368
33714
  label: "Segmentos",
33369
33715
  icon: "Filter",
33370
- content: React.createElement(SegmentsView)
33716
+ content: React__default.createElement(SegmentsView)
33371
33717
  }],
33372
33718
  registries: crmRegistries2,
33373
33719
  hostPluginId: "crm",