@fayz-ai/plugin-crm 0.15.0 → 0.17.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, DictateButton, 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();
@@ -3034,6 +3062,7 @@ function LogActivityButton({ target, onLogged }) {
3034
3062
  const [types, setTypes] = useState(() => DEFAULT_ACTIVITY_TYPES);
3035
3063
  const [type, setType] = useState("whatsapp");
3036
3064
  const [note, setNote] = useState("");
3065
+ const [noteBase, setNoteBase] = useState("");
3037
3066
  const [outcome, setOutcome] = useState("connected");
3038
3067
  const [nextDate, setNextDate] = useState("");
3039
3068
  const [saving, setSaving] = useState(false);
@@ -3082,6 +3111,7 @@ function LogActivityButton({ target, onLogged }) {
3082
3111
  });
3083
3112
  }
3084
3113
  setNote("");
3114
+ setNoteBase("");
3085
3115
  setNextDate("");
3086
3116
  setOutcome("connected");
3087
3117
  setOpen(false);
@@ -3113,23 +3143,40 @@ function LogActivityButton({ target, onLogged }) {
3113
3143
  /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9 text-sm", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
3114
3144
  /* @__PURE__ */ jsx(SelectContent, { children: OUTCOMES.map((o) => /* @__PURE__ */ jsx(SelectItem, { value: o, children: t2(`crm.outcome.${o}`) }, o)) })
3115
3145
  ] }),
3116
- /* @__PURE__ */ jsx(
3117
- "textarea",
3118
- {
3119
- autoFocus: true,
3120
- rows: 3,
3121
- value: note,
3122
- onChange: (e) => setNote(e.target.value),
3123
- onKeyDown: (e) => {
3124
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
3125
- e.preventDefault();
3126
- void submit();
3146
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
3147
+ /* @__PURE__ */ jsx(
3148
+ "textarea",
3149
+ {
3150
+ autoFocus: true,
3151
+ rows: 3,
3152
+ value: note,
3153
+ onChange: (e) => {
3154
+ setNote(e.target.value);
3155
+ setNoteBase(e.target.value);
3156
+ },
3157
+ onKeyDown: (e) => {
3158
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
3159
+ e.preventDefault();
3160
+ void submit();
3161
+ }
3162
+ },
3163
+ placeholder: t2("crm.followUp.placeholder"),
3164
+ className: "w-full resize-none rounded-lg border bg-background px-3 py-2 pr-10 text-sm outline-none placeholder:text-muted-foreground/70 focus:ring-2 focus:ring-ring"
3165
+ }
3166
+ ),
3167
+ /* @__PURE__ */ jsx(
3168
+ DictateButton,
3169
+ {
3170
+ className: "absolute right-1.5 top-1.5",
3171
+ startLabel: t2("crm.followUp.dictate"),
3172
+ stopLabel: t2("crm.followUp.dictateStop"),
3173
+ onTranscript: (texto) => {
3174
+ const base = noteBase.trimEnd();
3175
+ setNote(base ? `${base} ${texto}` : texto);
3127
3176
  }
3128
- },
3129
- placeholder: t2("crm.followUp.placeholder"),
3130
- className: "w-full resize-none rounded-lg border bg-background px-3 py-2 text-sm outline-none placeholder:text-muted-foreground/70 focus:ring-2 focus:ring-ring"
3131
- }
3132
- ),
3177
+ }
3178
+ )
3179
+ ] }),
3133
3180
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
3134
3181
  /* @__PURE__ */ jsx(CalendarClock, { className: "h-3.5 w-3.5 shrink-0 text-muted-foreground" }),
3135
3182
  /* @__PURE__ */ jsx(DatePicker, { value: nextDate, onChange: setNextDate }),
@@ -3212,6 +3259,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3212
3259
  const [draft, setDraft] = useState(null);
3213
3260
  const [company, setCompany] = useState(null);
3214
3261
  const [team, setTeam] = useState(null);
3262
+ const [myUserId, setMyUserId] = useState(null);
3215
3263
  const [savingOwner, setSavingOwner] = useState(false);
3216
3264
  useEffect(() => {
3217
3265
  if (open) void fetchTagDefs();
@@ -3263,10 +3311,24 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3263
3311
  void loadTeamOrNull().then((t3) => {
3264
3312
  if (!cancelled) setTeam(t3);
3265
3313
  });
3314
+ void loadMyUserId().then((u) => {
3315
+ if (!cancelled) setMyUserId(u);
3316
+ });
3266
3317
  return () => {
3267
3318
  cancelled = true;
3268
3319
  };
3269
3320
  }, [dealId, open]);
3321
+ const leadIdDoNegocio = deal?.leadId;
3322
+ useEffect(() => {
3323
+ if (!open || !leadIdDoNegocio) return;
3324
+ let cancelled = false;
3325
+ void provider.getActivities({ dealId, leadId: leadIdDoNegocio }).then((r) => {
3326
+ if (!cancelled) setActivities(r.data);
3327
+ });
3328
+ return () => {
3329
+ cancelled = true;
3330
+ };
3331
+ }, [dealId, leadIdDoNegocio, open]);
3270
3332
  const openStages = useMemo(() => stages.filter((s) => !s.isLost), [stages]);
3271
3333
  async function changeStage(stage) {
3272
3334
  if (!deal || stage.id === deal.stageId || movingStage) return;
@@ -3274,7 +3336,7 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3274
3336
  try {
3275
3337
  await moveDealToStage(deal.id, stage.id);
3276
3338
  setDeal({ ...deal, stageId: stage.id, stageName: stage.name, stageColor: stage.color, probability: stage.probability });
3277
- const refreshed = await provider.getActivities({ dealId });
3339
+ const refreshed = await provider.getActivities({ dealId, leadId: deal?.leadId });
3278
3340
  setActivities(refreshed.data);
3279
3341
  } catch {
3280
3342
  toast.error(t2("crm.pipeline.moveFailed"));
@@ -3494,27 +3556,43 @@ function DealCardModal({ dealId, open, onClose, onViewLead, onViewQuote, onViewC
3494
3556
  ]
3495
3557
  }
3496
3558
  ) }),
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
- ) }),
3559
+ /* @__PURE__ */ jsxs(Section, { title: t2("crm.card.owner"), children: [
3560
+ myUserId && deal?.assignedToId !== myUserId && /* @__PURE__ */ jsxs(
3561
+ "button",
3562
+ {
3563
+ onClick: () => {
3564
+ void changeOwner(myUserId);
3565
+ },
3566
+ disabled: savingOwner,
3567
+ 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",
3568
+ children: [
3569
+ /* @__PURE__ */ jsx(UserCheck, { className: "h-3.5 w-3.5" }),
3570
+ deal?.assignedToId ? t2("crm.card.takeOverFrom") : t2("crm.card.takeOver")
3571
+ ]
3572
+ }
3573
+ ),
3574
+ team === null ? /* @__PURE__ */ jsx("div", { className: "h-9 animate-pulse rounded-lg bg-muted/40", "aria-hidden": true }) : team.length === 0 ? (
3575
+ // Lista vazia aqui quase sempre é falta de `members.read`, e
3576
+ // não uma casa sem equipe. Dizer "ninguém" seria mentir.
3577
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.rota.cannotRead") })
3578
+ ) : /* @__PURE__ */ jsxs(
3579
+ Select,
3580
+ {
3581
+ value: deal?.assignedToId ?? "__none__",
3582
+ onValueChange: (v) => {
3583
+ void changeOwner(v === "__none__" ? void 0 : v);
3584
+ },
3585
+ disabled: savingOwner,
3586
+ children: [
3587
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "h-9", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
3588
+ /* @__PURE__ */ jsxs(SelectContent, { children: [
3589
+ /* @__PURE__ */ jsx(SelectItem, { value: "__none__", children: t2("crm.card.noOwner") }),
3590
+ team.map((m) => /* @__PURE__ */ jsx(SelectItem, { value: m.userId, children: m.name }, m.userId))
3591
+ ] })
3592
+ ]
3593
+ }
3594
+ )
3595
+ ] }),
3518
3596
  /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-5 gap-y-1 text-[11px] text-muted-foreground", children: [
3519
3597
  /* @__PURE__ */ jsxs("span", { children: [
3520
3598
  t2("crm.dealSidebar.probability"),
@@ -3891,6 +3969,19 @@ function LeadListView({ onNew, onEdit }) {
3891
3969
  const refreshLeads = useCrmStore((s) => s.refreshLeads);
3892
3970
  const [search, setSearch] = useState("");
3893
3971
  const [statusFilter, setStatusFilter] = useState([]);
3972
+ const [sourceFilter, setSourceFilter] = useState();
3973
+ const [tagFilter, setTagFilter] = useState([]);
3974
+ const [ownerFilter, setOwnerFilter] = useState();
3975
+ const [reachFilter, setReachFilter] = useState();
3976
+ const [companyFilter, setCompanyFilter] = useState();
3977
+ const leadSources = useCrmStore((s) => s.leadSources);
3978
+ const fetchLeadSources = useCrmStore((s) => s.fetchLeadSources);
3979
+ const tagDefs = useCrmStore((s) => s.tagDefs);
3980
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
3981
+ useEffect(() => {
3982
+ void fetchLeadSources();
3983
+ void fetchTagDefs();
3984
+ }, []);
3894
3985
  const [archiveTarget, setArchiveTarget] = useState(null);
3895
3986
  const [bulkBusy, setBulkBusy] = useState(false);
3896
3987
  const [page, setPage] = useState(1);
@@ -3914,15 +4005,21 @@ function LeadListView({ onNew, onEdit }) {
3914
4005
  const columns = useMemo(() => buildColumns(t2, leads2, scores), [t2, leads2, scores]);
3915
4006
  useEffect(() => {
3916
4007
  setPage(1);
3917
- }, [statusFilter, search]);
4008
+ }, [statusFilter, search, sourceFilter, tagFilter, ownerFilter, companyFilter, reachFilter]);
3918
4009
  useEffect(() => {
3919
4010
  fetchLeads({
3920
4011
  status: statusFilter.length > 0 ? statusFilter : void 0,
3921
4012
  search: search || void 0,
4013
+ sourceId: sourceFilter,
4014
+ tags: tagFilter.length ? tagFilter : void 0,
4015
+ assignedToId: ownerFilter,
4016
+ hasCompany: companyFilter === void 0 ? void 0 : companyFilter === "yes",
4017
+ hasPhone: reachFilter === "phone" ? true : reachFilter === "none" ? false : void 0,
4018
+ hasEmail: reachFilter === "email" ? true : void 0,
3922
4019
  page,
3923
4020
  pageSize: PAGE_SIZE2
3924
4021
  });
3925
- }, [statusFilter, search, page]);
4022
+ }, [statusFilter, search, sourceFilter, tagFilter, ownerFilter, companyFilter, reachFilter, page]);
3926
4023
  const tags = useMemo(() => LEAD_STATUS_OPTIONS.map((o) => ({ value: o.value, label: t2(o.labelKey) })), [t2]);
3927
4024
  const runBulk = useCallback(async (rows, write, labels) => {
3928
4025
  setBulkBusy(true);
@@ -4060,6 +4157,102 @@ function LeadListView({ onNew, onEdit }) {
4060
4157
  );
4061
4158
  toast.success(t2("crud.export.toastSuccess", { count: String(todos.length) }));
4062
4159
  }, [leads2, t2, provider, statusFilter, search]);
4160
+ const tagOptions = useMemo(() => {
4161
+ const doCadastro = [...tagDefs.values()].map((d) => ({ value: d.slug, label: d.name ?? d.slug, color: d.color }));
4162
+ if (doCadastro.length) return doCadastro;
4163
+ const vistas = /* @__PURE__ */ new Set();
4164
+ for (const l of leads2) for (const t3 of l.tags ?? []) vistas.add(t3);
4165
+ return [...vistas].sort().map((t3) => ({ value: t3, label: t3 }));
4166
+ }, [tagDefs, leads2]);
4167
+ const sourceOptions = useMemo(
4168
+ () => leadSources.map((o) => ({ value: o.id, label: o.name })),
4169
+ [leadSources]
4170
+ );
4171
+ const ownerOptions = useMemo(() => {
4172
+ const vistos = /* @__PURE__ */ new Map();
4173
+ for (const l of leads2) if (l.assignedToId) vistos.set(l.assignedToId, l.assignedToName ?? l.assignedToId);
4174
+ return [
4175
+ // "Ninguém" primeiro: é a pergunta que se faz antes de distribuir a
4176
+ // carteira, e a que a lista sozinha não responde.
4177
+ { value: "none", label: t2("crm.leads.filters.unassigned") },
4178
+ ...[...vistos].map(([id, nome]) => ({ value: id, label: nome }))
4179
+ ];
4180
+ }, [leads2, t2]);
4181
+ const activeFilterCount = (statusFilter.length ? 1 : 0) + (sourceFilter ? 1 : 0) + (tagFilter.length ? 1 : 0) + (ownerFilter ? 1 : 0) + (companyFilter ? 1 : 0) + (reachFilter ? 1 : 0);
4182
+ const clearFilters = () => {
4183
+ setStatusFilter([]);
4184
+ setSourceFilter(void 0);
4185
+ setTagFilter([]);
4186
+ setOwnerFilter(void 0);
4187
+ setCompanyFilter(void 0);
4188
+ setReachFilter(void 0);
4189
+ };
4190
+ const filtros = /* @__PURE__ */ jsxs(Fragment, { children: [
4191
+ /* @__PURE__ */ jsx(
4192
+ FilterChip,
4193
+ {
4194
+ label: t2("crm.leads.source"),
4195
+ icon: Send,
4196
+ allLabel: t2("crm.leads.filters.allSources"),
4197
+ options: sourceOptions,
4198
+ value: sourceFilter,
4199
+ onChange: setSourceFilter
4200
+ }
4201
+ ),
4202
+ /* @__PURE__ */ jsx(
4203
+ MultiSelect,
4204
+ {
4205
+ variant: "chip",
4206
+ icon: Tag,
4207
+ options: tagOptions,
4208
+ value: tagFilter,
4209
+ onChange: setTagFilter,
4210
+ allLabel: t2("crm.leads.filters.allTags"),
4211
+ searchPlaceholder: t2("crm.leads.filters.searchTag"),
4212
+ emptyLabel: t2("crm.leads.filters.noTag")
4213
+ }
4214
+ ),
4215
+ /* @__PURE__ */ jsx(
4216
+ FilterChip,
4217
+ {
4218
+ label: t2("crm.leads.filters.owner"),
4219
+ icon: User,
4220
+ allLabel: t2("crm.leads.filters.allOwners"),
4221
+ options: ownerOptions,
4222
+ value: ownerFilter,
4223
+ onChange: setOwnerFilter
4224
+ }
4225
+ ),
4226
+ /* @__PURE__ */ jsx(
4227
+ FilterChip,
4228
+ {
4229
+ label: t2("crm.leads.filters.reach"),
4230
+ icon: Phone,
4231
+ allLabel: t2("crm.leads.filters.anyReach"),
4232
+ options: [
4233
+ { value: "phone", label: t2("crm.leads.filters.hasPhone") },
4234
+ { value: "email", label: t2("crm.leads.filters.hasEmail") },
4235
+ { value: "none", label: t2("crm.leads.filters.noPhone") }
4236
+ ],
4237
+ value: reachFilter,
4238
+ onChange: setReachFilter
4239
+ }
4240
+ ),
4241
+ /* @__PURE__ */ jsx(
4242
+ FilterChip,
4243
+ {
4244
+ label: t2("crm.leads.companyCol"),
4245
+ icon: Building2,
4246
+ allLabel: t2("crm.leads.filters.anyCompany"),
4247
+ options: [
4248
+ { value: "yes", label: t2("crm.leads.filters.withCompany") },
4249
+ { value: "no", label: t2("crm.leads.filters.withoutCompany") }
4250
+ ],
4251
+ value: companyFilter,
4252
+ onChange: setCompanyFilter
4253
+ }
4254
+ )
4255
+ ] });
4063
4256
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
4064
4257
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
4065
4258
  /* @__PURE__ */ jsx(
@@ -4074,15 +4267,22 @@ function LeadListView({ onNew, onEdit }) {
4074
4267
  onPageChange: setPage,
4075
4268
  rangeOfLabel: t2("crm.leads.pageRangeOf"),
4076
4269
  firstPageLabel: t2("crm.leads.firstPage"),
4270
+ pageLabel: t2("crm.leads.page"),
4077
4271
  prevPageLabel: t2("crm.leads.prevPage"),
4078
4272
  nextPageLabel: t2("crm.leads.nextPage"),
4079
4273
  lastPageLabel: t2("crm.leads.lastPage"),
4080
4274
  searchPlaceholder: t2("crm.leads.searchPlaceholder"),
4081
4275
  search,
4082
4276
  onSearchChange: setSearch,
4277
+ filters: filtros,
4278
+ activeFilterCount,
4279
+ onClearFilters: activeFilterCount > 0 ? clearFilters : void 0,
4280
+ clearFiltersLabel: t2("crm.leads.filters.clear"),
4281
+ searchOwnRow: true,
4083
4282
  searchDebounce: 0,
4084
4283
  tags,
4085
4284
  activeTag: statusFilter.length === 1 ? statusFilter[0] : void 0,
4285
+ allTagLabel: t2("crm.leads.filters.allStatuses"),
4086
4286
  onTagChange: (v) => setStatusFilter(v ? [v] : []),
4087
4287
  newLabel: t2("crm.leads.newLead"),
4088
4288
  onNew,
@@ -5337,7 +5537,7 @@ function FieldRow({ label: label2, value }) {
5337
5537
  /* @__PURE__ */ jsx("dd", { className: "col-span-2 text-sm text-foreground", children: value ?? /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" }) })
5338
5538
  ] });
5339
5539
  }
5340
- function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenCompany, onOpenPerson }) {
5540
+ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenCompany, onOpenPerson, onOpenDeal }) {
5341
5541
  const provider = useCrmProvider();
5342
5542
  const { currency } = useCrmConfig();
5343
5543
  const locale = currency.locale;
@@ -5504,7 +5704,21 @@ function LeadDetailView({ leadId, onBack, onCreateQuote, onViewQuote, onOpenComp
5504
5704
  ] });
5505
5705
  })(),
5506
5706
  deal && /* @__PURE__ */ jsxs("div", { children: [
5507
- /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground mb-1", children: t2("crm.leadDetail.pipeline") }),
5707
+ /* @__PURE__ */ jsxs("div", { className: "mb-1 flex items-center justify-between gap-2", children: [
5708
+ /* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold text-foreground", children: t2("crm.leadDetail.pipeline") }),
5709
+ onOpenDeal && /* @__PURE__ */ jsxs(
5710
+ "button",
5711
+ {
5712
+ onClick: () => onOpenDeal(deal.id),
5713
+ className: "inline-flex items-center gap-1 rounded-button border bg-card px-2 py-1 text-[11px] font-medium hover:bg-muted",
5714
+ children: [
5715
+ t2("crm.leadDetail.openDeal"),
5716
+ " ",
5717
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3" })
5718
+ ]
5719
+ }
5720
+ )
5721
+ ] }),
5508
5722
  /* @__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
5723
  /* @__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
5724
  deal.stageColor && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 rounded-full", style: { backgroundColor: deal.stageColor } }),
@@ -8062,7 +8276,7 @@ function CrmPage({ config, provider, store, registries }) {
8062
8276
  { id: "offers", render: () => /* @__PURE__ */ jsx(MyOffersView, {}) },
8063
8277
  { id: "distribution-board", render: () => /* @__PURE__ */ jsx(DistributionView, {}) },
8064
8278
  { 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}`) }) },
8279
+ { 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
8280
  { id: "quotes-detail", render: ({ id }) => /* @__PURE__ */ jsx(QuoteDetailView, { quoteId: id, onBack: () => navigate("quotes-list"), onEdit: () => navigate(`quotes-edit:${id}`), onInvoiceCreated: (invoiceId) => {
8067
8281
  window.location.hash = `/financial/receivables/detail/${invoiceId}`;
8068
8282
  } }) },
@@ -8719,6 +8933,7 @@ function createStore(seedStages) {
8719
8933
  personPhones: []
8720
8934
  };
8721
8935
  }
8936
+ var MOCK_DEALS_POR_ETAPA = 100;
8722
8937
  function createMockCrmProvider(options) {
8723
8938
  const store = createStore(options?.dealStages);
8724
8939
  const tenantId = "mock-tenant";
@@ -8823,6 +9038,16 @@ function createMockCrmProvider(options) {
8823
9038
  const s = query.search.toLowerCase();
8824
9039
  results = results.filter((l) => l.name.toLowerCase().includes(s) || l.email?.toLowerCase().includes(s) || l.company?.toLowerCase().includes(s));
8825
9040
  }
9041
+ if (query.tags?.length) {
9042
+ results = results.filter((l) => query.tags.every((t2) => (l.tags ?? []).includes(t2)));
9043
+ }
9044
+ if (query.assignedToId === "none") results = results.filter((l) => !l.assignedToId);
9045
+ else if (query.assignedToId) results = results.filter((l) => l.assignedToId === query.assignedToId);
9046
+ if (query.hasCompany !== void 0) results = results.filter((l) => Boolean(l.companyId) === query.hasCompany);
9047
+ if (query.hasPhone !== void 0) results = results.filter((l) => Boolean(l.phone?.trim()) === query.hasPhone);
9048
+ if (query.hasEmail !== void 0) results = results.filter((l) => Boolean(l.email?.trim()) === query.hasEmail);
9049
+ if (query.createdFrom) results = results.filter((l) => l.createdAt >= query.createdFrom);
9050
+ if (query.createdTo) results = results.filter((l) => l.createdAt <= query.createdTo);
8826
9051
  results.sort((a, b) => b.createdAt.localeCompare(a.createdAt));
8827
9052
  return paginate(results, query.page, query.pageSize);
8828
9053
  },
@@ -8887,7 +9112,7 @@ function createMockCrmProvider(options) {
8887
9112
  async getDealById(id) {
8888
9113
  return store.deals.find((d) => d.id === id) ?? null;
8889
9114
  },
8890
- async getDealsByStage(pipelineId, filter, knownStages) {
9115
+ async getDealsByStage(pipelineId, filter, knownStages, limits) {
8891
9116
  const stages = knownStages ?? store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
8892
9117
  const matches2 = (d) => {
8893
9118
  if (filter?.tags?.length && !filter.tags.some((t2) => (d.tags ?? []).includes(t2))) return false;
@@ -8896,10 +9121,13 @@ function createMockCrmProvider(options) {
8896
9121
  return true;
8897
9122
  };
8898
9123
  const map = /* @__PURE__ */ new Map();
9124
+ const totals = /* @__PURE__ */ new Map();
8899
9125
  for (const stage of stages) {
8900
- map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d)));
9126
+ const todos = store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d));
9127
+ totals.set(stage.id, todos.length);
9128
+ map.set(stage.id, todos.slice(0, limits?.[stage.id] ?? MOCK_DEALS_POR_ETAPA));
8901
9129
  }
8902
- return map;
9130
+ return { byStage: map, totals };
8903
9131
  },
8904
9132
  async createDeal(input) {
8905
9133
  const stage = store.stages.find((s) => s.id === input.stageId);
@@ -8986,8 +9214,12 @@ function createMockCrmProvider(options) {
8986
9214
  // Activities
8987
9215
  async getActivities(query) {
8988
9216
  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);
9217
+ if (query.dealId && query.leadId) {
9218
+ results = results.filter((a) => a.dealId === query.dealId || a.leadId === query.leadId);
9219
+ } else {
9220
+ if (query.dealId) results = results.filter((a) => a.dealId === query.dealId);
9221
+ if (query.leadId) results = results.filter((a) => a.leadId === query.leadId);
9222
+ }
8991
9223
  if (query.activityType) results = results.filter((a) => a.activityType === query.activityType);
8992
9224
  if (query.completed !== void 0) {
8993
9225
  results = query.completed ? results.filter((a) => a.completedAt) : results.filter((a) => !a.completedAt);
@@ -9955,6 +10187,7 @@ function toDeal(r) {
9955
10187
  contactState: r.contact_state ?? void 0,
9956
10188
  contactStatus: r.contact_status ?? void 0,
9957
10189
  contactStatusName: r.contact_status_name ?? void 0,
10190
+ contactStatusDerivedFrom: r.contact_status_derived_from ?? void 0,
9958
10191
  contactStatusColor: r.contact_status_color ?? void 0,
9959
10192
  contactStatusAt: r.contact_status_at ?? void 0,
9960
10193
  companyId: r.company_id ?? void 0,
@@ -10134,6 +10367,18 @@ function createSupabaseCrmProvider(options) {
10134
10367
  const statuses = Array.isArray(query.status) ? query.status : [query.status];
10135
10368
  qb = qb.in("lead_status", statuses);
10136
10369
  }
10370
+ if (query.sourceId) qb = qb.eq("source_id", query.sourceId);
10371
+ if (query.tags?.length) qb = qb.contains("tags", query.tags);
10372
+ if (query.assignedToId === "none") qb = qb.is("assigned_to_id", null);
10373
+ else if (query.assignedToId) qb = qb.eq("assigned_to_id", query.assignedToId);
10374
+ if (query.hasCompany === true) qb = qb.not("company_id", "is", null);
10375
+ if (query.hasCompany === false) qb = qb.is("company_id", null);
10376
+ if (query.hasPhone === true) qb = qb.not("phone", "is", null).neq("phone", "");
10377
+ if (query.hasPhone === false) qb = qb.or("phone.is.null,phone.eq.");
10378
+ if (query.hasEmail === true) qb = qb.not("email", "is", null).neq("email", "");
10379
+ if (query.hasEmail === false) qb = qb.or("email.is.null,email.eq.");
10380
+ if (query.createdFrom) qb = qb.gte("created_at", query.createdFrom);
10381
+ if (query.createdTo) qb = qb.lte("created_at", query.createdTo);
10137
10382
  const page = query.page ?? 1;
10138
10383
  const pageSize = query.pageSize ?? 50;
10139
10384
  qb = qb.range((page - 1) * pageSize, page * pageSize - 1).order("created_at", { ascending: false });
@@ -10292,19 +10537,21 @@ function createSupabaseCrmProvider(options) {
10292
10537
  if (!r) return null;
10293
10538
  return toDeal(r);
10294
10539
  },
10295
- async getDealsByStage(pipelineId, filter, knownStages) {
10540
+ async getDealsByStage(pipelineId, filter, knownStages, limits) {
10296
10541
  const { pub } = getClients();
10297
10542
  const stages = knownStages ?? await provider.getPipelineStages(pipelineId);
10298
10543
  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)");
10544
+ let qb = pub.from("v_deals").select("*", { count: "exact" }).eq("pipeline_id", pipelineId).eq("stage_id", stageId).not("status", "in", "(lost,archived)");
10300
10545
  if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
10301
10546
  if (filter?.createdFrom) qb = qb.gte("created_at", filter.createdFrom);
10302
10547
  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 ?? [];
10548
+ const teto = limits?.[stageId] ?? DEALS_POR_ETAPA;
10549
+ const { data: data2, count } = await qb.order("updated_at", { ascending: false }).limit(teto);
10550
+ return { stageId, rows: data2 ?? [], total: count ?? (data2?.length ?? 0) };
10305
10551
  };
10306
10552
  const porEtapa = await Promise.all(stages.map((s) => montar(s.id)));
10307
- const data = porEtapa.flat();
10553
+ const totals = new Map(porEtapa.map((r) => [r.stageId, r.total]));
10554
+ const data = porEtapa.flatMap((r) => r.rows);
10308
10555
  const deals = (data ?? []).map(toDeal);
10309
10556
  const map = /* @__PURE__ */ new Map();
10310
10557
  for (const stage of stages) map.set(stage.id, []);
@@ -10312,7 +10559,7 @@ function createSupabaseCrmProvider(options) {
10312
10559
  const arr = map.get(deal.stageId);
10313
10560
  if (arr) arr.push(deal);
10314
10561
  }
10315
- return map;
10562
+ return { byStage: map, totals };
10316
10563
  },
10317
10564
  async createDeal(input) {
10318
10565
  const { pub } = getClients();
@@ -10482,8 +10729,12 @@ function createSupabaseCrmProvider(options) {
10482
10729
  async getActivities(query) {
10483
10730
  const { pub } = getClients();
10484
10731
  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);
10732
+ if (query.dealId && query.leadId) {
10733
+ qb = qb.or(`deal_id.eq.${query.dealId},lead_id.eq.${query.leadId}`);
10734
+ } else {
10735
+ if (query.dealId) qb = qb.eq("deal_id", query.dealId);
10736
+ if (query.leadId) qb = qb.eq("lead_id", query.leadId);
10737
+ }
10487
10738
  if (query.activityType) qb = qb.eq("activity_type", query.activityType);
10488
10739
  if (query.completed === true) qb = qb.not("completed_at", "is", null);
10489
10740
  if (query.completed === false) qb = qb.is("completed_at", null);
@@ -11859,6 +12110,8 @@ function createCrmStore(provider) {
11859
12110
  dealsTotal: 0,
11860
12111
  dealsLoading: false,
11861
12112
  dealsByStage: /* @__PURE__ */ new Map(),
12113
+ dealStageTotals: /* @__PURE__ */ new Map(),
12114
+ dealStageLimits: {},
11862
12115
  activities: [],
11863
12116
  activitiesTotal: 0,
11864
12117
  activitiesLoading: false,
@@ -11951,7 +12204,7 @@ function createCrmStore(provider) {
11951
12204
  async selectPipeline(pipelineId) {
11952
12205
  if (get().activePipelineId === pipelineId) return;
11953
12206
  const stages = await provider.getPipelineStages(pipelineId);
11954
- set({ stages, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map() });
12207
+ set({ stages, activePipelineId: pipelineId, dealsByStage: /* @__PURE__ */ new Map(), dealStageTotals: /* @__PURE__ */ new Map(), dealStageLimits: {} });
11955
12208
  },
11956
12209
  async fetchTagDefs() {
11957
12210
  return dedup(sid + "crm:tag-defs", async () => {
@@ -12000,16 +12253,22 @@ function createCrmStore(provider) {
12000
12253
  },
12001
12254
  async fetchDealsByStage(pipelineId, filter) {
12002
12255
  lastBoard = { pipelineId, filter };
12003
- const key = sid + "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {});
12256
+ const limits = get().dealStageLimits;
12257
+ const key = sid + "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {}) + ":" + JSON.stringify(limits);
12004
12258
  return dedup(key, async () => {
12005
12259
  set({ dealsLoading: true });
12006
12260
  const { activePipelineId, stages } = get();
12007
12261
  const known = pipelineId === activePipelineId && stages.length > 0 ? stages : void 0;
12008
- const dealsByStage = await provider.getDealsByStage(pipelineId, filter, known);
12262
+ const { byStage, totals } = await provider.getDealsByStage(pipelineId, filter, known, limits);
12009
12263
  if (get().activePipelineId !== pipelineId) return;
12010
- set({ dealsByStage, dealsLoading: false });
12264
+ set({ dealsByStage: byStage, dealStageTotals: totals, dealsLoading: false });
12011
12265
  });
12012
12266
  },
12267
+ async loadMoreStage(stageId) {
12268
+ const atual = get().dealStageLimits[stageId] ?? 100;
12269
+ set({ dealStageLimits: { ...get().dealStageLimits, [stageId]: atual + 100 } });
12270
+ await get().refreshBoard();
12271
+ },
12013
12272
  async refreshBoard() {
12014
12273
  if (!lastBoard) return;
12015
12274
  return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter);
@@ -24200,6 +24459,632 @@ create view public.plg_crm_rep_deals with (security_invoker = true) as SELECT id
24200
24459
  grant select, insert, update, delete on public.v_deals to authenticated, service_role;
24201
24460
  grant select, insert, update, delete on public.plg_crm_rep_deals to authenticated, service_role;
24202
24461
  `;
24462
+ var MIGRATION_042_A_ATIVIDADE_DIZ_QUEM_A_FEZ = `-- ---------------------------------------------------------------------------
24463
+ -- 042_a_atividade_diz_quem_a_fez.sql \u2014 a linha do tempo passa a ter sujeito.
24464
+ --
24465
+ -- \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
24466
+ --
24467
+ -- \`plg_crm_activities\` guarda \`assigned_to_id\`, que \xE9 QUEM DEVE FAZER \u2014 o dono
24468
+ -- da tarefa. N\xE3o havia nada dizendo QUEM FEZ. Uma linha do tempo em que toda
24469
+ -- entrada \xE9 an\xF4nima responde "o que aconteceu" e n\xE3o responde "com quem eu
24470
+ -- falo sobre isso", que \xE9 a pergunta que se faz olhando para ela.
24471
+ --
24472
+ -- Medido no cluster antes desta migration: 308 atividades, ZERO com autor \u2014
24473
+ -- porque n\xE3o havia onde p\xF4r.
24474
+ --
24475
+ -- O caso mais claro \xE9 a RPC do agente: \`agent_crm_log_activity\` RECEBE
24476
+ -- \`p_actor_user_id\`, usa-o para autorizar, e descarta. A informa\xE7\xE3o chegava \xE0
24477
+ -- porta e n\xE3o entrava.
24478
+ --
24479
+ -- \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
24480
+ --
24481
+ -- \`created_by\` aponta para o utilizador; \`created_by_name\` guarda o nome no
24482
+ -- momento em que o facto aconteceu. Um utilizador removido n\xE3o pode apagar a
24483
+ -- autoria do que fez \u2014 e uma linha do tempo que passa a dizer "(removido)"
24484
+ -- reescreve a hist\xF3ria para quem a l\xEA depois.
24485
+ --
24486
+ -- \xC9 a mesma disciplina que \`contact_name\` e \`assigned_to_name\` j\xE1 seguem
24487
+ -- nesta tabela.
24488
+ --
24489
+ -- \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
24490
+ --
24491
+ -- Os FACTOS DE SISTEMA (lead_created, stage_changed, status_changed\u2026) nascem
24492
+ -- sem autor de prop\xF3sito: quem os produziu foi uma regra, n\xE3o uma pessoa. O
24493
+ -- default cobre isso sem inventar um culpado.
24494
+ -- ---------------------------------------------------------------------------
24495
+
24496
+ ALTER TABLE public.plg_crm_activities
24497
+ ADD COLUMN IF NOT EXISTS created_by uuid REFERENCES auth.users(id) ON DELETE SET NULL,
24498
+ ADD COLUMN IF NOT EXISTS created_by_name text;
24499
+
24500
+ COMMENT ON COLUMN public.plg_crm_activities.created_by IS
24501
+ '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).';
24502
+ COMMENT ON COLUMN public.plg_crm_activities.created_by_name IS
24503
+ 'O nome no momento do fato. Um usu\xE1rio removido n\xE3o apaga a autoria do que fez (042).';
24504
+
24505
+ -- A linha do tempo abre ordenada por data e filtrada por neg\xF3cio ou por lead;
24506
+ -- o autor \xE9 coluna de LEITURA, n\xE3o de recorte. Um \xEDndice aqui seria mantido em
24507
+ -- toda escrita para uma consulta que ningu\xE9m faz.
24508
+
24509
+ -- \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
24510
+ --
24511
+ -- Ela j\xE1 recebe \`p_actor_user_id\` e j\xE1 o usa no \`agent_guard\`. S\xF3 n\xE3o gravava.
24512
+ -- O corpo abaixo \xE9 o da 021, INTEIRO, com duas linhas a mais: reescrever a
24513
+ -- fun\xE7\xE3o para acrescentar uma coluna trocaria o contrato do agente (o formato
24514
+ -- do retorno, o vocabul\xE1rio de \`outcome\`, a forma do guard) por um detalhe de
24515
+ -- autoria, e \xE9 assim que uma ferramenta que funcionava para de funcionar.
24516
+ CREATE OR REPLACE FUNCTION public.agent_crm_log_activity(p_tenant_id uuid, p_actor_user_id uuid, p_payload jsonb)
24517
+ RETURNS jsonb
24518
+ LANGUAGE plpgsql SECURITY DEFINER SET search_path TO 'public'
24519
+ AS $$
24520
+ DECLARE
24521
+ v_denial jsonb;
24522
+ v_deal uuid;
24523
+ v_lead uuid;
24524
+ v_type text;
24525
+ v_outcome text;
24526
+ v_title text;
24527
+ v_id uuid;
24528
+ BEGIN
24529
+ v_denial := agent_guard(p_tenant_id, p_actor_user_id, 'sales', 'create');
24530
+ IF v_denial IS NOT NULL THEN
24531
+ RETURN jsonb_build_object('ok', false, 'denial', v_denial);
24532
+ END IF;
24533
+
24534
+ BEGIN
24535
+ v_deal := nullif(p_payload->>'deal_id', '')::uuid;
24536
+ v_lead := nullif(p_payload->>'lead_id', '')::uuid;
24537
+ EXCEPTION WHEN OTHERS THEN
24538
+ RETURN jsonb_build_object('ok', false, 'error', 'invalid payload: ' || SQLERRM);
24539
+ END;
24540
+ IF v_deal IS NULL AND v_lead IS NULL THEN
24541
+ RETURN jsonb_build_object('ok', false, 'error', 'send deal_id or lead_id \u2014 an activity with neither belongs to nobody');
24542
+ END IF;
24543
+
24544
+ 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
24545
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown deal for this tenant');
24546
+ END IF;
24547
+ 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
24548
+ RETURN jsonb_build_object('ok', false, 'error', 'unknown person for this tenant');
24549
+ END IF;
24550
+
24551
+ -- O tipo vem do cadastro do inquilino (registro \`activity-types\`), n\xE3o de uma
24552
+ -- lista fixa: uma casa que criou "Visita t\xE9cnica" precisa poder registr\xE1-la.
24553
+ v_type := coalesce(nullif(trim(lower(p_payload->>'activity_type')), ''), 'note');
24554
+ IF NOT EXISTS (
24555
+ SELECT 1 FROM plg_crm_activity_types t
24556
+ WHERE t.tenant_id = p_tenant_id AND t.is_active
24557
+ AND lower(replace(t.name, ' ', '_')) = v_type
24558
+ ) AND v_type NOT IN ('call','email','meeting','note','task','whatsapp','visit') THEN
24559
+ RETURN jsonb_build_object(
24560
+ 'ok', false,
24561
+ 'error', format('unknown activity type %L', v_type),
24562
+ 'allowed', jsonb_build_array('call','email','meeting','note','task','whatsapp','visit'));
24563
+ END IF;
24564
+
24565
+ v_outcome := nullif(trim(lower(p_payload->>'outcome')), '');
24566
+ IF v_outcome IS NOT NULL AND v_outcome NOT IN ('connected','no_answer','left_message','replied','scheduled') THEN
24567
+ RETURN jsonb_build_object(
24568
+ 'ok', false,
24569
+ 'error', format('unknown outcome %L', v_outcome),
24570
+ 'allowed', jsonb_build_array('connected','no_answer','left_message','replied','scheduled'),
24571
+ 'hint', 'This is what moves the card''s contact status \u2014 send it whenever the activity was an attempt to reach somebody.');
24572
+ END IF;
24573
+
24574
+ v_title := coalesce(nullif(trim(p_payload->>'title'), ''), initcap(replace(v_type, '_', ' ')));
24575
+
24576
+ INSERT INTO plg_crm_activities
24577
+ (tenant_id, deal_id, lead_id, contact_id, activity_type, title, description, outcome, due_date, assigned_to_id,
24578
+ -- 042: o ator j\xE1 chegava aqui para AUTORIZAR e era descartado. Agora fica.
24579
+ created_by, created_by_name)
24580
+ VALUES (
24581
+ p_tenant_id, v_deal, v_lead,
24582
+ nullif(p_payload->>'contact_id', '')::uuid,
24583
+ v_type, left(v_title, 200), left(nullif(p_payload->>'description', ''), 2000),
24584
+ v_outcome,
24585
+ nullif(p_payload->>'due_date', '')::date,
24586
+ nullif(p_payload->>'assigned_to_id', '')::uuid,
24587
+ p_actor_user_id,
24588
+ (SELECT u.email FROM auth.users u WHERE u.id = p_actor_user_id))
24589
+ RETURNING id INTO v_id;
24590
+
24591
+ RETURN jsonb_build_object(
24592
+ 'ok', true, 'activity_id', v_id,
24593
+ -- O gatilho da 014 j\xE1 rodou: devolver o status novo \xE9 o que faz o
24594
+ -- assistente poder dizer "pronto, o card est\xE1 como N\xE3o atendeu".
24595
+ 'contact_status', (SELECT d.contact_status FROM plg_crm_deals d WHERE d.id = v_deal));
24596
+ END $$;
24597
+
24598
+ REVOKE ALL ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) FROM PUBLIC, anon;
24599
+ GRANT EXECUTE ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) TO authenticated, service_role;
24600
+
24601
+ COMMENT ON FUNCTION public.agent_crm_log_activity(uuid, uuid, jsonb) IS
24602
+ '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).';
24603
+ `;
24604
+ var MIGRATION_043_A_CADENCIA_PARA_DE_ESPERAR_UM_FATO_QUE_NUNCA_CHEGA = `-- ---------------------------------------------------------------------------
24605
+ -- 043_a_cadencia_para_de_esperar_um_fato_que_nunca_chega.sql
24606
+ --
24607
+ -- \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
24608
+ --
24609
+ -- \`plugin-automations\` ASSINA \`crm.stage_changed\` \u2014 a assinatura est\xE1 em
24610
+ -- \`automations/001:574-577\` e o handler existe de verdade. Nada emite esse
24611
+ -- fato. A cad\xEAncia que algu\xE9m montou para disparar quando o card muda de
24612
+ -- etapa est\xE1 esperando, em sil\xEAncio, desde que foi criada.
24613
+ --
24614
+ -- Sil\xEAncio \xE9 o pior modo de falhar: n\xE3o h\xE1 erro para investigar. A tela mostra
24615
+ -- a cad\xEAncia ativa, o card muda de etapa na frente de quem a montou, e nada
24616
+ -- acontece \u2014 e a conclus\xE3o razo\xE1vel de quem v\xEA \xE9 que a automa\xE7\xE3o est\xE1 quebrada,
24617
+ -- ou pior, que o produto n\xE3o faz aquilo.
24618
+ --
24619
+ -- A \`012\` corrigiu tr\xEAs dos seis fatos declarados e disse isso no cabe\xE7alho.
24620
+ -- Este \xE9 o quarto, e \xE9 o \xFAnico dos tr\xEAs restantes que tem consumidor.
24621
+ --
24622
+ -- \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
24623
+ --
24624
+ -- \`AFTER UPDATE OF stage_id\` j\xE1 recorta a coluna, mas um \`UPDATE\` que grava a
24625
+ -- mesma etapa ainda dispara. A cad\xEAncia que entra a cada salvar de um card
24626
+ -- parado entra duas vezes \u2014 \xE9 a mesma disciplina que a \`012\` aplica ao status.
24627
+ --
24628
+ -- \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
24629
+ --
24630
+ -- Como em \`crm.deal_won\`: tudo a jusante \xE9 indexado pela pessoa, e um handler
24631
+ -- que tivesse de resolver neg\xF3cio \u2192 lead sozinho seria um join repetido por
24632
+ -- cada um deles. Sem \`lead_id\` n\xE3o h\xE1 fato \u2014 um card sem lead n\xE3o tem a quem
24633
+ -- a cad\xEAncia falaria.
24634
+ -- ---------------------------------------------------------------------------
24635
+
24636
+ CREATE OR REPLACE FUNCTION public.trg_crm_emit_stage_changed() RETURNS trigger
24637
+ LANGUAGE plpgsql SECURITY DEFINER
24638
+ SET search_path TO ''
24639
+ AS $$
24640
+ DECLARE
24641
+ v_de text;
24642
+ v_para text;
24643
+ BEGIN
24644
+ IF NEW.stage_id IS NOT DISTINCT FROM OLD.stage_id THEN RETURN NULL; END IF;
24645
+ IF NEW.lead_id IS NULL THEN RETURN NULL; END IF;
24646
+
24647
+ -- Os NOMES junto dos ids: uma condi\xE7\xE3o de cad\xEAncia escrita por humano diz
24648
+ -- "quando entrar em Proposta enviada", n\xE3o "quando stage_id for este uuid".
24649
+ SELECT s.name INTO v_de FROM public.plg_crm_pipeline_stages s WHERE s.id = OLD.stage_id;
24650
+ SELECT s.name INTO v_para FROM public.plg_crm_pipeline_stages s WHERE s.id = NEW.stage_id;
24651
+
24652
+ PERFORM public.plg_emit_event(
24653
+ 'crm.stage_changed',
24654
+ jsonb_build_object(
24655
+ 'deal_id', NEW.id,
24656
+ 'lead_id', NEW.lead_id,
24657
+ 'person_id', NEW.lead_id,
24658
+ 'title', NEW.title,
24659
+ 'value', NEW.value,
24660
+ 'from_stage_id', OLD.stage_id,
24661
+ 'to_stage_id', NEW.stage_id,
24662
+ 'from_stage', v_de,
24663
+ 'to_stage', v_para
24664
+ ),
24665
+ 'lead', NEW.lead_id::text, NEW.tenant_id
24666
+ );
24667
+ RETURN NULL;
24668
+ END $$;
24669
+
24670
+ REVOKE ALL ON FUNCTION public.trg_crm_emit_stage_changed() FROM PUBLIC;
24671
+ GRANT EXECUTE ON FUNCTION public.trg_crm_emit_stage_changed() TO authenticated, service_role;
24672
+
24673
+ COMMENT ON FUNCTION public.trg_crm_emit_stage_changed() IS
24674
+ 'Emite \`crm.stage_changed\`, que o plugin-automations assina desde sempre e nunca recebeu (043).';
24675
+
24676
+ -- AFTER, como os irm\xE3os: falhar ao emitir n\xE3o pode recusar o movimento do
24677
+ -- card. \`plg_emit_event\` s\xF3 insere uma linha; quem tenta de novo \xE9 o consumidor.
24678
+ DROP TRIGGER IF EXISTS crm_emit_stage_changed ON public.plg_crm_deals;
24679
+ CREATE TRIGGER crm_emit_stage_changed
24680
+ AFTER UPDATE OF stage_id ON public.plg_crm_deals
24681
+ FOR EACH ROW EXECUTE FUNCTION public.trg_crm_emit_stage_changed();
24682
+ `;
24683
+ var MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO = `-- ---------------------------------------------------------------------------
24684
+ -- 044_o_status_nao_e_um_acontecimento.sql
24685
+ --
24686
+ -- \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
24687
+ --
24688
+ -- Um lead da feira, com UM fato na hist\xF3ria dele \u2014 o contato no estande \u2014
24689
+ -- aparecia com tr\xEAs:
24690
+ --
24691
+ -- \u2022 Contato presencial na feira (visit) \u2190 aconteceu
24692
+ -- \u2022 Contato n\xE3o feito (status_changed) \u2190 n\xE3o aconteceu
24693
+ -- \u2022 Falou com a pessoa (status_changed) \u2190 n\xE3o aconteceu
24694
+ --
24695
+ -- Medido antes desta migration: 312 visitas, 306 "Contato n\xE3o feito" e 311
24696
+ -- "Falou com a pessoa". Quase tr\xEAs linhas de hist\xF3ria para cada fato real.
24697
+ --
24698
+ -- \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
24699
+ --
24700
+ -- \`contact_status\` \xE9 DERIVADO. A 020 o calcula lendo as atividades e n\xE3o
24701
+ -- aceita que nenhuma tela o grave \u2014 \xE9 a regra boa desta tabela, e continua.
24702
+ -- Mas ela tamb\xE9m escrevia cada rec\xE1lculo de volta como uma atividade, e \xE9 a\xED
24703
+ -- que o modelo se dobra sobre si mesmo: a linha do tempo passa a conter o
24704
+ -- resumo dela pr\xF3pria.
24705
+ --
24706
+ -- Nada aconteceu quando o card virou "Falou com a pessoa". O que aconteceu foi
24707
+ -- a VISITA, e ela j\xE1 est\xE1 l\xE1, uma linha acima, dizendo mais: quando, com quem,
24708
+ -- por quem. A segunda linha \xE9 a primeira lida de longe.
24709
+ --
24710
+ -- "Contato n\xE3o feito" \xE9 pior ainda: \xE9 o estado de um card rec\xE9m-nascido. Um
24711
+ -- card existir n\xE3o \xE9 um acontecimento na vida do lead, e uma linha do tempo
24712
+ -- que abre com "ainda n\xE3o fizemos nada" est\xE1 gastando a aten\xE7\xE3o de quem l\xEA
24713
+ -- para n\xE3o dizer nada.
24714
+ --
24715
+ -- O teste \xE9 simples e vale para qualquer linha do tempo: se apagar a linha n\xE3o
24716
+ -- se perde informa\xE7\xE3o nenhuma \u2014 porque ela \xE9 calcul\xE1vel a partir das outras \u2014
24717
+ -- ela n\xE3o \xE9 um fato, \xE9 uma vista. E vista se renderiza no card, que \xE9 onde o
24718
+ -- status j\xE1 aparece.
24719
+ --
24720
+ -- \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
24721
+ --
24722
+ -- \`crm.deal_status_changed\` continua a ser emitido, intacto. Uma cad\xEAncia que
24723
+ -- dispara quando o card vira "N\xE3o atendeu" precisa desse sinal, e um evento
24724
+ -- n\xE3o ocupa espa\xE7o na leitura de ningu\xE9m. O que sai \xE9 s\xF3 a linha da hist\xF3ria.
24725
+ --
24726
+ -- Esta \xE9 a mesma fronteira que a 012 e a 043 v\xEAm desenhando: o \`event_log\` \xE9
24727
+ -- para M\xC1QUINAS reagirem; \`plg_crm_activities\` \xE9 para uma PESSOA ler.
24728
+ -- ---------------------------------------------------------------------------
24729
+
24730
+ -- O corpo \xE9 o da 020, inteiro, MENOS o INSERT da linha de status. Reescrever a
24731
+ -- fun\xE7\xE3o para tirar um bloco trocaria a escada de deriva\xE7\xE3o por um detalhe de
24732
+ -- apresenta\xE7\xE3o \u2014 e a escada est\xE1 certa.
24733
+ CREATE OR REPLACE FUNCTION public.crm_recompute_deal_status(p_deal_id uuid)
24734
+ RETURNS text
24735
+ LANGUAGE plpgsql
24736
+ SECURITY DEFINER
24737
+ SET search_path TO ''
24738
+ AS $$
24739
+ DECLARE
24740
+ d record;
24741
+ v_has_manual boolean := false;
24742
+ v_last_outcome text;
24743
+ v_connected boolean := false;
24744
+ v_replied boolean := false;
24745
+ v_meeting boolean := false;
24746
+ v_overdue boolean := false;
24747
+ v_key text;
24748
+ v_name text;
24749
+ BEGIN
24750
+ SELECT id, tenant_id, stage_id, contact_status INTO d
24751
+ FROM public.plg_crm_deals WHERE id = p_deal_id;
24752
+ IF d.id IS NULL THEN RETURN NULL; END IF;
24753
+
24754
+ -- Os fatos do sistema (lead_created, stage_changed\u2026) N\xC3O contam como
24755
+ -- contato: eles descrevem o software, n\xE3o uma tentativa de falar com algu\xE9m.
24756
+ SELECT
24757
+ bool_or(a.activity_type NOT IN (
24758
+ 'lead_created','lead_converted','lead_archived','deal_created','stage_changed','deal_won','deal_lost',
24759
+ 'deal_archived','quote_created','quote_sent','quote_approved','quote_rejected','quote_archived','status_changed')),
24760
+ bool_or(a.outcome = 'connected'),
24761
+ bool_or(a.outcome = 'replied'),
24762
+ bool_or(a.activity_type = 'meeting' OR a.outcome = 'scheduled'),
24763
+ bool_or(a.activity_type = 'task' AND a.completed_at IS NULL AND a.due_date < current_date)
24764
+ INTO v_has_manual, v_connected, v_replied, v_meeting, v_overdue
24765
+ FROM public.plg_crm_activities a
24766
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id;
24767
+
24768
+ -- A \xDALTIMA tentativa, n\xE3o qualquer uma: "n\xE3o atendeu" \xE9 um estado do agora,
24769
+ -- e uma liga\xE7\xE3o sem resposta em agosto n\xE3o descreve o card de hoje.
24770
+ SELECT a.outcome INTO v_last_outcome
24771
+ FROM public.plg_crm_activities a
24772
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id AND a.outcome IS NOT NULL
24773
+ ORDER BY a.created_at DESC LIMIT 1;
24774
+
24775
+ SELECT s.key, s.name INTO v_key, v_name
24776
+ FROM public.plg_crm_deal_statuses s
24777
+ WHERE s.tenant_id = d.tenant_id
24778
+ AND s.is_active
24779
+ AND (s.stage_id IS NULL OR s.stage_id = d.stage_id)
24780
+ AND CASE s.derived_from
24781
+ WHEN 'no_activity' THEN NOT coalesce(v_has_manual, false)
24782
+ WHEN 'attempted' THEN coalesce(v_has_manual, false)
24783
+ WHEN 'no_answer' THEN v_last_outcome IN ('no_answer', 'left_message')
24784
+ WHEN 'connected' THEN coalesce(v_connected, false)
24785
+ WHEN 'replied' THEN coalesce(v_replied, false)
24786
+ WHEN 'meeting_scheduled' THEN coalesce(v_meeting, false)
24787
+ WHEN 'overdue_task' THEN coalesce(v_overdue, false)
24788
+ ELSE false
24789
+ END
24790
+ -- Espec\xEDfico da etapa ganha do universal no empate.
24791
+ ORDER BY s.sort_order DESC, (s.stage_id IS NOT NULL) DESC
24792
+ LIMIT 1;
24793
+
24794
+ IF v_key IS NOT DISTINCT FROM d.contact_status THEN
24795
+ RETURN d.contact_status;
24796
+ END IF;
24797
+
24798
+ UPDATE public.plg_crm_deals
24799
+ SET contact_status = v_key, contact_status_at = now()
24800
+ WHERE id = p_deal_id;
24801
+
24802
+ -- 044: o INSERT de \`status_changed\` na linha do tempo saiu daqui. O evento
24803
+ -- fica \u2014 \xE9 o que uma cad\xEAncia escuta, e ningu\xE9m o l\xEA numa tela.
24804
+ IF v_key IS NOT NULL THEN
24805
+ BEGIN
24806
+ PERFORM public.plg_emit_event(
24807
+ 'crm.deal_status_changed',
24808
+ jsonb_build_object('deal_id', p_deal_id, 'status', v_key, 'status_name', v_name, 'stage_id', d.stage_id),
24809
+ 'deal', p_deal_id::text, d.tenant_id);
24810
+ EXCEPTION WHEN undefined_function THEN
24811
+ -- App sem o barramento de eventos montado: o card j\xE1 mostra o status.
24812
+ NULL;
24813
+ END;
24814
+ END IF;
24815
+
24816
+ RETURN v_key;
24817
+ END $$;
24818
+
24819
+ REVOKE ALL ON FUNCTION public.crm_recompute_deal_status(uuid) FROM PUBLIC, anon;
24820
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO authenticated;
24821
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO service_role;
24822
+
24823
+ COMMENT ON FUNCTION public.crm_recompute_deal_status(uuid) IS
24824
+ '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).';
24825
+
24826
+ -- \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
24827
+ --
24828
+ -- Deix\xE1-las seria deixar o defeito na tela e s\xF3 parar de aument\xE1-lo. Cada uma
24829
+ -- \xE9 reconstitu\xEDvel a partir das atividades que sobram \u2014 que \xE9 precisamente o
24830
+ -- argumento de n\xE3o as guardar.
24831
+ --
24832
+ -- O gatilho \`crm_activity_restatus\` \xE9 \`AFTER INSERT OR UPDATE\` (020), n\xE3o
24833
+ -- DELETE: apagar n\xE3o dispara rec\xE1lculo nenhum e n\xE3o h\xE1 cascata.
24834
+ DO $$
24835
+ DECLARE v_n bigint;
24836
+ BEGIN
24837
+ DELETE FROM public.plg_crm_activities WHERE activity_type = 'status_changed';
24838
+ GET DIAGNOSTICS v_n = ROW_COUNT;
24839
+ RAISE NOTICE 'crm/044: % linha(s) de status removida(s) da linha do tempo', v_n;
24840
+ END $$;
24841
+
24842
+ -- O valor continua ACEITO pelo CHECK da 020. Tir\xE1-lo da restri\xE7\xE3o recusaria
24843
+ -- qualquer banco que ainda tenha uma dessas linhas por um caminho que este
24844
+ -- arquivo n\xE3o conhece, e o ganho seria zero: nada mais o escreve.
24845
+ `;
24846
+ var MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ = `-- ---------------------------------------------------------------------------
24847
+ -- 045_contato_feito_e_contato_que_alguem_fez.sql
24848
+ --
24849
+ -- \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
24850
+ --
24851
+ -- 310 cards parados na etapa "Novo (feira)" com a pastilha "Contato feito" \u2014
24852
+ -- que \xE9, letra por letra, o NOME DA ETAPA SEGUINTE. O quadro dizia as duas
24853
+ -- coisas ao mesmo tempo: ningu\xE9m mexeu nisto, e j\xE1 falaram com ele.
24854
+ --
24855
+ -- O que produzia a pastilha era a atividade da importa\xE7\xE3o da feira. A \`044\`
24856
+ -- tirou-lhe o \`outcome\` e isso resolveu metade: o card deixou de ser "Falou
24857
+ -- com a pessoa". Mas \`attempted\` n\xE3o olha para o desfecho \u2014 olha para a
24858
+ -- EXIST\xCANCIA de qualquer atividade que n\xE3o seja fato de sistema. A visita
24859
+ -- importada \xE9 exatamente isso, e o card virou "Contato feito".
24860
+ --
24861
+ -- \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
24862
+ --
24863
+ -- "apenas deveriam marcar contato feito quando esse contato for feito
24864
+ -- pelos sdr pelo sistema"
24865
+ --
24866
+ -- A lista de tipos de sistema era uma aproxima\xE7\xE3o disso: enumerava os fatos
24867
+ -- que o software escreve sozinho e assumia que o resto foi algu\xE9m. A
24868
+ -- importa\xE7\xE3o quebra a suposi\xE7\xE3o \u2014 ela escreve atividades de tipo humano
24869
+ -- ('visit') sem que nenhum humano as tenha feito.
24870
+ --
24871
+ -- Ent\xE3o a pergunta deixa de ser o TIPO e passa a ser a PROCED\xCANCIA:
24872
+ --
24873
+ -- \`created_by IS NOT NULL\` algu\xE9m lan\xE7ou pela tela ou pela RPC do agente.
24874
+ -- A coluna existe desde a 042 justamente para
24875
+ -- responder "quem fez".
24876
+ -- \`outcome IS NOT NULL\` ou n\xE3o h\xE1 autor humano mas houve tentativa de
24877
+ -- falar: \xE9 o caso da caixa de entrada, que lan\xE7a
24878
+ -- como 'Caixa de entrada' e traz \`replied\` ou
24879
+ -- \`left_message\`. Uma resposta do lead \xE9 contato
24880
+ -- real mesmo sem SDR nenhum a regist\xE1-la.
24881
+ --
24882
+ -- Nenhuma das duas, e o registo descreve DE ONDE o lead veio, n\xE3o o que se
24883
+ -- fez com ele. \xC9 o caso da feira \u2014 e ser\xE1 o caso de toda importa\xE7\xE3o futura,
24884
+ -- que \xE9 a raz\xE3o de a regra n\xE3o citar 'visit' nem a feira em lado nenhum.
24885
+ --
24886
+ -- \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
24887
+ --
24888
+ -- 310 cards voltam a "Contato n\xE3o feito", que \xE9 a verdade: est\xE3o na primeira
24889
+ -- etapa desde a feira e ningu\xE9m ligou. E "Contato feito" volta a significar
24890
+ -- alguma coisa \u2014 quando aparecer, \xE9 porque um SDR fez.
24891
+ -- ---------------------------------------------------------------------------
24892
+
24893
+ CREATE OR REPLACE FUNCTION public.crm_recompute_deal_status(p_deal_id uuid)
24894
+ RETURNS text
24895
+ LANGUAGE plpgsql
24896
+ SECURITY DEFINER
24897
+ SET search_path TO ''
24898
+ AS $$
24899
+ DECLARE
24900
+ d record;
24901
+ v_has_manual boolean := false;
24902
+ v_last_outcome text;
24903
+ v_connected boolean := false;
24904
+ v_replied boolean := false;
24905
+ v_meeting boolean := false;
24906
+ v_overdue boolean := false;
24907
+ v_key text;
24908
+ v_name text;
24909
+ BEGIN
24910
+ SELECT id, tenant_id, stage_id, contact_status INTO d
24911
+ FROM public.plg_crm_deals WHERE id = p_deal_id;
24912
+ IF d.id IS NULL THEN RETURN NULL; END IF;
24913
+
24914
+ -- Os fatos do sistema (lead_created, stage_changed\u2026) N\xC3O contam como
24915
+ -- contato: eles descrevem o software, n\xE3o uma tentativa de falar com algu\xE9m.
24916
+ SELECT
24917
+ bool_or(
24918
+ a.activity_type NOT IN (
24919
+ 'lead_created','lead_converted','lead_archived','deal_created','stage_changed','deal_won','deal_lost',
24920
+ 'deal_archived','quote_created','quote_sent','quote_approved','quote_rejected','quote_archived','status_changed')
24921
+ -- 045: e algu\xE9m tem de ter FEITO. Ou uma pessoa a lan\xE7ou pelo sistema
24922
+ -- (\`created_by\`), ou ela traz um desfecho \u2014 que s\xF3 existe quando houve
24923
+ -- tentativa de falar com algu\xE9m. Um registro importado sem as duas
24924
+ -- coisas descreve a proced\xEAncia do lead, n\xE3o trabalho sobre ele.
24925
+ AND (a.created_by IS NOT NULL OR a.outcome IS NOT NULL)),
24926
+ bool_or(a.outcome = 'connected'),
24927
+ bool_or(a.outcome = 'replied'),
24928
+ bool_or(a.activity_type = 'meeting' OR a.outcome = 'scheduled'),
24929
+ bool_or(a.activity_type = 'task' AND a.completed_at IS NULL AND a.due_date < current_date)
24930
+ INTO v_has_manual, v_connected, v_replied, v_meeting, v_overdue
24931
+ FROM public.plg_crm_activities a
24932
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id;
24933
+
24934
+ -- A \xDALTIMA tentativa, n\xE3o qualquer uma: "n\xE3o atendeu" \xE9 um estado do agora,
24935
+ -- e uma liga\xE7\xE3o sem resposta em agosto n\xE3o descreve o card de hoje.
24936
+ SELECT a.outcome INTO v_last_outcome
24937
+ FROM public.plg_crm_activities a
24938
+ WHERE a.deal_id = p_deal_id AND a.tenant_id = d.tenant_id AND a.outcome IS NOT NULL
24939
+ ORDER BY a.created_at DESC LIMIT 1;
24940
+
24941
+ SELECT s.key, s.name INTO v_key, v_name
24942
+ FROM public.plg_crm_deal_statuses s
24943
+ WHERE s.tenant_id = d.tenant_id
24944
+ AND s.is_active
24945
+ AND (s.stage_id IS NULL OR s.stage_id = d.stage_id)
24946
+ AND CASE s.derived_from
24947
+ WHEN 'no_activity' THEN NOT coalesce(v_has_manual, false)
24948
+ WHEN 'attempted' THEN coalesce(v_has_manual, false)
24949
+ WHEN 'no_answer' THEN v_last_outcome IN ('no_answer', 'left_message')
24950
+ WHEN 'connected' THEN coalesce(v_connected, false)
24951
+ WHEN 'replied' THEN coalesce(v_replied, false)
24952
+ WHEN 'meeting_scheduled' THEN coalesce(v_meeting, false)
24953
+ WHEN 'overdue_task' THEN coalesce(v_overdue, false)
24954
+ ELSE false
24955
+ END
24956
+ -- Espec\xEDfico da etapa ganha do universal no empate.
24957
+ ORDER BY s.sort_order DESC, (s.stage_id IS NOT NULL) DESC
24958
+ LIMIT 1;
24959
+
24960
+ IF v_key IS NOT DISTINCT FROM d.contact_status THEN
24961
+ RETURN d.contact_status;
24962
+ END IF;
24963
+
24964
+ UPDATE public.plg_crm_deals
24965
+ SET contact_status = v_key, contact_status_at = now()
24966
+ WHERE id = p_deal_id;
24967
+
24968
+ -- 044: o INSERT de \`status_changed\` na linha do tempo saiu daqui. O evento
24969
+ -- fica \u2014 \xE9 o que uma cad\xEAncia escuta, e ningu\xE9m o l\xEA numa tela.
24970
+ IF v_key IS NOT NULL THEN
24971
+ BEGIN
24972
+ PERFORM public.plg_emit_event(
24973
+ 'crm.deal_status_changed',
24974
+ jsonb_build_object('deal_id', p_deal_id, 'status', v_key, 'status_name', v_name, 'stage_id', d.stage_id),
24975
+ 'deal', p_deal_id::text, d.tenant_id);
24976
+ EXCEPTION WHEN undefined_function THEN
24977
+ -- App sem o barramento de eventos montado: o card j\xE1 mostra o status.
24978
+ NULL;
24979
+ END;
24980
+ END IF;
24981
+
24982
+ RETURN v_key;
24983
+ END $$;
24984
+
24985
+ REVOKE ALL ON FUNCTION public.crm_recompute_deal_status(uuid) FROM PUBLIC, anon;
24986
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO authenticated;
24987
+ GRANT EXECUTE ON FUNCTION public.crm_recompute_deal_status(uuid) TO service_role;
24988
+
24989
+ COMMENT ON FUNCTION public.crm_recompute_deal_status(uuid) IS
24990
+ '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).';
24991
+
24992
+ -- \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
24993
+ --
24994
+ -- S\xF3 os que T\xCAM status: recalcular a base inteira seria uma passada por
24995
+ -- centenas de milhares de neg\xF3cios para mexer em trezentos.
24996
+ DO $$
24997
+ DECLARE r record; v_n bigint := 0;
24998
+ BEGIN
24999
+ FOR r IN SELECT id FROM public.plg_crm_deals WHERE contact_status IS NOT NULL LOOP
25000
+ PERFORM public.crm_recompute_deal_status(r.id);
25001
+ v_n := v_n + 1;
25002
+ END LOOP;
25003
+ RAISE NOTICE 'crm/045: % neg\xF3cio(s) recalculado(s)', v_n;
25004
+ END $$;
25005
+ `;
25006
+ var MIGRATION_046_A_PASTILHA_DO_CARD_SO_FALA_QUANDO_TEM_O_QUE_DIZER = `-- ---------------------------------------------------------------------------
25007
+ -- 046_a_pastilha_do_card_so_fala_quando_tem_o_que_dizer.sql
25008
+ --
25009
+ -- \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
25010
+ --
25011
+ -- Com a \`045\` os 319 cards da feira voltaram a "Contato n\xE3o feito", que \xE9 a
25012
+ -- verdade. S\xF3 que eles est\xE3o TODOS na coluna "Novo (feira)" \u2014 e a coluna j\xE1
25013
+ -- diz isso. A pastilha passou a repetir o cabe\xE7alho em cima de cada card.
25014
+ --
25015
+ -- \xC9 o mesmo defeito da \`044\` por outro lado: informa\xE7\xE3o derivada ocupando
25016
+ -- espa\xE7o de leitura para n\xE3o acrescentar nada. Antes era uma linha na hist\xF3ria
25017
+ -- que dizia o status; agora \xE9 uma pastilha que diz a etapa.
25018
+ --
25019
+ -- A pastilha de status ganha o lugar dela quando diz o que a COLUNA N\xC3O DIZ:
25020
+ -- um card em "Novo (feira)" marcado "N\xE3o atendeu" informa (tent\xE1mos, n\xE3o
25021
+ -- voltou); marcado "Contato n\xE3o feito", n\xE3o.
25022
+ --
25023
+ -- \u2500\u2500 e por que uma coluna nova em vez de \`key = 'not_contacted'\` \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
25024
+ --
25025
+ -- \`not_contacted\` \xE9 a chave que a escada de f\xE1brica da \`020\` semeia, mas o
25026
+ -- inquilino pode renomear, reordenar ou trocar as chaves dele \u2014 a tabela
25027
+ -- \`plg_crm_deal_statuses\` existe exatamente para isso. Uma tela que compara a
25028
+ -- chave com um literal funciona nesta casa e cala-se na pr\xF3xima que chamar o
25029
+ -- primeiro degrau de outro nome.
25030
+ --
25031
+ -- O que N\xC3O muda \xE9 \`derived_from\`: \xE9 o vocabul\xE1rio fechado da regra, n\xE3o do
25032
+ -- inquilino, e \`no_activity\` significa "nada foi feito" em qualquer casa. A
25033
+ -- view passa a lev\xE1-lo ao cliente, e a decis\xE3o de mostrar ou n\xE3o deixa de ser
25034
+ -- um palpite sobre nomes.
25035
+ --
25036
+ -- Colunas NOVAS entram no FIM: \`CREATE OR REPLACE VIEW\` aceita acrescentar ao
25037
+ -- final e recusa mexer nas que existem. Sem DROP, portanto sem derrubar a
25038
+ -- \`plg_crm_rep_deals\` que pende desta.
25039
+ -- ---------------------------------------------------------------------------
25040
+
25041
+ CREATE OR REPLACE VIEW public.v_deals WITH (security_invoker = true) AS
25042
+ SELECT d.id,
25043
+ d.tenant_id,
25044
+ d.status,
25045
+ d.value,
25046
+ COALESCE(d.title, d.notes) AS title,
25047
+ d.contact_id,
25048
+ d.assigned_to_id,
25049
+ d.tags,
25050
+ d.metadata ->> 'contactName'::text AS contact_name,
25051
+ d.created_at,
25052
+ d.updated_at,
25053
+ d.pipeline_id,
25054
+ d.stage_id,
25055
+ d.probability,
25056
+ d.expected_close_date,
25057
+ d.lead_id,
25058
+ d.lost_reason,
25059
+ ps.name AS stage_name,
25060
+ ps.color AS stage_color,
25061
+ ps."order" AS stage_order,
25062
+ ps.name AS stage,
25063
+ d.won_at,
25064
+ d.lost_at,
25065
+ d.company_id,
25066
+ d.contact_status,
25067
+ d.contact_status_at,
25068
+ cs.name AS contact_status_name,
25069
+ cs.color AS contact_status_color,
25070
+ d.notes,
25071
+ -- 046, no fim da lista: a regra de onde o status saiu. \`no_activity\` \xE9 o
25072
+ -- primeiro degrau \u2014 nada foi feito \u2014 e \xE9 o \xFAnico que a tela esconde.
25073
+ cs.derived_from AS contact_status_derived_from
25074
+ FROM plg_crm_deals d
25075
+ LEFT JOIN plg_crm_pipeline_stages ps ON ps.id = d.stage_id
25076
+ LEFT JOIN LATERAL ( SELECT s.name,
25077
+ s.color,
25078
+ s.derived_from
25079
+ FROM plg_crm_deal_statuses s
25080
+ 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)
25081
+ ORDER BY (s.stage_id IS NOT NULL) DESC
25082
+ LIMIT 1) cs ON true
25083
+ ;
25084
+
25085
+ COMMENT ON VIEW public.v_deals IS
25086
+ '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).';
25087
+ `;
24203
25088
  var MIGRATIONS = [
24204
25089
  { id: "000_baseline", sql: MIGRATION_000_BASELINE },
24205
25090
  { id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
@@ -24241,7 +25126,12 @@ var MIGRATIONS = [
24241
25126
  { id: "038_canal_origem_e_campanha_sao_tres_perguntas", sql: MIGRATION_038_CANAL_ORIGEM_E_CAMPANHA_SAO_TRES_PERGUNTAS },
24242
25127
  { 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
25128
  { 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 }
25129
+ { 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 },
25130
+ { id: "042_a_atividade_diz_quem_a_fez", sql: MIGRATION_042_A_ATIVIDADE_DIZ_QUEM_A_FEZ },
25131
+ { 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 },
25132
+ { id: "044_o_status_nao_e_um_acontecimento", sql: MIGRATION_044_O_STATUS_NAO_E_UM_ACONTECIMENTO },
25133
+ { id: "045_contato_feito_e_contato_que_alguem_fez", sql: MIGRATION_045_CONTATO_FEITO_E_CONTATO_QUE_ALGUEM_FEZ },
25134
+ { 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
25135
  ];
24246
25136
 
24247
25137
  // src/locales/en.ts
@@ -24326,7 +25216,26 @@ var en = {
24326
25216
  "crm.leadDetail.notFound": "Not found",
24327
25217
  "crm.leadDetail.notes": "Notes",
24328
25218
  "crm.leadDetail.phone": "Phone",
25219
+ "crm.leads.filters.allStatuses": "Any status",
25220
+ "crm.leads.filters.allSources": "Todas as origens",
25221
+ "crm.leads.filters.searchTag": "Search tag",
25222
+ "crm.leads.filters.noTag": "No tag found",
25223
+ "crm.leads.filters.tag": "Etiqueta",
25224
+ "crm.leads.filters.allTags": "Todas as etiquetas",
25225
+ "crm.leads.filters.owner": "Respons\xE1vel",
25226
+ "crm.leads.filters.allOwners": "Qualquer respons\xE1vel",
25227
+ "crm.leads.filters.unassigned": "Sem respons\xE1vel",
25228
+ "crm.leads.filters.reach": "Contat\xE1vel por",
25229
+ "crm.leads.filters.anyReach": "Qualquer canal",
25230
+ "crm.leads.filters.hasPhone": "Tem telefone",
25231
+ "crm.leads.filters.hasEmail": "Tem e-mail",
25232
+ "crm.leads.filters.noPhone": "Sem telefone",
25233
+ "crm.leads.filters.anyCompany": "Com ou sem empresa",
25234
+ "crm.leads.filters.withCompany": "Com empresa",
25235
+ "crm.leads.filters.withoutCompany": "Sem empresa",
25236
+ "crm.leads.filters.clear": "Limpar",
24329
25237
  "crm.leadDetail.pipeline": "Pipeline",
25238
+ "crm.leadDetail.openDeal": "Open in pipeline",
24330
25239
  "crm.leadDetail.probability": "Probability",
24331
25240
  "crm.leadDetail.quotes": "Quotes",
24332
25241
  "crm.leadDetail.source": "Source",
@@ -24428,6 +25337,7 @@ var en = {
24428
25337
  "crm.rota.count": "{{count}} in the rota",
24429
25338
  "crm.pipeline.pickFunnel": "Pick a funnel",
24430
25339
  "crm.pipeline.setupStages": "Set up stages",
25340
+ "crm.pipeline.loadMore": "Show {n} more",
24431
25341
  "crm.pipeline.noDeals": "No deals",
24432
25342
  "crm.pipeline.addLead": "Add lead",
24433
25343
  "crm.deals.switchView": "Switch deals view",
@@ -24441,6 +25351,8 @@ var en = {
24441
25351
  "crm.funnelView.fromTop": "{{pct}}% of the top",
24442
25352
  "crm.funnelView.fromPrev": "{{pct}}% of the previous stage",
24443
25353
  "crm.funnelView.dropped": "{{count}} dropped off",
25354
+ "crm.followUp.dictate": "Dictate the note",
25355
+ "crm.followUp.dictateStop": "Stop dictating",
24444
25356
  "crm.followUp.placeholder": "What happened on this touch?",
24445
25357
  "crm.followUp.save": "Log it",
24446
25358
  "crm.followUp.failed": "Could not log the follow-up",
@@ -24488,6 +25400,8 @@ var en = {
24488
25400
  "crm.deals.allCampaigns": "All campaigns",
24489
25401
  "crm.deals.allCities": "All cities",
24490
25402
  "crm.card.companyTitle": "Company",
25403
+ "crm.card.takeOver": "Take this lead",
25404
+ "crm.card.takeOverFrom": "Take over",
24491
25405
  "crm.card.owner": "Owner",
24492
25406
  "crm.card.noOwner": "No owner",
24493
25407
  "crm.card.noDocument": "No tax ID on file",
@@ -24945,6 +25859,7 @@ var en = {
24945
25859
  "crm.leadDetail.whatsapp": "WhatsApp",
24946
25860
  "crm.leads.companyCol": "Company",
24947
25861
  "crm.leads.pageRangeOf": "of",
25862
+ "crm.leads.page": "Page",
24948
25863
  "crm.leads.firstPage": "First page",
24949
25864
  "crm.leads.prevPage": "Previous page",
24950
25865
  "crm.leads.nextPage": "Next page",
@@ -25081,7 +25996,26 @@ var ptBR = {
25081
25996
  "crm.leadDetail.notFound": "N\xE3o encontrado",
25082
25997
  "crm.leadDetail.notes": "Observa\xE7\xF5es",
25083
25998
  "crm.leadDetail.phone": "Telefone",
25999
+ "crm.leads.filters.allStatuses": "Qualquer status",
26000
+ "crm.leads.filters.allSources": "Todas as origens",
26001
+ "crm.leads.filters.searchTag": "Buscar etiqueta",
26002
+ "crm.leads.filters.noTag": "Nenhuma etiqueta",
26003
+ "crm.leads.filters.tag": "Etiqueta",
26004
+ "crm.leads.filters.allTags": "Todas as etiquetas",
26005
+ "crm.leads.filters.owner": "Respons\xE1vel",
26006
+ "crm.leads.filters.allOwners": "Qualquer respons\xE1vel",
26007
+ "crm.leads.filters.unassigned": "Sem respons\xE1vel",
26008
+ "crm.leads.filters.reach": "Contat\xE1vel por",
26009
+ "crm.leads.filters.anyReach": "Qualquer canal",
26010
+ "crm.leads.filters.hasPhone": "Tem telefone",
26011
+ "crm.leads.filters.hasEmail": "Tem e-mail",
26012
+ "crm.leads.filters.noPhone": "Sem telefone",
26013
+ "crm.leads.filters.anyCompany": "Com ou sem empresa",
26014
+ "crm.leads.filters.withCompany": "Com empresa",
26015
+ "crm.leads.filters.withoutCompany": "Sem empresa",
26016
+ "crm.leads.filters.clear": "Limpar",
25084
26017
  "crm.leadDetail.pipeline": "Pipeline",
26018
+ "crm.leadDetail.openDeal": "Abrir no funil",
25085
26019
  "crm.leadDetail.probability": "Probabilidade",
25086
26020
  "crm.leadDetail.quotes": "Or\xE7amentos",
25087
26021
  "crm.leadDetail.source": "Origem",
@@ -25183,6 +26117,7 @@ var ptBR = {
25183
26117
  "crm.rota.count": "{{count}} na rota",
25184
26118
  "crm.pipeline.pickFunnel": "Escolher funil",
25185
26119
  "crm.pipeline.setupStages": "Configurar etapas",
26120
+ "crm.pipeline.loadMore": "Ver mais {n}",
25186
26121
  "crm.pipeline.noDeals": "Nenhum neg\xF3cio",
25187
26122
  "crm.pipeline.addLead": "Adicionar lead",
25188
26123
  "crm.deals.switchView": "Trocar a vis\xE3o dos neg\xF3cios",
@@ -25196,6 +26131,8 @@ var ptBR = {
25196
26131
  "crm.funnelView.fromTop": "{{pct}}% do topo",
25197
26132
  "crm.funnelView.fromPrev": "{{pct}}% da etapa anterior",
25198
26133
  "crm.funnelView.dropped": "{{count}} ficaram para tr\xE1s",
26134
+ "crm.followUp.dictate": "Ditar a nota",
26135
+ "crm.followUp.dictateStop": "Parar de ditar",
25199
26136
  "crm.followUp.placeholder": "O que aconteceu nesse contato?",
25200
26137
  "crm.followUp.save": "Registrar",
25201
26138
  "crm.followUp.failed": "N\xE3o foi poss\xEDvel registrar o follow-up",
@@ -25243,6 +26180,8 @@ var ptBR = {
25243
26180
  "crm.deals.allCampaigns": "Todas as campanhas",
25244
26181
  "crm.deals.allCities": "Todas as cidades",
25245
26182
  "crm.card.companyTitle": "Empresa",
26183
+ "crm.card.takeOver": "Assumir este lead",
26184
+ "crm.card.takeOverFrom": "Assumir de quem est\xE1",
25246
26185
  "crm.card.owner": "Respons\xE1vel",
25247
26186
  "crm.card.noOwner": "Sem respons\xE1vel",
25248
26187
  "crm.card.noDocument": "Sem CNPJ cadastrado",
@@ -25700,6 +26639,7 @@ var ptBR = {
25700
26639
  "crm.leadDetail.whatsapp": "WhatsApp",
25701
26640
  "crm.leads.companyCol": "Empresa",
25702
26641
  "crm.leads.pageRangeOf": "de",
26642
+ "crm.leads.page": "P\xE1gina",
25703
26643
  "crm.leads.firstPage": "Primeira p\xE1gina",
25704
26644
  "crm.leads.prevPage": "P\xE1gina anterior",
25705
26645
  "crm.leads.nextPage": "Pr\xF3xima p\xE1gina",