@fayz-ai/plugin-crm 0.24.0 → 0.26.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.
@@ -1 +1 @@
1
- {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA4S9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CAouElB"}
1
+ {"version":3,"file":"supabase.d.ts","sourceRoot":"","sources":["../../src/data/supabase.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,SAAS,CAAA;AA4S9C,wBAAgB,yBAAyB,CAAC,OAAO,CAAC,EAAE;IAClD,gBAAgB,CAAC,EAAE;QAAE,aAAa,EAAE,MAAM,CAAC;QAAC,cAAc,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAA;IACtF,kFAAkF;IAClF,aAAa,CAAC,EAAE,KAAK,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;CACvE,GAAG,eAAe,CA+vElB"}
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, useRecordVisit, 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(
@@ -3361,7 +3362,13 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3361
3362
  if (!o) onClose();
3362
3363
  }, children: /* @__PURE__ */ jsxs(ModalContent, { size: "5xl", noPadding: true, children: [
3363
3364
  /* @__PURE__ */ jsxs(ModalHeader, { className: "flex-row items-center justify-between gap-3 border-b px-5 py-3.5", children: [
3364
- /* @__PURE__ */ jsx(ModalTitle, { className: "truncate text-base", children: loading ? t2("crm.leadDetail.loading") : deal?.title ?? t2("crm.dealSidebar.deal") }),
3365
+ /* @__PURE__ */ jsxs(ModalTitle, { className: "min-w-0 truncate text-base", children: [
3366
+ loading ? t2("crm.leadDetail.loading") : deal?.companyName || deal?.title || t2("crm.dealSidebar.deal"),
3367
+ !loading && deal?.companyName && deal?.contactName && /* @__PURE__ */ jsxs("span", { className: "ml-2 truncate text-sm font-normal text-muted-foreground", children: [
3368
+ "\xB7 ",
3369
+ deal.contactName
3370
+ ] })
3371
+ ] }),
3365
3372
  /* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-2 pr-8", children: [
3366
3373
  deal?.status === "open" ? /* @__PURE__ */ jsxs(Fragment, { children: [
3367
3374
  /* @__PURE__ */ jsxs(Button, { size: "sm", variant: "outline", disabled: closing, onClick: () => {
@@ -3909,15 +3916,15 @@ function LeadListView({ onNew, onEdit }) {
3909
3916
  const fetchLeads = useCrmStore((s) => s.fetchLeads);
3910
3917
  const updateLead = useCrmStore((s) => s.updateLead);
3911
3918
  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([]);
3919
+ const [search, setSearch] = usePersistedState("crm.leads.search", "");
3920
+ const [statusFilter, setStatusFilter] = usePersistedState("crm.leads.status", []);
3921
+ const [sourceFilter, setSourceFilter] = usePersistedState("crm.leads.source", void 0);
3922
+ const [tagFilter, setTagFilter] = usePersistedState("crm.leads.tags", []);
3916
3923
  const [team, setTeam] = useState(null);
3917
3924
  const [myUserId, setMyUserId] = useState(null);
3918
- const [ownerFilter, setOwnerFilter] = useState();
3919
- const [reachFilter, setReachFilter] = useState();
3920
- const [companyFilter, setCompanyFilter] = useState();
3925
+ const [ownerFilter, setOwnerFilter] = usePersistedState("crm.leads.owner", void 0);
3926
+ const [reachFilter, setReachFilter] = usePersistedState("crm.leads.reach", void 0);
3927
+ const [companyFilter, setCompanyFilter] = usePersistedState("crm.leads.company", void 0);
3921
3928
  const leadSources = useCrmStore((s) => s.leadSources);
3922
3929
  const fetchLeadSources = useCrmStore((s) => s.fetchLeadSources);
3923
3930
  const tagDefs = useCrmStore((s) => s.tagDefs);
@@ -3928,7 +3935,7 @@ function LeadListView({ onNew, onEdit }) {
3928
3935
  }, []);
3929
3936
  const [archiveTarget, setArchiveTarget] = useState(null);
3930
3937
  const [bulkBusy, setBulkBusy] = useState(false);
3931
- const [page, setPage] = useState(1);
3938
+ const [page, setPage] = usePersistedState("crm.leads.page", 1);
3932
3939
  const PAGE_SIZE2 = 50;
3933
3940
  const [scores, setScores] = useState(/* @__PURE__ */ new Map());
3934
3941
  useEffect(() => {
@@ -4218,7 +4225,8 @@ function LeadListView({ onNew, onEdit }) {
4218
4225
  }
4219
4226
  )
4220
4227
  ] });
4221
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4228
+ const ancoraRolagem = useScrollMemory("crm.leads");
4229
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
4222
4230
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
4223
4231
  /* @__PURE__ */ jsx(
4224
4232
  ListView,
@@ -4514,7 +4522,8 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
4514
4522
  );
4515
4523
  toast.success(t2("crud.export.toastSuccess", { count: String(quotes2.length) }));
4516
4524
  }, [quotes2, currency, t2]);
4517
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4525
+ const ancoraRolagem = useScrollMemory("crm.quotes");
4526
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
4518
4527
  /* @__PURE__ */ jsx(
4519
4528
  SubpageHeader,
4520
4529
  {
@@ -5646,7 +5655,10 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5646
5655
  FieldRow,
5647
5656
  {
5648
5657
  label: t2("crm.leadDetail.phone"),
5649
- value: lead.phone ? /* @__PURE__ */ jsx(PhoneLink, { phone: lead.phone, className: "text-primary" }) : null
5658
+ 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: [
5659
+ /* @__PURE__ */ jsx("span", { className: "tabular-nums", children: lead.phoneRaw }),
5660
+ /* @__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") })
5661
+ ] }) : null
5650
5662
  }
5651
5663
  ) }),
5652
5664
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
@@ -5674,6 +5686,13 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5674
5686
  )
5675
5687
  }
5676
5688
  ) }),
5689
+ 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(
5690
+ FieldRow,
5691
+ {
5692
+ label: t2("crm.leadDetail.credentialCompany"),
5693
+ value: /* @__PURE__ */ jsx("span", { children: lead.credentialCompany })
5694
+ }
5695
+ ) }),
5677
5696
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b md:last:border-b-0", children: /* @__PURE__ */ jsx(
5678
5697
  FieldRow,
5679
5698
  {
@@ -5867,7 +5886,7 @@ function CompanyListView({ onNew, onEdit }) {
5867
5886
  const companiesLoading = useCrmStore((s) => s.companiesLoading);
5868
5887
  const fetchCompanies = useCrmStore((s) => s.fetchCompanies);
5869
5888
  const archiveCompany = useCrmStore((s) => s.archiveCompany);
5870
- const [search, setSearch] = useState("");
5889
+ const [search, setSearch] = usePersistedState("crm.companies.search", "");
5871
5890
  const [archiveTarget, setArchiveTarget] = useState(null);
5872
5891
  const [bulkBusy, setBulkBusy] = useState(false);
5873
5892
  const columns = useMemo(() => buildColumns2(t2), [t2]);
@@ -5893,7 +5912,8 @@ function CompanyListView({ onNew, onEdit }) {
5893
5912
  { key: "state", label: t2("crm.companyForm.state") },
5894
5913
  { key: "peopleCount", label: t2("crm.companies.peopleCol") }
5895
5914
  ], companies, "empresas.csv");
5896
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
5915
+ const ancoraRolagem = useScrollMemory("crm.companies");
5916
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
5897
5917
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.companies.title") }),
5898
5918
  /* @__PURE__ */ jsx(
5899
5919
  ListView,
@@ -6296,7 +6316,8 @@ function CompanyDetailView({
6296
6316
  onBack,
6297
6317
  onEdit,
6298
6318
  onOpenLead,
6299
- onOpenCompany
6319
+ onOpenCompany,
6320
+ onOpenDeal
6300
6321
  }) {
6301
6322
  const t2 = useTranslation();
6302
6323
  const { currency } = useCrmConfig();
@@ -6537,17 +6558,30 @@ function CompanyDetailView({
6537
6558
  /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.companyDetail.deals") }),
6538
6559
  /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card shadow-sm divide-y", children: [
6539
6560
  deals.length === 0 && /* @__PURE__ */ jsx("p", { className: "px-5 py-4 text-sm text-muted-foreground", children: t2("crm.companyDetail.noDeals") }),
6540
- deals.map((d) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-3 px-5 py-3", children: [
6541
- /* @__PURE__ */ jsxs("span", { className: "flex flex-col", children: [
6542
- /* @__PURE__ */ jsx("span", { className: "text-sm", children: d.title }),
6543
- /* @__PURE__ */ jsxs("span", { className: "text-[11px] text-muted-foreground", children: [
6544
- d.stageName,
6545
- " \xB7 ",
6546
- formatRelativeTime(d.createdAt)
6547
- ] })
6548
- ] }),
6549
- /* @__PURE__ */ jsx("span", { className: "text-sm tabular-nums", children: formatCurrency(d.value, currency) })
6550
- ] }, d.id))
6561
+ deals.map((d) => {
6562
+ const conteudo = /* @__PURE__ */ jsxs(Fragment, { children: [
6563
+ /* @__PURE__ */ jsxs("span", { className: "flex flex-col text-left", children: [
6564
+ /* @__PURE__ */ jsx("span", { className: "text-sm", children: d.title }),
6565
+ /* @__PURE__ */ jsxs("span", { className: "text-[11px] text-muted-foreground", children: [
6566
+ d.stageName,
6567
+ " \xB7 ",
6568
+ formatRelativeTime(d.createdAt)
6569
+ ] })
6570
+ ] }),
6571
+ /* @__PURE__ */ jsx("span", { className: "text-sm tabular-nums", children: formatCurrency(d.value, currency) })
6572
+ ] });
6573
+ const classe = "flex w-full items-center justify-between gap-3 px-5 py-3";
6574
+ return onOpenDeal ? /* @__PURE__ */ jsx(
6575
+ "button",
6576
+ {
6577
+ type: "button",
6578
+ onClick: () => onOpenDeal(d.id),
6579
+ className: `${classe} text-left transition-colors hover:bg-muted/40`,
6580
+ children: conteudo
6581
+ },
6582
+ d.id
6583
+ ) : /* @__PURE__ */ jsx("div", { className: classe, children: conteudo }, d.id);
6584
+ })
6551
6585
  ] })
6552
6586
  ] }),
6553
6587
  /* @__PURE__ */ jsx(
@@ -6857,7 +6891,7 @@ function ActivityListView({ onOpenLead, onOpenQuote, onOpenDeal } = {}) {
6857
6891
  const activities = useCrmStore((s) => s.activities);
6858
6892
  const activitiesLoading = useCrmStore((s) => s.activitiesLoading);
6859
6893
  const fetchActivities = useCrmStore((s) => s.fetchActivities);
6860
- const [typeFilter, setTypeFilter] = useState(null);
6894
+ const [typeFilter, setTypeFilter] = usePersistedState("crm.activities.type", null);
6861
6895
  const [showCompleted, setShowCompleted] = useState(null);
6862
6896
  const eventsFilter = typeFilter === "events";
6863
6897
  useEffect(() => {
@@ -6887,7 +6921,8 @@ function ActivityListView({ onOpenLead, onOpenQuote, onOpenDeal } = {}) {
6887
6921
  );
6888
6922
  toast.success(t2("crud.export.toastSuccess", { count: String(filtered.length) }));
6889
6923
  }, [filtered, t2]);
6890
- return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
6924
+ const ancoraRolagem = useScrollMemory("crm.activities");
6925
+ return /* @__PURE__ */ jsxs("div", { ref: ancoraRolagem, className: "space-y-4", children: [
6891
6926
  /* @__PURE__ */ jsx(
6892
6927
  SubpageHeader,
6893
6928
  {
@@ -8416,7 +8451,8 @@ function CrmPage({ config, provider, store, registries }) {
8416
8451
  onBack: () => navigate("companies-list"),
8417
8452
  onEdit: (cid) => navigate(`companies-edit:${cid}`),
8418
8453
  onOpenLead: (lid) => navigate(`leads-detail:${lid}`),
8419
- onOpenCompany: (cid) => navigate(`companies-detail:${cid}`)
8454
+ onOpenCompany: (cid) => navigate(`companies-detail:${cid}`),
8455
+ onOpenDeal: (did) => navigate(`pipeline-detail:${did}`, `/sales/pipeline/${did}`)
8420
8456
  }
8421
8457
  ) },
8422
8458
  { id: "surveys", render: () => /* @__PURE__ */ jsx(SurveysView, {}) },
@@ -10542,6 +10578,8 @@ function createSupabaseCrmProvider(options) {
10542
10578
  companyId: r.company_id ?? void 0,
10543
10579
  companyName: r.company_name ?? void 0,
10544
10580
  companyRole: r.company_role ?? void 0,
10581
+ credentialCompany: r.credential_company ?? void 0,
10582
+ phoneRaw: r.phone_raw ?? void 0,
10545
10583
  sourceId: r.source_id,
10546
10584
  sourceName: r.source_name,
10547
10585
  status: r.lead_status ?? "new",
@@ -12158,9 +12196,17 @@ function createSupabaseCrmProvider(options) {
12158
12196
  const { pub } = getClients();
12159
12197
  const tenantId = getTenantId();
12160
12198
  if (!tenantId) throw new Error("no tenant");
12161
- const { data: group, error } = await pub.from(T.companyGroups).insert({ tenant_id: tenantId, name, document_root: documentRoot2 ?? null, is_active: true }).select("id").single();
12162
- if (error) throw new Error(error.message);
12163
- const { error: e2 } = await pub.from(T.companyGroupMembers).insert(
12199
+ let group = null;
12200
+ if (documentRoot2) {
12201
+ const { data: existente } = await pub.from(T.companyGroups).select("id").eq("tenant_id", tenantId).eq("document_root", documentRoot2).maybeSingle();
12202
+ if (existente) group = existente;
12203
+ }
12204
+ if (!group) {
12205
+ const { data: criado, error } = await pub.from(T.companyGroups).insert({ tenant_id: tenantId, name, document_root: documentRoot2 ?? null, is_active: true }).select("id").single();
12206
+ if (error) throw new Error(error.message);
12207
+ group = criado;
12208
+ }
12209
+ const { error: e2 } = await pub.from(T.companyGroupMembers).upsert(
12164
12210
  companyIds.map((cid) => ({
12165
12211
  tenant_id: tenantId,
12166
12212
  group_id: group.id,
@@ -12176,7 +12222,8 @@ function createSupabaseCrmProvider(options) {
12176
12222
  // `plg_crm_company_group_members_source_check` na cara de quem
12177
12223
  // clicava. O banco é quem define este vocabulário.
12178
12224
  source: documentRoot2 ? "document_root" : "manual"
12179
- }))
12225
+ })),
12226
+ { onConflict: "group_id,company_id", ignoreDuplicates: true }
12180
12227
  );
12181
12228
  if (e2) throw new Error(e2.message);
12182
12229
  return group.id;
@@ -25454,6 +25501,166 @@ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25454
25501
  LIMIT 1) cp ON true
25455
25502
  LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
25456
25503
 
25504
+ GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25505
+ `;
25506
+ var MIGRATION_050_A_REUNIAO_E_UMA_ESPECIE_DECLARADA = `-- ---------------------------------------------------------------------------
25507
+ -- 050_a_reuniao_e_uma_especie_declarada.sql
25508
+ --
25509
+ -- \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
25510
+ --
25511
+ -- Marcar uma reuni\xE3o falhava com:
25512
+ --
25513
+ -- order_create: meeting is not a registered order kind
25514
+ -- HINT: public.order_kinds is the vocabulary; a plugin declares its own species.
25515
+ --
25516
+ -- O tipo de compromisso "Reuni\xE3o" foi declarado no APP (\`bookingTypes\`), e o
25517
+ -- app \xE9 quem decide o que a tela oferece. Mas \`kind\` n\xE3o \xE9 r\xF3tulo de tela: \xE9
25518
+ -- esp\xE9cie, e esp\xE9cie tem registro com chave estrangeira atr\xE1s. Um tipo que a
25519
+ -- tela oferece e o banco n\xE3o conhece \xE9 um bot\xE3o que s\xF3 falha no fim.
25520
+ --
25521
+ -- \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
25522
+ --
25523
+ -- \`agenda_booking_create\` grava em duas: o COMPROMISSO (\`appointments.kind\` \u2192
25524
+ -- \`appointment_kinds\`) e a VENDA que ele carrega (\`orders.kind\` \u2192
25525
+ -- \`order_kinds\`). Na agenda o compromisso \xC9 um pedido \u2014 \xE9 o que faz uma
25526
+ -- consulta virar fatura sem ningu\xE9m redigitar nada.
25527
+ --
25528
+ -- Registrar s\xF3 numa das duas \xE9 exatamente o estado em que isto estava: a
25529
+ -- esp\xE9cie existia para o compromisso e n\xE3o para a venda, ent\xE3o a primeira
25530
+ -- metade da transa\xE7\xE3o passava e a segunda derrubava tudo.
25531
+ --
25532
+ -- \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
25533
+ --
25534
+ -- Foi \xE0 m\xE3o que a \`appointment_kinds\` ganhou \`meeting\` \u2014 em produ\xE7\xE3o, no meio
25535
+ -- de uma sess\xE3o, sem arquivo. O cluster ficou certo e a corrente ficou errada:
25536
+ -- quem constru\xEDsse do zero teria a tela oferecendo "Reuni\xE3o" e o banco sem
25537
+ -- saber o que \xE9. Isto p\xF5e as duas no mesmo lugar, de onde saem juntas.
25538
+ --
25539
+ -- \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
25540
+ --
25541
+ -- Reuni\xE3o comercial \xE9 vocabul\xE1rio de quem vende. \`plugin-agenda\` serve sal\xE3o e
25542
+ -- cl\xEDnica, e nenhum dos dois marca "reuni\xE3o" \u2014 declarar ali obrigaria as duas
25543
+ -- verticais a carregar uma esp\xE9cie que n\xE3o usam. \xC9 a mesma raz\xE3o pela qual o
25544
+ -- \`appointment_kinds.meeting\` j\xE1 nasceu com \`plugin = 'crm'\`.
25545
+ --
25546
+ -- \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
25547
+ --
25548
+ -- Copiados de \`appointment\`, a esp\xE9cie irm\xE3, e n\xE3o inventados: quem escolhe
25549
+ -- "Ganho" numa reuni\xE3o espera o mesmo vocabul\xE1rio de estados que j\xE1 usa no
25550
+ -- resto da agenda, e um conjunto pr\xF3prio faria a mesma tela dizer coisas
25551
+ -- diferentes dependendo da aba.
25552
+ --
25553
+ -- Idempotente e replay-safe.
25554
+ -- ---------------------------------------------------------------------------
25555
+
25556
+ -- A esp\xE9cie do COMPROMISSO.
25557
+ INSERT INTO public.appointment_kinds (kind, plugin, description, statuses, transitions)
25558
+ VALUES (
25559
+ 'meeting',
25560
+ 'crm',
25561
+ 'Uma reuni\xE3o comercial (demo, discovery): compromisso sem servi\xE7o a entregar, com pessoas na sala em vez de um executor.',
25562
+ ARRAY['scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show']::text[],
25563
+ '{"*": ["*"], "no_show": [], "cancelled": []}'::jsonb
25564
+ )
25565
+ ON CONFLICT (kind) DO NOTHING;
25566
+
25567
+ -- A esp\xE9cie da VENDA que o compromisso carrega. \xC9 esta que faltava.
25568
+ INSERT INTO public.order_kinds (kind, plugin, description, statuses, transitions)
25569
+ VALUES (
25570
+ 'meeting',
25571
+ 'crm',
25572
+ '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.',
25573
+ ARRAY['scheduled', 'confirmed', 'in_progress', 'completed', 'cancelled', 'no_show', 'invoiced', 'paid', 'waiting']::text[],
25574
+ '{"*": ["*"], "paid": [], "no_show": [], "cancelled": []}'::jsonb
25575
+ )
25576
+ ON CONFLICT (kind) DO NOTHING;
25577
+
25578
+ COMMENT ON TABLE public.order_kinds IS
25579
+ '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).';
25580
+ `;
25581
+ var MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM = `-- ---------------------------------------------------------------------------
25582
+ -- 051_o_cracha_e_o_telefone_recusado_aparecem.sql
25583
+ --
25584
+ -- \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
25585
+ --
25586
+ -- A importa\xE7\xE3o do Sal\xE3o Abrasel guardou duas coisas no \`metadata\` da pessoa e
25587
+ -- nenhuma tela as l\xEA:
25588
+ --
25589
+ -- \`credential_company\` o NOME DA EMPRESA NA CREDENCIAL
25590
+ -- \`phone_raw\` o telefone que a valida\xE7\xE3o recusou
25591
+ --
25592
+ -- Em 27 dos 297 leads o crach\xE1 nomeia um estabelecimento DIFERENTE da empresa
25593
+ -- ligada, porque o v\xEDnculo foi feito pelo CNPJ declarado e o CNPJ nem sempre \xE9
25594
+ -- o do lugar que a pessoa toca \u2014 duas s\xF3cias do "Tata gastro bar" digitaram o
25595
+ -- CNPJ da Abrasel-GO, a associa\xE7\xE3o a que pertencem, e ficaram ligadas a ela.
25596
+ --
25597
+ -- E quatro telefones foram recusados de prop\xF3sito (dois com c\xF3digo de pa\xEDs
25598
+ -- estrangeiro, dois com um d\xEDgito a mais). A decis\xE3o est\xE1 certa: telefone
25599
+ -- errado no CRM \xE9 pior que nenhum. Guardar o valor cru e N\xC3O mostr\xE1-lo \xE9 que
25600
+ -- n\xE3o est\xE1 \u2014 a tela diz "\u2014" enquanto o dado existe no banco.
25601
+ --
25602
+ -- \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
25603
+ --
25604
+ -- Os dois j\xE1 existem, escritos pela importa\xE7\xE3o. Isto n\xE3o cria dado: abre a
25605
+ -- porta para o que est\xE1 atr\xE1s dela. \xC9 o mesmo movimento da 049 com o @.
25606
+ --
25607
+ -- Idempotente e replay-safe: a 013 DERRUBA esta view antes de cri\xE1-la, ent\xE3o
25608
+ -- alarg\xE1-la aqui n\xE3o quebra o replay dela \u2014 que foi exatamente o erro que a
25609
+ -- primeira vers\xE3o da 049 cometeu com a \`v_leads\`.
25610
+ -- ---------------------------------------------------------------------------
25611
+
25612
+ DROP VIEW IF EXISTS public.v_crm_leads;
25613
+ CREATE VIEW public.v_crm_leads WITH (security_invoker = true) AS
25614
+ SELECT l.id,
25615
+ l.tenant_id,
25616
+ l.name,
25617
+ l.email,
25618
+ l.phone,
25619
+ l.notes,
25620
+ l.tags,
25621
+ l.is_active,
25622
+ l.company,
25623
+ l.source_id,
25624
+ l.source_name,
25625
+ l.lead_status,
25626
+ l.lead_value,
25627
+ l.assigned_to_id,
25628
+ l.created_at,
25629
+ l.updated_at,
25630
+ l.form_id,
25631
+ l.custom_fields,
25632
+ l.utm,
25633
+ l.status,
25634
+ l.attachments,
25635
+ cp.company_id,
25636
+ cp.role AS company_role,
25637
+ c.name AS company_name,
25638
+ c.legal_name AS company_legal_name,
25639
+ c.document_number AS company_document,
25640
+ pess.instagram,
25641
+ -- 051: o que a planilha trouxe e a tela n\xE3o mostrava.
25642
+ --
25643
+ -- \`credential_company\` \xE9 o NOME DA EMPRESA NA CREDENCIAL \u2014 o que a pessoa
25644
+ -- escreveu no crach\xE1, que \xE9 o estabelecimento que ela toca. Em 27 casos
25645
+ -- ele diverge do CNPJ declarado, e o CNPJ \xE9 o que virou v\xEDnculo: duas
25646
+ -- s\xF3cias do Tata gastro bar ficaram ligadas \xE0 Abrasel-GO porque foi esse
25647
+ -- o CNPJ que digitaram.
25648
+ --
25649
+ -- \`phone_raw\` \xE9 o telefone que a importa\xE7\xE3o RECUSOU por n\xE3o virar n\xFAmero
25650
+ -- v\xE1lido. Guard\xE1-lo e n\xE3o mostr\xE1-lo \xE9 o pior dos dois mundos: a tela diz
25651
+ -- "\u2014" enquanto o dado est\xE1 no banco.
25652
+ pess.metadata ->> 'credential_company'::text AS credential_company,
25653
+ pess.metadata ->> 'phone_raw'::text AS phone_raw
25654
+ FROM v_leads l
25655
+ LEFT JOIN people pess ON pess.id = l.id
25656
+ LEFT JOIN LATERAL ( SELECT x.company_id,
25657
+ x.role
25658
+ FROM plg_crm_company_people x
25659
+ WHERE x.person_id = l.id
25660
+ ORDER BY x.is_primary DESC, x.created_at
25661
+ LIMIT 1) cp ON true
25662
+ LEFT JOIN plg_crm_companies c ON c.id = cp.company_id;
25663
+
25457
25664
  GRANT SELECT ON public.v_crm_leads TO authenticated, service_role;
25458
25665
  `;
25459
25666
  var MIGRATIONS = [
@@ -25505,7 +25712,9 @@ var MIGRATIONS = [
25505
25712
  { 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 },
25506
25713
  { id: "047_o_dono_do_lead_tem_um_lugar_so", sql: MIGRATION_047_O_DONO_DO_LEAD_TEM_UM_LUGAR_SO },
25507
25714
  { id: "048_a_empresa_tambem_tem_um_arroba", sql: MIGRATION_048_A_EMPRESA_TAMBEM_TEM_UM_ARROBA },
25508
- { id: "049_o_arroba_chega_ate_a_lista", sql: MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA }
25715
+ { id: "049_o_arroba_chega_ate_a_lista", sql: MIGRATION_049_O_ARROBA_CHEGA_ATE_A_LISTA },
25716
+ { id: "050_a_reuniao_e_uma_especie_declarada", sql: MIGRATION_050_A_REUNIAO_E_UMA_ESPECIE_DECLARADA },
25717
+ { id: "051_o_cracha_e_o_telefone_recusado_aparecem", sql: MIGRATION_051_O_CRACHA_E_O_TELEFONE_RECUSADO_APARECEM }
25509
25718
  ];
25510
25719
 
25511
25720
  // src/locales/en.ts
@@ -25576,6 +25785,8 @@ var en = {
25576
25785
  "crm.leadDetail.backToList": "Back to list",
25577
25786
  "crm.leadDetail.formAnswers": "Form answers",
25578
25787
  "crm.leadDetail.attachments": "Attachments",
25788
+ "crm.leadDetail.credentialCompany": "Company on badge",
25789
+ "crm.leadDetail.phoneUnverified": "unverified",
25579
25790
  "crm.leadDetail.company": "Company",
25580
25791
  "crm.leadDetail.contactInfo": "Contact Information",
25581
25792
  "crm.leadDetail.createQuote": "Create Quote",
@@ -26371,6 +26582,8 @@ var ptBR = {
26371
26582
  "crm.leadDetail.backToList": "Voltar \xE0 lista",
26372
26583
  "crm.leadDetail.formAnswers": "Dados do formul\xE1rio",
26373
26584
  "crm.leadDetail.attachments": "Anexos",
26585
+ "crm.leadDetail.credentialCompany": "Empresa no crach\xE1",
26586
+ "crm.leadDetail.phoneUnverified": "n\xE3o validado",
26374
26587
  "crm.leadDetail.company": "Empresa",
26375
26588
  "crm.leadDetail.contactInfo": "Informa\xE7\xF5es de Contato",
26376
26589
  "crm.leadDetail.createQuote": "Criar Or\xE7amento",