@fayz-ai/plugin-crm 0.15.0 → 0.16.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,8 +1,8 @@
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
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';
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, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Building2, Link2, Star, MessageSquareQuote, Search, SignalHigh, CalendarRange, Tag, ChevronLeft, TrendingDown, ThumbsDown, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Fingerprint, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, Clipboard, DollarSign, User, ThumbsUp } from 'lucide-react';
5
- import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, SegmentedControl, PageHeaderActions, ListView, Modal, ModalContent, ModalHeader, ModalTitle, ModalBody, Input, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, ModalFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, SheetBody, SheetFooter, DashboardCanvas, ModalDescription, Card, FilterChip, CurrencyInput, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, PageToolbar, ToolbarButton, RangeControl, Popover, PopoverTrigger, PopoverContent, getLucideIcon, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
4
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, PhoneCall, MoveRight, Target, ArrowRightLeft, UserPlus, MapPin, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, ArrowUp, ArrowDown, X, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Tag, User, Building2, Download, Inbox, Play, Clock, Sparkles, Calendar, ArrowRight, ChevronDown, Printer, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Loader2, Network, Link2, Star, MessageSquareQuote, Search, SignalHigh, CalendarRange, ChevronLeft, TrendingDown, ThumbsDown, UserCheck, AlertTriangle, Settings2, Repeat, Zap, Snowflake, Sun, Flame, Merge, Fingerprint, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, Clipboard, DollarSign, ThumbsUp } from 'lucide-react';
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, PageToolbar, ToolbarButton, RangeControl, Popover, PopoverTrigger, PopoverContent, getLucideIcon, normalizePhone, KpiCard, ChartWidget, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
6
6
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
@@ -1108,7 +1108,7 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
1108
1108
  children: formatRelativeTime(deal.createdAt, currency.locale)
1109
1109
  }
1110
1110
  ) : /* @__PURE__ */ jsx("span", {}),
1111
- deal.contactStatusName && /* @__PURE__ */ jsxs(
1111
+ deal.contactStatusName && deal.contactStatusDerivedFrom !== "no_activity" && /* @__PURE__ */ jsxs(
1112
1112
  "span",
1113
1113
  {
1114
1114
  className: "inline-flex shrink-0 items-center gap-1 rounded-full px-1.5 py-0.5 text-[9px] font-medium",
@@ -1127,24 +1127,35 @@ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragS
1127
1127
  }
1128
1128
  );
1129
1129
  }
1130
- function StageCards({ stageId, deals, savingDealIds, currency, tagDefs, onDealClick, onArchiveDeal, onDragStart, onDragEnd }) {
1131
- return /* @__PURE__ */ jsx(Fragment, { children: deals.map((deal) => /* @__PURE__ */ jsx(
1132
- DealCard,
1133
- {
1134
- deal,
1135
- saving: savingDealIds.has(deal.id),
1136
- currency,
1137
- tagDefs,
1138
- onClick: () => onDealClick?.(deal.id),
1139
- onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
1140
- onDragStart: (e) => {
1141
- e.dataTransfer.effectAllowed = "move";
1142
- onDragStart(deal.id, stageId);
1130
+ function StageCards({ stageId, deals, total, onLoadMore, loadMoreLabel, savingDealIds, currency, tagDefs, onDealClick, onArchiveDeal, onDragStart, onDragEnd }) {
1131
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
1132
+ deals.map((deal) => /* @__PURE__ */ jsx(
1133
+ DealCard,
1134
+ {
1135
+ deal,
1136
+ saving: savingDealIds.has(deal.id),
1137
+ currency,
1138
+ tagDefs,
1139
+ onClick: () => onDealClick?.(deal.id),
1140
+ onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
1141
+ onDragStart: (e) => {
1142
+ e.dataTransfer.effectAllowed = "move";
1143
+ onDragStart(deal.id, stageId);
1144
+ },
1145
+ onDragEnd
1143
1146
  },
1144
- onDragEnd
1145
- },
1146
- deal.id
1147
- )) });
1147
+ deal.id
1148
+ )),
1149
+ onLoadMore && total !== void 0 && total > deals.length && /* @__PURE__ */ jsx(
1150
+ "button",
1151
+ {
1152
+ type: "button",
1153
+ onClick: onLoadMore,
1154
+ className: "w-full rounded-card border border-dashed border-border py-2 text-xs font-medium text-muted-foreground transition-colors hover:border-primary/40 hover:bg-muted hover:text-foreground",
1155
+ children: loadMoreLabel?.(total - deals.length) ?? `+${total - deals.length}`
1156
+ }
1157
+ )
1158
+ ] });
1148
1159
  }
1149
1160
  function PipelineView({ onDealClick, onAddLead, onOpenSettings }) {
1150
1161
  const { currency } = useCrmConfig();
@@ -1152,6 +1163,8 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings }) {
1152
1163
  const activePipelineId = useCrmStore((s) => s.activePipelineId);
1153
1164
  const stages = useCrmStore((s) => s.stages);
1154
1165
  const dealsByStage = useCrmStore((s) => s.dealsByStage);
1166
+ const dealStageTotals = useCrmStore((s) => s.dealStageTotals);
1167
+ const loadMoreStage = useCrmStore((s) => s.loadMoreStage);
1155
1168
  const dealsLoading = useCrmStore((s) => s.dealsLoading);
1156
1169
  const pipelinesLoading = useCrmStore((s) => s.pipelinesLoading);
1157
1170
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
@@ -1327,7 +1340,7 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings }) {
1327
1340
  color: stage.color,
1328
1341
  emptyLabel: dragOverStageId === stage.id ? t2("crm.pipeline.dropHere") : t2("crm.pipeline.noDeals")
1329
1342
  })),
1330
- count: (col) => (displayBoard.get(col.id) ?? []).length,
1343
+ count: (col) => query ? (displayBoard.get(col.id) ?? []).length : dealStageTotals.get(col.id) ?? (displayBoard.get(col.id) ?? []).length,
1331
1344
  isOver: (col) => dragOverStageId === col.id,
1332
1345
  columnAction: onAddLead ? () => /* @__PURE__ */ jsx(
1333
1346
  "button",
@@ -1353,6 +1366,11 @@ function PipelineView({ onDealClick, onAddLead, onOpenSettings }) {
1353
1366
  {
1354
1367
  stageId: col.id,
1355
1368
  deals: displayBoard.get(col.id) ?? [],
1369
+ total: query ? void 0 : dealStageTotals.get(col.id),
1370
+ onLoadMore: query ? void 0 : () => {
1371
+ void loadMoreStage(col.id);
1372
+ },
1373
+ loadMoreLabel: (faltam) => t2("crm.pipeline.loadMore").replace("{n}", String(faltam)),
1356
1374
  savingDealIds,
1357
1375
  currency,
1358
1376
  tagDefs,
@@ -2543,6 +2561,16 @@ async function loadTeamOrNull() {
2543
2561
  return null;
2544
2562
  }
2545
2563
  }
2564
+ async function loadMyUserId() {
2565
+ const supabase = getSupabaseClientOptional();
2566
+ if (!supabase) return null;
2567
+ try {
2568
+ const { data } = await supabase.auth.getUser();
2569
+ return data?.user?.id ?? null;
2570
+ } catch {
2571
+ return null;
2572
+ }
2573
+ }
2546
2574
  var loadMembers = loadTeam;
2547
2575
  function AssigneeRotaInput({ value, onChange }) {
2548
2576
  const t2 = useTranslation();
@@ -3212,6 +3240,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3212
3240
  const [draft, setDraft] = useState(null);
3213
3241
  const [company, setCompany] = useState(null);
3214
3242
  const [team, setTeam] = useState(null);
3243
+ const [myUserId, setMyUserId] = useState(null);
3215
3244
  const [savingOwner, setSavingOwner] = useState(false);
3216
3245
  useEffect(() => {
3217
3246
  if (open) void fetchTagDefs();
@@ -3263,10 +3292,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3263
3292
  void loadTeamOrNull().then((t3) => {
3264
3293
  if (!cancelled) setTeam(t3);
3265
3294
  });
3295
+ void loadMyUserId().then((u) => {
3296
+ if (!cancelled) setMyUserId(u);
3297
+ });
3266
3298
  return () => {
3267
3299
  cancelled = true;
3268
3300
  };
3269
3301
  }, [dealId, open]);
3302
+ const leadIdDoNegocio = deal?.leadId;
3303
+ useEffect(() => {
3304
+ if (!open || !leadIdDoNegocio) return;
3305
+ let cancelled = false;
3306
+ void provider.getActivities({ dealId, leadId: leadIdDoNegocio }).then((r) => {
3307
+ if (!cancelled) setActivities(r.data);
3308
+ });
3309
+ return () => {
3310
+ cancelled = true;
3311
+ };
3312
+ }, [dealId, leadIdDoNegocio, open]);
3270
3313
  const openStages = useMemo(() => stages.filter((s) => !s.isLost), [stages]);
3271
3314
  async function changeStage(stage) {
3272
3315
  if (!deal || stage.id === deal.stageId || movingStage) return;
@@ -3274,7 +3317,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3274
3317
  try {
3275
3318
  await moveDealToStage(deal.id, stage.id);
3276
3319
  setDeal({ ...deal, stageId: stage.id, stageName: stage.name, stageColor: stage.color, probability: stage.probability });
3277
- const refreshed = await provider.getActivities({ dealId });
3320
+ const refreshed = await provider.getActivities({ dealId, leadId: deal?.leadId });
3278
3321
  setActivities(refreshed.data);
3279
3322
  } catch {
3280
3323
  toast.error(t2("crm.pipeline.moveFailed"));
@@ -3494,27 +3537,43 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3494
3537
  ]
3495
3538
  }
3496
3539
  ) }),
3497
- /* @__PURE__ */ jsx(Section, { title: t2("crm.card.owner"), children: team === null ? /* @__PURE__ */ jsx("div", { className: "h-9 animate-pulse rounded-lg bg-muted/40", "aria-hidden": true }) : team.length === 0 ? (
3498
- // Lista vazia aqui quase sempre é falta de `members.read`, e
3499
- // não uma casa sem equipe. Dizer "ninguém" seria mentir.
3500
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
3501
- ) : /* @__PURE__ */ jsxs(
3502
- Select,
3503
- {
3504
- value: deal?.assignedToId ?? "__none__",
3505
- onValueChange: (v) => {
3506
- void changeOwner(v === "__none__" ? void 0 : v);
3507
- },
3508
- disabled: savingOwner,
3509
- children: [
3510
- /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
3511
- /* @__PURE__ */ jsxs(SelectContent, { children: [
3512
- /* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t2("crm.card.noOwner") }),
3513
- team.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: m.userId, children: m.name }, m.userId))
3514
- ] })
3515
- ]
3516
- }
3517
- ) }),
3540
+ /* @__PURE__ */ jsxs(Section, { title: t2("crm.card.owner"), children: [
3541
+ myUserId && deal?.assignedToId !== myUserId && /* @__PURE__ */ jsxs(
3542
+ "button",
3543
+ {
3544
+ onClick: () => {
3545
+ void changeOwner(myUserId);
3546
+ },
3547
+ disabled: savingOwner,
3548
+ className: "mb-2 inline-flex w-full items-center justify-center gap-1.5 rounded-button border border-primary/30 bg-primary/5 px-3 py-2 text-xs font-medium text-primary transition-colors hover:bg-primary/10 disabled:opacity-60",
3549
+ children: [
3550
+ /* @__PURE__ */ jsx(UserCheck, { className: "h-3.5 w-3.5" }),
3551
+ deal?.assignedToId ? t2("crm.card.takeOverFrom") : t2("crm.card.takeOver")
3552
+ ]
3553
+ }
3554
+ ),
3555
+ team === null ? /* @__PURE__ */ jsx("div", { className: "h-9 animate-pulse rounded-lg bg-muted/40", "aria-hidden": true }) : team.length === 0 ? (
3556
+ // Lista vazia aqui quase sempre é falta de `members.read`, e
3557
+ // não uma casa sem equipe. Dizer "ninguém" seria mentir.
3558
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
3559
+ ) : /* @__PURE__ */ jsxs(
3560
+ Select,
3561
+ {
3562
+ value: deal?.assignedToId ?? "__none__",
3563
+ onValueChange: (v) => {
3564
+ void changeOwner(v === "__none__" ? void 0 : v);
3565
+ },
3566
+ disabled: savingOwner,
3567
+ children: [
3568
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
3569
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
3570
+ /* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t2("crm.card.noOwner") }),
3571
+ team.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: m.userId, children: m.name }, m.userId))
3572
+ ] })
3573
+ ]
3574
+ }
3575
+ )
3576
+ ] }),
3518
3577
  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-5 gap-y-1 text-[11px] text-muted-foreground", children: [
3519
3578
  /* @__PURE__ */ jsxs("span", { children: [
3520
3579
  t2("crm.dealSidebar.probability"),
@@ -3891,6 +3950,19 @@ function LeadListView({ onNew, onEdit }) {
3891
3950
  const refreshLeads = useCrmStore((s) => s.refreshLeads);
3892
3951
  const [search, setSearch] = useState("");
3893
3952
  const [statusFilter, setStatusFilter] = useState([]);
3953
+ const [sourceFilter, setSourceFilter] = useState();
3954
+ const [tagFilter, setTagFilter] = useState([]);
3955
+ const [ownerFilter, setOwnerFilter] = useState();
3956
+ const [reachFilter, setReachFilter] = useState();
3957
+ const [companyFilter, setCompanyFilter] = useState();
3958
+ const leadSources = useCrmStore((s) => s.leadSources);
3959
+ const fetchLeadSources = useCrmStore((s) => s.fetchLeadSources);
3960
+ const tagDefs = useCrmStore((s) => s.tagDefs);
3961
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3962
+ useEffect(() => {
3963
+ void fetchLeadSources();
3964
+ void fetchTagDefs();
3965
+ }, []);
3894
3966
  const [archiveTarget, setArchiveTarget] = useState(null);
3895
3967
  const [bulkBusy, setBulkBusy] = useState(false);
3896
3968
  const [page, setPage] = useState(1);
@@ -3914,15 +3986,21 @@ function LeadListView({ onNew, onEdit }) {
3914
3986
  const columns = useMemo(() => buildColumns(t2, leads2, scores), [t2, leads2, scores]);
3915
3987
  useEffect(() => {
3916
3988
  setPage(1);
3917
- }, [statusFilter, search]);
3989
+ }, [statusFilter, search, sourceFilter, tagFilter, ownerFilter, companyFilter, reachFilter]);
3918
3990
  useEffect(() => {
3919
3991
  fetchLeads({
3920
3992
  status: statusFilter.length > 0 ? statusFilter : void 0,
3921
3993
  search: search || void 0,
3994
+ sourceId: sourceFilter,
3995
+ tags: tagFilter.length ? tagFilter : void 0,
3996
+ assignedToId: ownerFilter,
3997
+ hasCompany: companyFilter === void 0 ? void 0 : companyFilter === "yes",
3998
+ hasPhone: reachFilter === "phone" ? true : reachFilter === "none" ? false : void 0,
3999
+ hasEmail: reachFilter === "email" ? true : void 0,
3922
4000
  page,
3923
4001
  pageSize: PAGE_SIZE2
3924
4002
  });
3925
- }, [statusFilter, search, page]);
4003
+ }, [statusFilter, search, sourceFilter, tagFilter, ownerFilter, companyFilter, reachFilter, page]);
3926
4004
  const tags = useMemo(() => LEAD_STATUS_OPTIONS.map((o) => ({ value: o.value, label: t2(o.labelKey) })), [t2]);
3927
4005
  const runBulk = useCallback(async (rows, write, labels) => {
3928
4006
  setBulkBusy(true);
@@ -4060,6 +4138,102 @@ function LeadListView({ onNew, onEdit }) {
4060
4138
  );
4061
4139
  toast.success(t2("crud.export.toastSuccess", { count: String(todos.length) }));
4062
4140
  }, [leads2, t2, provider, statusFilter, search]);
4141
+ const tagOptions = useMemo(() => {
4142
+ const doCadastro = [...tagDefs.values()].map((d) => ({ value: d.slug, label: d.name ?? d.slug, color: d.color }));
4143
+ if (doCadastro.length) return doCadastro;
4144
+ const vistas = /* @__PURE__ */ new Set();
4145
+ for (const l of leads2) for (const t3 of l.tags ?? []) vistas.add(t3);
4146
+ return [...vistas].sort().map((t3) => ({ value: t3, label: t3 }));
4147
+ }, [tagDefs, leads2]);
4148
+ const sourceOptions = useMemo(
4149
+ () => leadSources.map((o) => ({ value: o.id, label: o.name })),
4150
+ [leadSources]
4151
+ );
4152
+ const ownerOptions = useMemo(() => {
4153
+ const vistos = /* @__PURE__ */ new Map();
4154
+ for (const l of leads2) if (l.assignedToId) vistos.set(l.assignedToId, l.assignedToName ?? l.assignedToId);
4155
+ return [
4156
+ // "Ninguém" primeiro: é a pergunta que se faz antes de distribuir a
4157
+ // carteira, e a que a lista sozinha não responde.
4158
+ { value: "none", label: t2("crm.leads.filters.unassigned") },
4159
+ ...[...vistos].map(([id, nome]) => ({ value: id, label: nome }))
4160
+ ];
4161
+ }, [leads2, t2]);
4162
+ const activeFilterCount = (statusFilter.length ? 1 : 0) + (sourceFilter ? 1 : 0) + (tagFilter.length ? 1 : 0) + (ownerFilter ? 1 : 0) + (companyFilter ? 1 : 0) + (reachFilter ? 1 : 0);
4163
+ const clearFilters = () => {
4164
+ setStatusFilter([]);
4165
+ setSourceFilter(void 0);
4166
+ setTagFilter([]);
4167
+ setOwnerFilter(void 0);
4168
+ setCompanyFilter(void 0);
4169
+ setReachFilter(void 0);
4170
+ };
4171
+ const filtros = /* @__PURE__ */ jsxs(Fragment, { children: [
4172
+ /* @__PURE__ */ jsx(
4173
+ FilterChip,
4174
+ {
4175
+ label: t2("crm.leads.source"),
4176
+ icon: Send,
4177
+ allLabel: t2("crm.leads.filters.allSources"),
4178
+ options: sourceOptions,
4179
+ value: sourceFilter,
4180
+ onChange: setSourceFilter
4181
+ }
4182
+ ),
4183
+ /* @__PURE__ */ jsx(
4184
+ MultiSelect,
4185
+ {
4186
+ variant: "chip",
4187
+ icon: Tag,
4188
+ options: tagOptions,
4189
+ value: tagFilter,
4190
+ onChange: setTagFilter,
4191
+ allLabel: t2("crm.leads.filters.allTags"),
4192
+ searchPlaceholder: t2("crm.leads.filters.searchTag"),
4193
+ emptyLabel: t2("crm.leads.filters.noTag")
4194
+ }
4195
+ ),
4196
+ /* @__PURE__ */ jsx(
4197
+ FilterChip,
4198
+ {
4199
+ label: t2("crm.leads.filters.owner"),
4200
+ icon: User,
4201
+ allLabel: t2("crm.leads.filters.allOwners"),
4202
+ options: ownerOptions,
4203
+ value: ownerFilter,
4204
+ onChange: setOwnerFilter
4205
+ }
4206
+ ),
4207
+ /* @__PURE__ */ jsx(
4208
+ FilterChip,
4209
+ {
4210
+ label: t2("crm.leads.filters.reach"),
4211
+ icon: Phone,
4212
+ allLabel: t2("crm.leads.filters.anyReach"),
4213
+ options: [
4214
+ { value: "phone", label: t2("crm.leads.filters.hasPhone") },
4215
+ { value: "email", label: t2("crm.leads.filters.hasEmail") },
4216
+ { value: "none", label: t2("crm.leads.filters.noPhone") }
4217
+ ],
4218
+ value: reachFilter,
4219
+ onChange: setReachFilter
4220
+ }
4221
+ ),
4222
+ /* @__PURE__ */ jsx(
4223
+ FilterChip,
4224
+ {
4225
+ label: t2("crm.leads.companyCol"),
4226
+ icon: Building2,
4227
+ allLabel: t2("crm.leads.filters.anyCompany"),
4228
+ options: [
4229
+ { value: "yes", label: t2("crm.leads.filters.withCompany") },
4230
+ { value: "no", label: t2("crm.leads.filters.withoutCompany") }
4231
+ ],
4232
+ value: companyFilter,
4233
+ onChange: setCompanyFilter
4234
+ }
4235
+ )
4236
+ ] });
4063
4237
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4064
4238
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
4065
4239
  /* @__PURE__ */ jsx(
@@ -4074,15 +4248,22 @@ function LeadListView({ onNew, onEdit }) {
4074
4248
  onPageChange: setPage,
4075
4249
  rangeOfLabel: t2("crm.leads.pageRangeOf"),
4076
4250
  firstPageLabel: t2("crm.leads.firstPage"),
4251
+ pageLabel: t2("crm.leads.page"),
4077
4252
  prevPageLabel: t2("crm.leads.prevPage"),
4078
4253
  nextPageLabel: t2("crm.leads.nextPage"),
4079
4254
  lastPageLabel: t2("crm.leads.lastPage"),
4080
4255
  searchPlaceholder: t2("crm.leads.searchPlaceholder"),
4081
4256
  search,
4082
4257
  onSearchChange: setSearch,
4258
+ filters: filtros,
4259
+ activeFilterCount,
4260
+ onClearFilters: activeFilterCount > 0 ? clearFilters : void 0,
4261
+ clearFiltersLabel: t2("crm.leads.filters.clear"),
4262
+ searchOwnRow: true,
4083
4263
  searchDebounce: 0,
4084
4264
  tags,
4085
4265
  activeTag: statusFilter.length === 1 ? statusFilter[0] : void 0,
4266
+ allTagLabel: t2("crm.leads.filters.allStatuses"),
4086
4267
  onTagChange: (v) => setStatusFilter(v ? [v] : []),
4087
4268
  newLabel: t2("crm.leads.newLead"),
4088
4269
  onNew,
@@ -5337,7 +5518,7 @@ function FieldRow({ label: label2, value }) {
5337
5518
  /* @__PURE__ */ jsx("dd", { className: "col-span-2 text-sm text-foreground", children: value ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
5338
5519
  ] });
5339
5520
  }
5340
- function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenCompany, onOpenPerson }) {
5521
+ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenCompany, onOpenPerson, onOpenDeal }) {
5341
5522
  const provider = useCrmProvider();
5342
5523
  const { currency } = useCrmConfig();
5343
5524
  const locale = currency.locale;
@@ -5504,7 +5685,21 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5504
5685
  ] });
5505
5686
  })(),
5506
5687
  deal && /* @__PURE__ */ jsxs("div", { children: [
5507
- /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.pipeline") }),
5688
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center justify-between gap-2", children: [
5689
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground", children: t2("crm.leadDetail.pipeline") }),
5690
+ onOpenDeal && /* @__PURE__ */ jsxs(
5691
+ "button",
5692
+ {
5693
+ onClick: () => onOpenDeal(deal.id),
5694
+ className: "inline-flex items-center gap-1 rounded-button border bg-card px-2 py-1 text-[11px] font-medium hover:bg-muted",
5695
+ children: [
5696
+ t2("crm.leadDetail.openDeal"),
5697
+ " ",
5698
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
5699
+ ]
5700
+ }
5701
+ )
5702
+ ] }),
5508
5703
  /* @__PURE__ */ jsx("div", { className: "rounded-card border bg-card shadow-sm", children: /* @__PURE__ */ jsxs("dl", { className: "grid divide-y md:grid-cols-2 md:divide-y-0", children: [
5509
5704
  /* @__PURE__ */ jsx("div", { className: "px-5 md:border-b", children: /* @__PURE__ */ jsx(FieldRow, { label: t2("crm.leadDetail.stage"), value: deal.stageName ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1.5", children: [
5510
5705
  deal.stageColor && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: deal.stageColor } }),
@@ -8062,7 +8257,7 @@ function CrmPage({ config, provider, store, registries }) {
8062
8257
  { id: "offers", render: () => /* @__PURE__ */ jsx(MyOffersView, {}) },
8063
8258
  { id: "distribution-board", render: () => /* @__PURE__ */ jsx(DistributionView, {}) },
8064
8259
  { id: "activities", render: () => /* @__PURE__ */ jsx(ActivityListView, { onOpenLead: (id) => navigate(`leads-detail:${id}`), onOpenQuote: (id) => navigate(`quotes-detail:${id}`) }) },
8065
- { id: "leads-detail", render: ({ id }) => /* @__PURE__ */ jsx(LeadDetailView, { leadId: id, onBack: () => navigate("leads-list"), onCreateQuote: (lid) => navigate("quotes-new", `/sales/quotes/new?leadId=${lid}`), onViewQuote: (qid) => navigate(`quotes-detail:${qid}`), onOpenCompany: (cid) => navigate(`companies-detail:${cid}`), onOpenPerson: (pid) => navigate(`leads-detail:${pid}`) }) },
8260
+ { id: "leads-detail", render: ({ id }) => /* @__PURE__ */ jsx(LeadDetailView, { leadId: id, onBack: () => navigate("leads-list"), onCreateQuote: (lid) => navigate("quotes-new", `/sales/quotes/new?leadId=${lid}`), onViewQuote: (qid) => navigate(`quotes-detail:${qid}`), onOpenCompany: (cid) => navigate(`companies-detail:${cid}`), onOpenPerson: (pid) => navigate(`leads-detail:${pid}`), onOpenDeal: (did) => navigate(`pipeline-detail:${did}`, `/sales/pipeline/${did}`) }) },
8066
8261
  { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
8067
8262
  window.location.hash = `/financial/receivables/detail/${invoiceId}`;
8068
8263
  } }) },
@@ -8719,6 +8914,7 @@ function createStore(seedStages) {
8719
8914
  personPhones: []
8720
8915
  };
8721
8916
  }
8917
+ var MOCK_DEALS_POR_ETAPA = 100;
8722
8918
  function createMockCrmProvider(options) {
8723
8919
  const store = createStore(options?.dealStages);
8724
8920
  const tenantId = "mock-tenant";
@@ -8823,6 +9019,16 @@ function createMockCrmProvider(options) {
8823
9019
  const s = query.search.toLowerCase();
8824
9020
  results = results.filter((l) => l.name.toLowerCase().includes(s) || l.email?.toLowerCase().includes(s) || l.company?.toLowerCase().includes(s));
8825
9021
  }
9022
+ if (query.tags?.length) {
9023
+ results = results.filter((l) => query.tags.every((t2) => (l.tags ?? []).includes(t2)));
9024
+ }
9025
+ if (query.assignedToId === "none") results = results.filter((l) => !l.assignedToId);
9026
+ else if (query.assignedToId) results = results.filter((l) => l.assignedToId === query.assignedToId);
9027
+ if (query.hasCompany !== void 0) results = results.filter((l) => Boolean(l.companyId) === query.hasCompany);
9028
+ if (query.hasPhone !== void 0) results = results.filter((l) => Boolean(l.phone?.trim()) === query.hasPhone);
9029
+ if (query.hasEmail !== void 0) results = results.filter((l) => Boolean(l.email?.trim()) === query.hasEmail);
9030
+ if (query.createdFrom) results = results.filter((l) => l.createdAt >= query.createdFrom);
9031
+ if (query.createdTo) results = results.filter((l) => l.createdAt <= query.createdTo);
8826
9032
  results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
8827
9033
  return paginate(results, query.page, query.pageSize);
8828
9034
  },
@@ -8887,7 +9093,7 @@ function createMockCrmProvider(options) {
8887
9093
  async getDealById(id) {
8888
9094
  return store.deals.find((d) => d.id === id) ?? null;
8889
9095
  },
8890
- async getDealsByStage(pipelineId, filter, knownStages) {
9096
+ async getDealsByStage(pipelineId, filter, knownStages, limits) {
8891
9097
  const stages = knownStages ?? store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
8892
9098
  const matches2 = (d) => {
8893
9099
  if (filter?.tags?.length && !filter.tags.some((t2) => (d.tags ?? []).includes(t2))) return false;
@@ -8896,10 +9102,13 @@ function createMockCrmProvider(options) {
8896
9102
  return true;
8897
9103
  };
8898
9104
  const map = /* @__PURE__ */ new Map();
9105
+ const totals = /* @__PURE__ */ new Map();
8899
9106
  for (const stage of stages) {
8900
- map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d)));
9107
+ const todos = store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d));
9108
+ totals.set(stage.id, todos.length);
9109
+ map.set(stage.id, todos.slice(0, limits?.[stage.id] ?? MOCK_DEALS_POR_ETAPA));
8901
9110
  }
8902
- return map;
9111
+ return { byStage: map, totals };
8903
9112
  },
8904
9113
  async createDeal(input) {
8905
9114
  const stage = store.stages.find((s) => s.id === input.stageId);
@@ -8986,8 +9195,12 @@ function createMockCrmProvider(options) {
8986
9195
  // Activities
8987
9196
  async getActivities(query) {
8988
9197
  let results = [...store.activities];
8989
- if (query.dealId) results = results.filter((a) => a.dealId === query.dealId);
8990
- if (query.leadId) results = results.filter((a) => a.leadId === query.leadId);
9198
+ if (query.dealId && query.leadId) {
9199
+ results = results.filter((a) => a.dealId === query.dealId || a.leadId === query.leadId);
9200
+ } else {
9201
+ if (query.dealId) results = results.filter((a) => a.dealId === query.dealId);
9202
+ if (query.leadId) results = results.filter((a) => a.leadId === query.leadId);
9203
+ }
8991
9204
  if (query.activityType) results = results.filter((a) => a.activityType === query.activityType);
8992
9205
  if (query.completed !== void 0) {
8993
9206
  results = query.completed ? results.filter((a) => a.completedAt) : results.filter((a) => !a.completedAt);
@@ -9955,6 +10168,7 @@ function toDeal(r) {
9955
10168
  contactState: r.contact_state ?? void 0,
9956
10169
  contactStatus: r.contact_status ?? void 0,
9957
10170
  contactStatusName: r.contact_status_name ?? void 0,
10171
+ contactStatusDerivedFrom: r.contact_status_derived_from ?? void 0,
9958
10172
  contactStatusColor: r.contact_status_color ?? void 0,
9959
10173
  contactStatusAt: r.contact_status_at ?? void 0,
9960
10174
  companyId: r.company_id ?? void 0,
@@ -10134,6 +10348,18 @@ function createSupabaseCrmProvider(options) {
10134
10348
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
10135
10349
  qb = qb.in("lead_status", statuses);
10136
10350
  }
10351
+ if (query.sourceId) qb = qb.eq("source_id", query.sourceId);
10352
+ if (query.tags?.length) qb = qb.contains("tags", query.tags);
10353
+ if (query.assignedToId === "none") qb = qb.is("assigned_to_id", null);
10354
+ else if (query.assignedToId) qb = qb.eq("assigned_to_id", query.assignedToId);
10355
+ if (query.hasCompany === true) qb = qb.not("company_id", "is", null);
10356
+ if (query.hasCompany === false) qb = qb.is("company_id", null);
10357
+ if (query.hasPhone === true) qb = qb.not("phone", "is", null).neq("phone", "");
10358
+ if (query.hasPhone === false) qb = qb.or("phone.is.null,phone.eq.");
10359
+ if (query.hasEmail === true) qb = qb.not("email", "is", null).neq("email", "");
10360
+ if (query.hasEmail === false) qb = qb.or("email.is.null,email.eq.");
10361
+ if (query.createdFrom) qb = qb.gte("created_at", query.createdFrom);
10362
+ if (query.createdTo) qb = qb.lte("created_at", query.createdTo);
10137
10363
  const page = query.page ?? 1;
10138
10364
  const pageSize = query.pageSize ?? 50;
10139
10365
  qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
@@ -10292,19 +10518,21 @@ function createSupabaseCrmProvider(options) {
10292
10518
  if (!r) return null;
10293
10519
  return toDeal(r);
10294
10520
  },
10295
- async getDealsByStage(pipelineId, filter, knownStages) {
10521
+ async getDealsByStage(pipelineId, filter, knownStages, limits) {
10296
10522
  const { pub } = getClients();
10297
10523
  const stages = knownStages ?? await provider.getPipelineStages(pipelineId);
10298
10524
  const montar = async (stageId) => {
10299
- let qb = pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).eq("stage_id", stageId).not("status", "in", "(lost,archived)");
10525
+ let qb = pub.from("v_deals").select("*", { count: "exact" }).eq("pipeline_id", pipelineId).eq("stage_id", stageId).not("status", "in", "(lost,archived)");
10300
10526
  if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
10301
10527
  if (filter?.createdFrom) qb = qb.gte("created_at", filter.createdFrom);
10302
10528
  if (filter?.createdTo) qb = qb.lte("created_at", filter.createdTo);
10303
- const { data: data2 } = await qb.order("updated_at", { ascending: false }).limit(DEALS_POR_ETAPA);
10304
- return data2 ?? [];
10529
+ const teto = limits?.[stageId] ?? DEALS_POR_ETAPA;
10530
+ const { data: data2, count } = await qb.order("updated_at", { ascending: false }).limit(teto);
10531
+ return { stageId, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
10305
10532
  };
10306
10533
  const porEtapa = await Promise.all(stages.map((s) => montar(s.id)));
10307
- const data = porEtapa.flat();
10534
+ const totals = new Map(porEtapa.map((r) => [r.stageId, r.total]));
10535
+ const data = porEtapa.flatMap((r) => r.rows);
10308
10536
  const deals = (data ?? []).map(toDeal);
10309
10537
  const map = /* @__PURE__ */ new Map();
10310
10538
  for (const stage of stages) map.set(stage.id, []);
@@ -10312,7 +10540,7 @@ function createSupabaseCrmProvider(options) {
10312
10540
  const arr = map.get(deal.stageId);
10313
10541
  if (arr) arr.push(deal);
10314
10542
  }
10315
- return map;
10543
+ return { byStage: map, totals };
10316
10544
  },
10317
10545
  async createDeal(input) {
10318
10546
  const { pub } = getClients();
@@ -10482,8 +10710,12 @@ function createSupabaseCrmProvider(options) {
10482
10710
  async getActivities(query) {
10483
10711
  const { pub } = getClients();
10484
10712
  let qb = pub.from(T.activities).select("*", { count: "exact" });
10485
- if (query.dealId) qb = qb.eq("deal_id", query.dealId);
10486
- if (query.leadId) qb = qb.eq("lead_id", query.leadId);
10713
+ if (query.dealId && query.leadId) {
10714
+ qb = qb.or(`deal_id.eq.${query.dealId},lead_id.eq.${query.leadId}`);
10715
+ } else {
10716
+ if (query.dealId) qb = qb.eq("deal_id", query.dealId);
10717
+ if (query.leadId) qb = qb.eq("lead_id", query.leadId);
10718
+ }
10487
10719
  if (query.activityType) qb = qb.eq("activity_type", query.activityType);
10488
10720
  if (query.completed === true) qb = qb.not("completed_at", "is", null);
10489
10721
  if (query.completed === false) qb = qb.is("completed_at", null);
@@ -11859,6 +12091,8 @@ function createCrmStore(provider) {
11859
12091
  dealsTotal: 0,
11860
12092
  dealsLoading: false,
11861
12093
  dealsByStage: /* @__PURE__ */ new Map(),
12094
+ dealStageTotals: /* @__PURE__ */ new Map(),
12095
+ dealStageLimits: {},
11862
12096
  activities: [],
11863
12097
  activitiesTotal: 0,
11864
12098
  activitiesLoading: false,
@@ -11951,7 +12185,7 @@ function createCrmStore(provider) {
11951
12185
  async selectPipeline(pipelineId) {
11952
12186
  if (get().activePipelineId === pipelineId) return;
11953
12187
  const stages = await provider.getPipelineStages(pipelineId);
11954
- set({ stages, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map() });
12188
+ set({ stages, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map(), dealStageTotals: /* @__PURE__ */ new Map(), dealStageLimits: {} });
11955
12189
  },
11956
12190
  async fetchTagDefs() {
11957
12191
  return dedup(sid + "crm:tag-defs", async () => {
@@ -12000,16 +12234,22 @@ function createCrmStore(provider) {
12000
12234
  },
12001
12235
  async fetchDealsByStage(pipelineId, filter) {
12002
12236
  lastBoard = { pipelineId, filter };
12003
- const key = sid + "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {});
12237
+ const limits = get().dealStageLimits;
12238
+ const key = sid + "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {}) + ":" + JSON.stringify(limits);
12004
12239
  return dedup(key, async () => {
12005
12240
  set({ dealsLoading: true });
12006
12241
  const { activePipelineId, stages } = get();
12007
12242
  const known = pipelineId === activePipelineId && stages.length > 0 ? stages : void 0;
12008
- const dealsByStage = await provider.getDealsByStage(pipelineId, filter, known);
12243
+ const { byStage, totals } = await provider.getDealsByStage(pipelineId, filter, known, limits);
12009
12244
  if (get().activePipelineId !== pipelineId) return;
12010
- set({ dealsByStage, dealsLoading: false });
12245
+ set({ dealsByStage: byStage, dealStageTotals: totals, dealsLoading: false });
12011
12246
  });
12012
12247
  },
12248
+ async loadMoreStage(stageId) {
12249
+ const atual = get().dealStageLimits[stageId] ?? 100;
12250
+ set({ dealStageLimits: { ...get().dealStageLimits, [stageId]: atual + 100 } });
12251
+ await get().refreshBoard();
12252
+ },
12013
12253
  async refreshBoard() {
12014
12254
  if (!lastBoard) return;
12015
12255
  return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter);
@@ -24200,6 +24440,632 @@ create view public.plg_crm_rep_deals with (security_invoker = true) as SELECT id
24200
24440
  grant select, insert, update, delete on public.v_deals to authenticated, service_role;
24201
24441
  grant select, insert, update, delete on public.plg_crm_rep_deals to authenticated, service_role;
24202
24442
  `;
24443
+ var MIGRATION_042_A_ATIVIDADE_DIZ_QUEM_A_FEZ = `-- ---------------------------------------------------------------------------
24444
+ -- 042_a_atividade_diz_quem_a_fez.sql \u2014 a linha do tempo passa a ter sujeito.
24445
+ --
24446
+ -- \u2500\u2500 o que faltava \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24447
+ --
24448
+ -- \`plg_crm_activities\` guarda \`assigned_to_id\`, que \xE9 QUEM DEVE FAZER \u2014 o dono
24449
+ -- da tarefa. N\xE3o havia nada dizendo QUEM FEZ. Uma linha do tempo em que toda
24450
+ -- entrada \xE9 an\xF4nima responde "o que aconteceu" e n\xE3o responde "com quem eu
24451
+ -- falo sobre isso", que \xE9 a pergunta que se faz olhando para ela.
24452
+ --
24453
+ -- Medido no cluster antes desta migration: 308 atividades, ZERO com autor \u2014
24454
+ -- porque n\xE3o havia onde p\xF4r.
24455
+ --
24456
+ -- O caso mais claro \xE9 a RPC do agente: \`agent_crm_log_activity\` RECEBE
24457
+ -- \`p_actor_user_id\`, usa-o para autorizar, e descarta. A informa\xE7\xE3o chegava \xE0
24458
+ -- porta e n\xE3o entrava.
24459
+ --
24460
+ -- \u2500\u2500 por que duas colunas e n\xE3o uma FK \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24461
+ --
24462
+ -- \`created_by\` aponta para o utilizador; \`created_by_name\` guarda o nome no
24463
+ -- momento em que o facto aconteceu. Um utilizador removido n\xE3o pode apagar a
24464
+ -- autoria do que fez \u2014 e uma linha do tempo que passa a dizer "(removido)"
24465
+ -- reescreve a hist\xF3ria para quem a l\xEA depois.
24466
+ --
24467
+ -- \xC9 a mesma disciplina que \`contact_name\` e \`assigned_to_name\` j\xE1 seguem
24468
+ -- nesta tabela.
24469
+ --
24470
+ -- \u2500\u2500 quem preenche \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24471
+ --
24472
+ -- Os FACTOS DE SISTEMA (lead_created, stage_changed, status_changed\u2026) nascem
24473
+ -- sem autor de prop\xF3sito: quem os produziu foi uma regra, n\xE3o uma pessoa. O
24474
+ -- default cobre isso sem inventar um culpado.
24475
+ -- ---------------------------------------------------------------------------
24476
+
24477
+ ALTER TABLE public.plg_crm_activities
24478
+ ADD COLUMN IF NOT EXISTS created_by uuid REFERENCES auth.users(id) ON DELETE SET NULL,
24479
+ ADD COLUMN IF NOT EXISTS created_by_name text;
24480
+
24481
+ COMMENT ON COLUMN public.plg_crm_activities.created_by IS
24482
+ 'Quem FEZ. Diferente de \`assigned_to_id\`, que \xE9 quem deve fazer. Nulo nos fatos de sistema, onde o autor \xE9 uma regra e n\xE3o uma pessoa (042).';
24483
+ COMMENT ON COLUMN public.plg_crm_activities.created_by_name IS
24484
+ 'O nome no momento do fato. Um usu\xE1rio removido n\xE3o apaga a autoria do que fez (042).';
24485
+
24486
+ -- A linha do tempo abre ordenada por data e filtrada por neg\xF3cio ou por lead;
24487
+ -- o autor \xE9 coluna de LEITURA, n\xE3o de recorte. Um \xEDndice aqui seria mantido em
24488
+ -- toda escrita para uma consulta que ningu\xE9m faz.
24489
+
24490
+ -- \u2500\u2500 a RPC do agente para de descartar quem agiu \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24491
+ --
24492
+ -- Ela j\xE1 recebe \`p_actor_user_id\` e j\xE1 o usa no \`agent_guard\`. S\xF3 n\xE3o gravava.
24493
+ -- O corpo abaixo \xE9 o da 021, INTEIRO, com duas linhas a mais: reescrever a
24494
+ -- fun\xE7\xE3o para acrescentar uma coluna trocaria o contrato do agente (o formato
24495
+ -- do retorno, o vocabul\xE1rio de \`outcome\`, a forma do guard) por um detalhe de
24496
+ -- autoria, e \xE9 assim que uma ferramenta que funcionava para de funcionar.
24497
+ CREATE OR REPLACE FUNCTION public.agent_crm_log_activity(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb)
24498
+ RETURNS jsonb
24499
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
24500
+ AS $$
24501
+ DECLARE
24502
+ v_denial jsonb;
24503
+ v_deal uuid;
24504
+ v_lead uuid;
24505
+ v_type text;
24506
+ v_outcome text;
24507
+ v_title text;
24508
+ v_id uuid;
24509
+ BEGIN
24510
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create');
24511
+ IF v_denial IS NOT NULL THEN
24512
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
24513
+ END IF;
24514
+
24515
+ BEGIN
24516
+ v_deal := nullif(p_payload->>'deal_id', '')::uuid;
24517
+ v_lead := nullif(p_payload->>'lead_id', '')::uuid;
24518
+ EXCEPTION WHEN OTHERS THEN
24519
+ RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
24520
+ END;
24521
+ IF v_deal IS NULL AND v_lead IS NULL THEN
24522
+ RETURN jsonb_build_object('ok', false, 'error', 'send deal_id or lead_id \u2014 an activity with neither belongs to nobody');
24523
+ END IF;
24524
+
24525
+ IF v_deal IS NOT NULL AND NOT EXISTS (SELECT 1 FROM plg_crm_deals d WHERE d.id = v_deal AND d.tenant_id = p_tenant_id) THEN
24526
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown deal for this tenant');
24527
+ END IF;
24528
+ IF v_lead IS NOT NULL AND NOT EXISTS (SELECT 1 FROM people p WHERE p.id = v_lead AND p.tenant_id = p_tenant_id) THEN
24529
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown person for this tenant');
24530
+ END IF;
24531
+
24532
+ -- O tipo vem do cadastro do inquilino (registro \`activity-types\`), n\xE3o de uma
24533
+ -- lista fixa: uma casa que criou "Visita t\xE9cnica" precisa poder registr\xE1-la.
24534
+ v_type := coalesce(nullif(trim(lower(p_payload->>'activity_type')), ''), 'note');
24535
+ IF NOT EXISTS (
24536
+ SELECT 1 FROM plg_crm_activity_types t
24537
+ WHERE t.tenant_id = p_tenant_id AND t.is_active
24538
+ AND lower(replace(t.name, ' ', '_')) = v_type
24539
+ ) AND v_type NOT IN ('call','email','meeting','note','task','whatsapp','visit') THEN
24540
+ RETURN jsonb_build_object(
24541
+ 'ok', false,
24542
+ 'error', format('unknown activity type %L', v_type),
24543
+ 'allowed', jsonb_build_array('call','email','meeting','note','task','whatsapp','visit'));
24544
+ END IF;
24545
+
24546
+ v_outcome := nullif(trim(lower(p_payload->>'outcome')), '');
24547
+ IF v_outcome IS NOT NULL AND v_outcome NOT IN ('connected','no_answer','left_message','replied','scheduled') THEN
24548
+ RETURN jsonb_build_object(
24549
+ 'ok', false,
24550
+ 'error', format('unknown outcome %L', v_outcome),
24551
+ 'allowed', jsonb_build_array('connected','no_answer','left_message','replied','scheduled'),
24552
+ 'hint', 'This is what moves the card''s contact status \u2014 send it whenever the activity was an attempt to reach somebody.');
24553
+ END IF;
24554
+
24555
+ v_title := coalesce(nullif(trim(p_payload->>'title'), ''), initcap(replace(v_type, '_', ' ')));
24556
+
24557
+ INSERT INTO plg_crm_activities
24558
+ (tenant_id, deal_id, lead_id, contact_id, activity_type, title, description, outcome, due_date, assigned_to_id,
24559
+ -- 042: o ator j\xE1 chegava aqui para AUTORIZAR e era descartado. Agora fica.
24560
+ created_by, created_by_name)
24561
+ VALUES (
24562
+ p_tenant_id, v_deal, v_lead,
24563
+ nullif(p_payload->>'contact_id', '')::uuid,
24564
+ v_type, left(v_title, 200), left(nullif(p_payload->>'description', ''), 2000),
24565
+ v_outcome,
24566
+ nullif(p_payload->>'due_date', '')::date,
24567
+ nullif(p_payload->>'assigned_to_id', '')::uuid,
24568
+ p_actor_user_id,
24569
+ (SELECT u.email FROM auth.users u WHERE u.id = p_actor_user_id))
24570
+ RETURNING id INTO v_id;
24571
+
24572
+ RETURN jsonb_build_object(
24573
+ 'ok', true, 'activity_id', v_id,
24574
+ -- O gatilho da 014 j\xE1 rodou: devolver o status novo \xE9 o que faz o
24575
+ -- assistente poder dizer "pronto, o card est\xE1 como N\xE3o atendeu".
24576
+ 'contact_status', (SELECT d.contact_status FROM plg_crm_deals d WHERE d.id = v_deal));
24577
+ END $$;
24578
+
24579
+ REVOKE ALL ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) FROM PUBLIC, anon;
24580
+ GRANT EXECUTE ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) TO authenticated, service_role;
24581
+
24582
+ COMMENT ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) IS
24583
+ 'Registra um contato na linha do tempo com o desfecho, e agora com QUEM o fez. \xC9 o que recalcula o status do card (021, autor em 042).';
24584
+ `;
24585
+ var MIGRATION_043_A_CADENCIA_PARA_DE_ESPERAR_UM_FATO_QUE_NUNCA_CHEGA = `-- ---------------------------------------------------------------------------
24586
+ -- 043_a_cadencia_para_de_esperar_um_fato_que_nunca_chega.sql
24587
+ --
24588
+ -- \u2500\u2500 o consumidor morto \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24589
+ --
24590
+ -- \`plugin-automations\` ASSINA \`crm.stage_changed\` \u2014 a assinatura est\xE1 em
24591
+ -- \`automations/001:574-577\` e o handler existe de verdade. Nada emite esse
24592
+ -- fato. A cad\xEAncia que algu\xE9m montou para disparar quando o card muda de
24593
+ -- etapa est\xE1 esperando, em sil\xEAncio, desde que foi criada.
24594
+ --
24595
+ -- Sil\xEAncio \xE9 o pior modo de falhar: n\xE3o h\xE1 erro para investigar. A tela mostra
24596
+ -- a cad\xEAncia ativa, o card muda de etapa na frente de quem a montou, e nada
24597
+ -- acontece \u2014 e a conclus\xE3o razo\xE1vel de quem v\xEA \xE9 que a automa\xE7\xE3o est\xE1 quebrada,
24598
+ -- ou pior, que o produto n\xE3o faz aquilo.
24599
+ --
24600
+ -- A \`012\` corrigiu tr\xEAs dos seis fatos declarados e disse isso no cabe\xE7alho.
24601
+ -- Este \xE9 o quarto, e \xE9 o \xFAnico dos tr\xEAs restantes que tem consumidor.
24602
+ --
24603
+ -- \u2500\u2500 s\xF3 a TRANSI\xC7\xC3O \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24604
+ --
24605
+ -- \`AFTER UPDATE OF stage_id\` j\xE1 recorta a coluna, mas um \`UPDATE\` que grava a
24606
+ -- mesma etapa ainda dispara. A cad\xEAncia que entra a cada salvar de um card
24607
+ -- parado entra duas vezes \u2014 \xE9 a mesma disciplina que a \`012\` aplica ao status.
24608
+ --
24609
+ -- \u2500\u2500 o SUJEITO \xE9 o lead \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24610
+ --
24611
+ -- Como em \`crm.deal_won\`: tudo a jusante \xE9 indexado pela pessoa, e um handler
24612
+ -- que tivesse de resolver neg\xF3cio \u2192 lead sozinho seria um join repetido por
24613
+ -- cada um deles. Sem \`lead_id\` n\xE3o h\xE1 fato \u2014 um card sem lead n\xE3o tem a quem
24614
+ -- a cad\xEAncia falaria.
24615
+ -- ---------------------------------------------------------------------------
24616
+
24617
+ CREATE OR REPLACE FUNCTION public.trg_crm_emit_stage_changed() RETURNS trigger
24618
+ LANGUAGE plpgsql SECURITY DEFINER
24619
+ SET search_path TO ''
24620
+ AS $$
24621
+ DECLARE
24622
+ v_de text;
24623
+ v_para text;
24624
+ BEGIN
24625
+ IF NEW.stage_id IS NOT DISTINCT FROM OLD.stage_id THEN RETURN NULL; END IF;
24626
+ IF NEW.lead_id IS NULL THEN RETURN NULL; END IF;
24627
+
24628
+ -- Os NOMES junto dos ids: uma condi\xE7\xE3o de cad\xEAncia escrita por humano diz
24629
+ -- "quando entrar em Proposta enviada", n\xE3o "quando stage_id for este uuid".
24630
+ SELECT s.name INTO v_de FROM public.plg_crm_pipeline_stages s WHERE s.id = OLD.stage_id;
24631
+ SELECT s.name INTO v_para FROM public.plg_crm_pipeline_stages s WHERE s.id = NEW.stage_id;
24632
+
24633
+ PERFORM public.plg_emit_event(
24634
+ 'crm.stage_changed',
24635
+ jsonb_build_object(
24636
+ 'deal_id', NEW.id,
24637
+ 'lead_id', NEW.lead_id,
24638
+ 'person_id', NEW.lead_id,
24639
+ 'title', NEW.title,
24640
+ 'value', NEW.value,
24641
+ 'from_stage_id', OLD.stage_id,
24642
+ 'to_stage_id', NEW.stage_id,
24643
+ 'from_stage', v_de,
24644
+ 'to_stage', v_para
24645
+ ),
24646
+ 'lead', NEW.lead_id::text, NEW.tenant_id
24647
+ );
24648
+ RETURN NULL;
24649
+ END $$;
24650
+
24651
+ REVOKE ALL ON FUNCTION public.trg_crm_emit_stage_changed() FROM PUBLIC;
24652
+ GRANT EXECUTE ON FUNCTION public.trg_crm_emit_stage_changed() TO authenticated, service_role;
24653
+
24654
+ COMMENT ON FUNCTION public.trg_crm_emit_stage_changed() IS
24655
+ 'Emite \`crm.stage_changed\`, que o plugin-automations assina desde sempre e nunca recebeu (043).';
24656
+
24657
+ -- AFTER, como os irm\xE3os: falhar ao emitir n\xE3o pode recusar o movimento do
24658
+ -- card. \`plg_emit_event\` s\xF3 insere uma linha; quem tenta de novo \xE9 o consumidor.
24659
+ DROP TRIGGER IF EXISTS crm_emit_stage_changed ON public.plg_crm_deals;
24660
+ CREATE TRIGGER crm_emit_stage_changed
24661
+ AFTER UPDATE OF stage_id ON public.plg_crm_deals
24662
+ FOR EACH ROW EXECUTE FUNCTION public.trg_crm_emit_stage_changed();
24663
+ `;
24664
+ var MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO = `-- ---------------------------------------------------------------------------
24665
+ -- 044_o_status_nao_e_um_acontecimento.sql
24666
+ --
24667
+ -- \u2500\u2500 o que se v\xEA na tela \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24668
+ --
24669
+ -- Um lead da feira, com UM fato na hist\xF3ria dele \u2014 o contato no estande \u2014
24670
+ -- aparecia com tr\xEAs:
24671
+ --
24672
+ -- \u2022 Contato presencial na feira (visit) \u2190 aconteceu
24673
+ -- \u2022 Contato n\xE3o feito (status_changed) \u2190 n\xE3o aconteceu
24674
+ -- \u2022 Falou com a pessoa (status_changed) \u2190 n\xE3o aconteceu
24675
+ --
24676
+ -- Medido antes desta migration: 312 visitas, 306 "Contato n\xE3o feito" e 311
24677
+ -- "Falou com a pessoa". Quase tr\xEAs linhas de hist\xF3ria para cada fato real.
24678
+ --
24679
+ -- \u2500\u2500 por que as duas \xFAltimas n\xE3o s\xE3o fatos \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24680
+ --
24681
+ -- \`contact_status\` \xE9 DERIVADO. A 020 o calcula lendo as atividades e n\xE3o
24682
+ -- aceita que nenhuma tela o grave \u2014 \xE9 a regra boa desta tabela, e continua.
24683
+ -- Mas ela tamb\xE9m escrevia cada rec\xE1lculo de volta como uma atividade, e \xE9 a\xED
24684
+ -- que o modelo se dobra sobre si mesmo: a linha do tempo passa a conter o
24685
+ -- resumo dela pr\xF3pria.
24686
+ --
24687
+ -- Nada aconteceu quando o card virou "Falou com a pessoa". O que aconteceu foi
24688
+ -- a VISITA, e ela j\xE1 est\xE1 l\xE1, uma linha acima, dizendo mais: quando, com quem,
24689
+ -- por quem. A segunda linha \xE9 a primeira lida de longe.
24690
+ --
24691
+ -- "Contato n\xE3o feito" \xE9 pior ainda: \xE9 o estado de um card rec\xE9m-nascido. Um
24692
+ -- card existir n\xE3o \xE9 um acontecimento na vida do lead, e uma linha do tempo
24693
+ -- que abre com "ainda n\xE3o fizemos nada" est\xE1 gastando a aten\xE7\xE3o de quem l\xEA
24694
+ -- para n\xE3o dizer nada.
24695
+ --
24696
+ -- O teste \xE9 simples e vale para qualquer linha do tempo: se apagar a linha n\xE3o
24697
+ -- se perde informa\xE7\xE3o nenhuma \u2014 porque ela \xE9 calcul\xE1vel a partir das outras \u2014
24698
+ -- ela n\xE3o \xE9 um fato, \xE9 uma vista. E vista se renderiza no card, que \xE9 onde o
24699
+ -- status j\xE1 aparece.
24700
+ --
24701
+ -- \u2500\u2500 o event_log FICA \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24702
+ --
24703
+ -- \`crm.deal_status_changed\` continua a ser emitido, intacto. Uma cad\xEAncia que
24704
+ -- dispara quando o card vira "N\xE3o atendeu" precisa desse sinal, e um evento
24705
+ -- n\xE3o ocupa espa\xE7o na leitura de ningu\xE9m. O que sai \xE9 s\xF3 a linha da hist\xF3ria.
24706
+ --
24707
+ -- Esta \xE9 a mesma fronteira que a 012 e a 043 v\xEAm desenhando: o \`event_log\` \xE9
24708
+ -- para M\xC1QUINAS reagirem; \`plg_crm_activities\` \xE9 para uma PESSOA ler.
24709
+ -- ---------------------------------------------------------------------------
24710
+
24711
+ -- O corpo \xE9 o da 020, inteiro, MENOS o INSERT da linha de status. Reescrever a
24712
+ -- fun\xE7\xE3o para tirar um bloco trocaria a escada de deriva\xE7\xE3o por um detalhe de
24713
+ -- apresenta\xE7\xE3o \u2014 e a escada est\xE1 certa.
24714
+ CREATE OR REPLACE FUNCTION public.crm_recompute_deal_status(p_deal_id uuid)
24715
+ RETURNS text
24716
+ LANGUAGE plpgsql
24717
+ SECURITY DEFINER
24718
+ SET search_path TO ''
24719
+ AS $$
24720
+ DECLARE
24721
+ d record;
24722
+ v_has_manual boolean := false;
24723
+ v_last_outcome text;
24724
+ v_connected boolean := false;
24725
+ v_replied boolean := false;
24726
+ v_meeting boolean := false;
24727
+ v_overdue boolean := false;
24728
+ v_key text;
24729
+ v_name text;
24730
+ BEGIN
24731
+ SELECT id, tenant_id, stage_id, contact_status INTO d
24732
+ FROM public.plg_crm_deals WHERE id = p_deal_id;
24733
+ IF d.id IS NULL THEN RETURN NULL; END IF;
24734
+
24735
+ -- Os fatos do sistema (lead_created, stage_changed\u2026) N\xC3O contam como
24736
+ -- contato: eles descrevem o software, n\xE3o uma tentativa de falar com algu\xE9m.
24737
+ SELECT
24738
+ bool_or(a.activity_type NOT IN (
24739
+ 'lead_created','lead_converted','lead_archived','deal_created','stage_changed','deal_won','deal_lost',
24740
+ 'deal_archived','quote_created','quote_sent','quote_approved','quote_rejected','quote_archived','status_changed')),
24741
+ bool_or(a.outcome = 'connected'),
24742
+ bool_or(a.outcome = 'replied'),
24743
+ bool_or(a.activity_type = 'meeting' OR a.outcome = 'scheduled'),
24744
+ bool_or(a.activity_type = 'task' AND a.completed_at IS NULL AND a.due_date < current_date)
24745
+ INTO v_has_manual, v_connected, v_replied, v_meeting, v_overdue
24746
+ FROM public.plg_crm_activities a
24747
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id;
24748
+
24749
+ -- A \xDALTIMA tentativa, n\xE3o qualquer uma: "n\xE3o atendeu" \xE9 um estado do agora,
24750
+ -- e uma liga\xE7\xE3o sem resposta em agosto n\xE3o descreve o card de hoje.
24751
+ SELECT a.outcome INTO v_last_outcome
24752
+ FROM public.plg_crm_activities a
24753
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id AND a.outcome IS NOT NULL
24754
+ ORDER BY a.created_at DESC LIMIT 1;
24755
+
24756
+ SELECT s.key, s.name INTO v_key, v_name
24757
+ FROM public.plg_crm_deal_statuses s
24758
+ WHERE s.tenant_id = d.tenant_id
24759
+ AND s.is_active
24760
+ AND (s.stage_id IS NULL OR s.stage_id = d.stage_id)
24761
+ AND CASE s.derived_from
24762
+ WHEN 'no_activity' THEN NOT coalesce(v_has_manual, false)
24763
+ WHEN 'attempted' THEN coalesce(v_has_manual, false)
24764
+ WHEN 'no_answer' THEN v_last_outcome IN ('no_answer', 'left_message')
24765
+ WHEN 'connected' THEN coalesce(v_connected, false)
24766
+ WHEN 'replied' THEN coalesce(v_replied, false)
24767
+ WHEN 'meeting_scheduled' THEN coalesce(v_meeting, false)
24768
+ WHEN 'overdue_task' THEN coalesce(v_overdue, false)
24769
+ ELSE false
24770
+ END
24771
+ -- Espec\xEDfico da etapa ganha do universal no empate.
24772
+ ORDER BY s.sort_order DESC, (s.stage_id IS NOT NULL) DESC
24773
+ LIMIT 1;
24774
+
24775
+ IF v_key IS NOT DISTINCT FROM d.contact_status THEN
24776
+ RETURN d.contact_status;
24777
+ END IF;
24778
+
24779
+ UPDATE public.plg_crm_deals
24780
+ SET contact_status = v_key, contact_status_at = now()
24781
+ WHERE id = p_deal_id;
24782
+
24783
+ -- 044: o INSERT de \`status_changed\` na linha do tempo saiu daqui. O evento
24784
+ -- fica \u2014 \xE9 o que uma cad\xEAncia escuta, e ningu\xE9m o l\xEA numa tela.
24785
+ IF v_key IS NOT NULL THEN
24786
+ BEGIN
24787
+ PERFORM public.plg_emit_event(
24788
+ 'crm.deal_status_changed',
24789
+ jsonb_build_object('deal_id', p_deal_id, 'status', v_key, 'status_name', v_name, 'stage_id', d.stage_id),
24790
+ 'deal', p_deal_id::text, d.tenant_id);
24791
+ EXCEPTION WHEN undefined_function THEN
24792
+ -- App sem o barramento de eventos montado: o card j\xE1 mostra o status.
24793
+ NULL;
24794
+ END;
24795
+ END IF;
24796
+
24797
+ RETURN v_key;
24798
+ END $$;
24799
+
24800
+ REVOKE ALL ON FUNCTION public.crm_recompute_deal_status(uuid) FROM PUBLIC, anon;
24801
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO authenticated;
24802
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO service_role;
24803
+
24804
+ COMMENT ON FUNCTION public.crm_recompute_deal_status(uuid) IS
24805
+ 'Recalcula o status do neg\xF3cio a partir dos lan\xE7amentos. Nenhuma tela grava contact_status \u2014 ela registra a atividade e isto acontece (020). O status n\xE3o entra na linha do tempo: ele \xE9 uma vista das atividades, n\xE3o um acontecimento a mais (044).';
24806
+
24807
+ -- \u2500\u2500 e as que j\xE1 foram escritas \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24808
+ --
24809
+ -- Deix\xE1-las seria deixar o defeito na tela e s\xF3 parar de aument\xE1-lo. Cada uma
24810
+ -- \xE9 reconstitu\xEDvel a partir das atividades que sobram \u2014 que \xE9 precisamente o
24811
+ -- argumento de n\xE3o as guardar.
24812
+ --
24813
+ -- O gatilho \`crm_activity_restatus\` \xE9 \`AFTER INSERT OR UPDATE\` (020), n\xE3o
24814
+ -- DELETE: apagar n\xE3o dispara rec\xE1lculo nenhum e n\xE3o h\xE1 cascata.
24815
+ DO $$
24816
+ DECLARE v_n bigint;
24817
+ BEGIN
24818
+ DELETE FROM public.plg_crm_activities WHERE activity_type = 'status_changed';
24819
+ GET DIAGNOSTICS v_n = ROW_COUNT;
24820
+ RAISE NOTICE 'crm/044: % linha(s) de status removida(s) da linha do tempo', v_n;
24821
+ END $$;
24822
+
24823
+ -- O valor continua ACEITO pelo CHECK da 020. Tir\xE1-lo da restri\xE7\xE3o recusaria
24824
+ -- qualquer banco que ainda tenha uma dessas linhas por um caminho que este
24825
+ -- arquivo n\xE3o conhece, e o ganho seria zero: nada mais o escreve.
24826
+ `;
24827
+ var MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ = `-- ---------------------------------------------------------------------------
24828
+ -- 045_contato_feito_e_contato_que_alguem_fez.sql
24829
+ --
24830
+ -- \u2500\u2500 o card que se contradizia \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24831
+ --
24832
+ -- 310 cards parados na etapa "Novo (feira)" com a pastilha "Contato feito" \u2014
24833
+ -- que \xE9, letra por letra, o NOME DA ETAPA SEGUINTE. O quadro dizia as duas
24834
+ -- coisas ao mesmo tempo: ningu\xE9m mexeu nisto, e j\xE1 falaram com ele.
24835
+ --
24836
+ -- O que produzia a pastilha era a atividade da importa\xE7\xE3o da feira. A \`044\`
24837
+ -- tirou-lhe o \`outcome\` e isso resolveu metade: o card deixou de ser "Falou
24838
+ -- com a pessoa". Mas \`attempted\` n\xE3o olha para o desfecho \u2014 olha para a
24839
+ -- EXIST\xCANCIA de qualquer atividade que n\xE3o seja fato de sistema. A visita
24840
+ -- importada \xE9 exatamente isso, e o card virou "Contato feito".
24841
+ --
24842
+ -- \u2500\u2500 a regra que faltava, dita por quem usa \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24843
+ --
24844
+ -- "apenas deveriam marcar contato feito quando esse contato for feito
24845
+ -- pelos sdr pelo sistema"
24846
+ --
24847
+ -- A lista de tipos de sistema era uma aproxima\xE7\xE3o disso: enumerava os fatos
24848
+ -- que o software escreve sozinho e assumia que o resto foi algu\xE9m. A
24849
+ -- importa\xE7\xE3o quebra a suposi\xE7\xE3o \u2014 ela escreve atividades de tipo humano
24850
+ -- ('visit') sem que nenhum humano as tenha feito.
24851
+ --
24852
+ -- Ent\xE3o a pergunta deixa de ser o TIPO e passa a ser a PROCED\xCANCIA:
24853
+ --
24854
+ -- \`created_by IS NOT NULL\` algu\xE9m lan\xE7ou pela tela ou pela RPC do agente.
24855
+ -- A coluna existe desde a 042 justamente para
24856
+ -- responder "quem fez".
24857
+ -- \`outcome IS NOT NULL\` ou n\xE3o h\xE1 autor humano mas houve tentativa de
24858
+ -- falar: \xE9 o caso da caixa de entrada, que lan\xE7a
24859
+ -- como 'Caixa de entrada' e traz \`replied\` ou
24860
+ -- \`left_message\`. Uma resposta do lead \xE9 contato
24861
+ -- real mesmo sem SDR nenhum a regist\xE1-la.
24862
+ --
24863
+ -- Nenhuma das duas, e o registo descreve DE ONDE o lead veio, n\xE3o o que se
24864
+ -- fez com ele. \xC9 o caso da feira \u2014 e ser\xE1 o caso de toda importa\xE7\xE3o futura,
24865
+ -- que \xE9 a raz\xE3o de a regra n\xE3o citar 'visit' nem a feira em lado nenhum.
24866
+ --
24867
+ -- \u2500\u2500 o que isto devolve ao funil \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24868
+ --
24869
+ -- 310 cards voltam a "Contato n\xE3o feito", que \xE9 a verdade: est\xE3o na primeira
24870
+ -- etapa desde a feira e ningu\xE9m ligou. E "Contato feito" volta a significar
24871
+ -- alguma coisa \u2014 quando aparecer, \xE9 porque um SDR fez.
24872
+ -- ---------------------------------------------------------------------------
24873
+
24874
+ CREATE OR REPLACE FUNCTION public.crm_recompute_deal_status(p_deal_id uuid)
24875
+ RETURNS text
24876
+ LANGUAGE plpgsql
24877
+ SECURITY DEFINER
24878
+ SET search_path TO ''
24879
+ AS $$
24880
+ DECLARE
24881
+ d record;
24882
+ v_has_manual boolean := false;
24883
+ v_last_outcome text;
24884
+ v_connected boolean := false;
24885
+ v_replied boolean := false;
24886
+ v_meeting boolean := false;
24887
+ v_overdue boolean := false;
24888
+ v_key text;
24889
+ v_name text;
24890
+ BEGIN
24891
+ SELECT id, tenant_id, stage_id, contact_status INTO d
24892
+ FROM public.plg_crm_deals WHERE id = p_deal_id;
24893
+ IF d.id IS NULL THEN RETURN NULL; END IF;
24894
+
24895
+ -- Os fatos do sistema (lead_created, stage_changed\u2026) N\xC3O contam como
24896
+ -- contato: eles descrevem o software, n\xE3o uma tentativa de falar com algu\xE9m.
24897
+ SELECT
24898
+ bool_or(
24899
+ a.activity_type NOT IN (
24900
+ 'lead_created','lead_converted','lead_archived','deal_created','stage_changed','deal_won','deal_lost',
24901
+ 'deal_archived','quote_created','quote_sent','quote_approved','quote_rejected','quote_archived','status_changed')
24902
+ -- 045: e algu\xE9m tem de ter FEITO. Ou uma pessoa a lan\xE7ou pelo sistema
24903
+ -- (\`created_by\`), ou ela traz um desfecho \u2014 que s\xF3 existe quando houve
24904
+ -- tentativa de falar com algu\xE9m. Um registro importado sem as duas
24905
+ -- coisas descreve a proced\xEAncia do lead, n\xE3o trabalho sobre ele.
24906
+ AND (a.created_by IS NOT NULL OR a.outcome IS NOT NULL)),
24907
+ bool_or(a.outcome = 'connected'),
24908
+ bool_or(a.outcome = 'replied'),
24909
+ bool_or(a.activity_type = 'meeting' OR a.outcome = 'scheduled'),
24910
+ bool_or(a.activity_type = 'task' AND a.completed_at IS NULL AND a.due_date < current_date)
24911
+ INTO v_has_manual, v_connected, v_replied, v_meeting, v_overdue
24912
+ FROM public.plg_crm_activities a
24913
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id;
24914
+
24915
+ -- A \xDALTIMA tentativa, n\xE3o qualquer uma: "n\xE3o atendeu" \xE9 um estado do agora,
24916
+ -- e uma liga\xE7\xE3o sem resposta em agosto n\xE3o descreve o card de hoje.
24917
+ SELECT a.outcome INTO v_last_outcome
24918
+ FROM public.plg_crm_activities a
24919
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id AND a.outcome IS NOT NULL
24920
+ ORDER BY a.created_at DESC LIMIT 1;
24921
+
24922
+ SELECT s.key, s.name INTO v_key, v_name
24923
+ FROM public.plg_crm_deal_statuses s
24924
+ WHERE s.tenant_id = d.tenant_id
24925
+ AND s.is_active
24926
+ AND (s.stage_id IS NULL OR s.stage_id = d.stage_id)
24927
+ AND CASE s.derived_from
24928
+ WHEN 'no_activity' THEN NOT coalesce(v_has_manual, false)
24929
+ WHEN 'attempted' THEN coalesce(v_has_manual, false)
24930
+ WHEN 'no_answer' THEN v_last_outcome IN ('no_answer', 'left_message')
24931
+ WHEN 'connected' THEN coalesce(v_connected, false)
24932
+ WHEN 'replied' THEN coalesce(v_replied, false)
24933
+ WHEN 'meeting_scheduled' THEN coalesce(v_meeting, false)
24934
+ WHEN 'overdue_task' THEN coalesce(v_overdue, false)
24935
+ ELSE false
24936
+ END
24937
+ -- Espec\xEDfico da etapa ganha do universal no empate.
24938
+ ORDER BY s.sort_order DESC, (s.stage_id IS NOT NULL) DESC
24939
+ LIMIT 1;
24940
+
24941
+ IF v_key IS NOT DISTINCT FROM d.contact_status THEN
24942
+ RETURN d.contact_status;
24943
+ END IF;
24944
+
24945
+ UPDATE public.plg_crm_deals
24946
+ SET contact_status = v_key, contact_status_at = now()
24947
+ WHERE id = p_deal_id;
24948
+
24949
+ -- 044: o INSERT de \`status_changed\` na linha do tempo saiu daqui. O evento
24950
+ -- fica \u2014 \xE9 o que uma cad\xEAncia escuta, e ningu\xE9m o l\xEA numa tela.
24951
+ IF v_key IS NOT NULL THEN
24952
+ BEGIN
24953
+ PERFORM public.plg_emit_event(
24954
+ 'crm.deal_status_changed',
24955
+ jsonb_build_object('deal_id', p_deal_id, 'status', v_key, 'status_name', v_name, 'stage_id', d.stage_id),
24956
+ 'deal', p_deal_id::text, d.tenant_id);
24957
+ EXCEPTION WHEN undefined_function THEN
24958
+ -- App sem o barramento de eventos montado: o card j\xE1 mostra o status.
24959
+ NULL;
24960
+ END;
24961
+ END IF;
24962
+
24963
+ RETURN v_key;
24964
+ END $$;
24965
+
24966
+ REVOKE ALL ON FUNCTION public.crm_recompute_deal_status(uuid) FROM PUBLIC, anon;
24967
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO authenticated;
24968
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO service_role;
24969
+
24970
+ COMMENT ON FUNCTION public.crm_recompute_deal_status(uuid) IS
24971
+ 'Recalcula o status do neg\xF3cio a partir dos lan\xE7amentos. Nenhuma tela grava contact_status (020). O status n\xE3o entra na linha do tempo (044). E s\xF3 conta como contato o que uma pessoa lan\xE7ou pelo sistema ou o que traz desfecho \u2014 importa\xE7\xE3o n\xE3o \xE9 trabalho sobre o lead (045).';
24972
+
24973
+ -- \u2500\u2500 os cards que j\xE1 carregam a pastilha errada \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24974
+ --
24975
+ -- S\xF3 os que T\xCAM status: recalcular a base inteira seria uma passada por
24976
+ -- centenas de milhares de neg\xF3cios para mexer em trezentos.
24977
+ DO $$
24978
+ DECLARE r record; v_n bigint := 0;
24979
+ BEGIN
24980
+ FOR r IN SELECT id FROM public.plg_crm_deals WHERE contact_status IS NOT NULL LOOP
24981
+ PERFORM public.crm_recompute_deal_status(r.id);
24982
+ v_n := v_n + 1;
24983
+ END LOOP;
24984
+ RAISE NOTICE 'crm/045: % neg\xF3cio(s) recalculado(s)', v_n;
24985
+ END $$;
24986
+ `;
24987
+ var MIGRATION_046_A_PASTILHA_DO_CARD_SO_FALA_QUANDO_TEM_O_QUE_DIZER = `-- ---------------------------------------------------------------------------
24988
+ -- 046_a_pastilha_do_card_so_fala_quando_tem_o_que_dizer.sql
24989
+ --
24990
+ -- \u2500\u2500 a pastilha que repete a coluna \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
24991
+ --
24992
+ -- Com a \`045\` os 319 cards da feira voltaram a "Contato n\xE3o feito", que \xE9 a
24993
+ -- verdade. S\xF3 que eles est\xE3o TODOS na coluna "Novo (feira)" \u2014 e a coluna j\xE1
24994
+ -- diz isso. A pastilha passou a repetir o cabe\xE7alho em cima de cada card.
24995
+ --
24996
+ -- \xC9 o mesmo defeito da \`044\` por outro lado: informa\xE7\xE3o derivada ocupando
24997
+ -- espa\xE7o de leitura para n\xE3o acrescentar nada. Antes era uma linha na hist\xF3ria
24998
+ -- que dizia o status; agora \xE9 uma pastilha que diz a etapa.
24999
+ --
25000
+ -- A pastilha de status ganha o lugar dela quando diz o que a COLUNA N\xC3O DIZ:
25001
+ -- um card em "Novo (feira)" marcado "N\xE3o atendeu" informa (tent\xE1mos, n\xE3o
25002
+ -- voltou); marcado "Contato n\xE3o feito", n\xE3o.
25003
+ --
25004
+ -- \u2500\u2500 e por que uma coluna nova em vez de \`key = 'not_contacted'\` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25005
+ --
25006
+ -- \`not_contacted\` \xE9 a chave que a escada de f\xE1brica da \`020\` semeia, mas o
25007
+ -- inquilino pode renomear, reordenar ou trocar as chaves dele \u2014 a tabela
25008
+ -- \`plg_crm_deal_statuses\` existe exatamente para isso. Uma tela que compara a
25009
+ -- chave com um literal funciona nesta casa e cala-se na pr\xF3xima que chamar o
25010
+ -- primeiro degrau de outro nome.
25011
+ --
25012
+ -- O que N\xC3O muda \xE9 \`derived_from\`: \xE9 o vocabul\xE1rio fechado da regra, n\xE3o do
25013
+ -- inquilino, e \`no_activity\` significa "nada foi feito" em qualquer casa. A
25014
+ -- view passa a lev\xE1-lo ao cliente, e a decis\xE3o de mostrar ou n\xE3o deixa de ser
25015
+ -- um palpite sobre nomes.
25016
+ --
25017
+ -- Colunas NOVAS entram no FIM: \`CREATE OR REPLACE VIEW\` aceita acrescentar ao
25018
+ -- final e recusa mexer nas que existem. Sem DROP, portanto sem derrubar a
25019
+ -- \`plg_crm_rep_deals\` que pende desta.
25020
+ -- ---------------------------------------------------------------------------
25021
+
25022
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
25023
+ SELECT d.id,
25024
+ d.tenant_id,
25025
+ d.status,
25026
+ d.value,
25027
+ COALESCE(d.title, d.notes) AS title,
25028
+ d.contact_id,
25029
+ d.assigned_to_id,
25030
+ d.tags,
25031
+ d.metadata ->> 'contactName'::text AS contact_name,
25032
+ d.created_at,
25033
+ d.updated_at,
25034
+ d.pipeline_id,
25035
+ d.stage_id,
25036
+ d.probability,
25037
+ d.expected_close_date,
25038
+ d.lead_id,
25039
+ d.lost_reason,
25040
+ ps.name AS stage_name,
25041
+ ps.color AS stage_color,
25042
+ ps."order" AS stage_order,
25043
+ ps.name AS stage,
25044
+ d.won_at,
25045
+ d.lost_at,
25046
+ d.company_id,
25047
+ d.contact_status,
25048
+ d.contact_status_at,
25049
+ cs.name AS contact_status_name,
25050
+ cs.color AS contact_status_color,
25051
+ d.notes,
25052
+ -- 046, no fim da lista: a regra de onde o status saiu. \`no_activity\` \xE9 o
25053
+ -- primeiro degrau \u2014 nada foi feito \u2014 e \xE9 o \xFAnico que a tela esconde.
25054
+ cs.derived_from AS contact_status_derived_from
25055
+ FROM plg_crm_deals d
25056
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
25057
+ LEFT JOIN LATERAL ( SELECT s.name,
25058
+ s.color,
25059
+ s.derived_from
25060
+ FROM plg_crm_deal_statuses s
25061
+ 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)
25062
+ ORDER BY (s.stage_id IS NOT NULL) DESC
25063
+ LIMIT 1) cs ON true
25064
+ ;
25065
+
25066
+ COMMENT ON VIEW public.v_deals IS
25067
+ 'O card do funil, com a etapa e o status derivado j\xE1 resolvidos. \`contact_status_derived_from\` diz de que regra o status saiu \u2014 a tela usa isso para calar a pastilha no primeiro degrau, em vez de comparar a chave com um literal que o inquilino pode renomear (046).';
25068
+ `;
24203
25069
  var MIGRATIONS = [
24204
25070
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
24205
25071
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -24241,7 +25107,12 @@ var MIGRATIONS = [
24241
25107
  { id: "038_canal_origem_e_campanha_sao_tres_perguntas", sql: MIGRATION_038_CANAL_ORIGEM_E_CAMPANHA_SAO_TRES_PERGUNTAS },
24242
25108
  { id: "039_a_bandeira_agrupa_o_que_a_raiz_do_cnpj_nao_ve", sql: MIGRATION_039_A_BANDEIRA_AGRUPA_O_QUE_A_RAIZ_DO_CNPJ_NAO_VE },
24243
25109
  { id: "040_o_card_do_funil_nao_le_a_agenda_inteira", sql: MIGRATION_040_O_CARD_DO_FUNIL_NAO_LE_A_AGENDA_INTEIRA },
24244
- { id: "041_o_nome_no_card_e_do_negocio_nao_da_agenda", sql: MIGRATION_041_O_NOME_NO_CARD_E_DO_NEGOCIO_NAO_DA_AGENDA }
25110
+ { id: "041_o_nome_no_card_e_do_negocio_nao_da_agenda", sql: MIGRATION_041_O_NOME_NO_CARD_E_DO_NEGOCIO_NAO_DA_AGENDA },
25111
+ { id: "042_a_atividade_diz_quem_a_fez", sql: MIGRATION_042_A_ATIVIDADE_DIZ_QUEM_A_FEZ },
25112
+ { id: "043_a_cadencia_para_de_esperar_um_fato_que_nunca_chega", sql: MIGRATION_043_A_CADENCIA_PARA_DE_ESPERAR_UM_FATO_QUE_NUNCA_CHEGA },
25113
+ { id: "044_o_status_nao_e_um_acontecimento", sql: MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO },
25114
+ { id: "045_contato_feito_e_contato_que_alguem_fez", sql: MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ },
25115
+ { 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 }
24245
25116
  ];
24246
25117
 
24247
25118
  // src/locales/en.ts
@@ -24326,7 +25197,26 @@ var en = {
24326
25197
  "crm.leadDetail.notFound": "Not found",
24327
25198
  "crm.leadDetail.notes": "Notes",
24328
25199
  "crm.leadDetail.phone": "Phone",
25200
+ "crm.leads.filters.allStatuses": "Any status",
25201
+ "crm.leads.filters.allSources": "Todas as origens",
25202
+ "crm.leads.filters.searchTag": "Search tag",
25203
+ "crm.leads.filters.noTag": "No tag found",
25204
+ "crm.leads.filters.tag": "Etiqueta",
25205
+ "crm.leads.filters.allTags": "Todas as etiquetas",
25206
+ "crm.leads.filters.owner": "Respons\xE1vel",
25207
+ "crm.leads.filters.allOwners": "Qualquer respons\xE1vel",
25208
+ "crm.leads.filters.unassigned": "Sem respons\xE1vel",
25209
+ "crm.leads.filters.reach": "Contat\xE1vel por",
25210
+ "crm.leads.filters.anyReach": "Qualquer canal",
25211
+ "crm.leads.filters.hasPhone": "Tem telefone",
25212
+ "crm.leads.filters.hasEmail": "Tem e-mail",
25213
+ "crm.leads.filters.noPhone": "Sem telefone",
25214
+ "crm.leads.filters.anyCompany": "Com ou sem empresa",
25215
+ "crm.leads.filters.withCompany": "Com empresa",
25216
+ "crm.leads.filters.withoutCompany": "Sem empresa",
25217
+ "crm.leads.filters.clear": "Limpar",
24329
25218
  "crm.leadDetail.pipeline": "Pipeline",
25219
+ "crm.leadDetail.openDeal": "Open in pipeline",
24330
25220
  "crm.leadDetail.probability": "Probability",
24331
25221
  "crm.leadDetail.quotes": "Quotes",
24332
25222
  "crm.leadDetail.source": "Source",
@@ -24428,6 +25318,7 @@ var en = {
24428
25318
  "crm.rota.count": "{{count}} in the rota",
24429
25319
  "crm.pipeline.pickFunnel": "Pick a funnel",
24430
25320
  "crm.pipeline.setupStages": "Set up stages",
25321
+ "crm.pipeline.loadMore": "Show {n} more",
24431
25322
  "crm.pipeline.noDeals": "No deals",
24432
25323
  "crm.pipeline.addLead": "Add lead",
24433
25324
  "crm.deals.switchView": "Switch deals view",
@@ -24488,6 +25379,8 @@ var en = {
24488
25379
  "crm.deals.allCampaigns": "All campaigns",
24489
25380
  "crm.deals.allCities": "All cities",
24490
25381
  "crm.card.companyTitle": "Company",
25382
+ "crm.card.takeOver": "Take this lead",
25383
+ "crm.card.takeOverFrom": "Take over",
24491
25384
  "crm.card.owner": "Owner",
24492
25385
  "crm.card.noOwner": "No owner",
24493
25386
  "crm.card.noDocument": "No tax ID on file",
@@ -24945,6 +25838,7 @@ var en = {
24945
25838
  "crm.leadDetail.whatsapp": "WhatsApp",
24946
25839
  "crm.leads.companyCol": "Company",
24947
25840
  "crm.leads.pageRangeOf": "of",
25841
+ "crm.leads.page": "Page",
24948
25842
  "crm.leads.firstPage": "First page",
24949
25843
  "crm.leads.prevPage": "Previous page",
24950
25844
  "crm.leads.nextPage": "Next page",
@@ -25081,7 +25975,26 @@ var ptBR = {
25081
25975
  "crm.leadDetail.notFound": "N\xE3o encontrado",
25082
25976
  "crm.leadDetail.notes": "Observa\xE7\xF5es",
25083
25977
  "crm.leadDetail.phone": "Telefone",
25978
+ "crm.leads.filters.allStatuses": "Qualquer status",
25979
+ "crm.leads.filters.allSources": "Todas as origens",
25980
+ "crm.leads.filters.searchTag": "Buscar etiqueta",
25981
+ "crm.leads.filters.noTag": "Nenhuma etiqueta",
25982
+ "crm.leads.filters.tag": "Etiqueta",
25983
+ "crm.leads.filters.allTags": "Todas as etiquetas",
25984
+ "crm.leads.filters.owner": "Respons\xE1vel",
25985
+ "crm.leads.filters.allOwners": "Qualquer respons\xE1vel",
25986
+ "crm.leads.filters.unassigned": "Sem respons\xE1vel",
25987
+ "crm.leads.filters.reach": "Contat\xE1vel por",
25988
+ "crm.leads.filters.anyReach": "Qualquer canal",
25989
+ "crm.leads.filters.hasPhone": "Tem telefone",
25990
+ "crm.leads.filters.hasEmail": "Tem e-mail",
25991
+ "crm.leads.filters.noPhone": "Sem telefone",
25992
+ "crm.leads.filters.anyCompany": "Com ou sem empresa",
25993
+ "crm.leads.filters.withCompany": "Com empresa",
25994
+ "crm.leads.filters.withoutCompany": "Sem empresa",
25995
+ "crm.leads.filters.clear": "Limpar",
25084
25996
  "crm.leadDetail.pipeline": "Pipeline",
25997
+ "crm.leadDetail.openDeal": "Abrir no funil",
25085
25998
  "crm.leadDetail.probability": "Probabilidade",
25086
25999
  "crm.leadDetail.quotes": "Or\xE7amentos",
25087
26000
  "crm.leadDetail.source": "Origem",
@@ -25183,6 +26096,7 @@ var ptBR = {
25183
26096
  "crm.rota.count": "{{count}} na rota",
25184
26097
  "crm.pipeline.pickFunnel": "Escolher funil",
25185
26098
  "crm.pipeline.setupStages": "Configurar etapas",
26099
+ "crm.pipeline.loadMore": "Ver mais {n}",
25186
26100
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
25187
26101
  "crm.pipeline.addLead": "Adicionar lead",
25188
26102
  "crm.deals.switchView": "Trocar a vis\xE3o dos neg\xF3cios",
@@ -25243,6 +26157,8 @@ var ptBR = {
25243
26157
  "crm.deals.allCampaigns": "Todas as campanhas",
25244
26158
  "crm.deals.allCities": "Todas as cidades",
25245
26159
  "crm.card.companyTitle": "Empresa",
26160
+ "crm.card.takeOver": "Assumir este lead",
26161
+ "crm.card.takeOverFrom": "Assumir de quem est\xE1",
25246
26162
  "crm.card.owner": "Respons\xE1vel",
25247
26163
  "crm.card.noOwner": "Sem respons\xE1vel",
25248
26164
  "crm.card.noDocument": "Sem CNPJ cadastrado",
@@ -25700,6 +26616,7 @@ var ptBR = {
25700
26616
  "crm.leadDetail.whatsapp": "WhatsApp",
25701
26617
  "crm.leads.companyCol": "Empresa",
25702
26618
  "crm.leads.pageRangeOf": "de",
26619
+ "crm.leads.page": "P\xE1gina",
25703
26620
  "crm.leads.firstPage": "Primeira p\xE1gina",
25704
26621
  "crm.leads.prevPage": "P\xE1gina anterior",
25705
26622
  "crm.leads.nextPage": "Pr\xF3xima p\xE1gina",