@fayz-ai/plugin-crm 0.11.1 → 0.11.2
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/components/CrmGeneralSettings.d.ts.map +1 -1
- package/dist/components/SegmentEditorDialog.d.ts +12 -0
- package/dist/components/SegmentEditorDialog.d.ts.map +1 -0
- package/dist/context.d.ts +2 -0
- package/dist/context.d.ts.map +1 -1
- package/dist/data/mock.d.ts.map +1 -1
- package/dist/data/registries.d.ts.map +1 -1
- package/dist/data/supabase.d.ts.map +1 -1
- package/dist/data/tables.d.ts +6 -0
- package/dist/data/tables.d.ts.map +1 -1
- package/dist/data/types.d.ts +36 -1
- package/dist/data/types.d.ts.map +1 -1
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3364 -188
- package/dist/index.js.map +1 -1
- package/dist/lib/scorecard.d.ts +19 -0
- package/dist/lib/scorecard.d.ts.map +1 -0
- package/dist/lib/segments.d.ts +32 -0
- package/dist/lib/segments.d.ts.map +1 -0
- package/dist/locales/en.d.ts.map +1 -1
- package/dist/locales/pt-BR.d.ts.map +1 -1
- package/dist/migrations/index.d.ts +5 -1
- package/dist/migrations/index.d.ts.map +1 -1
- package/dist/store.d.ts.map +1 -1
- package/dist/types.d.ts +168 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/views/CrmPage.d.ts.map +1 -1
- package/dist/views/NetworkView.d.ts +3 -0
- package/dist/views/NetworkView.d.ts.map +1 -0
- package/dist/views/SegmentsView.d.ts +3 -0
- package/dist/views/SegmentsView.d.ts.map +1 -0
- package/dist/views/dashboardWidgets.d.ts.map +1 -1
- package/package.json +4 -4
- package/dist/components/PipelineSettings.d.ts +0 -3
- package/dist/components/PipelineSettings.d.ts.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import
|
|
1
|
+
import React20, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
|
|
2
2
|
import { tl, useTranslation, registerTranslations, registerMessageDefaults, createSafeDataProvider, getSupabaseClientOptional, countByTenant, usePluginRuntimeOptional, useActiveTenantId, exportCSV, getActiveTenantId, loadMessageOverrides, resolveMessages, useActiveUnitId } from '@fayz-ai/core';
|
|
3
|
-
import { createPluginContext, useUnitBootstrap, useUnitStore, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, TeachMeLink,
|
|
4
|
-
import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button,
|
|
3
|
+
import { createPluginContext, useUnitBootstrap, useUnitStore, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, usePermissionOptional, PageActions, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, TeachMeLink, KanbanBoard, useLimitGuard, RightRailPage, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, useAccessOptional, invalidateLimit, useOrganizationStore, getRailPage, ContactPicker } from '@fayz-ai/admin';
|
|
4
|
+
import { Badge, Checkbox, toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, SubpageHeader, Button, TooltipProvider, Tooltip, TooltipTrigger, TooltipContent, Switch, ConfirmDialog, useIsWide, PageHeaderActions, ListView, SheetBody, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SheetFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, Input, DashboardCanvas, Modal, ModalContent, ModalHeader, ModalTitle, ModalDescription, ModalBody, ModalFooter, PageToolbar, ToolbarButton, RangeControl, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, normalizePhone, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
|
|
5
5
|
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
|
|
6
|
-
import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, MoveRight, Target, ArrowRightLeft, UserPlus, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight,
|
|
6
|
+
import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, MoveRight, Target, ArrowRightLeft, UserPlus, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Plus, Filter, Lock, Pencil, Trash2, Globe, Check, ChevronRight, Settings, Download, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Star, MessageSquareQuote, Network, Loader2, Tag, Zap, Paperclip, ImageOff, CircleAlert, CircleDashed, CheckCircle2, DollarSign, User, Building2, ThumbsUp, ThumbsDown } from 'lucide-react';
|
|
7
7
|
import { createPortal } from 'react-dom';
|
|
8
8
|
import { createStore as createStore$1 } from 'zustand/vanilla';
|
|
9
9
|
|
|
@@ -173,6 +173,62 @@ var CrmContextProvider = ctx.ContextProvider;
|
|
|
173
173
|
var useCrmConfig = ctx.useConfig;
|
|
174
174
|
var useCrmProvider = ctx.useProvider;
|
|
175
175
|
var useCrmStore = ctx.useStore;
|
|
176
|
+
function EngagementLadderSettings() {
|
|
177
|
+
const t2 = useTranslation();
|
|
178
|
+
const provider = useCrmProvider();
|
|
179
|
+
const [cfg, setCfg] = React20.useState(null);
|
|
180
|
+
const [saving, setSaving] = React20.useState(false);
|
|
181
|
+
React20.useEffect(() => {
|
|
182
|
+
let alive = true;
|
|
183
|
+
provider.getEngagementSummary().then((d) => {
|
|
184
|
+
if (alive) setCfg(d.settings);
|
|
185
|
+
}).catch(() => {
|
|
186
|
+
if (alive) setCfg({ newDays: 30, activeDays: 90, atRiskDays: 180 });
|
|
187
|
+
});
|
|
188
|
+
return () => {
|
|
189
|
+
alive = false;
|
|
190
|
+
};
|
|
191
|
+
}, [provider]);
|
|
192
|
+
async function commit(next) {
|
|
193
|
+
setSaving(true);
|
|
194
|
+
try {
|
|
195
|
+
await provider.saveEngagementSettings(next);
|
|
196
|
+
setCfg(next);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
toast.error(e?.message ?? t2("crm.engagement.saveFailed"));
|
|
199
|
+
const d = await provider.getEngagementSummary().catch(() => null);
|
|
200
|
+
if (d) setCfg(d.settings);
|
|
201
|
+
} finally {
|
|
202
|
+
setSaving(false);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
const rows = [
|
|
206
|
+
["newDays", "crm.engagement.newDays", "crm.engagement.newDaysDesc"],
|
|
207
|
+
["activeDays", "crm.engagement.activeDays", "crm.engagement.activeDaysDesc"],
|
|
208
|
+
["atRiskDays", "crm.engagement.atRiskDays", "crm.engagement.atRiskDaysDesc"]
|
|
209
|
+
];
|
|
210
|
+
return /* @__PURE__ */ jsx(SettingsGroup, { title: t2("crm.engagement.settingsTitle"), description: t2("crm.engagement.settingsDesc"), children: rows.map(([key, label2, desc]) => /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-4 py-2", "data-testid": `ladder-${key}`, children: [
|
|
211
|
+
/* @__PURE__ */ jsxs("div", { className: "min-w-0", children: [
|
|
212
|
+
/* @__PURE__ */ jsx("p", { className: "text-sm", children: t2(label2) }),
|
|
213
|
+
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2(desc) })
|
|
214
|
+
] }),
|
|
215
|
+
/* @__PURE__ */ jsxs("div", { className: "flex shrink-0 items-center gap-1", children: [
|
|
216
|
+
/* @__PURE__ */ jsx(
|
|
217
|
+
Input,
|
|
218
|
+
{
|
|
219
|
+
className: "h-8 w-[80px] text-sm",
|
|
220
|
+
type: "number",
|
|
221
|
+
min: 1,
|
|
222
|
+
disabled: !cfg || saving,
|
|
223
|
+
value: cfg ? String(cfg[key]) : "",
|
|
224
|
+
onChange: (e) => cfg && setCfg({ ...cfg, [key]: Number(e.target.value) }),
|
|
225
|
+
onBlur: () => cfg && void commit(cfg)
|
|
226
|
+
}
|
|
227
|
+
),
|
|
228
|
+
/* @__PURE__ */ jsx("span", { className: "text-xs text-muted-foreground", children: t2("crm.engagement.daysUnit") })
|
|
229
|
+
] })
|
|
230
|
+
] }, key)) });
|
|
231
|
+
}
|
|
176
232
|
var CRM_DEFAULTS = {
|
|
177
233
|
autoAssign: false,
|
|
178
234
|
requireSource: true,
|
|
@@ -210,6 +266,7 @@ function CrmGeneralSettings() {
|
|
|
210
266
|
/* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.defaultValidity"), description: t2("crm.settings.defaultValidityDesc"), checked: s.get("defaultValidity"), onChange: (v) => s.set("defaultValidity", v) }),
|
|
211
267
|
/* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.requireApproval"), description: t2("crm.settings.requireApprovalDesc"), checked: s.get("requireApproval"), onChange: (v) => s.set("requireApproval", v) })
|
|
212
268
|
] }),
|
|
269
|
+
/* @__PURE__ */ jsx(EngagementLadderSettings, {}),
|
|
213
270
|
/* @__PURE__ */ jsxs(SettingsGroup, { title: t2("crm.settings.notifications"), description: t2("crm.settings.notificationsDesc"), children: [
|
|
214
271
|
/* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.overdueAlerts"), description: t2("crm.settings.overdueAlertsDesc"), checked: s.get("overdueAlerts"), onChange: (v) => s.set("overdueAlerts", v) }),
|
|
215
272
|
/* @__PURE__ */ jsx(ToggleRow, { label: t2("crm.settings.stageChangeAlerts"), description: t2("crm.settings.stageChangeAlertsDesc"), checked: s.get("stageChangeAlerts"), onChange: (v) => s.set("stageChangeAlerts", v) }),
|
|
@@ -2145,7 +2202,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
|
|
|
2145
2202
|
observations,
|
|
2146
2203
|
items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
|
|
2147
2204
|
};
|
|
2148
|
-
const snapshot =
|
|
2205
|
+
const snapshot = React20.useRef(null);
|
|
2149
2206
|
useEffect(() => {
|
|
2150
2207
|
if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
|
|
2151
2208
|
}, [loadingExisting]);
|
|
@@ -3249,6 +3306,170 @@ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
|
|
|
3249
3306
|
)
|
|
3250
3307
|
] });
|
|
3251
3308
|
}
|
|
3309
|
+
|
|
3310
|
+
// src/lib/scorecard.ts
|
|
3311
|
+
var MEASURED_DIMENSIONS = [
|
|
3312
|
+
"conversion",
|
|
3313
|
+
"retention",
|
|
3314
|
+
"reactivation",
|
|
3315
|
+
"productivity",
|
|
3316
|
+
"satisfaction"
|
|
3317
|
+
];
|
|
3318
|
+
function normalizeProductivity(rows) {
|
|
3319
|
+
const best = Math.max(0, ...rows.map((r) => r.productivity ?? 0));
|
|
3320
|
+
const out = /* @__PURE__ */ new Map();
|
|
3321
|
+
if (best <= 0) return out;
|
|
3322
|
+
for (const r of rows) {
|
|
3323
|
+
if (r.productivity != null) out.set(r.unitId, Math.round(r.productivity / best * 1e3) / 10);
|
|
3324
|
+
}
|
|
3325
|
+
return out;
|
|
3326
|
+
}
|
|
3327
|
+
function scoreUnits(rows, weights) {
|
|
3328
|
+
const prod = normalizeProductivity(rows);
|
|
3329
|
+
return rows.map((r) => {
|
|
3330
|
+
const values = {
|
|
3331
|
+
conversion: r.conversion ?? void 0,
|
|
3332
|
+
retention: r.retention ?? void 0,
|
|
3333
|
+
reactivation: r.reactivation ?? void 0,
|
|
3334
|
+
productivity: prod.get(r.unitId),
|
|
3335
|
+
satisfaction: r.satisfaction ?? void 0
|
|
3336
|
+
};
|
|
3337
|
+
let sum = 0;
|
|
3338
|
+
let totalWeight = 0;
|
|
3339
|
+
let measured = 0;
|
|
3340
|
+
for (const dim of MEASURED_DIMENSIONS) {
|
|
3341
|
+
const v = values[dim];
|
|
3342
|
+
const w = weights[dim] ?? 0;
|
|
3343
|
+
if (v == null || w <= 0) continue;
|
|
3344
|
+
sum += v * w;
|
|
3345
|
+
totalWeight += w;
|
|
3346
|
+
measured += 1;
|
|
3347
|
+
}
|
|
3348
|
+
return {
|
|
3349
|
+
...r,
|
|
3350
|
+
// Renormalizado: divide pelo peso do que ENTROU, não pelos 100 do
|
|
3351
|
+
// cadastro. Sem isso, uma unidade medida em duas dimensões teria teto de
|
|
3352
|
+
// 35 e pareceria péssima ao lado de outra medida em cinco.
|
|
3353
|
+
score: totalWeight > 0 ? Math.round(sum / totalWeight * 10) / 10 : null,
|
|
3354
|
+
measured
|
|
3355
|
+
};
|
|
3356
|
+
});
|
|
3357
|
+
}
|
|
3358
|
+
function networkScore(units) {
|
|
3359
|
+
const scored = units.filter((u) => u.score != null);
|
|
3360
|
+
if (scored.length === 0) return null;
|
|
3361
|
+
return Math.round(scored.reduce((s, u) => s + (u.score ?? 0), 0) / scored.length * 10) / 10;
|
|
3362
|
+
}
|
|
3363
|
+
function Cell({ value, suffix = "%" }) {
|
|
3364
|
+
if (value == null) return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground/50", children: "\u2014" });
|
|
3365
|
+
return /* @__PURE__ */ jsxs("span", { className: "tabular-nums", children: [
|
|
3366
|
+
value,
|
|
3367
|
+
suffix
|
|
3368
|
+
] });
|
|
3369
|
+
}
|
|
3370
|
+
function NetworkView() {
|
|
3371
|
+
const t2 = useTranslation();
|
|
3372
|
+
const provider = useCrmProvider();
|
|
3373
|
+
const { currency } = useCrmConfig();
|
|
3374
|
+
const [days, setDays] = React20.useState("90");
|
|
3375
|
+
const [rows, setRows] = React20.useState(null);
|
|
3376
|
+
const [weights, setWeights] = React20.useState({});
|
|
3377
|
+
React20.useEffect(() => {
|
|
3378
|
+
let alive = true;
|
|
3379
|
+
const to = (/* @__PURE__ */ new Date()).toISOString();
|
|
3380
|
+
const from = new Date(Date.now() - Number(days) * 864e5).toISOString();
|
|
3381
|
+
provider.getUnitScorecard(from, to).then((r) => {
|
|
3382
|
+
if (alive) setRows(r);
|
|
3383
|
+
}).catch(() => {
|
|
3384
|
+
if (alive) setRows([]);
|
|
3385
|
+
});
|
|
3386
|
+
provider.getScorecardWeights().then((w) => {
|
|
3387
|
+
if (alive) setWeights(w);
|
|
3388
|
+
}).catch(() => {
|
|
3389
|
+
});
|
|
3390
|
+
return () => {
|
|
3391
|
+
alive = false;
|
|
3392
|
+
};
|
|
3393
|
+
}, [provider, days]);
|
|
3394
|
+
const scored = React20.useMemo(() => scoreUnits(rows ?? [], weights), [rows, weights]);
|
|
3395
|
+
const avg = networkScore(scored);
|
|
3396
|
+
const ranked = React20.useMemo(() => [...scored].sort((a, b) => b.revenue - a.revenue), [scored]);
|
|
3397
|
+
return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
|
|
3398
|
+
/* @__PURE__ */ jsx(
|
|
3399
|
+
SubpageHeader,
|
|
3400
|
+
{
|
|
3401
|
+
title: t2("crm.network.title"),
|
|
3402
|
+
subtitle: t2("crm.network.subtitle"),
|
|
3403
|
+
actions: /* @__PURE__ */ jsxs(Select, { value: days, onValueChange: setDays, children: [
|
|
3404
|
+
/* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-[150px] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
3405
|
+
/* @__PURE__ */ jsx(SelectContent, { children: ["30", "90", "180", "365"].map((d) => /* @__PURE__ */ jsx(SelectItem, { value: d, children: t2("crm.network.lastDays", { days: d }) }, d)) })
|
|
3406
|
+
] })
|
|
3407
|
+
}
|
|
3408
|
+
),
|
|
3409
|
+
/* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card p-4 shadow-sm", "data-testid": "network-score", children: [
|
|
3410
|
+
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-end justify-between gap-4", children: [
|
|
3411
|
+
/* @__PURE__ */ jsxs("div", { children: [
|
|
3412
|
+
/* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.network.avgScore") }),
|
|
3413
|
+
/* @__PURE__ */ jsxs("p", { className: "text-3xl font-semibold", children: [
|
|
3414
|
+
avg == null ? "\u2014" : `${avg}`,
|
|
3415
|
+
/* @__PURE__ */ jsx("span", { className: "text-base text-muted-foreground", children: "/100" })
|
|
3416
|
+
] })
|
|
3417
|
+
] }),
|
|
3418
|
+
/* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-3", "data-testid": "scorecard-weights", children: MEASURED_DIMENSIONS.map((dim) => /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
|
|
3419
|
+
/* @__PURE__ */ jsx(
|
|
3420
|
+
Input,
|
|
3421
|
+
{
|
|
3422
|
+
className: "h-7 w-[64px] text-center text-xs",
|
|
3423
|
+
type: "number",
|
|
3424
|
+
min: 0,
|
|
3425
|
+
max: 100,
|
|
3426
|
+
value: String(weights[dim] ?? 0),
|
|
3427
|
+
onChange: (e) => setWeights((w) => ({ ...w, [dim]: Number(e.target.value) })),
|
|
3428
|
+
onBlur: () => void provider.saveScorecardWeights(weights).catch(() => {
|
|
3429
|
+
})
|
|
3430
|
+
}
|
|
3431
|
+
),
|
|
3432
|
+
/* @__PURE__ */ jsx("p", { className: "mt-1 text-[10px] text-muted-foreground", children: t2(`crm.network.dim.${dim}`) })
|
|
3433
|
+
] }, dim)) })
|
|
3434
|
+
] }),
|
|
3435
|
+
/* @__PURE__ */ jsx("p", { className: "mt-3 text-[10px] text-muted-foreground", children: t2("crm.network.weightsNote") })
|
|
3436
|
+
] }),
|
|
3437
|
+
/* @__PURE__ */ jsx("div", { className: "overflow-x-auto rounded-card border bg-card", children: /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
|
|
3438
|
+
/* @__PURE__ */ jsx("thead", { className: "border-b bg-muted/30 text-left text-xs text-muted-foreground", children: /* @__PURE__ */ jsxs("tr", { children: [
|
|
3439
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: "#" }),
|
|
3440
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 font-medium", children: t2("crm.network.unit") }),
|
|
3441
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.orders") }),
|
|
3442
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.revenue") }),
|
|
3443
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.dim.conversion") }),
|
|
3444
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.dim.retention") }),
|
|
3445
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.dim.reactivation") }),
|
|
3446
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.dim.satisfaction") }),
|
|
3447
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.score") }),
|
|
3448
|
+
/* @__PURE__ */ jsx("th", { className: "px-3 py-2 text-right font-medium", children: t2("crm.network.measured") })
|
|
3449
|
+
] }) }),
|
|
3450
|
+
/* @__PURE__ */ jsx("tbody", { "data-testid": "network-rows", children: rows === null ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 10, className: "px-3 py-8 text-center text-xs text-muted-foreground", children: t2("common.loading") }) }) : ranked.length === 0 ? /* @__PURE__ */ jsx("tr", { children: /* @__PURE__ */ jsx("td", { colSpan: 10, className: "px-3 py-8 text-center text-xs text-muted-foreground", children: t2("crm.network.empty") }) }) : ranked.map((u, i) => /* @__PURE__ */ jsxs("tr", { className: "border-b last:border-b-0", "data-testid": "network-row", children: [
|
|
3451
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-xs text-muted-foreground", children: i === 0 && u.revenue > 0 ? /* @__PURE__ */ jsx(Trophy, { className: "h-3 w-3 text-warning" }) : i + 1 }),
|
|
3452
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-xs font-medium", children: u.unitName }),
|
|
3453
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs tabular-nums", children: u.ordersCount }),
|
|
3454
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs tabular-nums", children: formatCurrency(u.revenue, currency) }),
|
|
3455
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs", children: /* @__PURE__ */ jsx(Cell, { value: u.conversion }) }),
|
|
3456
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs", children: /* @__PURE__ */ jsx(Cell, { value: u.retention }) }),
|
|
3457
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs", children: /* @__PURE__ */ jsx(Cell, { value: u.reactivation }) }),
|
|
3458
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-xs", children: /* @__PURE__ */ jsx(Cell, { value: u.satisfaction }) }),
|
|
3459
|
+
/* @__PURE__ */ jsx("td", { className: "px-3 py-2 text-right text-sm font-semibold", children: /* @__PURE__ */ jsx(Cell, { value: u.score, suffix: "" }) }),
|
|
3460
|
+
/* @__PURE__ */ jsxs("td", { className: "px-3 py-2 text-right text-[10px] text-muted-foreground", children: [
|
|
3461
|
+
u.measured,
|
|
3462
|
+
"/",
|
|
3463
|
+
MEASURED_DIMENSIONS.length
|
|
3464
|
+
] })
|
|
3465
|
+
] }, u.unitId)) })
|
|
3466
|
+
] }) }),
|
|
3467
|
+
ranked.some((u) => u.measured === 0) && /* @__PURE__ */ jsxs("p", { className: "rounded-lg bg-muted/30 px-3 py-2 text-xs text-muted-foreground", "data-testid": "network-note", children: [
|
|
3468
|
+
/* @__PURE__ */ jsx(Network, { className: "mr-1 inline h-3 w-3" }),
|
|
3469
|
+
t2("crm.network.unmeasuredNote")
|
|
3470
|
+
] })
|
|
3471
|
+
] });
|
|
3472
|
+
}
|
|
3252
3473
|
var QUESTION_TYPES = [
|
|
3253
3474
|
{ value: "stars", label: "Estrelas (1 a 5)" },
|
|
3254
3475
|
{ value: "nps", label: "Nota de 0 a 10 (NPS)" },
|
|
@@ -3353,11 +3574,11 @@ function SurveyScale({ type, value, onChange, readOnly, compact }) {
|
|
|
3353
3574
|
] });
|
|
3354
3575
|
}
|
|
3355
3576
|
function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, onSaved }) {
|
|
3356
|
-
const [name, setName] =
|
|
3357
|
-
const [isActive, setIsActive] =
|
|
3358
|
-
const [askOnCheckout, setAskOnCheckout] =
|
|
3359
|
-
const [thanks, setThanks] =
|
|
3360
|
-
const [questions, setQuestions] =
|
|
3577
|
+
const [name, setName] = React20.useState(survey?.name ?? "Pesquisa p\xF3s-atendimento");
|
|
3578
|
+
const [isActive, setIsActive] = React20.useState(survey?.isActive ?? true);
|
|
3579
|
+
const [askOnCheckout, setAskOnCheckout] = React20.useState(survey?.askOnCheckout ?? true);
|
|
3580
|
+
const [thanks, setThanks] = React20.useState(survey?.thankYouMessage ?? "");
|
|
3581
|
+
const [questions, setQuestions] = React20.useState(
|
|
3361
3582
|
(survey?.questions ?? []).map((q) => ({
|
|
3362
3583
|
id: q.id,
|
|
3363
3584
|
text: q.text,
|
|
@@ -3367,8 +3588,8 @@ function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, on
|
|
|
3367
3588
|
answered: answeredQuestionIds?.has(q.id)
|
|
3368
3589
|
}))
|
|
3369
3590
|
);
|
|
3370
|
-
const [saving, setSaving] =
|
|
3371
|
-
const [error, setError] =
|
|
3591
|
+
const [saving, setSaving] = React20.useState(false);
|
|
3592
|
+
const [error, setError] = React20.useState(null);
|
|
3372
3593
|
function patch(i, changes) {
|
|
3373
3594
|
setQuestions((qs) => qs.map((q, j) => j === i ? { ...q, ...changes } : q));
|
|
3374
3595
|
}
|
|
@@ -3562,13 +3783,13 @@ function SurveyEditorDialog({ survey, provider, answeredQuestionIds, onClose, on
|
|
|
3562
3783
|
}
|
|
3563
3784
|
function SurveyCollectDialog({ survey, provider, contactLookup, onClose, onSaved }) {
|
|
3564
3785
|
const unitId = useActiveUnitId();
|
|
3565
|
-
const [contact, setContact] =
|
|
3566
|
-
const [answers, setAnswers] =
|
|
3786
|
+
const [contact, setContact] = React20.useState(null);
|
|
3787
|
+
const [answers, setAnswers] = React20.useState(
|
|
3567
3788
|
Object.fromEntries(survey.questions.map((q) => [q.id, { rating: null, comment: "" }]))
|
|
3568
3789
|
);
|
|
3569
|
-
const [saving, setSaving] =
|
|
3570
|
-
const [done, setDone] =
|
|
3571
|
-
const [error, setError] =
|
|
3790
|
+
const [saving, setSaving] = React20.useState(false);
|
|
3791
|
+
const [done, setDone] = React20.useState(false);
|
|
3792
|
+
const [error, setError] = React20.useState(null);
|
|
3572
3793
|
function patch(id, changes) {
|
|
3573
3794
|
setAnswers((a) => ({ ...a, [id]: { ...a[id], ...changes } }));
|
|
3574
3795
|
}
|
|
@@ -3667,8 +3888,8 @@ function ResponseSkeleton() {
|
|
|
3667
3888
|
] }, i)) });
|
|
3668
3889
|
}
|
|
3669
3890
|
function SurveyResponsesRail({ survey, provider, onClose }) {
|
|
3670
|
-
const [responses, setResponses] =
|
|
3671
|
-
|
|
3891
|
+
const [responses, setResponses] = React20.useState(null);
|
|
3892
|
+
React20.useEffect(() => {
|
|
3672
3893
|
let cancelled = false;
|
|
3673
3894
|
setResponses(null);
|
|
3674
3895
|
void provider.getSurveyResponses(survey.id).then((r) => {
|
|
@@ -3728,19 +3949,19 @@ function SurveysView() {
|
|
|
3728
3949
|
const can = usePermissionOptional();
|
|
3729
3950
|
const canEdit = can("sales", "edit");
|
|
3730
3951
|
const canDelete = can("sales", "delete");
|
|
3731
|
-
const [surveys, setSurveys] =
|
|
3732
|
-
const [stats, setStats] =
|
|
3733
|
-
const [editing, setEditing] =
|
|
3734
|
-
const [collecting, setCollecting] =
|
|
3735
|
-
const [viewing, setViewing] =
|
|
3736
|
-
const [removing, setRemoving] =
|
|
3737
|
-
const [answeredIds, setAnsweredIds] =
|
|
3738
|
-
const load =
|
|
3952
|
+
const [surveys, setSurveys] = React20.useState(null);
|
|
3953
|
+
const [stats, setStats] = React20.useState({});
|
|
3954
|
+
const [editing, setEditing] = React20.useState(void 0);
|
|
3955
|
+
const [collecting, setCollecting] = React20.useState(null);
|
|
3956
|
+
const [viewing, setViewing] = React20.useState(null);
|
|
3957
|
+
const [removing, setRemoving] = React20.useState(null);
|
|
3958
|
+
const [answeredIds, setAnsweredIds] = React20.useState(/* @__PURE__ */ new Set());
|
|
3959
|
+
const load = React20.useCallback(async () => {
|
|
3739
3960
|
const [list, st] = await Promise.all([provider.getSurveys(), provider.getSurveyStats()]);
|
|
3740
3961
|
setSurveys(list);
|
|
3741
3962
|
setStats(Object.fromEntries(st.map((s) => [s.surveyId, s])));
|
|
3742
3963
|
}, [provider]);
|
|
3743
|
-
|
|
3964
|
+
React20.useEffect(() => {
|
|
3744
3965
|
void load();
|
|
3745
3966
|
}, [load]);
|
|
3746
3967
|
const askers = (surveys ?? []).filter((s) => s.isActive && s.askOnCheckout);
|
|
@@ -3970,7 +4191,7 @@ function SurveysView() {
|
|
|
3970
4191
|
)
|
|
3971
4192
|
] });
|
|
3972
4193
|
}
|
|
3973
|
-
function buildNav(config, view, navigate, hasAutomations, surveysLabel) {
|
|
4194
|
+
function buildNav(config, view, navigate, hasAutomations, surveysLabel, networkLabel, hasNetwork) {
|
|
3974
4195
|
const items = [
|
|
3975
4196
|
{ id: "dashboard", label: config.labels.dashboard, icon: "BarChart3", active: view === "dashboard", onClick: () => navigate("dashboard") }
|
|
3976
4197
|
];
|
|
@@ -4003,6 +4224,9 @@ function buildNav(config, view, navigate, hasAutomations, surveysLabel) {
|
|
|
4003
4224
|
if (config.modules.surveys) {
|
|
4004
4225
|
items.push({ id: "surveys", label: surveysLabel, icon: "Star", active: view === "surveys", onClick: () => navigate("surveys") });
|
|
4005
4226
|
}
|
|
4227
|
+
if (config.modules.network && hasNetwork) {
|
|
4228
|
+
items.push({ id: "network", label: networkLabel, icon: "Network", active: view === "network", onClick: () => navigate("network") });
|
|
4229
|
+
}
|
|
4006
4230
|
if (hasAutomations) {
|
|
4007
4231
|
items.push({
|
|
4008
4232
|
id: "automations",
|
|
@@ -4027,6 +4251,7 @@ function CrmPage({ config, provider, store, registries }) {
|
|
|
4027
4251
|
"quotes-edit": 2,
|
|
4028
4252
|
activities: 0,
|
|
4029
4253
|
surveys: 0,
|
|
4254
|
+
network: 0,
|
|
4030
4255
|
settings: 1
|
|
4031
4256
|
}, "dashboard");
|
|
4032
4257
|
const [onboardingComplete, setOnboardingComplete] = useState(() => {
|
|
@@ -4053,7 +4278,8 @@ function CrmPage({ config, provider, store, registries }) {
|
|
|
4053
4278
|
const runtime = usePluginRuntimeOptional();
|
|
4054
4279
|
const hasAutomations = Boolean(runtime?.activePlugins.some((p) => p.id === "automations"));
|
|
4055
4280
|
const t2 = useTranslation();
|
|
4056
|
-
const
|
|
4281
|
+
const hasNetwork = useUnitStore((u) => u.units.length > 1);
|
|
4282
|
+
const nav = buildNav(config, view, navigate, hasAutomations, config.labels.surveys ?? t2("crm.surveys.title"), t2("crm.network.title"), hasNetwork);
|
|
4057
4283
|
const quickActions = useMemo(() => [
|
|
4058
4284
|
{ id: "new-lead", label: t2("crm.quickActions.newLead"), icon: "UserPlus", description: t2("crm.quickActions.newLeadDesc"), action: () => navigate("leads-new") },
|
|
4059
4285
|
{ id: "new-deal", label: t2("crm.quickActions.newDeal"), icon: "Target", description: t2("crm.quickActions.newDealDesc"), action: () => navigate("pipeline") },
|
|
@@ -4100,6 +4326,7 @@ function CrmPage({ config, provider, store, registries }) {
|
|
|
4100
4326
|
} }) },
|
|
4101
4327
|
{ id: "quotes-edit", render: ({ id }) => /* @__PURE__ */ jsx(QuoteFormView, { quoteId: id, onSaved: () => navigate(`quotes-detail:${id}`) }) },
|
|
4102
4328
|
{ id: "surveys", render: () => /* @__PURE__ */ jsx(SurveysView, {}) },
|
|
4329
|
+
{ id: "network", render: () => /* @__PURE__ */ jsx(NetworkView, {}) },
|
|
4103
4330
|
{ id: "dashboard", render: () => /* @__PURE__ */ jsx(DashboardView, {}) }
|
|
4104
4331
|
], "dashboard");
|
|
4105
4332
|
return /* @__PURE__ */ jsx(CrmContextProvider, { config, provider, store, children: /* @__PURE__ */ jsx(
|
|
@@ -4261,7 +4488,7 @@ function PerformancePanel() {
|
|
|
4261
4488
|
}
|
|
4262
4489
|
function NpsKpi() {
|
|
4263
4490
|
const provider = useCrmProvider();
|
|
4264
|
-
const [stats, setStats] =
|
|
4491
|
+
const [stats, setStats] = React20.useState(null);
|
|
4265
4492
|
useEffect(() => {
|
|
4266
4493
|
let cancelled = false;
|
|
4267
4494
|
void provider.getSurveyStats().then((s) => {
|
|
@@ -4293,6 +4520,80 @@ function NpsKpi() {
|
|
|
4293
4520
|
}
|
|
4294
4521
|
);
|
|
4295
4522
|
}
|
|
4523
|
+
function useEngagement() {
|
|
4524
|
+
const provider = useCrmProvider();
|
|
4525
|
+
const [data, setData] = React20.useState(null);
|
|
4526
|
+
React20.useEffect(() => {
|
|
4527
|
+
let alive = true;
|
|
4528
|
+
provider.getEngagementSummary().then((d) => {
|
|
4529
|
+
if (alive) setData(d);
|
|
4530
|
+
}).catch(() => {
|
|
4531
|
+
if (alive) setData(null);
|
|
4532
|
+
});
|
|
4533
|
+
return () => {
|
|
4534
|
+
alive = false;
|
|
4535
|
+
};
|
|
4536
|
+
}, [provider]);
|
|
4537
|
+
return data;
|
|
4538
|
+
}
|
|
4539
|
+
function AtRiskKpi() {
|
|
4540
|
+
const t2 = useTranslation();
|
|
4541
|
+
const d = useEngagement();
|
|
4542
|
+
return /* @__PURE__ */ jsx(
|
|
4543
|
+
KpiCard,
|
|
4544
|
+
{
|
|
4545
|
+
label: t2("crm.engagement.atRisk"),
|
|
4546
|
+
value: d ? String(d.at_risk) : "\u2014",
|
|
4547
|
+
icon: "AlarmClock",
|
|
4548
|
+
sub: d ? t2("crm.engagement.atRiskSub", { days: String(d.settings.activeDays) }) : ""
|
|
4549
|
+
}
|
|
4550
|
+
);
|
|
4551
|
+
}
|
|
4552
|
+
function RetentionKpi() {
|
|
4553
|
+
const t2 = useTranslation();
|
|
4554
|
+
const d = useEngagement();
|
|
4555
|
+
const rate = d && d.returnable > 0 ? Math.round(d.returned / d.returnable * 100) : null;
|
|
4556
|
+
return /* @__PURE__ */ jsx(
|
|
4557
|
+
KpiCard,
|
|
4558
|
+
{
|
|
4559
|
+
label: t2("crm.engagement.retention"),
|
|
4560
|
+
value: rate === null ? "\u2014" : `${rate}%`,
|
|
4561
|
+
icon: "Repeat",
|
|
4562
|
+
sub: d ? t2("crm.engagement.retentionSub", { returned: String(d.returned), base: String(d.returnable) }) : ""
|
|
4563
|
+
}
|
|
4564
|
+
);
|
|
4565
|
+
}
|
|
4566
|
+
var LADDER = [
|
|
4567
|
+
{ key: "lead", labelKey: "crm.engagement.lead", tone: "bg-muted-foreground/40" },
|
|
4568
|
+
{ key: "prospect", labelKey: "crm.engagement.prospect", tone: "bg-info/50" },
|
|
4569
|
+
{ key: "new", labelKey: "crm.engagement.new", tone: "bg-info" },
|
|
4570
|
+
{ key: "active", labelKey: "crm.engagement.active", tone: "bg-success" },
|
|
4571
|
+
{ key: "at_risk", labelKey: "crm.engagement.atRisk", tone: "bg-warning" },
|
|
4572
|
+
{ key: "dormant", labelKey: "crm.engagement.dormant", tone: "bg-destructive/70" }
|
|
4573
|
+
];
|
|
4574
|
+
function LifecyclePanel() {
|
|
4575
|
+
const t2 = useTranslation();
|
|
4576
|
+
const d = useEngagement();
|
|
4577
|
+
const total = d?.people ?? 0;
|
|
4578
|
+
return /* @__PURE__ */ jsxs(Card, { children: [
|
|
4579
|
+
/* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: t2("crm.engagement.ladder") }) }),
|
|
4580
|
+
/* @__PURE__ */ jsxs(CardContent, { className: "space-y-2", children: [
|
|
4581
|
+
LADDER.map((row) => {
|
|
4582
|
+
const n = d ? Number(d[row.key] ?? 0) : 0;
|
|
4583
|
+
const pct = total > 0 ? Math.round(n / total * 100) : 0;
|
|
4584
|
+
return /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", "data-testid": `lifecycle-${row.key}`, children: [
|
|
4585
|
+
/* @__PURE__ */ jsx("span", { className: "w-28 shrink-0 text-xs text-muted-foreground", children: t2(row.labelKey) }),
|
|
4586
|
+
/* @__PURE__ */ jsx("div", { className: "h-2 flex-1 overflow-hidden rounded-full bg-muted/40", children: /* @__PURE__ */ jsx("div", { className: `h-full rounded-full ${row.tone}`, style: { width: `${pct}%` } }) }),
|
|
4587
|
+
/* @__PURE__ */ jsx("span", { className: "w-10 shrink-0 text-right text-xs font-medium", children: d ? n : "\xB7" })
|
|
4588
|
+
] }, row.key);
|
|
4589
|
+
}),
|
|
4590
|
+
/* @__PURE__ */ jsx("p", { className: "pt-1 text-[10px] text-muted-foreground", children: d ? t2("crm.engagement.derivedNote", {
|
|
4591
|
+
active: String(d.settings.activeDays),
|
|
4592
|
+
risk: String(d.settings.atRiskDays)
|
|
4593
|
+
}) : "" })
|
|
4594
|
+
] })
|
|
4595
|
+
] });
|
|
4596
|
+
}
|
|
4296
4597
|
var LEAD_STATUS = {
|
|
4297
4598
|
new: "bg-info",
|
|
4298
4599
|
contacted: "bg-magic",
|
|
@@ -4337,6 +4638,77 @@ function RecentQuotesTable() {
|
|
|
4337
4638
|
];
|
|
4338
4639
|
return /* @__PURE__ */ jsx(TableWidget, { title: t2("crm.dashboard.recentQuotes"), icon: "FileText", columns, data: quotes2.slice(0, 5), emptyMessage: t2("crm.dashboard.noQuotesYet") });
|
|
4339
4640
|
}
|
|
4641
|
+
function ActiveCustomersKpi() {
|
|
4642
|
+
const t2 = useTranslation();
|
|
4643
|
+
const d = useEngagement();
|
|
4644
|
+
return /* @__PURE__ */ jsx(
|
|
4645
|
+
KpiCard,
|
|
4646
|
+
{
|
|
4647
|
+
label: t2("crm.engagement.active"),
|
|
4648
|
+
value: d ? String(d.active) : "\u2014",
|
|
4649
|
+
icon: "UserCheck",
|
|
4650
|
+
sub: d ? t2("crm.dashboard.activeSub", { days: String(d.settings.activeDays) }) : ""
|
|
4651
|
+
}
|
|
4652
|
+
);
|
|
4653
|
+
}
|
|
4654
|
+
function SourceConversionChart() {
|
|
4655
|
+
const t2 = useTranslation();
|
|
4656
|
+
const provider = useCrmProvider();
|
|
4657
|
+
const [rows, setRows] = React20.useState([]);
|
|
4658
|
+
React20.useEffect(() => {
|
|
4659
|
+
let alive = true;
|
|
4660
|
+
provider.getSourceConversion(90).then((r) => {
|
|
4661
|
+
if (alive) setRows(r);
|
|
4662
|
+
}).catch(() => {
|
|
4663
|
+
});
|
|
4664
|
+
return () => {
|
|
4665
|
+
alive = false;
|
|
4666
|
+
};
|
|
4667
|
+
}, [provider]);
|
|
4668
|
+
return /* @__PURE__ */ jsx(
|
|
4669
|
+
ChartWidget,
|
|
4670
|
+
{
|
|
4671
|
+
title: t2("crm.dashboard.bySource"),
|
|
4672
|
+
icon: "Globe",
|
|
4673
|
+
type: "bar",
|
|
4674
|
+
data: rows.map((r) => ({ name: r.sourceName, leads: r.leads, converted: r.converted })),
|
|
4675
|
+
categoryKey: "name",
|
|
4676
|
+
series: [
|
|
4677
|
+
{ dataKey: "leads", label: t2("crm.dashboard.leadsLabel"), color: "hsl(var(--muted-foreground))" },
|
|
4678
|
+
{ dataKey: "converted", label: t2("crm.dashboard.convertedLabel"), color: "hsl(var(--magic))" }
|
|
4679
|
+
]
|
|
4680
|
+
}
|
|
4681
|
+
);
|
|
4682
|
+
}
|
|
4683
|
+
function MonthlyTrendChart() {
|
|
4684
|
+
const t2 = useTranslation();
|
|
4685
|
+
const provider = useCrmProvider();
|
|
4686
|
+
const [rows, setRows] = React20.useState([]);
|
|
4687
|
+
React20.useEffect(() => {
|
|
4688
|
+
let alive = true;
|
|
4689
|
+
provider.getMonthlySeries(6).then((r) => {
|
|
4690
|
+
if (alive) setRows(r);
|
|
4691
|
+
}).catch(() => {
|
|
4692
|
+
});
|
|
4693
|
+
return () => {
|
|
4694
|
+
alive = false;
|
|
4695
|
+
};
|
|
4696
|
+
}, [provider]);
|
|
4697
|
+
return /* @__PURE__ */ jsx(
|
|
4698
|
+
ChartWidget,
|
|
4699
|
+
{
|
|
4700
|
+
title: t2("crm.dashboard.monthly"),
|
|
4701
|
+
icon: "TrendingUp",
|
|
4702
|
+
type: "line",
|
|
4703
|
+
data: rows.map((r) => ({ name: r.month, leads: r.leads, converted: r.converted })),
|
|
4704
|
+
categoryKey: "name",
|
|
4705
|
+
series: [
|
|
4706
|
+
{ dataKey: "leads", label: t2("crm.dashboard.leadsLabel"), color: "hsl(var(--muted-foreground))" },
|
|
4707
|
+
{ dataKey: "converted", label: t2("crm.dashboard.convertedLabel"), color: "hsl(var(--magic))" }
|
|
4708
|
+
]
|
|
4709
|
+
}
|
|
4710
|
+
);
|
|
4711
|
+
}
|
|
4340
4712
|
function createCrmDashboardWidgets(ctx2) {
|
|
4341
4713
|
const withCtx = (Inner) => {
|
|
4342
4714
|
const Wrapped = () => /* @__PURE__ */ jsx(CrmContextProvider, { config: ctx2.config, provider: ctx2.provider, store: ctx2.store, children: /* @__PURE__ */ jsx(Inner, {}) });
|
|
@@ -4355,12 +4727,20 @@ function createCrmDashboardWidgets(ctx2) {
|
|
|
4355
4727
|
// cadastrou a pesquisa.
|
|
4356
4728
|
defineKpiWidget({ id: "crm.kpi.nps", title: "crm.surveys.nps", domain: "crm", defaultOrder: 4, defaultVisible: false, component: withCtx(NpsKpi) }),
|
|
4357
4729
|
defineKpiWidget({ id: "crm.kpi.pending-tasks", title: "crm.dashboard.pendingTasks", domain: "crm", defaultOrder: 3, defaultVisible: false, component: withCtx(PendingTasksKpi) }),
|
|
4730
|
+
// "Em risco" é o único destes que vira trabalho na hora: é uma lista de
|
|
4731
|
+
// gente para quem ainda dá tempo de ligar, não um número de relatório.
|
|
4732
|
+
defineKpiWidget({ id: "crm.kpi.at-risk", title: "crm.engagement.atRisk", domain: "crm", defaultOrder: 5, defaultVisible: false, component: withCtx(AtRiskKpi) }),
|
|
4733
|
+
defineKpiWidget({ id: "crm.kpi.retention", title: "crm.engagement.retention", domain: "crm", defaultOrder: 6, defaultVisible: false, component: withCtx(RetentionKpi) }),
|
|
4734
|
+
defineKpiWidget({ id: "crm.kpi.active-customers", title: "crm.engagement.active", domain: "crm", defaultOrder: 7, defaultVisible: false, component: withCtx(ActiveCustomersKpi) }),
|
|
4358
4735
|
// Charts/tables are richer — default them to the CRM plugin-home only, so
|
|
4359
4736
|
// the global app home stays a clean cross-domain KPI overview. Users can
|
|
4360
4737
|
// still surface them via the Customize menu / app layout.
|
|
4361
4738
|
defineChartWidget({ id: "crm.chart.funnel", title: "crm.dashboard.pipelineOverview", domain: "crm", span: 2, defaultOrder: 10, surfaces: ["plugin-home"], component: withCtx(SalesFunnelChart) }),
|
|
4362
4739
|
defineCustomWidget({ id: "crm.panel.performance", title: "crm.dashboard.performance", domain: "crm", span: 2, defaultOrder: 11, surfaces: ["plugin-home"], component: withCtx(PerformancePanel) }),
|
|
4363
4740
|
defineChartWidget({ id: "crm.chart.pipeline-value", title: "crm.dashboard.pipelineValue", domain: "crm", span: 4, defaultOrder: 12, surfaces: ["plugin-home"], component: withCtx(PipelineValueChart) }),
|
|
4741
|
+
defineChartWidget({ id: "crm.chart.by-source", title: "crm.dashboard.bySource", domain: "crm", span: 2, defaultOrder: 14, surfaces: ["plugin-home"], component: withCtx(SourceConversionChart) }),
|
|
4742
|
+
defineChartWidget({ id: "crm.chart.monthly", title: "crm.dashboard.monthly", domain: "crm", span: 2, defaultOrder: 15, surfaces: ["plugin-home"], component: withCtx(MonthlyTrendChart) }),
|
|
4743
|
+
defineCustomWidget({ id: "crm.panel.lifecycle", title: "crm.engagement.ladder", domain: "crm", span: 2, defaultOrder: 13, surfaces: ["plugin-home"], component: withCtx(LifecyclePanel) }),
|
|
4364
4744
|
defineTableWidget({ id: "crm.table.recent-leads", title: "crm.dashboard.recentLeads", domain: "crm", span: 2, defaultOrder: 20, surfaces: ["plugin-home"], component: withCtx(RecentLeadsTable) }),
|
|
4365
4745
|
defineTableWidget({ id: "crm.table.recent-quotes", title: "crm.dashboard.recentQuotes", domain: "crm", span: 2, defaultOrder: 21, surfaces: ["plugin-home"], component: withCtx(RecentQuotesTable) })
|
|
4366
4746
|
];
|
|
@@ -4381,6 +4761,115 @@ function deriveQuoteStatus(stage, current) {
|
|
|
4381
4761
|
return current;
|
|
4382
4762
|
}
|
|
4383
4763
|
|
|
4764
|
+
// src/lib/segments.ts
|
|
4765
|
+
var SEGMENT_FIELDS = [
|
|
4766
|
+
{ column: "kind", labelKey: "crm.segments.field.kind", type: "kind", ops: ["=", "<>"] },
|
|
4767
|
+
{ column: "tags", labelKey: "crm.segments.field.tags", type: "tags", ops: ["has_tag"] },
|
|
4768
|
+
{ column: "created_at", labelKey: "crm.segments.field.createdAt", type: "date", ops: ["within_days", "older_than_days"] },
|
|
4769
|
+
{ column: "updated_at", labelKey: "crm.segments.field.updatedAt", type: "date", ops: ["within_days", "older_than_days"] },
|
|
4770
|
+
{ column: "date_of_birth", labelKey: "crm.segments.field.birthday", type: "date", ops: ["birthday_within_days"] },
|
|
4771
|
+
{ column: "email", labelKey: "crm.segments.field.email", type: "text", ops: ["is_null", "not_null", "ilike"] },
|
|
4772
|
+
{ column: "phone", labelKey: "crm.segments.field.phone", type: "text", ops: ["is_null", "not_null", "ilike"] },
|
|
4773
|
+
{ column: "city", labelKey: "crm.segments.field.city", type: "text", ops: ["=", "ilike", "in"] },
|
|
4774
|
+
{ column: "name", labelKey: "crm.segments.field.name", type: "text", ops: ["ilike"] },
|
|
4775
|
+
{ column: "is_active", labelKey: "crm.segments.field.isActive", type: "boolean", ops: ["="] }
|
|
4776
|
+
];
|
|
4777
|
+
function segmentFieldFor(column) {
|
|
4778
|
+
return SEGMENT_FIELDS.find((f) => f.column === column);
|
|
4779
|
+
}
|
|
4780
|
+
var VALUELESS_OPS = ["is_null", "not_null"];
|
|
4781
|
+
var DAY_OPS = ["within_days", "older_than_days", "birthday_within_days"];
|
|
4782
|
+
function describeRule(rule, t2) {
|
|
4783
|
+
const field = segmentFieldFor(rule.column);
|
|
4784
|
+
const label2 = field ? t2(field.labelKey) : rule.column;
|
|
4785
|
+
const v = Array.isArray(rule.value) ? rule.value.join(", ") : String(rule.value ?? "");
|
|
4786
|
+
switch (rule.op) {
|
|
4787
|
+
case "is_null":
|
|
4788
|
+
return t2("crm.segments.rule.isNull", { field: label2 });
|
|
4789
|
+
case "not_null":
|
|
4790
|
+
return t2("crm.segments.rule.notNull", { field: label2 });
|
|
4791
|
+
case "has_tag":
|
|
4792
|
+
return t2("crm.segments.rule.hasTag", { value: v });
|
|
4793
|
+
case "within_days":
|
|
4794
|
+
return t2("crm.segments.rule.withinDays", { field: label2, days: v });
|
|
4795
|
+
case "older_than_days":
|
|
4796
|
+
return t2("crm.segments.rule.olderThanDays", { field: label2, days: v });
|
|
4797
|
+
case "birthday_within_days":
|
|
4798
|
+
return t2("crm.segments.rule.birthdayWithinDays", { days: v });
|
|
4799
|
+
case "ilike":
|
|
4800
|
+
return t2("crm.segments.rule.contains", { field: label2, value: v });
|
|
4801
|
+
case "in":
|
|
4802
|
+
return t2("crm.segments.rule.in", { field: label2, value: v });
|
|
4803
|
+
case "not_in":
|
|
4804
|
+
return t2("crm.segments.rule.notIn", { field: label2, value: v });
|
|
4805
|
+
default:
|
|
4806
|
+
return `${label2} ${rule.op} ${v}`;
|
|
4807
|
+
}
|
|
4808
|
+
}
|
|
4809
|
+
function daysBetween(iso, nowMs) {
|
|
4810
|
+
if (!iso) return null;
|
|
4811
|
+
const t2 = Date.parse(iso);
|
|
4812
|
+
return Number.isNaN(t2) ? null : (nowMs - t2) / 864e5;
|
|
4813
|
+
}
|
|
4814
|
+
function dayOfYear(d) {
|
|
4815
|
+
return Math.floor((Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - Date.UTC(d.getUTCFullYear(), 0, 0)) / 864e5);
|
|
4816
|
+
}
|
|
4817
|
+
function matches(row, rule, nowMs) {
|
|
4818
|
+
const raw = row[rule.column];
|
|
4819
|
+
const v = rule.value;
|
|
4820
|
+
switch (rule.op) {
|
|
4821
|
+
case "=":
|
|
4822
|
+
return String(raw ?? "") === String(v ?? "");
|
|
4823
|
+
case "<>":
|
|
4824
|
+
return String(raw ?? "") !== String(v ?? "");
|
|
4825
|
+
case ">":
|
|
4826
|
+
return Number(raw) > Number(v);
|
|
4827
|
+
case "<":
|
|
4828
|
+
return Number(raw) < Number(v);
|
|
4829
|
+
case ">=":
|
|
4830
|
+
return Number(raw) >= Number(v);
|
|
4831
|
+
case "<=":
|
|
4832
|
+
return Number(raw) <= Number(v);
|
|
4833
|
+
case "ilike":
|
|
4834
|
+
return String(raw ?? "").toLowerCase().includes(String(v ?? "").toLowerCase());
|
|
4835
|
+
case "in":
|
|
4836
|
+
return Array.isArray(v) && v.map(String).includes(String(raw ?? ""));
|
|
4837
|
+
case "not_in":
|
|
4838
|
+
return !(Array.isArray(v) && v.map(String).includes(String(raw ?? "")));
|
|
4839
|
+
// NULO e VAZIO são a mesma coisa aqui de propósito: um lead gravado com
|
|
4840
|
+
// telefone '' não tem telefone, e o recorte "sem como falar" existe para
|
|
4841
|
+
// achá-lo. No banco a coluna é NULL; no mock, às vezes, string vazia.
|
|
4842
|
+
case "is_null":
|
|
4843
|
+
return raw === null || raw === void 0 || raw === "";
|
|
4844
|
+
case "not_null":
|
|
4845
|
+
return !(raw === null || raw === void 0 || raw === "");
|
|
4846
|
+
case "has_tag":
|
|
4847
|
+
return Array.isArray(raw) && raw.map(String).includes(String(v ?? ""));
|
|
4848
|
+
case "within_days": {
|
|
4849
|
+
const d = daysBetween(raw, nowMs);
|
|
4850
|
+
return d !== null && d <= Number(v);
|
|
4851
|
+
}
|
|
4852
|
+
case "older_than_days": {
|
|
4853
|
+
const d = daysBetween(raw, nowMs);
|
|
4854
|
+
return d !== null && d > Number(v);
|
|
4855
|
+
}
|
|
4856
|
+
case "birthday_within_days": {
|
|
4857
|
+
if (!raw) return false;
|
|
4858
|
+
const b = new Date(String(raw));
|
|
4859
|
+
if (Number.isNaN(b.getTime())) return false;
|
|
4860
|
+
const delta = (dayOfYear(b) - dayOfYear(new Date(nowMs)) + 366) % 366;
|
|
4861
|
+
return delta <= Number(v);
|
|
4862
|
+
}
|
|
4863
|
+
default:
|
|
4864
|
+
return false;
|
|
4865
|
+
}
|
|
4866
|
+
}
|
|
4867
|
+
function evaluateSegment(segment, rows, nowMs = Date.now()) {
|
|
4868
|
+
if (segment.kind === "list") return [];
|
|
4869
|
+
const where = segment.rules?.where ?? [];
|
|
4870
|
+
return rows.filter((r) => where.every((rule) => matches(r, rule, nowMs))).map((r) => r.id);
|
|
4871
|
+
}
|
|
4872
|
+
|
|
4384
4873
|
// src/data/mock.ts
|
|
4385
4874
|
var CRM_MOCK_LEAD_SOURCES = [
|
|
4386
4875
|
{ name: "E-mail", description: "Escreveu para o e-mail da casa." },
|
|
@@ -4393,12 +4882,132 @@ var CRM_MOCK_LEAD_SOURCES = [
|
|
|
4393
4882
|
{ name: "Site", description: "Formul\xE1rio ou contato pelo site." },
|
|
4394
4883
|
{ name: "WhatsApp", description: "Chamou direto no WhatsApp." }
|
|
4395
4884
|
];
|
|
4885
|
+
var MOCK_SEGMENT_SEEDS = [
|
|
4886
|
+
{
|
|
4887
|
+
key: "new-leads",
|
|
4888
|
+
name: "Leads novos",
|
|
4889
|
+
description: "Entraram nos \xFAltimos 7 dias.",
|
|
4890
|
+
kind: "rule",
|
|
4891
|
+
sourceView: "people",
|
|
4892
|
+
color: "#3b82f6",
|
|
4893
|
+
icon: "UserPlus",
|
|
4894
|
+
isSystem: true,
|
|
4895
|
+
isActive: true,
|
|
4896
|
+
sortOrder: 10,
|
|
4897
|
+
rules: { where: [{ column: "kind", op: "=", value: "lead" }, { column: "created_at", op: "within_days", value: 7 }] }
|
|
4898
|
+
},
|
|
4899
|
+
{
|
|
4900
|
+
key: "unreachable-leads",
|
|
4901
|
+
name: "Sem como falar",
|
|
4902
|
+
description: "Leads sem telefone e sem e-mail.",
|
|
4903
|
+
kind: "rule",
|
|
4904
|
+
sourceView: "people",
|
|
4905
|
+
color: "#f59e0b",
|
|
4906
|
+
icon: "PhoneOff",
|
|
4907
|
+
isSystem: true,
|
|
4908
|
+
isActive: true,
|
|
4909
|
+
sortOrder: 20,
|
|
4910
|
+
rules: { where: [{ column: "kind", op: "=", value: "lead" }, { column: "phone", op: "is_null" }, { column: "email", op: "is_null" }] }
|
|
4911
|
+
},
|
|
4912
|
+
{
|
|
4913
|
+
key: "vip",
|
|
4914
|
+
name: "VIP",
|
|
4915
|
+
description: "Quem est\xE1 marcado com a etiqueta VIP.",
|
|
4916
|
+
kind: "rule",
|
|
4917
|
+
sourceView: "people",
|
|
4918
|
+
color: "#a855f7",
|
|
4919
|
+
icon: "Star",
|
|
4920
|
+
isSystem: true,
|
|
4921
|
+
isActive: true,
|
|
4922
|
+
sortOrder: 30,
|
|
4923
|
+
rules: { where: [{ column: "tags", op: "has_tag", value: "vip" }] }
|
|
4924
|
+
},
|
|
4925
|
+
{
|
|
4926
|
+
key: "dormant-90",
|
|
4927
|
+
name: "Parados h\xE1 90 dias",
|
|
4928
|
+
description: "J\xE1 n\xE3o s\xE3o lead e n\xE3o t\xEAm movimento h\xE1 tr\xEAs meses.",
|
|
4929
|
+
kind: "rule",
|
|
4930
|
+
sourceView: "people",
|
|
4931
|
+
color: "#64748b",
|
|
4932
|
+
icon: "Moon",
|
|
4933
|
+
isSystem: true,
|
|
4934
|
+
isActive: true,
|
|
4935
|
+
sortOrder: 40,
|
|
4936
|
+
rules: { where: [{ column: "kind", op: "<>", value: "lead" }, { column: "updated_at", op: "older_than_days", value: 90 }] }
|
|
4937
|
+
},
|
|
4938
|
+
{
|
|
4939
|
+
key: "birthdays-30",
|
|
4940
|
+
name: "Anivers\xE1rio em 30 dias",
|
|
4941
|
+
description: "Faz anivers\xE1rio no pr\xF3ximo m\xEAs.",
|
|
4942
|
+
kind: "rule",
|
|
4943
|
+
sourceView: "people",
|
|
4944
|
+
color: "#ec4899",
|
|
4945
|
+
icon: "Cake",
|
|
4946
|
+
isSystem: true,
|
|
4947
|
+
isActive: true,
|
|
4948
|
+
sortOrder: 50,
|
|
4949
|
+
rules: { where: [{ column: "date_of_birth", op: "birthday_within_days", value: 30 }] }
|
|
4950
|
+
}
|
|
4951
|
+
];
|
|
4952
|
+
var mockSegments = [];
|
|
4953
|
+
var mockEngagementSettings = { newDays: 30, activeDays: 90, atRiskDays: 180 };
|
|
4954
|
+
var mockScorecardWeights = {
|
|
4955
|
+
conversion: 20,
|
|
4956
|
+
retention: 15,
|
|
4957
|
+
reactivation: 10,
|
|
4958
|
+
productivity: 15,
|
|
4959
|
+
satisfaction: 15,
|
|
4960
|
+
speed: 10,
|
|
4961
|
+
occupancy: 5,
|
|
4962
|
+
financial: 10
|
|
4963
|
+
};
|
|
4964
|
+
var mockScorecard = [
|
|
4965
|
+
{
|
|
4966
|
+
unitId: "u1",
|
|
4967
|
+
unitName: "Matriz",
|
|
4968
|
+
ordersCount: 320,
|
|
4969
|
+
revenue: 96e3,
|
|
4970
|
+
peopleCount: 210,
|
|
4971
|
+
conversion: 42,
|
|
4972
|
+
retention: 61,
|
|
4973
|
+
reactivation: 18,
|
|
4974
|
+
productivity: 12e3,
|
|
4975
|
+
satisfaction: 78
|
|
4976
|
+
},
|
|
4977
|
+
{
|
|
4978
|
+
unitId: "u2",
|
|
4979
|
+
unitName: "Filial Norte",
|
|
4980
|
+
ordersCount: 180,
|
|
4981
|
+
revenue: 41e3,
|
|
4982
|
+
peopleCount: 130,
|
|
4983
|
+
conversion: 35,
|
|
4984
|
+
retention: 48,
|
|
4985
|
+
reactivation: 11,
|
|
4986
|
+
productivity: 8200,
|
|
4987
|
+
satisfaction: null
|
|
4988
|
+
},
|
|
4989
|
+
{
|
|
4990
|
+
unitId: "u3",
|
|
4991
|
+
unitName: "Quiosque",
|
|
4992
|
+
ordersCount: 24,
|
|
4993
|
+
revenue: 3600,
|
|
4994
|
+
peopleCount: 30,
|
|
4995
|
+
conversion: null,
|
|
4996
|
+
retention: 55,
|
|
4997
|
+
reactivation: null,
|
|
4998
|
+
productivity: null,
|
|
4999
|
+
satisfaction: null
|
|
5000
|
+
}
|
|
5001
|
+
];
|
|
4396
5002
|
var mockSurveys = [];
|
|
4397
5003
|
var mockResponses = [];
|
|
4398
5004
|
var nextId2 = 1;
|
|
4399
5005
|
function uid() {
|
|
4400
5006
|
return String(nextId2++);
|
|
4401
5007
|
}
|
|
5008
|
+
function slugStage(name) {
|
|
5009
|
+
return name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || "etapa";
|
|
5010
|
+
}
|
|
4402
5011
|
function now() {
|
|
4403
5012
|
return (/* @__PURE__ */ new Date()).toISOString();
|
|
4404
5013
|
}
|
|
@@ -4431,6 +5040,10 @@ function createStore(seedStages) {
|
|
|
4431
5040
|
order: i,
|
|
4432
5041
|
color: s.color,
|
|
4433
5042
|
probability: s.probability,
|
|
5043
|
+
code: slugStage(s.name),
|
|
5044
|
+
// A primeira etapa não-terminal é a entrada, e agora isso é um DADO e não
|
|
5045
|
+
// uma dedução do cliente — igual ao banco depois da 005.
|
|
5046
|
+
isInitial: i === 0,
|
|
4434
5047
|
isWon: s.name === "Won",
|
|
4435
5048
|
isLost: s.name === "Lost",
|
|
4436
5049
|
tenantId,
|
|
@@ -4486,6 +5099,46 @@ function createMockCrmProvider(options) {
|
|
|
4486
5099
|
}
|
|
4487
5100
|
}
|
|
4488
5101
|
}
|
|
5102
|
+
function mockPeopleRows() {
|
|
5103
|
+
return store.leads.map((l) => ({
|
|
5104
|
+
id: l.id,
|
|
5105
|
+
kind: "lead",
|
|
5106
|
+
name: l.name,
|
|
5107
|
+
email: l.email ?? null,
|
|
5108
|
+
phone: l.phone ?? null,
|
|
5109
|
+
city: null,
|
|
5110
|
+
tags: l.tags ?? [],
|
|
5111
|
+
is_active: true,
|
|
5112
|
+
created_at: l.createdAt,
|
|
5113
|
+
updated_at: l.updatedAt,
|
|
5114
|
+
date_of_birth: null
|
|
5115
|
+
}));
|
|
5116
|
+
}
|
|
5117
|
+
function mockEngagement() {
|
|
5118
|
+
const dayMs = 864e5;
|
|
5119
|
+
return store.leads.map((l) => {
|
|
5120
|
+
const won = store.deals.filter((d) => d.leadId === l.id && d.status === "won");
|
|
5121
|
+
const dates = won.map((d) => d.updatedAt ?? d.createdAt).sort();
|
|
5122
|
+
const first = dates[0];
|
|
5123
|
+
const last = dates[dates.length - 1];
|
|
5124
|
+
const days = last ? Math.floor((Date.now() - Date.parse(last)) / dayMs) : void 0;
|
|
5125
|
+
const c = mockEngagementSettings;
|
|
5126
|
+
const lifecycle = !last ? l.status === "converted" ? "prospect" : "lead" : (Date.now() - Date.parse(first)) / dayMs <= c.newDays ? "new" : (days ?? 1e9) <= c.activeDays ? "active" : (days ?? 1e9) <= c.atRiskDays ? "at_risk" : "dormant";
|
|
5127
|
+
const totalValue = won.reduce((s, d) => s + (d.value ?? 0), 0);
|
|
5128
|
+
return {
|
|
5129
|
+
personId: l.id,
|
|
5130
|
+
name: l.name,
|
|
5131
|
+
kind: "lead",
|
|
5132
|
+
firstAt: first,
|
|
5133
|
+
lastAt: last,
|
|
5134
|
+
visits: won.length,
|
|
5135
|
+
totalValue,
|
|
5136
|
+
avgValue: won.length ? totalValue / won.length : void 0,
|
|
5137
|
+
daysSinceLast: days,
|
|
5138
|
+
lifecycle
|
|
5139
|
+
};
|
|
5140
|
+
});
|
|
5141
|
+
}
|
|
4489
5142
|
const provider = {
|
|
4490
5143
|
async getPipelines() {
|
|
4491
5144
|
return store.pipelines;
|
|
@@ -4571,7 +5224,7 @@ function createMockCrmProvider(options) {
|
|
|
4571
5224
|
},
|
|
4572
5225
|
async getDealsByStage(pipelineId, filter, knownStages) {
|
|
4573
5226
|
const stages = knownStages ?? store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
|
|
4574
|
-
const
|
|
5227
|
+
const matches2 = (d) => {
|
|
4575
5228
|
if (filter?.tags?.length && !filter.tags.some((t2) => (d.tags ?? []).includes(t2))) return false;
|
|
4576
5229
|
if (filter?.createdFrom && d.createdAt < filter.createdFrom) return false;
|
|
4577
5230
|
if (filter?.createdTo && d.createdAt > filter.createdTo) return false;
|
|
@@ -4579,7 +5232,7 @@ function createMockCrmProvider(options) {
|
|
|
4579
5232
|
};
|
|
4580
5233
|
const map = /* @__PURE__ */ new Map();
|
|
4581
5234
|
for (const stage of stages) {
|
|
4582
|
-
map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" &&
|
|
5235
|
+
map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches2(d)));
|
|
4583
5236
|
}
|
|
4584
5237
|
return map;
|
|
4585
5238
|
},
|
|
@@ -5008,6 +5661,254 @@ function createMockCrmProvider(options) {
|
|
|
5008
5661
|
});
|
|
5009
5662
|
},
|
|
5010
5663
|
// Summary
|
|
5664
|
+
// ── Desenhar o funil ──────────────────────────────────────────────────
|
|
5665
|
+
async savePipeline(input) {
|
|
5666
|
+
if (input.isDefault) store.pipelines.forEach((p) => {
|
|
5667
|
+
p.isDefault = false;
|
|
5668
|
+
});
|
|
5669
|
+
if (input.id) {
|
|
5670
|
+
const found = store.pipelines.find((p) => p.id === input.id);
|
|
5671
|
+
if (!found) throw new Error("Funil n\xE3o encontrado.");
|
|
5672
|
+
found.name = input.name.trim();
|
|
5673
|
+
if (input.isDefault !== void 0) found.isDefault = input.isDefault;
|
|
5674
|
+
if (input.isActive !== void 0) found.isActive = input.isActive;
|
|
5675
|
+
found.updatedAt = now();
|
|
5676
|
+
return found;
|
|
5677
|
+
}
|
|
5678
|
+
const created = {
|
|
5679
|
+
id: uid(),
|
|
5680
|
+
name: input.name.trim(),
|
|
5681
|
+
isDefault: input.isDefault ?? false,
|
|
5682
|
+
isActive: input.isActive ?? true,
|
|
5683
|
+
tenantId: "mock",
|
|
5684
|
+
createdAt: now(),
|
|
5685
|
+
updatedAt: now()
|
|
5686
|
+
};
|
|
5687
|
+
store.pipelines.push(created);
|
|
5688
|
+
const seed = [
|
|
5689
|
+
["Novo", "#64748b", 10, { isInitial: true }],
|
|
5690
|
+
["Ganho", "#10b981", 100, { isWon: true }],
|
|
5691
|
+
["Perdido", "#ef4444", 0, { isLost: true }]
|
|
5692
|
+
];
|
|
5693
|
+
seed.forEach(([name, color, probability, extra], i) => {
|
|
5694
|
+
store.stages.push({
|
|
5695
|
+
id: uid(),
|
|
5696
|
+
pipelineId: created.id,
|
|
5697
|
+
name,
|
|
5698
|
+
code: slugStage(name),
|
|
5699
|
+
order: i + 1,
|
|
5700
|
+
color,
|
|
5701
|
+
probability,
|
|
5702
|
+
isInitial: false,
|
|
5703
|
+
isWon: false,
|
|
5704
|
+
isLost: false,
|
|
5705
|
+
tenantId: "mock",
|
|
5706
|
+
createdAt: now(),
|
|
5707
|
+
...extra
|
|
5708
|
+
});
|
|
5709
|
+
});
|
|
5710
|
+
return created;
|
|
5711
|
+
},
|
|
5712
|
+
async deletePipeline(id) {
|
|
5713
|
+
const active = store.pipelines.filter((p) => p.isActive !== false);
|
|
5714
|
+
if (active.length <= 1) throw new Error("Este \xE9 o \xFAnico funil da casa \u2014 um CRM sem funil n\xE3o tem onde p\xF4r neg\xF3cio.");
|
|
5715
|
+
const found = store.pipelines.find((p) => p.id === id);
|
|
5716
|
+
if (found) found.isActive = false;
|
|
5717
|
+
},
|
|
5718
|
+
async saveStage(input) {
|
|
5719
|
+
if (input.isInitial) {
|
|
5720
|
+
store.stages.filter((s) => s.pipelineId === input.pipelineId && s.id !== input.id).forEach((s) => {
|
|
5721
|
+
s.isInitial = false;
|
|
5722
|
+
});
|
|
5723
|
+
}
|
|
5724
|
+
if (input.id) {
|
|
5725
|
+
const found = store.stages.find((s) => s.id === input.id);
|
|
5726
|
+
if (!found) throw new Error("Etapa n\xE3o encontrada.");
|
|
5727
|
+
found.name = input.name.trim();
|
|
5728
|
+
if (input.color !== void 0) found.color = input.color;
|
|
5729
|
+
if (input.probability !== void 0) found.probability = input.probability;
|
|
5730
|
+
if (input.isInitial !== void 0) found.isInitial = input.isInitial;
|
|
5731
|
+
if (input.isWon !== void 0) found.isWon = input.isWon;
|
|
5732
|
+
if (input.isLost !== void 0) found.isLost = input.isLost;
|
|
5733
|
+
if (input.order !== void 0) found.order = input.order;
|
|
5734
|
+
return found;
|
|
5735
|
+
}
|
|
5736
|
+
const siblings = store.stages.filter((s) => s.pipelineId === input.pipelineId);
|
|
5737
|
+
let code = slugStage(input.code || input.name);
|
|
5738
|
+
let n = 1;
|
|
5739
|
+
while (siblings.some((s) => s.code === code)) {
|
|
5740
|
+
n += 1;
|
|
5741
|
+
code = `${slugStage(input.code || input.name)}-${n}`;
|
|
5742
|
+
}
|
|
5743
|
+
const created = {
|
|
5744
|
+
id: uid(),
|
|
5745
|
+
pipelineId: input.pipelineId,
|
|
5746
|
+
name: input.name.trim(),
|
|
5747
|
+
code,
|
|
5748
|
+
order: input.order ?? Math.max(0, ...siblings.map((s) => s.order)) + 1,
|
|
5749
|
+
color: input.color ?? "#6366f1",
|
|
5750
|
+
probability: input.probability ?? 0,
|
|
5751
|
+
isInitial: input.isInitial ?? false,
|
|
5752
|
+
isWon: input.isWon ?? false,
|
|
5753
|
+
isLost: input.isLost ?? false,
|
|
5754
|
+
tenantId: "mock",
|
|
5755
|
+
createdAt: now()
|
|
5756
|
+
};
|
|
5757
|
+
store.stages.push(created);
|
|
5758
|
+
return created;
|
|
5759
|
+
},
|
|
5760
|
+
async deleteStage(id) {
|
|
5761
|
+
const held = store.deals.filter((d) => d.stageId === id).length;
|
|
5762
|
+
if (held > 0) throw new Error(`Esta etapa tem ${held} neg\xF3cio(s). Mova-os antes de exclu\xED-la.`);
|
|
5763
|
+
const i = store.stages.findIndex((s) => s.id === id);
|
|
5764
|
+
if (i >= 0) store.stages.splice(i, 1);
|
|
5765
|
+
},
|
|
5766
|
+
async reorderStages(pipelineId, orderedIds) {
|
|
5767
|
+
orderedIds.forEach((id, i) => {
|
|
5768
|
+
const found = store.stages.find((s) => s.id === id && s.pipelineId === pipelineId);
|
|
5769
|
+
if (found) found.order = i + 1;
|
|
5770
|
+
});
|
|
5771
|
+
},
|
|
5772
|
+
// ── Painel ────────────────────────────────────────────────────────────
|
|
5773
|
+
async getSourceConversion(days = 90) {
|
|
5774
|
+
const since = Date.now() - days * 864e5;
|
|
5775
|
+
const acc = /* @__PURE__ */ new Map();
|
|
5776
|
+
for (const l of store.leads) {
|
|
5777
|
+
if (Date.parse(l.createdAt) < since) continue;
|
|
5778
|
+
const key = l.sourceName || "Sem origem";
|
|
5779
|
+
const cur = acc.get(key) ?? { leads: 0, converted: 0 };
|
|
5780
|
+
cur.leads += 1;
|
|
5781
|
+
if (l.status === "converted") cur.converted += 1;
|
|
5782
|
+
acc.set(key, cur);
|
|
5783
|
+
}
|
|
5784
|
+
return [...acc.entries()].map(([sourceName, v]) => ({
|
|
5785
|
+
sourceName,
|
|
5786
|
+
leads: v.leads,
|
|
5787
|
+
converted: v.converted,
|
|
5788
|
+
rate: v.leads > 0 ? Math.round(v.converted / v.leads * 1e3) / 10 : null
|
|
5789
|
+
})).sort((a, b) => b.leads - a.leads);
|
|
5790
|
+
},
|
|
5791
|
+
async getMonthlySeries(months = 6) {
|
|
5792
|
+
const acc = /* @__PURE__ */ new Map();
|
|
5793
|
+
const start = /* @__PURE__ */ new Date();
|
|
5794
|
+
start.setUTCDate(1);
|
|
5795
|
+
start.setUTCHours(0, 0, 0, 0);
|
|
5796
|
+
start.setUTCMonth(start.getUTCMonth() - (months - 1));
|
|
5797
|
+
for (let i = 0; i < months; i++) {
|
|
5798
|
+
const d = new Date(start);
|
|
5799
|
+
d.setUTCMonth(start.getUTCMonth() + i);
|
|
5800
|
+
acc.set(d.toISOString().slice(0, 7), { leads: 0, converted: 0 });
|
|
5801
|
+
}
|
|
5802
|
+
for (const l of store.leads) {
|
|
5803
|
+
const cur = acc.get(l.createdAt.slice(0, 7));
|
|
5804
|
+
if (!cur) continue;
|
|
5805
|
+
cur.leads += 1;
|
|
5806
|
+
if (l.status === "converted") cur.converted += 1;
|
|
5807
|
+
}
|
|
5808
|
+
return [...acc.entries()].map(([month, v]) => ({ month, ...v }));
|
|
5809
|
+
},
|
|
5810
|
+
// ── Placar da rede ────────────────────────────────────────────────────
|
|
5811
|
+
async getUnitScorecard() {
|
|
5812
|
+
return [...mockScorecard];
|
|
5813
|
+
},
|
|
5814
|
+
async getScorecardWeights() {
|
|
5815
|
+
return { ...mockScorecardWeights };
|
|
5816
|
+
},
|
|
5817
|
+
async saveScorecardWeights(weights) {
|
|
5818
|
+
Object.assign(mockScorecardWeights, weights);
|
|
5819
|
+
return { ...mockScorecardWeights };
|
|
5820
|
+
},
|
|
5821
|
+
// ── Engajamento ───────────────────────────────────────────────────────
|
|
5822
|
+
async getEngagementSummary() {
|
|
5823
|
+
const rows = mockEngagement();
|
|
5824
|
+
const count = (l) => rows.filter((r) => r.lifecycle === l).length;
|
|
5825
|
+
const returnable = rows.filter((r) => r.visits > 1);
|
|
5826
|
+
return {
|
|
5827
|
+
lead: count("lead"),
|
|
5828
|
+
prospect: count("prospect"),
|
|
5829
|
+
new: count("new"),
|
|
5830
|
+
active: count("active"),
|
|
5831
|
+
at_risk: count("at_risk"),
|
|
5832
|
+
dormant: count("dormant"),
|
|
5833
|
+
people: rows.length,
|
|
5834
|
+
returned: returnable.filter((r) => (r.daysSinceLast ?? 1e9) <= mockEngagementSettings.activeDays).length,
|
|
5835
|
+
returnable: returnable.length,
|
|
5836
|
+
settings: { ...mockEngagementSettings }
|
|
5837
|
+
};
|
|
5838
|
+
},
|
|
5839
|
+
async getPeopleByLifecycle(lifecycle, limit = 100) {
|
|
5840
|
+
return mockEngagement().filter((r) => !lifecycle || r.lifecycle === lifecycle).sort((a, b) => (b.lastAt ?? "").localeCompare(a.lastAt ?? "")).slice(0, limit);
|
|
5841
|
+
},
|
|
5842
|
+
async saveEngagementSettings(input) {
|
|
5843
|
+
if (!(input.newDays > 0 && input.activeDays > input.newDays && input.atRiskDays > input.activeDays)) {
|
|
5844
|
+
throw new Error("Os degraus precisam subir: rec\xE9m-chegado < ativo < em risco.");
|
|
5845
|
+
}
|
|
5846
|
+
Object.assign(mockEngagementSettings, input);
|
|
5847
|
+
return { ...mockEngagementSettings };
|
|
5848
|
+
},
|
|
5849
|
+
// ── Segmentos ─────────────────────────────────────────────────────────
|
|
5850
|
+
async getSegments() {
|
|
5851
|
+
if (mockSegments.length === 0) {
|
|
5852
|
+
for (const seed of MOCK_SEGMENT_SEEDS) {
|
|
5853
|
+
mockSegments.push({ ...seed, id: uid(), tenantId: "mock", createdAt: now(), updatedAt: now() });
|
|
5854
|
+
}
|
|
5855
|
+
}
|
|
5856
|
+
return [...mockSegments].sort((a, b) => a.sortOrder - b.sortOrder || a.name.localeCompare(b.name));
|
|
5857
|
+
},
|
|
5858
|
+
async getSegmentCounts() {
|
|
5859
|
+
const segs = await provider.getSegments();
|
|
5860
|
+
const rows = mockPeopleRows();
|
|
5861
|
+
return segs.filter((s) => s.isActive).map((s) => ({ segmentId: s.id, count: evaluateSegment(s, rows).length }));
|
|
5862
|
+
},
|
|
5863
|
+
async saveSegment(input) {
|
|
5864
|
+
await provider.getSegments();
|
|
5865
|
+
if (input.id) {
|
|
5866
|
+
const found = mockSegments.find((s) => s.id === input.id);
|
|
5867
|
+
if (!found) throw new Error("Segmento n\xE3o encontrado.");
|
|
5868
|
+
Object.assign(found, {
|
|
5869
|
+
name: input.name.trim(),
|
|
5870
|
+
description: input.description?.trim() || void 0,
|
|
5871
|
+
kind: input.kind ?? found.kind,
|
|
5872
|
+
rules: input.rules ?? found.rules,
|
|
5873
|
+
color: input.color ?? found.color,
|
|
5874
|
+
icon: input.icon ?? found.icon,
|
|
5875
|
+
isActive: input.isActive ?? found.isActive,
|
|
5876
|
+
sortOrder: input.sortOrder ?? found.sortOrder,
|
|
5877
|
+
updatedAt: now()
|
|
5878
|
+
});
|
|
5879
|
+
return found;
|
|
5880
|
+
}
|
|
5881
|
+
const created = {
|
|
5882
|
+
id: uid(),
|
|
5883
|
+
key: input.key?.trim() || `seg-${uid()}`,
|
|
5884
|
+
name: input.name.trim(),
|
|
5885
|
+
description: input.description?.trim() || void 0,
|
|
5886
|
+
kind: input.kind ?? "rule",
|
|
5887
|
+
sourceView: "people",
|
|
5888
|
+
rules: input.rules ?? { where: [] },
|
|
5889
|
+
color: input.color,
|
|
5890
|
+
icon: input.icon,
|
|
5891
|
+
isSystem: false,
|
|
5892
|
+
isActive: input.isActive ?? true,
|
|
5893
|
+
sortOrder: input.sortOrder ?? 100,
|
|
5894
|
+
tenantId: "mock",
|
|
5895
|
+
createdAt: now(),
|
|
5896
|
+
updatedAt: now()
|
|
5897
|
+
};
|
|
5898
|
+
mockSegments.push(created);
|
|
5899
|
+
return created;
|
|
5900
|
+
},
|
|
5901
|
+
async deleteSegment(id) {
|
|
5902
|
+
const i = mockSegments.findIndex((s) => s.id === id);
|
|
5903
|
+
if (i >= 0 && mockSegments[i].isSystem) throw new Error("Segmento do sistema n\xE3o pode ser apagado.");
|
|
5904
|
+
if (i >= 0) mockSegments.splice(i, 1);
|
|
5905
|
+
},
|
|
5906
|
+
async resolveSegment(id) {
|
|
5907
|
+
const segs = await provider.getSegments();
|
|
5908
|
+
const seg = segs.find((s) => s.id === id);
|
|
5909
|
+
if (!seg) return [];
|
|
5910
|
+
return evaluateSegment(seg, mockPeopleRows());
|
|
5911
|
+
},
|
|
5011
5912
|
async getSummary() {
|
|
5012
5913
|
const monthStart = today().slice(0, 7) + "-01";
|
|
5013
5914
|
const monthLeads = store.leads.filter((l) => l.createdAt >= monthStart);
|
|
@@ -5061,10 +5962,48 @@ var T = {
|
|
|
5061
5962
|
surveyQuestions: "plg_crm_survey_questions",
|
|
5062
5963
|
surveyResponses: "plg_crm_survey_responses",
|
|
5063
5964
|
surveyAnswers: "plg_crm_survey_answers",
|
|
5064
|
-
surveyStats: "v_crm_survey_stats"
|
|
5965
|
+
surveyStats: "v_crm_survey_stats",
|
|
5966
|
+
segments: "plg_crm_segments",
|
|
5967
|
+
segmentMembers: "plg_crm_segment_members",
|
|
5968
|
+
engagementSettings: "plg_crm_engagement_settings",
|
|
5969
|
+
personEngagement: "v_crm_person_engagement",
|
|
5970
|
+
scorecardWeights: "plg_crm_scorecard_weights",
|
|
5971
|
+
repLeads: "plg_crm_rep_leads"
|
|
5065
5972
|
};
|
|
5066
5973
|
|
|
5067
5974
|
// src/data/supabase.ts
|
|
5975
|
+
function toSegment(row) {
|
|
5976
|
+
let rules = row.rules;
|
|
5977
|
+
if (typeof rules === "string") {
|
|
5978
|
+
try {
|
|
5979
|
+
rules = JSON.parse(rules);
|
|
5980
|
+
} catch {
|
|
5981
|
+
rules = null;
|
|
5982
|
+
}
|
|
5983
|
+
}
|
|
5984
|
+
return {
|
|
5985
|
+
id: row.id,
|
|
5986
|
+
key: row.key,
|
|
5987
|
+
name: row.name,
|
|
5988
|
+
description: row.description ?? void 0,
|
|
5989
|
+
kind: row.kind === "list" ? "list" : "rule",
|
|
5990
|
+
sourceView: row.source_view ?? "people",
|
|
5991
|
+
rules: { where: Array.isArray(rules?.where) ? rules.where : [] },
|
|
5992
|
+
color: row.color ?? void 0,
|
|
5993
|
+
icon: row.icon ?? void 0,
|
|
5994
|
+
isSystem: row.is_system === true,
|
|
5995
|
+
isActive: row.is_active !== false,
|
|
5996
|
+
sortOrder: typeof row.sort_order === "number" ? row.sort_order : 100,
|
|
5997
|
+
unitId: row.unit_id ?? void 0,
|
|
5998
|
+
tenantId: row.tenant_id,
|
|
5999
|
+
createdAt: row.created_at,
|
|
6000
|
+
updatedAt: row.updated_at ?? row.created_at
|
|
6001
|
+
};
|
|
6002
|
+
}
|
|
6003
|
+
function slugifySegmentName(name) {
|
|
6004
|
+
const base = name.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
|
6005
|
+
return base || `segmento-${Date.now().toString(36)}`;
|
|
6006
|
+
}
|
|
5068
6007
|
function getTenantId() {
|
|
5069
6008
|
return getActiveTenantId();
|
|
5070
6009
|
}
|
|
@@ -5447,9 +6386,11 @@ function createSupabaseCrmProvider(options) {
|
|
|
5447
6386
|
id: stageRow.id,
|
|
5448
6387
|
pipelineId: stageRow.pipeline_id,
|
|
5449
6388
|
name: stageRow.name,
|
|
6389
|
+
code: stageRow.code,
|
|
5450
6390
|
order: stageRow.order,
|
|
5451
6391
|
color: stageRow.color,
|
|
5452
6392
|
probability: stageRow.probability,
|
|
6393
|
+
isInitial: stageRow.is_initial === true,
|
|
5453
6394
|
isWon: stageRow.is_won,
|
|
5454
6395
|
isLost: stageRow.is_lost,
|
|
5455
6396
|
tenantId: stageRow.tenant_id,
|
|
@@ -6065,24 +7006,320 @@ function createSupabaseCrmProvider(options) {
|
|
|
6065
7006
|
if (aErr) throw new Error(aErr.message);
|
|
6066
7007
|
}
|
|
6067
7008
|
},
|
|
6068
|
-
|
|
6069
|
-
|
|
6070
|
-
const
|
|
6071
|
-
const
|
|
6072
|
-
|
|
6073
|
-
|
|
6074
|
-
|
|
6075
|
-
|
|
6076
|
-
const
|
|
6077
|
-
|
|
6078
|
-
|
|
6079
|
-
|
|
6080
|
-
|
|
6081
|
-
|
|
6082
|
-
|
|
6083
|
-
|
|
6084
|
-
|
|
6085
|
-
|
|
7009
|
+
// ── Desenhar o funil ──────────────────────────────────────────────────
|
|
7010
|
+
async savePipeline(input) {
|
|
7011
|
+
const { pub } = getClients();
|
|
7012
|
+
const tenantId = getTenantId();
|
|
7013
|
+
if (!tenantId) throw new Error("Sem tenant ativo.");
|
|
7014
|
+
if (input.isDefault) {
|
|
7015
|
+
await pub.from(T.pipelines).update({ is_default: false }).eq("tenant_id", tenantId).neq("id", input.id ?? "00000000-0000-0000-0000-000000000000");
|
|
7016
|
+
}
|
|
7017
|
+
const row = { tenant_id: tenantId, name: input.name.trim() };
|
|
7018
|
+
if (input.isDefault !== void 0) row.is_default = input.isDefault;
|
|
7019
|
+
if (input.isActive !== void 0) row.is_active = input.isActive;
|
|
7020
|
+
if (input.id) {
|
|
7021
|
+
const { data: data2, error: error2 } = await pub.from(T.pipelines).update(row).eq("id", input.id).select("*").single();
|
|
7022
|
+
if (error2) throw new Error(error2.message);
|
|
7023
|
+
return snakeToCamel(data2);
|
|
7024
|
+
}
|
|
7025
|
+
const { data, error } = await pub.from(T.pipelines).insert(row).select("*").single();
|
|
7026
|
+
if (error) throw new Error(error.message);
|
|
7027
|
+
const created = snakeToCamel(data);
|
|
7028
|
+
await pub.from(T.pipelineStages).insert([
|
|
7029
|
+
{ tenant_id: tenantId, pipeline_id: created.id, name: "Novo", order: 1, color: "#64748b", probability: 10, is_initial: true },
|
|
7030
|
+
{ tenant_id: tenantId, pipeline_id: created.id, name: "Ganho", order: 2, color: "#10b981", probability: 100, is_won: true },
|
|
7031
|
+
{ tenant_id: tenantId, pipeline_id: created.id, name: "Perdido", order: 3, color: "#ef4444", probability: 0, is_lost: true }
|
|
7032
|
+
]);
|
|
7033
|
+
return created;
|
|
7034
|
+
},
|
|
7035
|
+
async deletePipeline(id) {
|
|
7036
|
+
const { pub } = getClients();
|
|
7037
|
+
const tenantId = getTenantId();
|
|
7038
|
+
const { count } = await pub.from(T.pipelines).select("id", { count: "exact", head: true }).eq("tenant_id", tenantId).eq("is_active", true);
|
|
7039
|
+
if ((count ?? 0) <= 1) throw new Error("Este \xE9 o \xFAnico funil da casa \u2014 um CRM sem funil n\xE3o tem onde p\xF4r neg\xF3cio.");
|
|
7040
|
+
const { error } = await pub.from(T.pipelines).update({ is_active: false }).eq("id", id);
|
|
7041
|
+
if (error) throw new Error(error.message);
|
|
7042
|
+
},
|
|
7043
|
+
async saveStage(input) {
|
|
7044
|
+
const { pub } = getClients();
|
|
7045
|
+
const tenantId = getTenantId();
|
|
7046
|
+
if (!tenantId) throw new Error("Sem tenant ativo.");
|
|
7047
|
+
if (input.isInitial) {
|
|
7048
|
+
await pub.from(T.pipelineStages).update({ is_initial: false }).eq("pipeline_id", input.pipelineId).neq("id", input.id ?? "00000000-0000-0000-0000-000000000000");
|
|
7049
|
+
}
|
|
7050
|
+
const row = {
|
|
7051
|
+
tenant_id: tenantId,
|
|
7052
|
+
pipeline_id: input.pipelineId,
|
|
7053
|
+
name: input.name.trim()
|
|
7054
|
+
};
|
|
7055
|
+
if (input.color !== void 0) row.color = input.color;
|
|
7056
|
+
if (input.probability !== void 0) row.probability = input.probability;
|
|
7057
|
+
if (input.isInitial !== void 0) row.is_initial = input.isInitial;
|
|
7058
|
+
if (input.isWon !== void 0) row.is_won = input.isWon;
|
|
7059
|
+
if (input.isLost !== void 0) row.is_lost = input.isLost;
|
|
7060
|
+
if (input.order !== void 0) row.order = input.order;
|
|
7061
|
+
if (input.id) {
|
|
7062
|
+
const { data: data2, error: error2 } = await pub.from(T.pipelineStages).update(row).eq("id", input.id).select("*").single();
|
|
7063
|
+
if (error2) throw new Error(error2.message);
|
|
7064
|
+
return snakeToCamel(data2);
|
|
7065
|
+
}
|
|
7066
|
+
if (input.code) row.code = input.code;
|
|
7067
|
+
if (row.order === void 0) {
|
|
7068
|
+
const { data: last } = await pub.from(T.pipelineStages).select("order").eq("pipeline_id", input.pipelineId).order("order", { ascending: false }).limit(1);
|
|
7069
|
+
row.order = ((last ?? [])[0]?.order ?? 0) + 1;
|
|
7070
|
+
}
|
|
7071
|
+
const { data, error } = await pub.from(T.pipelineStages).insert(row).select("*").single();
|
|
7072
|
+
if (error) throw new Error(error.message);
|
|
7073
|
+
return snakeToCamel(data);
|
|
7074
|
+
},
|
|
7075
|
+
async deleteStage(id) {
|
|
7076
|
+
const { pub } = getClients();
|
|
7077
|
+
const { count } = await pub.from("orders").select("id", { count: "exact", head: true }).eq("stage_id", id);
|
|
7078
|
+
if ((count ?? 0) > 0) {
|
|
7079
|
+
throw new Error(`Esta etapa tem ${count} neg\xF3cio(s). Mova-os antes de exclu\xED-la.`);
|
|
7080
|
+
}
|
|
7081
|
+
const { error } = await pub.from(T.pipelineStages).delete().eq("id", id);
|
|
7082
|
+
if (error) throw new Error(error.message);
|
|
7083
|
+
},
|
|
7084
|
+
async reorderStages(pipelineId, orderedIds) {
|
|
7085
|
+
const { pub } = getClients();
|
|
7086
|
+
for (const [i, id] of orderedIds.entries()) {
|
|
7087
|
+
await pub.from(T.pipelineStages).update({ order: -(i + 1) }).eq("id", id).eq("pipeline_id", pipelineId);
|
|
7088
|
+
}
|
|
7089
|
+
for (const [i, id] of orderedIds.entries()) {
|
|
7090
|
+
await pub.from(T.pipelineStages).update({ order: i + 1 }).eq("id", id).eq("pipeline_id", pipelineId);
|
|
7091
|
+
}
|
|
7092
|
+
},
|
|
7093
|
+
// ── Painel ────────────────────────────────────────────────────────────
|
|
7094
|
+
//
|
|
7095
|
+
// As duas leituras abaixo saem de `plg_crm_rep_leads`, que já existia com
|
|
7096
|
+
// `source_name`, `leads` e `is_converted` — e que NINGUÉM lia. É o mesmo
|
|
7097
|
+
// padrão que este porte encontrou nas Origens e no motor de notificações:
|
|
7098
|
+
// o read model pronto e sem consumidor.
|
|
7099
|
+
async getSourceConversion(days = 90) {
|
|
7100
|
+
const { pub } = getClients();
|
|
7101
|
+
const tenantId = getTenantId();
|
|
7102
|
+
if (!tenantId) return [];
|
|
7103
|
+
const since = new Date(Date.now() - days * 864e5).toISOString();
|
|
7104
|
+
const { data } = await pub.from(T.repLeads).select("source_name,is_converted").eq("tenant_id", tenantId).gte("created_at", since);
|
|
7105
|
+
const acc = /* @__PURE__ */ new Map();
|
|
7106
|
+
for (const r of data ?? []) {
|
|
7107
|
+
const key = r.source_name || "Sem origem";
|
|
7108
|
+
const cur = acc.get(key) ?? { leads: 0, converted: 0 };
|
|
7109
|
+
cur.leads += 1;
|
|
7110
|
+
cur.converted += Number(r.is_converted ?? 0);
|
|
7111
|
+
acc.set(key, cur);
|
|
7112
|
+
}
|
|
7113
|
+
return [...acc.entries()].map(([sourceName, v]) => ({
|
|
7114
|
+
sourceName,
|
|
7115
|
+
leads: v.leads,
|
|
7116
|
+
converted: v.converted,
|
|
7117
|
+
rate: v.leads > 0 ? Math.round(v.converted / v.leads * 1e3) / 10 : null
|
|
7118
|
+
})).sort((a, b) => b.leads - a.leads);
|
|
7119
|
+
},
|
|
7120
|
+
async getMonthlySeries(months = 6) {
|
|
7121
|
+
const { pub } = getClients();
|
|
7122
|
+
const tenantId = getTenantId();
|
|
7123
|
+
if (!tenantId) return [];
|
|
7124
|
+
const start = /* @__PURE__ */ new Date();
|
|
7125
|
+
start.setUTCDate(1);
|
|
7126
|
+
start.setUTCHours(0, 0, 0, 0);
|
|
7127
|
+
start.setUTCMonth(start.getUTCMonth() - (months - 1));
|
|
7128
|
+
const { data } = await pub.from(T.repLeads).select("created_at,is_converted").eq("tenant_id", tenantId).gte("created_at", start.toISOString());
|
|
7129
|
+
const acc = /* @__PURE__ */ new Map();
|
|
7130
|
+
for (let i = 0; i < months; i++) {
|
|
7131
|
+
const d = new Date(start);
|
|
7132
|
+
d.setUTCMonth(start.getUTCMonth() + i);
|
|
7133
|
+
acc.set(d.toISOString().slice(0, 7), { leads: 0, converted: 0 });
|
|
7134
|
+
}
|
|
7135
|
+
for (const r of data ?? []) {
|
|
7136
|
+
const key = String(r.created_at).slice(0, 7);
|
|
7137
|
+
const cur = acc.get(key);
|
|
7138
|
+
if (!cur) continue;
|
|
7139
|
+
cur.leads += 1;
|
|
7140
|
+
cur.converted += Number(r.is_converted ?? 0);
|
|
7141
|
+
}
|
|
7142
|
+
return [...acc.entries()].map(([month, v]) => ({ month, ...v }));
|
|
7143
|
+
},
|
|
7144
|
+
// ── Placar da rede ────────────────────────────────────────────────────
|
|
7145
|
+
async getUnitScorecard(from, to) {
|
|
7146
|
+
const { pub } = getClients();
|
|
7147
|
+
const { data, error } = await pub.rpc("crm_unit_scorecard", { p_from: from, p_to: to });
|
|
7148
|
+
if (error) throw new Error(error.message);
|
|
7149
|
+
return (data ?? []).map((r) => ({
|
|
7150
|
+
unitId: r.unit_id,
|
|
7151
|
+
unitName: r.unit_name,
|
|
7152
|
+
ordersCount: Number(r.orders_count ?? 0),
|
|
7153
|
+
revenue: Number(r.revenue ?? 0),
|
|
7154
|
+
peopleCount: Number(r.people_count ?? 0),
|
|
7155
|
+
// `== null` de propósito, e não `?? 0`: a diferença entre "não há fonte"
|
|
7156
|
+
// e "mediu zero" é a coisa toda deste placar.
|
|
7157
|
+
conversion: r.conversion == null ? null : Number(r.conversion),
|
|
7158
|
+
retention: r.retention == null ? null : Number(r.retention),
|
|
7159
|
+
reactivation: r.reactivation == null ? null : Number(r.reactivation),
|
|
7160
|
+
productivity: r.productivity == null ? null : Number(r.productivity),
|
|
7161
|
+
satisfaction: r.satisfaction == null ? null : Number(r.satisfaction)
|
|
7162
|
+
}));
|
|
7163
|
+
},
|
|
7164
|
+
async getScorecardWeights() {
|
|
7165
|
+
const { pub } = getClients();
|
|
7166
|
+
const tenantId = getTenantId();
|
|
7167
|
+
if (!tenantId) return {};
|
|
7168
|
+
const { data } = await pub.from(T.scorecardWeights).select("*").eq("tenant_id", tenantId);
|
|
7169
|
+
const out = {};
|
|
7170
|
+
for (const r of data ?? []) out[r.dimension] = Number(r.weight);
|
|
7171
|
+
return out;
|
|
7172
|
+
},
|
|
7173
|
+
async saveScorecardWeights(weights) {
|
|
7174
|
+
const { pub } = getClients();
|
|
7175
|
+
const tenantId = getTenantId();
|
|
7176
|
+
if (!tenantId) throw new Error("Sem tenant ativo.");
|
|
7177
|
+
const rows = Object.entries(weights).map(([dimension, weight]) => ({
|
|
7178
|
+
tenant_id: tenantId,
|
|
7179
|
+
dimension,
|
|
7180
|
+
weight,
|
|
7181
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
7182
|
+
}));
|
|
7183
|
+
if (rows.length === 0) return weights;
|
|
7184
|
+
const { error } = await pub.from(T.scorecardWeights).upsert(rows, { onConflict: "tenant_id,dimension" });
|
|
7185
|
+
if (error) throw new Error(error.message);
|
|
7186
|
+
return weights;
|
|
7187
|
+
},
|
|
7188
|
+
// ── Engajamento ───────────────────────────────────────────────────────
|
|
7189
|
+
async getEngagementSummary() {
|
|
7190
|
+
const { pub } = getClients();
|
|
7191
|
+
const { data, error } = await pub.rpc("crm_engagement_summary");
|
|
7192
|
+
if (error) throw new Error(error.message);
|
|
7193
|
+
const d = data ?? {};
|
|
7194
|
+
return {
|
|
7195
|
+
lead: Number(d.lead ?? 0),
|
|
7196
|
+
prospect: Number(d.prospect ?? 0),
|
|
7197
|
+
new: Number(d.new ?? 0),
|
|
7198
|
+
active: Number(d.active ?? 0),
|
|
7199
|
+
at_risk: Number(d.at_risk ?? 0),
|
|
7200
|
+
dormant: Number(d.dormant ?? 0),
|
|
7201
|
+
people: Number(d.people ?? 0),
|
|
7202
|
+
returned: Number(d.returned ?? 0),
|
|
7203
|
+
returnable: Number(d.returnable ?? 0),
|
|
7204
|
+
settings: {
|
|
7205
|
+
newDays: Number(d.settings?.newDays ?? 30),
|
|
7206
|
+
activeDays: Number(d.settings?.activeDays ?? 90),
|
|
7207
|
+
atRiskDays: Number(d.settings?.atRiskDays ?? 180)
|
|
7208
|
+
}
|
|
7209
|
+
};
|
|
7210
|
+
},
|
|
7211
|
+
async getPeopleByLifecycle(lifecycle, limit = 100) {
|
|
7212
|
+
const { pub } = getClients();
|
|
7213
|
+
const tenantId = getTenantId();
|
|
7214
|
+
if (!tenantId) return [];
|
|
7215
|
+
let qb = pub.from(T.personEngagement).select("*").eq("tenant_id", tenantId);
|
|
7216
|
+
if (lifecycle) qb = qb.eq("lifecycle", lifecycle);
|
|
7217
|
+
const { data } = await qb.order("last_at", { ascending: false, nullsFirst: false }).limit(limit);
|
|
7218
|
+
return (data ?? []).map((r) => ({
|
|
7219
|
+
personId: r.person_id,
|
|
7220
|
+
name: r.name,
|
|
7221
|
+
kind: r.kind,
|
|
7222
|
+
unitId: r.unit_id ?? void 0,
|
|
7223
|
+
firstAt: r.first_at ?? void 0,
|
|
7224
|
+
lastAt: r.last_at ?? void 0,
|
|
7225
|
+
visits: Number(r.visits ?? 0),
|
|
7226
|
+
totalValue: Number(r.total_value ?? 0),
|
|
7227
|
+
avgValue: r.avg_value == null ? void 0 : Number(r.avg_value),
|
|
7228
|
+
daysSinceLast: r.days_since_last == null ? void 0 : Number(r.days_since_last),
|
|
7229
|
+
lifecycle: r.lifecycle
|
|
7230
|
+
}));
|
|
7231
|
+
},
|
|
7232
|
+
async saveEngagementSettings(input) {
|
|
7233
|
+
const { pub } = getClients();
|
|
7234
|
+
const tenantId = getTenantId();
|
|
7235
|
+
if (!tenantId) throw new Error("Sem tenant ativo.");
|
|
7236
|
+
const { error } = await pub.from(T.engagementSettings).upsert({
|
|
7237
|
+
tenant_id: tenantId,
|
|
7238
|
+
new_days: input.newDays,
|
|
7239
|
+
active_days: input.activeDays,
|
|
7240
|
+
at_risk_days: input.atRiskDays,
|
|
7241
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
7242
|
+
}, { onConflict: "tenant_id" });
|
|
7243
|
+
if (error) {
|
|
7244
|
+
throw new Error(/plg_crm_engagement_settings_ladder/.test(error.message) ? "Os degraus precisam subir: rec\xE9m-chegado < ativo < em risco." : error.message);
|
|
7245
|
+
}
|
|
7246
|
+
return input;
|
|
7247
|
+
},
|
|
7248
|
+
// ── Segmentos ─────────────────────────────────────────────────────────
|
|
7249
|
+
async getSegments() {
|
|
7250
|
+
const { pub } = getClients();
|
|
7251
|
+
const tenantId = getTenantId();
|
|
7252
|
+
if (!tenantId) return [];
|
|
7253
|
+
const { data } = await pub.from(T.segments).select("*").eq("tenant_id", tenantId).order("sort_order").order("name");
|
|
7254
|
+
return (data ?? []).map(toSegment);
|
|
7255
|
+
},
|
|
7256
|
+
async getSegmentCounts() {
|
|
7257
|
+
const { pub } = getClients();
|
|
7258
|
+
const { data, error } = await pub.rpc("crm_segment_counts");
|
|
7259
|
+
if (error) throw new Error(error.message);
|
|
7260
|
+
return (data ?? []).map((r) => ({
|
|
7261
|
+
segmentId: r.segment_id,
|
|
7262
|
+
// `member_count` volta NULO quando a regra daquele segmento quebrou.
|
|
7263
|
+
// Number(null) é 0, e mostrar 0 onde a resposta é "não sei" seria a
|
|
7264
|
+
// pior leitura possível — o chip diria "vazio" para um recorte cheio.
|
|
7265
|
+
count: r.member_count == null ? null : Number(r.member_count)
|
|
7266
|
+
}));
|
|
7267
|
+
},
|
|
7268
|
+
async saveSegment(input) {
|
|
7269
|
+
const { pub } = getClients();
|
|
7270
|
+
const tenantId = getTenantId();
|
|
7271
|
+
if (!tenantId) throw new Error("Sem tenant ativo.");
|
|
7272
|
+
const row = {
|
|
7273
|
+
tenant_id: tenantId,
|
|
7274
|
+
name: input.name.trim(),
|
|
7275
|
+
description: input.description?.trim() || null,
|
|
7276
|
+
kind: input.kind ?? "rule",
|
|
7277
|
+
rules: input.rules ?? { where: [] },
|
|
7278
|
+
color: input.color ?? null,
|
|
7279
|
+
icon: input.icon ?? null,
|
|
7280
|
+
unit_id: input.unitId ?? null
|
|
7281
|
+
};
|
|
7282
|
+
if (input.isActive !== void 0) row.is_active = input.isActive;
|
|
7283
|
+
if (input.sortOrder !== void 0) row.sort_order = input.sortOrder;
|
|
7284
|
+
if (input.id) {
|
|
7285
|
+
const { data: data2, error: error2 } = await pub.from(T.segments).update(row).eq("id", input.id).select("*").single();
|
|
7286
|
+
if (error2) throw new Error(error2.message);
|
|
7287
|
+
return toSegment(data2);
|
|
7288
|
+
}
|
|
7289
|
+
row.key = input.key?.trim() || slugifySegmentName(input.name);
|
|
7290
|
+
const { data, error } = await pub.from(T.segments).insert(row).select("*").single();
|
|
7291
|
+
if (error) throw new Error(error.message);
|
|
7292
|
+
return toSegment(data);
|
|
7293
|
+
},
|
|
7294
|
+
async deleteSegment(id) {
|
|
7295
|
+
const { pub } = getClients();
|
|
7296
|
+
const { error } = await pub.from(T.segments).delete().eq("id", id);
|
|
7297
|
+
if (error) throw new Error(error.message);
|
|
7298
|
+
},
|
|
7299
|
+
async resolveSegment(id) {
|
|
7300
|
+
const { pub } = getClients();
|
|
7301
|
+
const { data, error } = await pub.rpc("crm_resolve_segment", { p_segment_id: id });
|
|
7302
|
+
if (error) throw new Error(error.message);
|
|
7303
|
+
return (data ?? []).map((r) => typeof r === "string" ? r : r.person_id);
|
|
7304
|
+
},
|
|
7305
|
+
async getSummary() {
|
|
7306
|
+
const { core, pub } = getClients();
|
|
7307
|
+
const monthStart = (/* @__PURE__ */ new Date()).toISOString().slice(0, 7) + "-01";
|
|
7308
|
+
const today2 = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
|
|
7309
|
+
const { count: totalLeads } = await core.from("people").select("*", { count: "exact", head: true }).eq("kind", "lead");
|
|
7310
|
+
const { count: newLeads } = await core.from("people").select("*", { count: "exact", head: true }).eq("kind", "lead").gte("created_at", monthStart);
|
|
7311
|
+
const { data: deals } = await core.from("orders").select("status, total, updated_at").eq("kind", "deal");
|
|
7312
|
+
const allDeals = deals ?? [];
|
|
7313
|
+
const openDeals = allDeals.filter((d) => d.status === "open");
|
|
7314
|
+
const wonDeals = allDeals.filter((d) => d.status === "won");
|
|
7315
|
+
const wonThisMonth = wonDeals.filter((d) => d.updated_at >= monthStart);
|
|
7316
|
+
const convertedLeads = allDeals.length;
|
|
7317
|
+
const { count: pendingActs } = await pub.from(T.activities).select("*", { count: "exact", head: true }).is("completed_at", null);
|
|
7318
|
+
const { count: overdueActs } = await pub.from(T.activities).select("*", { count: "exact", head: true }).is("completed_at", null).lt("due_date", today2);
|
|
7319
|
+
return {
|
|
7320
|
+
totalLeads: totalLeads ?? 0,
|
|
7321
|
+
newLeadsThisMonth: newLeads ?? 0,
|
|
7322
|
+
totalDeals: allDeals.length,
|
|
6086
7323
|
openDealsValue: openDeals.reduce((s, d) => s + (d.total ?? 0), 0),
|
|
6087
7324
|
wonDealsThisMonth: wonThisMonth.length,
|
|
6088
7325
|
wonDealsValueThisMonth: wonThisMonth.reduce((s, d) => s + (d.total ?? 0), 0),
|
|
@@ -6110,6 +7347,9 @@ function createSupabaseCrmProvider(options) {
|
|
|
6110
7347
|
};
|
|
6111
7348
|
return provider;
|
|
6112
7349
|
}
|
|
7350
|
+
function entryStage(stages) {
|
|
7351
|
+
return stages.find((s) => s.isInitial) ?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0];
|
|
7352
|
+
}
|
|
6113
7353
|
function createCrmStore(provider) {
|
|
6114
7354
|
let lastActivitiesQuery = {};
|
|
6115
7355
|
let lastLeadsQuery = {};
|
|
@@ -6246,9 +7486,8 @@ function createCrmStore(provider) {
|
|
|
6246
7486
|
try {
|
|
6247
7487
|
const lead = await provider.createLead(input);
|
|
6248
7488
|
const { pipeline: pipeline2, stages: entryStages } = await get().resolveEntryPipeline();
|
|
6249
|
-
const open = entryStages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order);
|
|
6250
7489
|
const chosen = input.stageId ? entryStages.find((s) => s.id === input.stageId) : void 0;
|
|
6251
|
-
const stage = chosen ??
|
|
7490
|
+
const stage = chosen ?? entryStage(entryStages);
|
|
6252
7491
|
if (pipeline2 && stage) {
|
|
6253
7492
|
try {
|
|
6254
7493
|
await provider.createDeal({
|
|
@@ -6335,7 +7574,7 @@ function createCrmStore(provider) {
|
|
|
6335
7574
|
if (existingDeal) {
|
|
6336
7575
|
dealId = existingDeal.id;
|
|
6337
7576
|
} else if (defaultPipeline) {
|
|
6338
|
-
const firstStage = stages
|
|
7577
|
+
const firstStage = entryStage(stages);
|
|
6339
7578
|
if (firstStage) {
|
|
6340
7579
|
const deal = await provider.createDeal({
|
|
6341
7580
|
leadId,
|
|
@@ -6358,7 +7597,7 @@ function createCrmStore(provider) {
|
|
|
6358
7597
|
const deal = await provider.getDealById(dealId);
|
|
6359
7598
|
if (deal && deal.status === "open") {
|
|
6360
7599
|
const currentStage = stages.find((s) => s.id === deal.stageId);
|
|
6361
|
-
const proposalStage = stages.find((s) => s.name === "Proposal") ?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0];
|
|
7600
|
+
const proposalStage = stages.find((s) => s.code === "proposal") ?? stages.find((s) => s.name === "Proposal") ?? stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => b.order - a.order)[0];
|
|
6362
7601
|
if (proposalStage && currentStage && proposalStage.order > currentStage.order) {
|
|
6363
7602
|
await provider.moveDealToStage(dealId, proposalStage.id);
|
|
6364
7603
|
}
|
|
@@ -6856,11 +8095,11 @@ var partnerEntity = {
|
|
|
6856
8095
|
// escondido, e sem isto a coluna NOT NULL recebe null e o save volta 400.
|
|
6857
8096
|
defaultValue: [],
|
|
6858
8097
|
visibleWhen: (values) => values.allUnits === false,
|
|
6859
|
-
renderInput: ({ value, onChange }) =>
|
|
8098
|
+
renderInput: ({ value, onChange }) => React20.createElement(PartnerUnitsInput, {
|
|
6860
8099
|
value,
|
|
6861
8100
|
onChange
|
|
6862
8101
|
}),
|
|
6863
|
-
renderCell: (value) =>
|
|
8102
|
+
renderCell: (value) => React20.createElement(PartnerUnitsCell, { value })
|
|
6864
8103
|
},
|
|
6865
8104
|
{
|
|
6866
8105
|
key: "allowsOnlineBooking",
|
|
@@ -6869,7 +8108,7 @@ var partnerEntity = {
|
|
|
6869
8108
|
showInTable: true,
|
|
6870
8109
|
defaultValue: false,
|
|
6871
8110
|
hint: "Members can book on their own from the public page.",
|
|
6872
|
-
renderCell: (value) =>
|
|
8111
|
+
renderCell: (value) => React20.createElement(PartnerOnlineBookingCell, { value })
|
|
6873
8112
|
},
|
|
6874
8113
|
{ key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true, inlineToggle: true }
|
|
6875
8114
|
],
|
|
@@ -6912,8 +8151,18 @@ var pipelineStageEntity = {
|
|
|
6912
8151
|
{ key: "order", label: "Order", type: "number", required: true, showInTable: true, defaultValue: 0 },
|
|
6913
8152
|
{ key: "color", label: "Color", type: "color", showInTable: true, defaultValue: "#6366f1" },
|
|
6914
8153
|
{ key: "probability", label: "Probability %", type: "number", min: 0, max: 100, showInTable: true, defaultValue: 0 },
|
|
8154
|
+
// O terceiro papel especial, que o V1 tem desde sempre e o V2 não tinha:
|
|
8155
|
+
// ONDE O LEAD ENTRA. Antes era inferido no cliente pela menor ordem entre
|
|
8156
|
+
// as não-terminais — acerta quase sempre e erra em silêncio quando alguém
|
|
8157
|
+
// reordena o funil. O índice único da 005 garante uma por funil.
|
|
8158
|
+
{ key: "isInitial", label: "Entry Stage", type: "boolean", showInTable: true, defaultValue: false },
|
|
6915
8159
|
{ key: "isWon", label: "Won Stage", type: "boolean", showInTable: true, defaultValue: false },
|
|
6916
|
-
{ key: "isLost", label: "Lost Stage", type: "boolean", showInTable: true, defaultValue: false }
|
|
8160
|
+
{ key: "isLost", label: "Lost Stage", type: "boolean", showInTable: true, defaultValue: false },
|
|
8161
|
+
// O código fica FORA do formulário: é a identidade estável por onde uma
|
|
8162
|
+
// automação aponta para a etapa, e deixá-lo editável ofereceria justamente
|
|
8163
|
+
// quebrar o que ele protege. O banco o deriva do nome quando a etapa nasce
|
|
8164
|
+
// (gatilho da 005) e nunca mais o toca.
|
|
8165
|
+
{ key: "code", label: "Code", type: "text", showInForm: false }
|
|
6917
8166
|
],
|
|
6918
8167
|
data: { table: T.pipelineStages, tenantScoped: true }
|
|
6919
8168
|
};
|
|
@@ -6946,7 +8195,7 @@ var crmRegistries = [
|
|
|
6946
8195
|
description: "Pipeline stages used by CRM deals",
|
|
6947
8196
|
display: "table",
|
|
6948
8197
|
seedData: [
|
|
6949
|
-
{ id: "stage-new", pipelineId: "pipe-default", name: "New Lead", order: 1, color: "#64748b", probability: 10, isWon: false, isLost: false },
|
|
8198
|
+
{ id: "stage-new", pipelineId: "pipe-default", name: "New Lead", order: 1, color: "#64748b", probability: 10, isInitial: true, isWon: false, isLost: false },
|
|
6950
8199
|
{ id: "stage-qualified", pipelineId: "pipe-default", name: "Qualified", order: 2, color: "#3b82f6", probability: 30, isWon: false, isLost: false },
|
|
6951
8200
|
{ id: "stage-proposal", pipelineId: "pipe-default", name: "Proposal", order: 3, color: "#8b5cf6", probability: 60, isWon: false, isLost: false },
|
|
6952
8201
|
{ id: "stage-negotiation", pipelineId: "pipe-default", name: "Negotiation", order: 4, color: "#f59e0b", probability: 80, isWon: false, isLost: false },
|
|
@@ -9443,6 +10692,46 @@ var MIGRATION_003_O_CLIENTE_RESPONDE_NO_PROPRIO_TELEFONE = `-- 003_o_cliente_res
|
|
|
9443
10692
|
-- insuficiente para algu\xE9m varrer a base de clientes com tokens adivinhados.
|
|
9444
10693
|
-- Um token errado responde exatamente como um token expirado: \`not_found\`.
|
|
9445
10694
|
|
|
10695
|
+
-- \u2500\u2500 um token aleat\xF3rio que funciona nos dois lugares \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
10696
|
+
--
|
|
10697
|
+
-- CORRIGIDO DEPOIS DE APLICADA. A vers\xE3o original chamava \`gen_random_bytes\`
|
|
10698
|
+
-- sem qualificar, dentro de uma fun\xE7\xE3o com \`SET search_path TO ''\`. Isso NUNCA
|
|
10699
|
+
-- resolveria: o pgcrypto do Supabase vive no esquema \`extensions\`, e com o
|
|
10700
|
+
-- search_path vazio nada \xE9 encontrado sem nome completo. O DDL passou porque
|
|
10701
|
+
-- \`check_function_bodies = false\` n\xE3o compila o corpo \u2014 o erro s\xF3 apareceria na
|
|
10702
|
+
-- primeira vez que algu\xE9m gerasse um link de pesquisa, meses depois, como
|
|
10703
|
+
-- "42883: function gen_random_bytes does not exist".
|
|
10704
|
+
--
|
|
10705
|
+
-- \xC9 por isso que o auxiliar existe em vez de um \`extensions.\` cravado: num
|
|
10706
|
+
-- Postgres nu (o que a su\xEDte da corrente usa) o pgcrypto fica em \`public\`, e
|
|
10707
|
+
-- um nome fixo trocaria um ambiente quebrado pelo outro.
|
|
10708
|
+
CREATE OR REPLACE FUNCTION public.crm_url_token(p_bytes integer DEFAULT 18)
|
|
10709
|
+
RETURNS text
|
|
10710
|
+
LANGUAGE plpgsql
|
|
10711
|
+
SECURITY DEFINER
|
|
10712
|
+
SET search_path TO ''
|
|
10713
|
+
AS $$
|
|
10714
|
+
DECLARE v bytea;
|
|
10715
|
+
BEGIN
|
|
10716
|
+
IF to_regprocedure('extensions.gen_random_bytes(integer)') IS NOT NULL THEN
|
|
10717
|
+
EXECUTE 'SELECT extensions.gen_random_bytes($1)' INTO v USING p_bytes;
|
|
10718
|
+
ELSIF to_regprocedure('public.gen_random_bytes(integer)') IS NOT NULL THEN
|
|
10719
|
+
EXECUTE 'SELECT public.gen_random_bytes($1)' INTO v USING p_bytes;
|
|
10720
|
+
ELSE
|
|
10721
|
+
RAISE EXCEPTION 'crm_url_token: pgcrypto n\xE3o est\xE1 instalado' USING ERRCODE = '42883';
|
|
10722
|
+
END IF;
|
|
10723
|
+
-- base64url: o token vive dentro de uma URL, e \`+\` e \`/\` do base64 comum
|
|
10724
|
+
-- viram outra coisa no caminho.
|
|
10725
|
+
RETURN translate(encode(v, 'base64'), '+/=', '-_');
|
|
10726
|
+
END $$;
|
|
10727
|
+
|
|
10728
|
+
COMMENT ON FUNCTION public.crm_url_token(integer) IS
|
|
10729
|
+
'Token aleat\xF3rio para URL. Resolve o pgcrypto em tempo de execu\xE7\xE3o porque ele mora em \`extensions\` no Supabase e em \`public\` num Postgres nu (003).';
|
|
10730
|
+
|
|
10731
|
+
REVOKE ALL ON FUNCTION public.crm_url_token(integer) FROM PUBLIC, anon;
|
|
10732
|
+
GRANT EXECUTE ON FUNCTION public.crm_url_token(integer) TO authenticated;
|
|
10733
|
+
GRANT EXECUTE ON FUNCTION public.crm_url_token(integer) TO service_role;
|
|
10734
|
+
|
|
9446
10735
|
-- \u2500\u2500 o convite \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
9447
10736
|
CREATE TABLE IF NOT EXISTS public.plg_crm_survey_invites (
|
|
9448
10737
|
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
@@ -9587,8 +10876,7 @@ BEGIN
|
|
|
9587
10876
|
RAISE EXCEPTION 'crm_survey_invite_create: pesquisa n\xE3o encontrada' USING ERRCODE = 'P0002';
|
|
9588
10877
|
END IF;
|
|
9589
10878
|
|
|
9590
|
-
|
|
9591
|
-
v_token := translate(encode(gen_random_bytes(18), 'base64'), '+/=', '-_');
|
|
10879
|
+
v_token := public.crm_url_token(18);
|
|
9592
10880
|
|
|
9593
10881
|
INSERT INTO public.plg_crm_survey_invites
|
|
9594
10882
|
(tenant_id, survey_id, token, person_id, order_id, unit_id, single_use, expires_at, created_by)
|
|
@@ -9760,125 +11048,1315 @@ GRANT EXECUTE ON FUNCTION public.crm_survey_invite_submit(text, jsonb, text) TO
|
|
|
9760
11048
|
GRANT EXECUTE ON FUNCTION public.crm_survey_invite_submit(text, jsonb, text) TO authenticated;
|
|
9761
11049
|
GRANT EXECUTE ON FUNCTION public.crm_survey_invite_submit(text, jsonb, text) TO service_role;
|
|
9762
11050
|
`;
|
|
9763
|
-
var
|
|
9764
|
-
|
|
9765
|
-
|
|
9766
|
-
|
|
9767
|
-
|
|
9768
|
-
|
|
11051
|
+
var MIGRATION_004_UM_RECORTE_DE_GENTE_QUE_TEM_NOME = `-- 004_um_recorte_de_gente_que_tem_nome.sql
|
|
11052
|
+
--
|
|
11053
|
+
-- O V1 tem quatro itens de menu \u2014 Potenciais, Ativos, Inativos, VIP \u2014 que s\xE3o
|
|
11054
|
+
-- a MESMA tela de clientes com um filtro diferente na URL. O recorte n\xE3o tem
|
|
11055
|
+
-- nome, n\xE3o tem dono, n\xE3o \xE9 reus\xE1vel e n\xE3o d\xE1 para apontar uma campanha para
|
|
11056
|
+
-- ele: ele vive no endere\xE7o do navegador. Ao lado deles, "Segmenta\xE7\xE3o" \xE9 item
|
|
11057
|
+
-- de menu que n\xE3o abre nada.
|
|
11058
|
+
--
|
|
11059
|
+
-- Aqui o recorte vira ENTIDADE. Um segmento tem nome, \xE9 do tenant, \xE9 escolhido
|
|
11060
|
+
-- num select, e a campanha aponta para ele em vez de carregar a pr\xF3pria c\xF3pia
|
|
11061
|
+
-- do filtro.
|
|
11062
|
+
--
|
|
11063
|
+
-- N\xC3O ESCREVI UM FILTRO NOVO. \`marketing_resolve_audience()\` j\xE1 resolve
|
|
11064
|
+
-- p\xFAblico de forma declarativa e segura desde a 013 do marketing: nome de
|
|
11065
|
+
-- rela\xE7\xE3o conferido no cat\xE1logo, coluna conferida no \`information_schema\`,
|
|
11066
|
+
-- operador vindo de um CASE de conjunto fechado e valor citado como literal \u2014
|
|
11067
|
+
-- \xE9 isso que impede uma campanha de virar um jeito de rodar SQL arbitr\xE1rio.
|
|
11068
|
+
-- Esta migration GENERALIZA aquele desenho de "preso \xE0 campanha" para
|
|
11069
|
+
-- "segmento nomeado", com a mesma disciplina, e acrescenta os tr\xEAs operadores
|
|
11070
|
+
-- que faltavam para o recorte sobreviver ao tempo.
|
|
11071
|
+
--
|
|
11072
|
+
-- OS OPERADORES DE TEMPO S\xC3O O PONTO. Um segmento gravado como
|
|
11073
|
+
-- \`created_at >= '2026-09-08'\` \xE9 uma fotografia: certo hoje, errado em
|
|
11074
|
+
-- novembro, e ningu\xE9m percebe. \`within_days: 7\` e \`older_than_days: 90\` s\xE3o
|
|
11075
|
+
-- perguntas, n\xE3o datas \u2014 "quem entrou nos \xFAltimos 7 dias" continua respondendo
|
|
11076
|
+
-- a mesma coisa no ano que vem. \xC9 o que transforma "Inativos" de lista
|
|
11077
|
+
-- congelada em recorte vivo.
|
|
11078
|
+
--
|
|
11079
|
+
-- E \xC9 POR ISSO QUE O SEGMENTO N\xC3O \xC9 MATERIALIZADO. N\xE3o h\xE1 tabela de
|
|
11080
|
+
-- pertencimento para o tipo \`rule\`, n\xE3o h\xE1 job que recalcula, n\xE3o h\xE1 linha
|
|
11081
|
+
-- velha para explicar por que algu\xE9m ainda aparece: a resposta \xE9 computada na
|
|
11082
|
+
-- hora. O tipo \`list\` existe para o outro caso leg\xEDtimo \u2014 a lista escolhida a
|
|
11083
|
+
-- dedo, que \xE9 justamente a que N\xC3O deve mudar sozinha.
|
|
11084
|
+
--
|
|
11085
|
+
-- VOCABUL\xC1RIO. Este plugin serve restaurante e sal\xE3o pela mesma porta. Por
|
|
11086
|
+
-- isso a tabela fala \`people\`, \`tags\` e \`days\`, e nunca "cliente ativo",
|
|
11087
|
+
-- "atendimento" ou "comanda". Quem d\xE1 nome ao recorte \xE9 o lojista, na tela.
|
|
9769
11088
|
|
|
9770
|
-
|
|
9771
|
-
|
|
9772
|
-
|
|
9773
|
-
|
|
9774
|
-
|
|
9775
|
-
|
|
9776
|
-
|
|
9777
|
-
|
|
9778
|
-
|
|
9779
|
-
|
|
9780
|
-
|
|
9781
|
-
|
|
9782
|
-
|
|
9783
|
-
|
|
9784
|
-
|
|
9785
|
-
|
|
9786
|
-
|
|
9787
|
-
|
|
9788
|
-
|
|
9789
|
-
|
|
9790
|
-
|
|
9791
|
-
|
|
9792
|
-
|
|
9793
|
-
|
|
9794
|
-
|
|
9795
|
-
|
|
9796
|
-
|
|
9797
|
-
|
|
9798
|
-
|
|
9799
|
-
|
|
9800
|
-
|
|
9801
|
-
|
|
9802
|
-
|
|
9803
|
-
|
|
9804
|
-
|
|
9805
|
-
|
|
9806
|
-
|
|
9807
|
-
|
|
9808
|
-
|
|
9809
|
-
|
|
9810
|
-
|
|
9811
|
-
|
|
9812
|
-
|
|
9813
|
-
|
|
9814
|
-
|
|
9815
|
-
|
|
9816
|
-
|
|
9817
|
-
|
|
9818
|
-
|
|
9819
|
-
|
|
9820
|
-
|
|
9821
|
-
|
|
9822
|
-
|
|
9823
|
-
|
|
9824
|
-
|
|
9825
|
-
|
|
9826
|
-
|
|
9827
|
-
|
|
9828
|
-
|
|
9829
|
-
|
|
9830
|
-
|
|
9831
|
-
|
|
9832
|
-
|
|
9833
|
-
|
|
9834
|
-
|
|
9835
|
-
|
|
9836
|
-
|
|
9837
|
-
|
|
9838
|
-
|
|
9839
|
-
|
|
9840
|
-
|
|
9841
|
-
|
|
9842
|
-
|
|
9843
|
-
|
|
9844
|
-
|
|
9845
|
-
|
|
9846
|
-
|
|
9847
|
-
|
|
9848
|
-
|
|
9849
|
-
|
|
9850
|
-
|
|
9851
|
-
|
|
9852
|
-
|
|
9853
|
-
|
|
9854
|
-
|
|
9855
|
-
|
|
9856
|
-
|
|
9857
|
-
|
|
9858
|
-
|
|
9859
|
-
|
|
9860
|
-
|
|
9861
|
-
|
|
9862
|
-
|
|
9863
|
-
|
|
9864
|
-
|
|
9865
|
-
|
|
9866
|
-
|
|
9867
|
-
|
|
9868
|
-
|
|
9869
|
-
|
|
9870
|
-
|
|
9871
|
-
|
|
9872
|
-
|
|
9873
|
-
|
|
9874
|
-
|
|
9875
|
-
|
|
9876
|
-
|
|
9877
|
-
|
|
9878
|
-
|
|
9879
|
-
|
|
9880
|
-
|
|
9881
|
-
|
|
11089
|
+
-- \u2500\u2500 a entidade \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11090
|
+
CREATE TABLE IF NOT EXISTS public.plg_crm_segments (
|
|
11091
|
+
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
11092
|
+
tenant_id uuid NOT NULL,
|
|
11093
|
+
-- Escopo de unidade opcional: uma rede pode ter "parados" por loja. Nulo =
|
|
11094
|
+
-- a rede inteira, a mesma conven\xE7\xE3o das parcerias (001).
|
|
11095
|
+
unit_id uuid,
|
|
11096
|
+
-- O identificador est\xE1vel. \xC9 por ele que uma campanha, um preset ou um
|
|
11097
|
+
-- teste apontam para o segmento \u2014 \`name\` \xE9 do lojista e pode ser renomeado
|
|
11098
|
+
-- a qualquer hora sem quebrar nada.
|
|
11099
|
+
key text NOT NULL,
|
|
11100
|
+
name text NOT NULL,
|
|
11101
|
+
description text,
|
|
11102
|
+
kind text DEFAULT 'rule' NOT NULL,
|
|
11103
|
+
-- Sobre QUAL leitura o recorte \xE9 feito. \`people\` hoje; quando a W2 trouxer
|
|
11104
|
+
-- a leitura de engajamento, um segmento novo aponta para ela sem que esta
|
|
11105
|
+
-- tabela mude. O resolvedor confere o nome no cat\xE1logo antes de usar.
|
|
11106
|
+
source_view text DEFAULT 'people' NOT NULL,
|
|
11107
|
+
-- As cl\xE1usulas: [{"column":"kind","op":"=","value":"lead"}, \u2026]. Combinam
|
|
11108
|
+
-- com E. OU n\xE3o existe de prop\xF3sito \u2014 dois recortes que se somam s\xE3o dois
|
|
11109
|
+
-- segmentos, e um editor de \xE1rvore booleana \xE9 uma tela que ningu\xE9m pediu.
|
|
11110
|
+
rules jsonb DEFAULT '{"where": []}'::jsonb NOT NULL,
|
|
11111
|
+
color text,
|
|
11112
|
+
icon text,
|
|
11113
|
+
-- Semeado pela casa. O lojista pode desativar e renomear; apagar n\xE3o, para
|
|
11114
|
+
-- que um preset n\xE3o suma e volte na pr\xF3xima semeadura.
|
|
11115
|
+
is_system boolean DEFAULT false NOT NULL,
|
|
11116
|
+
is_active boolean DEFAULT true NOT NULL,
|
|
11117
|
+
sort_order integer DEFAULT 100 NOT NULL,
|
|
11118
|
+
created_by uuid,
|
|
11119
|
+
created_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
11120
|
+
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
11121
|
+
CONSTRAINT plg_crm_segments_kind_check CHECK ((kind = ANY (ARRAY['rule'::text, 'list'::text])))
|
|
11122
|
+
);
|
|
11123
|
+
|
|
11124
|
+
ALTER TABLE public.plg_crm_segments FORCE ROW LEVEL SECURITY;
|
|
11125
|
+
|
|
11126
|
+
DO $$ BEGIN
|
|
11127
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'public.plg_crm_segments'::regclass AND contype = 'p') THEN
|
|
11128
|
+
ALTER TABLE ONLY public.plg_crm_segments ADD CONSTRAINT plg_crm_segments_pkey PRIMARY KEY (id);
|
|
11129
|
+
END IF;
|
|
11130
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segments_tenant_key_key') THEN
|
|
11131
|
+
ALTER TABLE ONLY public.plg_crm_segments ADD CONSTRAINT plg_crm_segments_tenant_key_key UNIQUE (tenant_id, key);
|
|
11132
|
+
END IF;
|
|
11133
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segments_tenant_fkey') THEN
|
|
11134
|
+
ALTER TABLE ONLY public.plg_crm_segments
|
|
11135
|
+
ADD CONSTRAINT plg_crm_segments_tenant_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
11136
|
+
END IF;
|
|
11137
|
+
END $$;
|
|
11138
|
+
|
|
11139
|
+
CREATE INDEX IF NOT EXISTS idx_plg_crm_segments_tenant ON public.plg_crm_segments USING btree (tenant_id);
|
|
11140
|
+
|
|
11141
|
+
COMMENT ON TABLE public.plg_crm_segments IS
|
|
11142
|
+
'Um recorte de pessoas com NOME: o que no V1 era um filtro na URL e n\xE3o dava para apontar uma campanha (004).';
|
|
11143
|
+
COMMENT ON COLUMN public.plg_crm_segments.kind IS
|
|
11144
|
+
'rule: calculado na hora, muda sozinho com o tempo. list: escolhido a dedo, N\xC3O muda sozinho (004).';
|
|
11145
|
+
COMMENT ON COLUMN public.plg_crm_segments.rules IS
|
|
11146
|
+
'Cl\xE1usulas declarativas combinadas com E. Operador vem de conjunto fechado; valor entra como literal citado (004).';
|
|
11147
|
+
|
|
11148
|
+
-- \u2500\u2500 a lista escolhida a dedo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11149
|
+
CREATE TABLE IF NOT EXISTS public.plg_crm_segment_members (
|
|
11150
|
+
id uuid DEFAULT gen_random_uuid() NOT NULL,
|
|
11151
|
+
tenant_id uuid NOT NULL,
|
|
11152
|
+
segment_id uuid NOT NULL,
|
|
11153
|
+
person_id uuid NOT NULL,
|
|
11154
|
+
added_by uuid,
|
|
11155
|
+
created_at timestamp with time zone DEFAULT now() NOT NULL
|
|
11156
|
+
);
|
|
11157
|
+
|
|
11158
|
+
ALTER TABLE public.plg_crm_segment_members FORCE ROW LEVEL SECURITY;
|
|
11159
|
+
|
|
11160
|
+
DO $$ BEGIN
|
|
11161
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid = 'public.plg_crm_segment_members'::regclass AND contype = 'p') THEN
|
|
11162
|
+
ALTER TABLE ONLY public.plg_crm_segment_members ADD CONSTRAINT plg_crm_segment_members_pkey PRIMARY KEY (id);
|
|
11163
|
+
END IF;
|
|
11164
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segment_members_unique') THEN
|
|
11165
|
+
ALTER TABLE ONLY public.plg_crm_segment_members ADD CONSTRAINT plg_crm_segment_members_unique UNIQUE (segment_id, person_id);
|
|
11166
|
+
END IF;
|
|
11167
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segment_members_segment_fkey') THEN
|
|
11168
|
+
ALTER TABLE ONLY public.plg_crm_segment_members
|
|
11169
|
+
ADD CONSTRAINT plg_crm_segment_members_segment_fkey FOREIGN KEY (segment_id) REFERENCES public.plg_crm_segments(id) ON DELETE CASCADE;
|
|
11170
|
+
END IF;
|
|
11171
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segment_members_person_fkey') THEN
|
|
11172
|
+
ALTER TABLE ONLY public.plg_crm_segment_members
|
|
11173
|
+
ADD CONSTRAINT plg_crm_segment_members_person_fkey FOREIGN KEY (person_id) REFERENCES public.people(id) ON DELETE CASCADE;
|
|
11174
|
+
END IF;
|
|
11175
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_segment_members_tenant_fkey') THEN
|
|
11176
|
+
ALTER TABLE ONLY public.plg_crm_segment_members
|
|
11177
|
+
ADD CONSTRAINT plg_crm_segment_members_tenant_fkey FOREIGN KEY (tenant_id) REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
11178
|
+
END IF;
|
|
11179
|
+
END $$;
|
|
11180
|
+
|
|
11181
|
+
CREATE INDEX IF NOT EXISTS idx_plg_crm_segment_members_segment ON public.plg_crm_segment_members USING btree (segment_id);
|
|
11182
|
+
CREATE INDEX IF NOT EXISTS idx_plg_crm_segment_members_tenant ON public.plg_crm_segment_members USING btree (tenant_id);
|
|
11183
|
+
|
|
11184
|
+
COMMENT ON TABLE public.plg_crm_segment_members IS
|
|
11185
|
+
'Quem foi posto \xE0 m\xE3o num segmento do tipo list. Segmento do tipo rule n\xE3o tem linha aqui \u2014 ele \xE9 calculado (004).';
|
|
11186
|
+
|
|
11187
|
+
-- \u2500\u2500 authz \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11188
|
+
--
|
|
11189
|
+
-- \`sales.read\` para ver, \`sales.edit\` para mexer \u2014 a mesma r\xE9gua do resto do
|
|
11190
|
+
-- CRM. Um segmento \xE9 cadastro, n\xE3o relat\xF3rio: quem pode ver a lista de leads
|
|
11191
|
+
-- pode ver o recorte dela.
|
|
11192
|
+
ALTER TABLE public.plg_crm_segments ENABLE ROW LEVEL SECURITY;
|
|
11193
|
+
|
|
11194
|
+
DROP POLICY IF EXISTS plg_crm_segments_authz_select ON public.plg_crm_segments;
|
|
11195
|
+
CREATE POLICY plg_crm_segments_authz_select ON public.plg_crm_segments
|
|
11196
|
+
FOR SELECT TO authenticated USING (
|
|
11197
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11198
|
+
AND (SELECT app.has_permission('sales.read', NULL::uuid)));
|
|
11199
|
+
|
|
11200
|
+
DROP POLICY IF EXISTS plg_crm_segments_authz_insert ON public.plg_crm_segments;
|
|
11201
|
+
CREATE POLICY plg_crm_segments_authz_insert ON public.plg_crm_segments
|
|
11202
|
+
FOR INSERT TO authenticated WITH CHECK (
|
|
11203
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11204
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11205
|
+
|
|
11206
|
+
DROP POLICY IF EXISTS plg_crm_segments_authz_update ON public.plg_crm_segments;
|
|
11207
|
+
CREATE POLICY plg_crm_segments_authz_update ON public.plg_crm_segments
|
|
11208
|
+
FOR UPDATE TO authenticated USING (
|
|
11209
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11210
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
|
|
11211
|
+
WITH CHECK (
|
|
11212
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11213
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11214
|
+
|
|
11215
|
+
-- Preset da casa n\xE3o se apaga: desativar \xE9 o caminho. Sem esta cl\xE1usula o
|
|
11216
|
+
-- lojista apaga "Parados h\xE1 90 dias", a semeadura do pr\xF3ximo tenant n\xE3o o
|
|
11217
|
+
-- traz de volta para ele, e a casa fica com um cadastro diferente da outra
|
|
11218
|
+
-- sem que ningu\xE9m saiba por qu\xEA.
|
|
11219
|
+
DROP POLICY IF EXISTS plg_crm_segments_authz_delete ON public.plg_crm_segments;
|
|
11220
|
+
CREATE POLICY plg_crm_segments_authz_delete ON public.plg_crm_segments
|
|
11221
|
+
FOR DELETE TO authenticated USING (
|
|
11222
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11223
|
+
AND is_system = false
|
|
11224
|
+
AND (SELECT app.has_permission('sales.delete', NULL::uuid)));
|
|
11225
|
+
|
|
11226
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_segments TO authenticated;
|
|
11227
|
+
GRANT ALL ON public.plg_crm_segments TO service_role;
|
|
11228
|
+
|
|
11229
|
+
ALTER TABLE public.plg_crm_segment_members ENABLE ROW LEVEL SECURITY;
|
|
11230
|
+
|
|
11231
|
+
DROP POLICY IF EXISTS plg_crm_segment_members_authz_select ON public.plg_crm_segment_members;
|
|
11232
|
+
CREATE POLICY plg_crm_segment_members_authz_select ON public.plg_crm_segment_members
|
|
11233
|
+
FOR SELECT TO authenticated USING (
|
|
11234
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11235
|
+
AND (SELECT app.has_permission('sales.read', NULL::uuid)));
|
|
11236
|
+
|
|
11237
|
+
DROP POLICY IF EXISTS plg_crm_segment_members_authz_insert ON public.plg_crm_segment_members;
|
|
11238
|
+
CREATE POLICY plg_crm_segment_members_authz_insert ON public.plg_crm_segment_members
|
|
11239
|
+
FOR INSERT TO authenticated WITH CHECK (
|
|
11240
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11241
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11242
|
+
|
|
11243
|
+
DROP POLICY IF EXISTS plg_crm_segment_members_authz_update ON public.plg_crm_segment_members;
|
|
11244
|
+
CREATE POLICY plg_crm_segment_members_authz_update ON public.plg_crm_segment_members
|
|
11245
|
+
FOR UPDATE TO authenticated USING (
|
|
11246
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11247
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
|
|
11248
|
+
WITH CHECK (
|
|
11249
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11250
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11251
|
+
|
|
11252
|
+
DROP POLICY IF EXISTS plg_crm_segment_members_authz_delete ON public.plg_crm_segment_members;
|
|
11253
|
+
CREATE POLICY plg_crm_segment_members_authz_delete ON public.plg_crm_segment_members
|
|
11254
|
+
FOR DELETE TO authenticated USING (
|
|
11255
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11256
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11257
|
+
|
|
11258
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_segment_members TO authenticated;
|
|
11259
|
+
GRANT ALL ON public.plg_crm_segment_members TO service_role;
|
|
11260
|
+
|
|
11261
|
+
INSERT INTO app.scaffold_registry
|
|
11262
|
+
(table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)
|
|
11263
|
+
VALUES
|
|
11264
|
+
('public', 'plg_crm_segments', 'crm.segment', 'crm', false, 'enforce', ARRAY[]::text[], false, 'unit_optional', false),
|
|
11265
|
+
('public', 'plg_crm_segment_members', 'crm.segment_member', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)
|
|
11266
|
+
ON CONFLICT DO NOTHING;
|
|
11267
|
+
|
|
11268
|
+
-- \u2500\u2500 o resolvedor \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11269
|
+
--
|
|
11270
|
+
-- Quem est\xE1 no segmento AGORA. Herda de \`marketing_resolve_audience()\` as tr\xEAs
|
|
11271
|
+
-- defesas que fazem um filtro declarativo n\xE3o virar execu\xE7\xE3o de SQL alheio:
|
|
11272
|
+
--
|
|
11273
|
+
-- 1. a rela\xE7\xE3o \xE9 conferida no cat\xE1logo (\`pg_class\`) depois de passar por um
|
|
11274
|
+
-- regex de nome simples \u2014 nada de \`public.x; DROP \u2026\` nem de esquema;
|
|
11275
|
+
-- 2. a coluna \xE9 conferida no \`information_schema\` da rela\xE7\xE3o escolhida \u2014
|
|
11276
|
+
-- quem inventa nome de coluna leva 42703, n\xE3o uma consulta torta;
|
|
11277
|
+
-- 3. o operador NUNCA vem da entrada: ele sai de um CASE de conjunto
|
|
11278
|
+
-- fechado, e o valor entra sempre por \`%L\`.
|
|
11279
|
+
--
|
|
11280
|
+
-- O que este acrescenta s\xE3o os operadores que o p\xFAblico de campanha n\xE3o
|
|
11281
|
+
-- precisava e o recorte precisa: conjunto (\`in\`), aus\xEAncia (\`is_null\`),
|
|
11282
|
+
-- etiqueta (\`has_tag\`) e \u2014 o que importa \u2014 TEMPO RELATIVO.
|
|
11283
|
+
CREATE OR REPLACE FUNCTION public.crm_resolve_segment(p_segment_id uuid)
|
|
11284
|
+
RETURNS TABLE(person_id uuid)
|
|
11285
|
+
LANGUAGE plpgsql
|
|
11286
|
+
SECURITY DEFINER
|
|
11287
|
+
STABLE
|
|
11288
|
+
SET search_path TO ''
|
|
11289
|
+
AS $$
|
|
11290
|
+
DECLARE
|
|
11291
|
+
v_tenant uuid := app.current_tenant_id();
|
|
11292
|
+
v_seg record;
|
|
11293
|
+
v_kind char;
|
|
11294
|
+
v_where text;
|
|
11295
|
+
v_clause jsonb;
|
|
11296
|
+
v_col text;
|
|
11297
|
+
v_op text;
|
|
11298
|
+
v_days integer;
|
|
11299
|
+
v_list text;
|
|
11300
|
+
BEGIN
|
|
11301
|
+
IF v_tenant IS NULL THEN
|
|
11302
|
+
RAISE EXCEPTION 'crm_resolve_segment: sem tenant na sess\xE3o' USING ERRCODE = '42501';
|
|
11303
|
+
END IF;
|
|
11304
|
+
IF NOT app.has_permission('sales.read', NULL::uuid) THEN
|
|
11305
|
+
RAISE EXCEPTION 'crm_resolve_segment: exige sales.read' USING ERRCODE = '42501';
|
|
11306
|
+
END IF;
|
|
11307
|
+
|
|
11308
|
+
SELECT * INTO v_seg FROM public.plg_crm_segments s
|
|
11309
|
+
WHERE s.id = p_segment_id AND s.tenant_id = v_tenant;
|
|
11310
|
+
IF v_seg.id IS NULL THEN
|
|
11311
|
+
RAISE EXCEPTION 'crm_resolve_segment: segmento n\xE3o encontrado' USING ERRCODE = 'P0002';
|
|
11312
|
+
END IF;
|
|
11313
|
+
|
|
11314
|
+
-- A lista escolhida a dedo n\xE3o passa pelo motor de regras: ela \xC9 a resposta.
|
|
11315
|
+
IF v_seg.kind = 'list' THEN
|
|
11316
|
+
RETURN QUERY
|
|
11317
|
+
SELECT m.person_id FROM public.plg_crm_segment_members m
|
|
11318
|
+
WHERE m.segment_id = v_seg.id AND m.tenant_id = v_tenant;
|
|
11319
|
+
RETURN;
|
|
11320
|
+
END IF;
|
|
11321
|
+
|
|
11322
|
+
IF v_seg.source_view !~ '^[a-z_][a-z0-9_]*$' THEN
|
|
11323
|
+
RAISE EXCEPTION 'crm_resolve_segment: % n\xE3o \xE9 um nome de rela\xE7\xE3o simples', v_seg.source_view USING ERRCODE = '22023';
|
|
11324
|
+
END IF;
|
|
11325
|
+
SELECT cl.relkind INTO v_kind FROM pg_catalog.pg_class cl
|
|
11326
|
+
JOIN pg_catalog.pg_namespace n ON n.oid = cl.relnamespace
|
|
11327
|
+
WHERE n.nspname = 'public' AND cl.relname = v_seg.source_view;
|
|
11328
|
+
IF v_kind IS NULL THEN
|
|
11329
|
+
RAISE EXCEPTION 'crm_resolve_segment: public.% n\xE3o existe', v_seg.source_view USING ERRCODE = '42P01';
|
|
11330
|
+
END IF;
|
|
11331
|
+
|
|
11332
|
+
v_where := format('tenant_id = %L', v_tenant);
|
|
11333
|
+
|
|
11334
|
+
-- Segmento com unidade s\xF3 enxerga aquela unidade; sem unidade, a rede
|
|
11335
|
+
-- inteira. Mesma conven\xE7\xE3o das parcerias (001) \u2014 e a coluna s\xF3 entra na
|
|
11336
|
+
-- consulta se a leitura escolhida realmente a tiver.
|
|
11337
|
+
IF v_seg.unit_id IS NOT NULL AND EXISTS (
|
|
11338
|
+
SELECT 1 FROM information_schema.columns
|
|
11339
|
+
WHERE table_schema = 'public' AND table_name = v_seg.source_view AND column_name = 'unit_id'
|
|
11340
|
+
) THEN
|
|
11341
|
+
v_where := v_where || format(' AND unit_id = %L', v_seg.unit_id);
|
|
11342
|
+
END IF;
|
|
11343
|
+
|
|
11344
|
+
FOR v_clause IN SELECT * FROM jsonb_array_elements(coalesce(v_seg.rules -> 'where', '[]'::jsonb)) LOOP
|
|
11345
|
+
v_col := v_clause ->> 'column';
|
|
11346
|
+
v_op := coalesce(v_clause ->> 'op', '=');
|
|
11347
|
+
|
|
11348
|
+
IF NOT EXISTS (SELECT 1 FROM information_schema.columns
|
|
11349
|
+
WHERE table_schema = 'public' AND table_name = v_seg.source_view
|
|
11350
|
+
AND column_name = v_col) THEN
|
|
11351
|
+
RAISE EXCEPTION 'crm_resolve_segment: public.% n\xE3o tem a coluna %', v_seg.source_view, v_col
|
|
11352
|
+
USING ERRCODE = '42703';
|
|
11353
|
+
END IF;
|
|
11354
|
+
|
|
11355
|
+
-- CASE PESQUISADO, n\xE3o simples: \`WHEN 'a', 'b' THEN\` n\xE3o existe em
|
|
11356
|
+
-- Postgres, e o erro s\xF3 aparece quando a migration roda.
|
|
11357
|
+
v_where := v_where || CASE
|
|
11358
|
+
|
|
11359
|
+
-- Compara\xE7\xE3o simples. O operador sai deste CASE, o valor entra por %L.
|
|
11360
|
+
WHEN v_op IN ('=', '<>', '>', '<', '>=', '<=') THEN
|
|
11361
|
+
format(' AND %I %s %L', v_col,
|
|
11362
|
+
CASE v_op WHEN '<>' THEN '<>' WHEN '>' THEN '>' WHEN '<' THEN '<'
|
|
11363
|
+
WHEN '>=' THEN '>=' WHEN '<=' THEN '<=' ELSE '=' END,
|
|
11364
|
+
v_clause ->> 'value')
|
|
11365
|
+
|
|
11366
|
+
WHEN v_op = 'ilike' THEN
|
|
11367
|
+
format(' AND %I ILIKE %L', v_col, '%' || coalesce(v_clause ->> 'value', '') || '%')
|
|
11368
|
+
|
|
11369
|
+
-- Conjunto. Cada elemento vira literal citado por conta pr\xF3pria; uma
|
|
11370
|
+
-- lista vazia vira \`IN (NULL)\`, que n\xE3o casa com ningu\xE9m \u2014 que \xE9 a
|
|
11371
|
+
-- leitura honesta de "nenhum valor escolhido".
|
|
11372
|
+
WHEN v_op IN ('in', 'not_in') THEN (
|
|
11373
|
+
SELECT format(' AND %I %s (%s)', v_col,
|
|
11374
|
+
CASE WHEN v_op = 'not_in' THEN 'NOT IN' ELSE 'IN' END,
|
|
11375
|
+
coalesce(string_agg(quote_literal(e), ','), 'NULL'))
|
|
11376
|
+
FROM jsonb_array_elements_text(coalesce(v_clause -> 'value', '[]'::jsonb)) AS e)
|
|
11377
|
+
|
|
11378
|
+
WHEN v_op = 'is_null' THEN format(' AND %I IS NULL', v_col)
|
|
11379
|
+
WHEN v_op = 'not_null' THEN format(' AND %I IS NOT NULL', v_col)
|
|
11380
|
+
|
|
11381
|
+
-- Etiqueta. \`tags\` \xE9 text[]; perguntar por igualdade nele n\xE3o acha nada
|
|
11382
|
+
-- e n\xE3o d\xE1 erro, que \xE9 o pior desfecho poss\xEDvel.
|
|
11383
|
+
WHEN v_op = 'has_tag' THEN
|
|
11384
|
+
format(' AND %L = ANY(%I)', v_clause ->> 'value', v_col)
|
|
11385
|
+
|
|
11386
|
+
-- Tempo RELATIVO \u2014 o motivo desta migration existir. Nunca grava data.
|
|
11387
|
+
WHEN v_op IN ('within_days', 'older_than_days') THEN (
|
|
11388
|
+
SELECT format(' AND %I %s now() - make_interval(days => %s)', v_col,
|
|
11389
|
+
CASE WHEN v_op = 'within_days' THEN '>=' ELSE '<' END,
|
|
11390
|
+
-- O cast \xE9 a defesa: o que n\xE3o for inteiro estoura aqui
|
|
11391
|
+
-- e n\xE3o chega a virar texto de consulta.
|
|
11392
|
+
(coalesce(v_clause ->> 'value', '0'))::integer))
|
|
11393
|
+
|
|
11394
|
+
-- Anivers\xE1rio dentro de N dias, dando a volta no ano (dezembro para
|
|
11395
|
+
-- janeiro). O m\xF3dulo 366 tolera um dia de erro em ano bissexto: \xE9
|
|
11396
|
+
-- cart\xE3o de anivers\xE1rio, n\xE3o juros.
|
|
11397
|
+
WHEN v_op = 'birthday_within_days' THEN (
|
|
11398
|
+
SELECT format(
|
|
11399
|
+
' AND %I IS NOT NULL AND ((EXTRACT(doy FROM %I::date)::int - EXTRACT(doy FROM now())::int + 366) %% 366) <= %s',
|
|
11400
|
+
v_col, v_col, (coalesce(v_clause ->> 'value', '0'))::integer))
|
|
11401
|
+
|
|
11402
|
+
ELSE
|
|
11403
|
+
-- Operador desconhecido n\xE3o \xE9 ignorado em sil\xEAncio: ignorar alarga o
|
|
11404
|
+
-- recorte sem avisar, e um recorte alargado em sil\xEAncio \xE9 uma
|
|
11405
|
+
-- campanha indo para quem n\xE3o devia.
|
|
11406
|
+
NULL
|
|
11407
|
+
END;
|
|
11408
|
+
|
|
11409
|
+
IF v_where IS NULL THEN
|
|
11410
|
+
RAISE EXCEPTION 'crm_resolve_segment: operador % n\xE3o \xE9 reconhecido', v_op USING ERRCODE = '22023';
|
|
11411
|
+
END IF;
|
|
11412
|
+
END LOOP;
|
|
11413
|
+
|
|
11414
|
+
RETURN QUERY EXECUTE format('SELECT s.id FROM public.%I s WHERE %s', v_seg.source_view, v_where);
|
|
11415
|
+
END $$;
|
|
11416
|
+
|
|
11417
|
+
COMMENT ON FUNCTION public.crm_resolve_segment(uuid) IS
|
|
11418
|
+
'Quem est\xE1 no segmento agora. Declarativo: rela\xE7\xE3o e coluna conferidas no cat\xE1logo, operador de conjunto fechado, valor como literal (004).';
|
|
11419
|
+
|
|
11420
|
+
REVOKE ALL ON FUNCTION public.crm_resolve_segment(uuid) FROM PUBLIC, anon;
|
|
11421
|
+
GRANT EXECUTE ON FUNCTION public.crm_resolve_segment(uuid) TO authenticated;
|
|
11422
|
+
GRANT EXECUTE ON FUNCTION public.crm_resolve_segment(uuid) TO service_role;
|
|
11423
|
+
|
|
11424
|
+
-- \u2500\u2500 a contagem, para a 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
|
|
11425
|
+
--
|
|
11426
|
+
-- A lista de segmentos mostra o tamanho de cada um. Sem esta fun\xE7\xE3o a tela
|
|
11427
|
+
-- faria N chamadas para desenhar N chips \u2014 e \xE9 assim que uma tela de cadastro
|
|
11428
|
+
-- vira uma tela lenta.
|
|
11429
|
+
CREATE OR REPLACE FUNCTION public.crm_segment_counts()
|
|
11430
|
+
RETURNS TABLE(segment_id uuid, member_count bigint)
|
|
11431
|
+
LANGUAGE plpgsql
|
|
11432
|
+
SECURITY DEFINER
|
|
11433
|
+
STABLE
|
|
11434
|
+
SET search_path TO ''
|
|
11435
|
+
AS $$
|
|
11436
|
+
DECLARE
|
|
11437
|
+
v_tenant uuid := app.current_tenant_id();
|
|
11438
|
+
r record;
|
|
11439
|
+
v_n bigint;
|
|
11440
|
+
BEGIN
|
|
11441
|
+
IF v_tenant IS NULL THEN
|
|
11442
|
+
RAISE EXCEPTION 'crm_segment_counts: sem tenant na sess\xE3o' USING ERRCODE = '42501';
|
|
11443
|
+
END IF;
|
|
11444
|
+
IF NOT app.has_permission('sales.read', NULL::uuid) THEN
|
|
11445
|
+
RAISE EXCEPTION 'crm_segment_counts: exige sales.read' USING ERRCODE = '42501';
|
|
11446
|
+
END IF;
|
|
11447
|
+
|
|
11448
|
+
FOR r IN SELECT s.id FROM public.plg_crm_segments s
|
|
11449
|
+
WHERE s.tenant_id = v_tenant AND s.is_active
|
|
11450
|
+
ORDER BY s.sort_order, s.name LOOP
|
|
11451
|
+
BEGIN
|
|
11452
|
+
SELECT count(*) INTO v_n FROM public.crm_resolve_segment(r.id);
|
|
11453
|
+
EXCEPTION WHEN OTHERS THEN
|
|
11454
|
+
-- Um segmento com regra quebrada (coluna renomeada, leitura removida)
|
|
11455
|
+
-- n\xE3o pode derrubar a contagem dos outros. Ele volta como NULL e a tela
|
|
11456
|
+
-- mostra "\u2014" naquele chip.
|
|
11457
|
+
v_n := NULL;
|
|
11458
|
+
END;
|
|
11459
|
+
segment_id := r.id; member_count := v_n; RETURN NEXT;
|
|
11460
|
+
END LOOP;
|
|
11461
|
+
END $$;
|
|
11462
|
+
|
|
11463
|
+
COMMENT ON FUNCTION public.crm_segment_counts() IS
|
|
11464
|
+
'Tamanho de cada segmento ativo do tenant, numa chamada s\xF3. Regra quebrada volta NULL sem derrubar as outras (004).';
|
|
11465
|
+
|
|
11466
|
+
REVOKE ALL ON FUNCTION public.crm_segment_counts() FROM PUBLIC, anon;
|
|
11467
|
+
GRANT EXECUTE ON FUNCTION public.crm_segment_counts() TO authenticated;
|
|
11468
|
+
GRANT EXECUTE ON FUNCTION public.crm_segment_counts() TO service_role;
|
|
11469
|
+
|
|
11470
|
+
-- \u2500\u2500 os recortes que a casa j\xE1 nasce sabendo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11471
|
+
--
|
|
11472
|
+
-- A li\xE7\xE3o das Origens (001) foi: cadastro que nasce vazio \xE9 cadastro morto \u2014
|
|
11473
|
+
-- o registry existia, e nenhuma casa tinha uma origem. Segmento vazio seria
|
|
11474
|
+
-- pior, porque "Segmenta\xE7\xE3o" \xE9 justamente a tela que no V1 n\xE3o abria.
|
|
11475
|
+
--
|
|
11476
|
+
-- Nenhum destes cinco nomeia ramo. N\xE3o h\xE1 "cliente", "atendimento" nem
|
|
11477
|
+
-- "pedido": h\xE1 \`kind = 'lead'\` (que este plugin grava), etiqueta, telefone,
|
|
11478
|
+
-- data de nascimento e tempo parado. Um restaurante l\xEA "Parados h\xE1 90 dias"
|
|
11479
|
+
-- como quem n\xE3o pede h\xE1 tr\xEAs meses; um sal\xE3o, como quem n\xE3o volta h\xE1 tr\xEAs
|
|
11480
|
+
-- meses. \xC9 a MESMA pergunta, e \xE9 por isso que ela pode morar aqui.
|
|
11481
|
+
CREATE OR REPLACE FUNCTION public.crm_seed_tenant_segments(p_tenant uuid)
|
|
11482
|
+
RETURNS jsonb
|
|
11483
|
+
LANGUAGE plpgsql
|
|
11484
|
+
SECURITY DEFINER
|
|
11485
|
+
SET search_path TO ''
|
|
11486
|
+
AS $$
|
|
11487
|
+
DECLARE v_made integer := 0;
|
|
11488
|
+
BEGIN
|
|
11489
|
+
IF p_tenant IS NULL THEN RETURN jsonb_build_object('seeded', false, 'reason', 'no tenant'); END IF;
|
|
11490
|
+
|
|
11491
|
+
INSERT INTO public.plg_crm_segments (tenant_id, key, name, description, kind, source_view, rules, color, icon, is_system, sort_order)
|
|
11492
|
+
SELECT p_tenant, v.key, v.name, v.description, 'rule', 'people', v.rules::jsonb, v.color, v.icon, true, v.sort_order
|
|
11493
|
+
FROM (VALUES
|
|
11494
|
+
('new-leads', 'Leads novos', 'Entraram nos \xFAltimos 7 dias.',
|
|
11495
|
+
'{"where":[{"column":"kind","op":"=","value":"lead"},{"column":"created_at","op":"within_days","value":7}]}',
|
|
11496
|
+
'#3b82f6', 'UserPlus', 10),
|
|
11497
|
+
|
|
11498
|
+
-- Um lead sem telefone E sem e-mail n\xE3o \xE9 um lead ruim: \xE9 um lead com
|
|
11499
|
+
-- quem N\xC3O D\xC1 para falar. Vale um recorte pr\xF3prio porque a a\xE7\xE3o \xE9 outra
|
|
11500
|
+
-- \u2014 n\xE3o \xE9 insistir, \xE9 descobrir o contato.
|
|
11501
|
+
('unreachable-leads', 'Sem como falar', 'Leads sem telefone e sem e-mail.',
|
|
11502
|
+
'{"where":[{"column":"kind","op":"=","value":"lead"},{"column":"phone","op":"is_null"},{"column":"email","op":"is_null"}]}',
|
|
11503
|
+
'#f59e0b', 'PhoneOff', 20),
|
|
11504
|
+
|
|
11505
|
+
('vip', 'VIP', 'Quem est\xE1 marcado com a etiqueta VIP.',
|
|
11506
|
+
'{"where":[{"column":"tags","op":"has_tag","value":"vip"}]}',
|
|
11507
|
+
'#a855f7', 'Star', 30),
|
|
11508
|
+
|
|
11509
|
+
-- O "Inativos" do V1, sem a palavra do ramo e sem data congelada.
|
|
11510
|
+
('dormant-90', 'Parados h\xE1 90 dias', 'J\xE1 n\xE3o s\xE3o lead e n\xE3o t\xEAm movimento h\xE1 tr\xEAs meses.',
|
|
11511
|
+
'{"where":[{"column":"kind","op":"<>","value":"lead"},{"column":"updated_at","op":"older_than_days","value":90}]}',
|
|
11512
|
+
'#64748b', 'Moon', 40),
|
|
11513
|
+
|
|
11514
|
+
('birthdays-30', 'Anivers\xE1rio em 30 dias', 'Faz anivers\xE1rio no pr\xF3ximo m\xEAs.',
|
|
11515
|
+
'{"where":[{"column":"date_of_birth","op":"birthday_within_days","value":30}]}',
|
|
11516
|
+
'#ec4899', 'Cake', 50)
|
|
11517
|
+
) AS v(key, name, description, rules, color, icon, sort_order)
|
|
11518
|
+
WHERE NOT EXISTS (
|
|
11519
|
+
SELECT 1 FROM public.plg_crm_segments x
|
|
11520
|
+
WHERE x.tenant_id = p_tenant AND x.key = v.key);
|
|
11521
|
+
|
|
11522
|
+
GET DIAGNOSTICS v_made = ROW_COUNT;
|
|
11523
|
+
RETURN jsonb_build_object('seeded', true, 'tenant_id', p_tenant, 'segments', v_made);
|
|
11524
|
+
END $$;
|
|
11525
|
+
|
|
11526
|
+
COMMENT ON FUNCTION public.crm_seed_tenant_segments(uuid) IS
|
|
11527
|
+
'Os cinco recortes que toda casa come\xE7a tendo. Nenhum nomeia ramo \u2014 servem restaurante e sal\xE3o pela mesma regra (004).';
|
|
11528
|
+
|
|
11529
|
+
REVOKE ALL ON FUNCTION public.crm_seed_tenant_segments(uuid) FROM PUBLIC, anon;
|
|
11530
|
+
GRANT EXECUTE ON FUNCTION public.crm_seed_tenant_segments(uuid) TO authenticated;
|
|
11531
|
+
GRANT EXECUTE ON FUNCTION public.crm_seed_tenant_segments(uuid) TO service_role;
|
|
11532
|
+
|
|
11533
|
+
-- O gatilho de tenant novo j\xE1 existe desde a 001. Ele ganha uma segunda
|
|
11534
|
+
-- semeadura em vez de um segundo gatilho: dois AFTER INSERT na mesma tabela
|
|
11535
|
+
-- correm em ordem de nome, e depender disso \xE9 depender de um detalhe.
|
|
11536
|
+
CREATE OR REPLACE FUNCTION public.trg_crm_seed_new_tenant()
|
|
11537
|
+
RETURNS trigger
|
|
11538
|
+
LANGUAGE plpgsql
|
|
11539
|
+
SECURITY DEFINER
|
|
11540
|
+
SET search_path TO ''
|
|
11541
|
+
AS $$
|
|
11542
|
+
BEGIN
|
|
11543
|
+
-- Nunca derruba a cria\xE7\xE3o do tenant: uma casa sem origens \xE9 repar\xE1vel com uma
|
|
11544
|
+
-- chamada; uma casa que n\xE3o nasceu, n\xE3o.
|
|
11545
|
+
BEGIN
|
|
11546
|
+
PERFORM public.crm_seed_tenant_lead_sources(NEW.id);
|
|
11547
|
+
EXCEPTION WHEN OTHERS THEN
|
|
11548
|
+
RAISE WARNING 'crm_seed_tenant_lead_sources falhou para o tenant %: %', NEW.id, SQLERRM;
|
|
11549
|
+
END;
|
|
11550
|
+
BEGIN
|
|
11551
|
+
PERFORM public.crm_seed_tenant_segments(NEW.id);
|
|
11552
|
+
EXCEPTION WHEN OTHERS THEN
|
|
11553
|
+
RAISE WARNING 'crm_seed_tenant_segments falhou para o tenant %: %', NEW.id, SQLERRM;
|
|
11554
|
+
END;
|
|
11555
|
+
RETURN NEW;
|
|
11556
|
+
END $$;
|
|
11557
|
+
|
|
11558
|
+
-- e as casas que j\xE1 nasceram sem
|
|
11559
|
+
DO $$
|
|
11560
|
+
DECLARE r record;
|
|
11561
|
+
BEGIN
|
|
11562
|
+
FOR r IN SELECT t.id FROM public.tenants t LOOP
|
|
11563
|
+
BEGIN
|
|
11564
|
+
PERFORM public.crm_seed_tenant_segments(r.id);
|
|
11565
|
+
EXCEPTION WHEN OTHERS THEN
|
|
11566
|
+
RAISE WARNING 'backfill crm_seed_tenant_segments % : %', r.id, SQLERRM;
|
|
11567
|
+
END;
|
|
11568
|
+
END LOOP;
|
|
11569
|
+
END $$;
|
|
11570
|
+
`;
|
|
11571
|
+
var MIGRATION_005_A_ETAPA_GANHA_UM_CODIGO_E_UM_COMECO = `-- 005_a_etapa_ganha_um_codigo_e_um_comeco.sql
|
|
11572
|
+
--
|
|
11573
|
+
-- O V1 tem uma tela chamada "Configurar Pipelines" onde se desenham as etapas
|
|
11574
|
+
-- do funil. O V2 tem uma que MOSTRA as etapas e n\xE3o deixa mexer em nenhuma \u2014 o
|
|
11575
|
+
-- pr\xF3prio rodap\xE9 dela avisa que customizar n\xE3o d\xE1. Um funil cujas colunas
|
|
11576
|
+
-- ningu\xE9m consegue desenhar n\xE3o \xE9 um funil configur\xE1vel; \xE9 um funil de f\xE1brica
|
|
11577
|
+
-- com uma vitrine na frente.
|
|
11578
|
+
--
|
|
11579
|
+
-- Para a tela poder editar, faltam duas colunas \u2014 e as duas s\xE3o as que o V1
|
|
11580
|
+
-- acerta:
|
|
11581
|
+
--
|
|
11582
|
+
-- 1. \`code\`. O V1 guarda um c\xF3digo est\xE1vel ao lado do nome (\`new\`, \`qualified\`,
|
|
11583
|
+
-- \`won\`). \xC9 o que faz renomear "Qualificado" para "Triado" N\xC3O quebrar a
|
|
11584
|
+
-- automa\xE7\xE3o que aponta para aquela etapa. Sem ele, a \xFAnica identidade da
|
|
11585
|
+
-- etapa \xE9 o uuid \u2014 que ningu\xE9m escreve numa regra \u2014 ou o nome, que \xE9
|
|
11586
|
+
-- exatamente o que muda. (O V1 erra em MOSTRAR o c\xF3digo na tela, o que a
|
|
11587
|
+
-- ISSUES.md dele registra como V1-025; aqui ele \xE9 identificador, n\xE3o texto
|
|
11588
|
+
-- de interface.)
|
|
11589
|
+
--
|
|
11590
|
+
-- 2. \`is_initial\`. O V1 marca tr\xEAs etapas como especiais: Inicial, Ganho e
|
|
11591
|
+
-- Perdido. O V2 tinha duas \u2014 ganho e perda \u2014 e INFERIA a inicial com
|
|
11592
|
+
-- \`stages.filter(!won && !lost).sort(order)[0]\`, no cliente. A infer\xEAncia
|
|
11593
|
+
-- acerta quase sempre e erra em sil\xEAncio quando algu\xE9m reordena: o lead novo
|
|
11594
|
+
-- passa a entrar noutra etapa e ningu\xE9m liga uma coisa \xE0 outra. Onde entrar
|
|
11595
|
+
-- no funil \xE9 uma decis\xE3o, e decis\xE3o se grava.
|
|
11596
|
+
--
|
|
11597
|
+
-- O QUE ESTA MIGRATION N\xC3O FAZ: n\xE3o impede duas etapas de ganho nem duas de
|
|
11598
|
+
-- perda. "Perdido por pre\xE7o" e "Perdido para concorrente" s\xE3o dois desfechos
|
|
11599
|
+
-- leg\xEDtimos, e o \`deriveLeadStatus\` j\xE1 l\xEA os dois como perda. A ENTRADA \xE9 que
|
|
11600
|
+
-- n\xE3o pode ser amb\xEDgua \u2014 da\xED o \xEDndice \xFAnico parcial s\xF3 em \`is_initial\`.
|
|
11601
|
+
|
|
11602
|
+
-- \u2500\u2500 um slug est\xE1vel, para nascer com c\xF3digo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11603
|
+
--
|
|
11604
|
+
-- IMMUTABLE porque um \xEDndice pode precisar dela, e sem acento porque o c\xF3digo
|
|
11605
|
+
-- vive em regra de automa\xE7\xE3o, em endere\xE7o e em arquivo de configura\xE7\xE3o.
|
|
11606
|
+
CREATE OR REPLACE FUNCTION public.crm_slug(p_text text)
|
|
11607
|
+
RETURNS text
|
|
11608
|
+
LANGUAGE sql
|
|
11609
|
+
IMMUTABLE
|
|
11610
|
+
SET search_path TO ''
|
|
11611
|
+
AS $$
|
|
11612
|
+
SELECT nullif(
|
|
11613
|
+
btrim(
|
|
11614
|
+
regexp_replace(
|
|
11615
|
+
lower(translate(coalesce(p_text, ''),
|
|
11616
|
+
'\xE1\xE0\xE2\xE3\xE4\xE9\xE8\xEA\xEB\xED\xEC\xEE\xEF\xF3\xF2\xF4\xF5\xF6\xFA\xF9\xFB\xFC\xE7\xF1\xC1\xC0\xC2\xC3\xC4\xC9\xC8\xCA\xCB\xCD\xCC\xCE\xCF\xD3\xD2\xD4\xD5\xD6\xDA\xD9\xDB\xDC\xC7\xD1',
|
|
11617
|
+
'aaaaaeeeeiiiiooooouuuucnaaaaaeeeeiiiiooooouuuucn')),
|
|
11618
|
+
'[^a-z0-9]+', '-', 'g'),
|
|
11619
|
+
'-'),
|
|
11620
|
+
'')
|
|
11621
|
+
$$;
|
|
11622
|
+
|
|
11623
|
+
COMMENT ON FUNCTION public.crm_slug(text) IS
|
|
11624
|
+
'Nome \u2192 c\xF3digo est\xE1vel, sem acento. Usado para dar \`code\` a uma etapa que nasce sem (005).';
|
|
11625
|
+
|
|
11626
|
+
-- \u2500\u2500 as duas colunas \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11627
|
+
ALTER TABLE public.plg_crm_pipeline_stages
|
|
11628
|
+
ADD COLUMN IF NOT EXISTS code text,
|
|
11629
|
+
ADD COLUMN IF NOT EXISTS is_initial boolean DEFAULT false NOT NULL;
|
|
11630
|
+
|
|
11631
|
+
COMMENT ON COLUMN public.plg_crm_pipeline_stages.code IS
|
|
11632
|
+
'Identidade est\xE1vel da etapa. Renomear a etapa N\xC3O muda o c\xF3digo, e \xE9 isso que mant\xE9m a automa\xE7\xE3o apontando para ela (005).';
|
|
11633
|
+
COMMENT ON COLUMN public.plg_crm_pipeline_stages.is_initial IS
|
|
11634
|
+
'Onde o lead entra no funil. Antes era inferido no cliente pela menor ordem entre as n\xE3o-terminais \u2014 o que errava em sil\xEAncio a cada reordena\xE7\xE3o (005).';
|
|
11635
|
+
|
|
11636
|
+
-- \u2500\u2500 as etapas que j\xE1 existem \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11637
|
+
--
|
|
11638
|
+
-- C\xF3digo a partir do nome, com desempate por ordem quando dois nomes colidem
|
|
11639
|
+
-- ("Perdido" e "perdido " dariam o mesmo slug). Sem o desempate, o \xEDndice \xFAnico
|
|
11640
|
+
-- abaixo recusaria a migration numa casa que j\xE1 tem esse par.
|
|
11641
|
+
WITH slugged AS (
|
|
11642
|
+
SELECT s.id, s.pipeline_id,
|
|
11643
|
+
coalesce(public.crm_slug(s.name), 'etapa') AS base,
|
|
11644
|
+
row_number() OVER (
|
|
11645
|
+
PARTITION BY s.pipeline_id, coalesce(public.crm_slug(s.name), 'etapa')
|
|
11646
|
+
ORDER BY s."order", s.created_at, s.id) AS dup
|
|
11647
|
+
FROM public.plg_crm_pipeline_stages s
|
|
11648
|
+
WHERE s.code IS NULL
|
|
11649
|
+
)
|
|
11650
|
+
UPDATE public.plg_crm_pipeline_stages t
|
|
11651
|
+
SET code = CASE WHEN g.dup = 1 THEN g.base ELSE g.base || '-' || g.dup END
|
|
11652
|
+
FROM slugged g
|
|
11653
|
+
WHERE t.id = g.id;
|
|
11654
|
+
|
|
11655
|
+
ALTER TABLE public.plg_crm_pipeline_stages
|
|
11656
|
+
ALTER COLUMN code SET NOT NULL;
|
|
11657
|
+
|
|
11658
|
+
DO $$ BEGIN
|
|
11659
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_pipeline_stages_code_key') THEN
|
|
11660
|
+
ALTER TABLE ONLY public.plg_crm_pipeline_stages
|
|
11661
|
+
ADD CONSTRAINT plg_crm_pipeline_stages_code_key UNIQUE (pipeline_id, code);
|
|
11662
|
+
END IF;
|
|
11663
|
+
-- Ganhar e perder ao mesmo tempo n\xE3o \xE9 um desfecho. \`deriveLeadStatus\` l\xEA
|
|
11664
|
+
-- \`isWon\` primeiro, ent\xE3o uma etapa com os dois marcados se comportaria como
|
|
11665
|
+
-- ganho e se leria na tela como perda.
|
|
11666
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_pipeline_stages_not_both') THEN
|
|
11667
|
+
ALTER TABLE public.plg_crm_pipeline_stages
|
|
11668
|
+
ADD CONSTRAINT plg_crm_pipeline_stages_not_both CHECK (NOT (is_won AND is_lost));
|
|
11669
|
+
END IF;
|
|
11670
|
+
END $$;
|
|
11671
|
+
|
|
11672
|
+
-- A inicial de cada funil: a mesma que o cliente vinha inferindo, gravada uma
|
|
11673
|
+
-- vez. S\xF3 onde ningu\xE9m marcou ainda \u2014 rodar de novo n\xE3o mexe em escolha feita.
|
|
11674
|
+
WITH first_open AS (
|
|
11675
|
+
SELECT DISTINCT ON (s.pipeline_id) s.id, s.pipeline_id
|
|
11676
|
+
FROM public.plg_crm_pipeline_stages s
|
|
11677
|
+
WHERE NOT s.is_won AND NOT s.is_lost
|
|
11678
|
+
ORDER BY s.pipeline_id, s."order", s.created_at
|
|
11679
|
+
)
|
|
11680
|
+
UPDATE public.plg_crm_pipeline_stages t
|
|
11681
|
+
SET is_initial = true
|
|
11682
|
+
FROM first_open f
|
|
11683
|
+
WHERE t.id = f.id
|
|
11684
|
+
AND NOT EXISTS (
|
|
11685
|
+
SELECT 1 FROM public.plg_crm_pipeline_stages x
|
|
11686
|
+
WHERE x.pipeline_id = t.pipeline_id AND x.is_initial);
|
|
11687
|
+
|
|
11688
|
+
-- UMA entrada por funil. \xCDndice parcial e n\xE3o CHECK: a regra \xE9 entre linhas.
|
|
11689
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_plg_crm_stage_one_initial
|
|
11690
|
+
ON public.plg_crm_pipeline_stages (pipeline_id) WHERE is_initial;
|
|
11691
|
+
|
|
11692
|
+
-- Etapa que nasce sem c\xF3digo ganha um. A tela manda o c\xF3digo, mas uma
|
|
11693
|
+
-- importa\xE7\xE3o, um seed ou um \`insert\` de agente n\xE3o mandam \u2014 e uma etapa sem
|
|
11694
|
+
-- c\xF3digo \xE9 uma etapa que nenhuma automa\xE7\xE3o consegue nomear.
|
|
11695
|
+
CREATE OR REPLACE FUNCTION public.trg_crm_stage_code()
|
|
11696
|
+
RETURNS trigger
|
|
11697
|
+
LANGUAGE plpgsql
|
|
11698
|
+
SET search_path TO ''
|
|
11699
|
+
AS $$
|
|
11700
|
+
DECLARE v_base text; v_try text; v_n integer := 1;
|
|
11701
|
+
BEGIN
|
|
11702
|
+
IF NEW.code IS NOT NULL AND btrim(NEW.code) <> '' THEN
|
|
11703
|
+
NEW.code := public.crm_slug(NEW.code);
|
|
11704
|
+
IF NEW.code IS NULL THEN NEW.code := 'etapa'; END IF;
|
|
11705
|
+
RETURN NEW;
|
|
11706
|
+
END IF;
|
|
11707
|
+
v_base := coalesce(public.crm_slug(NEW.name), 'etapa');
|
|
11708
|
+
v_try := v_base;
|
|
11709
|
+
WHILE EXISTS (SELECT 1 FROM public.plg_crm_pipeline_stages s
|
|
11710
|
+
WHERE s.pipeline_id = NEW.pipeline_id AND s.code = v_try
|
|
11711
|
+
AND s.id IS DISTINCT FROM NEW.id) LOOP
|
|
11712
|
+
v_n := v_n + 1;
|
|
11713
|
+
v_try := v_base || '-' || v_n;
|
|
11714
|
+
END LOOP;
|
|
11715
|
+
NEW.code := v_try;
|
|
11716
|
+
RETURN NEW;
|
|
11717
|
+
END $$;
|
|
11718
|
+
|
|
11719
|
+
DROP TRIGGER IF EXISTS plg_crm_stage_code ON public.plg_crm_pipeline_stages;
|
|
11720
|
+
CREATE TRIGGER plg_crm_stage_code
|
|
11721
|
+
BEFORE INSERT OR UPDATE OF code, name ON public.plg_crm_pipeline_stages
|
|
11722
|
+
FOR EACH ROW
|
|
11723
|
+
EXECUTE FUNCTION public.trg_crm_stage_code();
|
|
11724
|
+
|
|
11725
|
+
COMMENT ON FUNCTION public.trg_crm_stage_code() IS
|
|
11726
|
+
'Garante c\xF3digo \xE0 etapa que nasce sem. Renomear N\xC3O regera o c\xF3digo de quem j\xE1 tem \u2014 \xE9 o que faz o c\xF3digo ser est\xE1vel (005).';
|
|
11727
|
+
`;
|
|
11728
|
+
var MIGRATION_006_A_ESCADA_DO_RELACIONAMENTO = `-- 006_a_escada_do_relacionamento.sql
|
|
11729
|
+
--
|
|
11730
|
+
-- O V1 tem um eixo de est\xE1gio no cadastro do cliente \u2014 Lead, Prospect,
|
|
11731
|
+
-- Oportunidade, Cliente, Inativo \u2014 e quatro itens de menu que o recortam. O
|
|
11732
|
+
-- eixo \xE9 um CAMPO: algu\xE9m digita, algu\xE9m esquece. O resultado est\xE1 na captura
|
|
11733
|
+
-- do pr\xF3prio guia: **795 leads e 0 clientes ativos**, numa casa com receita no
|
|
11734
|
+
-- m\xEAs. N\xE3o \xE9 que a casa n\xE3o tenha cliente; \xE9 que ningu\xE9m foi promover 795
|
|
11735
|
+
-- fichas \xE0 m\xE3o.
|
|
11736
|
+
--
|
|
11737
|
+
-- Por isso aqui o est\xE1gio \xE9 DERIVADO. Ningu\xE9m digita "ativo": a pessoa \xE9 ativa
|
|
11738
|
+
-- porque comprou/atendeu-se dentro da janela que a casa considera ativa. N\xE3o h\xE1
|
|
11739
|
+
-- campo para esquecer, n\xE3o h\xE1 mutir\xE3o de arruma\xE7\xE3o, e o n\xFAmero da tela n\xE3o pode
|
|
11740
|
+
-- discordar do hist\xF3rico \u2014 ele \xC9 o hist\xF3rico.
|
|
11741
|
+
--
|
|
11742
|
+
-- A ESCADA \xC9 A MESMA NOS DOIS IRM\xC3OS; OS DEGRAUS, N\xC3O. Noventa dias sem
|
|
11743
|
+
-- aparecer \xE9 rotina num sal\xE3o e \xE9 quase um cliente perdido num delivery. Por
|
|
11744
|
+
-- isso os limites s\xE3o por casa (\`plg_crm_engagement_settings\`) e a view os l\xEA
|
|
11745
|
+
-- com COALESCE para o padr\xE3o: quem nunca abriu a tela de configura\xE7\xE3o tem
|
|
11746
|
+
-- 30/90/180, e quem abriu manda.
|
|
11747
|
+
--
|
|
11748
|
+
-- DUAS ARMADILHAS DOS DADOS, ACHADAS OLHANDO O CLUSTER E N\xC3O O C\xD3DIGO:
|
|
11749
|
+
--
|
|
11750
|
+
-- 1. \`completed_at\` N\xC3O quer dizer que aconteceu. H\xE1 166 vendas com status
|
|
11751
|
+
-- 'cancelled' e \`completed_at\` preenchido. Contar por \`completed_at IS NOT
|
|
11752
|
+
-- NULL\` faria a venda cancelada manter o cliente "ativo" \u2014 o filtro \xE9 pelo
|
|
11753
|
+
-- STATUS.
|
|
11754
|
+
-- 2. \`direction\` n\xE3o separa venda de compra: 8.278 das 8.311 vendas est\xE3o com
|
|
11755
|
+
-- ele nulo. Quem separa \xE9 \`kind\`, e por isso a lista de esp\xE9cies que contam
|
|
11756
|
+
-- \xE9 expl\xEDcita: esp\xE9cie nova n\xE3o entra na conta por acidente. \`purchase\` fica
|
|
11757
|
+
-- de fora de prop\xF3sito \u2014 comprar do fornecedor n\xE3o \xE9 o cliente aparecendo.
|
|
11758
|
+
|
|
11759
|
+
-- \u2500\u2500 os degraus, por casa \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11760
|
+
CREATE TABLE IF NOT EXISTS public.plg_crm_engagement_settings (
|
|
11761
|
+
tenant_id uuid NOT NULL,
|
|
11762
|
+
-- Rec\xE9m-chegado: o primeiro atendimento foi h\xE1 menos que isto.
|
|
11763
|
+
new_days integer DEFAULT 30 NOT NULL,
|
|
11764
|
+
-- Ativo: apareceu dentro desta janela.
|
|
11765
|
+
active_days integer DEFAULT 90 NOT NULL,
|
|
11766
|
+
-- Em risco at\xE9 aqui; passou disto, est\xE1 parado.
|
|
11767
|
+
at_risk_days integer DEFAULT 180 NOT NULL,
|
|
11768
|
+
updated_by uuid,
|
|
11769
|
+
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
11770
|
+
CONSTRAINT plg_crm_engagement_settings_pkey PRIMARY KEY (tenant_id),
|
|
11771
|
+
-- A escada tem de subir. Sem isto, \`active_days\` maior que \`at_risk_days\`
|
|
11772
|
+
-- produz uma faixa "em risco" vazia e ningu\xE9m entende por que o n\xFAmero
|
|
11773
|
+
-- ficou zero.
|
|
11774
|
+
CONSTRAINT plg_crm_engagement_settings_ladder
|
|
11775
|
+
CHECK (new_days > 0 AND active_days > new_days AND at_risk_days > active_days)
|
|
11776
|
+
);
|
|
11777
|
+
|
|
11778
|
+
ALTER TABLE public.plg_crm_engagement_settings FORCE ROW LEVEL SECURITY;
|
|
11779
|
+
|
|
11780
|
+
DO $$ BEGIN
|
|
11781
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_engagement_settings_tenant_fkey') THEN
|
|
11782
|
+
ALTER TABLE ONLY public.plg_crm_engagement_settings
|
|
11783
|
+
ADD CONSTRAINT plg_crm_engagement_settings_tenant_fkey FOREIGN KEY (tenant_id)
|
|
11784
|
+
REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
11785
|
+
END IF;
|
|
11786
|
+
END $$;
|
|
11787
|
+
|
|
11788
|
+
COMMENT ON TABLE public.plg_crm_engagement_settings IS
|
|
11789
|
+
'Os degraus da escada de relacionamento, por casa. 90 dias sem aparecer \xE9 rotina num sal\xE3o e quase perda num delivery (006).';
|
|
11790
|
+
|
|
11791
|
+
ALTER TABLE public.plg_crm_engagement_settings ENABLE ROW LEVEL SECURITY;
|
|
11792
|
+
|
|
11793
|
+
DROP POLICY IF EXISTS plg_crm_engagement_settings_authz_select ON public.plg_crm_engagement_settings;
|
|
11794
|
+
CREATE POLICY plg_crm_engagement_settings_authz_select ON public.plg_crm_engagement_settings
|
|
11795
|
+
FOR SELECT TO authenticated USING (
|
|
11796
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11797
|
+
AND (SELECT app.has_permission('sales.read', NULL::uuid)));
|
|
11798
|
+
|
|
11799
|
+
DROP POLICY IF EXISTS plg_crm_engagement_settings_authz_insert ON public.plg_crm_engagement_settings;
|
|
11800
|
+
CREATE POLICY plg_crm_engagement_settings_authz_insert ON public.plg_crm_engagement_settings
|
|
11801
|
+
FOR INSERT TO authenticated WITH CHECK (
|
|
11802
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11803
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11804
|
+
|
|
11805
|
+
DROP POLICY IF EXISTS plg_crm_engagement_settings_authz_update ON public.plg_crm_engagement_settings;
|
|
11806
|
+
CREATE POLICY plg_crm_engagement_settings_authz_update ON public.plg_crm_engagement_settings
|
|
11807
|
+
FOR UPDATE TO authenticated USING (
|
|
11808
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11809
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
|
|
11810
|
+
WITH CHECK (
|
|
11811
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
11812
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
11813
|
+
|
|
11814
|
+
GRANT SELECT, INSERT, UPDATE ON public.plg_crm_engagement_settings TO authenticated;
|
|
11815
|
+
GRANT ALL ON public.plg_crm_engagement_settings TO service_role;
|
|
11816
|
+
|
|
11817
|
+
INSERT INTO app.scaffold_registry
|
|
11818
|
+
(table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)
|
|
11819
|
+
VALUES
|
|
11820
|
+
('public', 'plg_crm_engagement_settings', 'crm.engagement_settings', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)
|
|
11821
|
+
ON CONFLICT DO NOTHING;
|
|
11822
|
+
|
|
11823
|
+
-- \u2500\u2500 a leitura \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11824
|
+
--
|
|
11825
|
+
-- \`security_invoker\` porque uma view sem ele roda com os direitos de QUEM A
|
|
11826
|
+
-- CRIOU e ignora a RLS de quem a l\xEA \u2014 foi assim que views vazaram entre tenants
|
|
11827
|
+
-- neste repo antes.
|
|
11828
|
+
--
|
|
11829
|
+
-- Uma linha por pessoa, com o que a escada precisa e nada al\xE9m: quem quer a
|
|
11830
|
+
-- ficha busca em \`people\`, que \xE9 onde ela mora.
|
|
11831
|
+
CREATE OR REPLACE VIEW public.v_crm_person_engagement WITH (security_invoker='true') AS
|
|
11832
|
+
WITH cfg AS (
|
|
11833
|
+
SELECT t.id AS tenant_id,
|
|
11834
|
+
coalesce(e.new_days, 30) AS new_days,
|
|
11835
|
+
coalesce(e.active_days, 90) AS active_days,
|
|
11836
|
+
coalesce(e.at_risk_days, 180) AS at_risk_days
|
|
11837
|
+
FROM public.tenants t
|
|
11838
|
+
LEFT JOIN public.plg_crm_engagement_settings e ON e.tenant_id = t.id
|
|
11839
|
+
),
|
|
11840
|
+
visits AS (
|
|
11841
|
+
SELECT o.tenant_id,
|
|
11842
|
+
o.party_id AS person_id,
|
|
11843
|
+
min(o.completed_at) AS first_at,
|
|
11844
|
+
max(o.completed_at) AS last_at,
|
|
11845
|
+
count(*) AS visits,
|
|
11846
|
+
sum(o.total) AS total_value
|
|
11847
|
+
FROM public.orders o
|
|
11848
|
+
WHERE o.party_id IS NOT NULL
|
|
11849
|
+
-- Pelo STATUS, n\xE3o por \`completed_at\`: h\xE1 venda cancelada com
|
|
11850
|
+
-- \`completed_at\` preenchido, e cont\xE1-la manteria o cliente "ativo" por
|
|
11851
|
+
-- causa de uma compra que n\xE3o houve.
|
|
11852
|
+
AND o.status = 'completed'
|
|
11853
|
+
-- Lista expl\xEDcita: esp\xE9cie nova n\xE3o entra na conta por acidente.
|
|
11854
|
+
-- \`purchase\` fora \u2014 comprar do fornecedor n\xE3o \xE9 o cliente aparecendo.
|
|
11855
|
+
AND o.kind = ANY (ARRAY['sale', 'dine_in', 'takeout', 'delivery', 'appointment', 'service_order'])
|
|
11856
|
+
GROUP BY o.tenant_id, o.party_id
|
|
11857
|
+
)
|
|
11858
|
+
SELECT
|
|
11859
|
+
p.id AS person_id,
|
|
11860
|
+
p.tenant_id,
|
|
11861
|
+
p.unit_id,
|
|
11862
|
+
p.name,
|
|
11863
|
+
p.kind,
|
|
11864
|
+
v.first_at,
|
|
11865
|
+
v.last_at,
|
|
11866
|
+
coalesce(v.visits, 0)::bigint AS visits,
|
|
11867
|
+
coalesce(v.total_value, 0)::numeric AS total_value,
|
|
11868
|
+
CASE WHEN v.visits > 0 THEN round(v.total_value / v.visits, 2) END AS avg_value,
|
|
11869
|
+
CASE WHEN v.last_at IS NOT NULL
|
|
11870
|
+
THEN floor(EXTRACT(epoch FROM (now() - v.last_at)) / 86400)::integer END AS days_since_last,
|
|
11871
|
+
-- A ESCADA. A ordem dos ramos \xE9 a regra: rec\xE9m-chegado ganha de ativo nos
|
|
11872
|
+
-- primeiros dias porque \xE9 a informa\xE7\xE3o mais \xFAtil ali \u2014 depois ele vira ativo
|
|
11873
|
+
-- sozinho, sem ningu\xE9m tocar em nada.
|
|
11874
|
+
CASE
|
|
11875
|
+
WHEN v.last_at IS NULL AND p.kind = 'lead' THEN 'lead'
|
|
11876
|
+
WHEN v.last_at IS NULL THEN 'prospect'
|
|
11877
|
+
WHEN v.first_at >= now() - make_interval(days => c.new_days) THEN 'new'
|
|
11878
|
+
WHEN v.last_at >= now() - make_interval(days => c.active_days) THEN 'active'
|
|
11879
|
+
WHEN v.last_at >= now() - make_interval(days => c.at_risk_days) THEN 'at_risk'
|
|
11880
|
+
ELSE 'dormant'
|
|
11881
|
+
END AS lifecycle
|
|
11882
|
+
FROM public.people p
|
|
11883
|
+
JOIN cfg c ON c.tenant_id = p.tenant_id
|
|
11884
|
+
LEFT JOIN visits v ON v.person_id = p.id AND v.tenant_id = p.tenant_id
|
|
11885
|
+
WHERE p.merged_into_id IS NULL;
|
|
11886
|
+
|
|
11887
|
+
COMMENT ON VIEW public.v_crm_person_engagement IS
|
|
11888
|
+
'Rec\xEAncia, frequ\xEAncia, valor e o degrau da escada, por pessoa. O degrau \xE9 DERIVADO: no V1 \xE9 campo digitado, e a captura do guia dele mostra 795 leads com 0 clientes ativos numa casa faturando (006).';
|
|
11889
|
+
|
|
11890
|
+
GRANT SELECT ON public.v_crm_person_engagement TO authenticated;
|
|
11891
|
+
GRANT SELECT ON public.v_crm_person_engagement TO service_role;
|
|
11892
|
+
|
|
11893
|
+
-- \u2500\u2500 o resumo, para o painel \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
11894
|
+
--
|
|
11895
|
+
-- Quantos em cada degrau, mais as duas perguntas que o painel do V1 faz e n\xE3o
|
|
11896
|
+
-- responde: quantos voltaram no m\xEAs (reten\xE7\xE3o) e quantos voltaram DEPOIS de
|
|
11897
|
+
-- terem sumido (reativa\xE7\xE3o). A segunda \xE9 a que paga campanha.
|
|
11898
|
+
CREATE OR REPLACE FUNCTION public.crm_engagement_summary()
|
|
11899
|
+
RETURNS jsonb
|
|
11900
|
+
LANGUAGE plpgsql
|
|
11901
|
+
SECURITY DEFINER
|
|
11902
|
+
STABLE
|
|
11903
|
+
SET search_path TO ''
|
|
11904
|
+
AS $$
|
|
11905
|
+
DECLARE
|
|
11906
|
+
v_tenant uuid := app.current_tenant_id();
|
|
11907
|
+
v_cfg record;
|
|
11908
|
+
v_out jsonb;
|
|
11909
|
+
BEGIN
|
|
11910
|
+
IF v_tenant IS NULL THEN
|
|
11911
|
+
RAISE EXCEPTION 'crm_engagement_summary: sem tenant na sess\xE3o' USING ERRCODE = '42501';
|
|
11912
|
+
END IF;
|
|
11913
|
+
IF NOT app.has_permission('sales.read', NULL::uuid) THEN
|
|
11914
|
+
RAISE EXCEPTION 'crm_engagement_summary: exige sales.read' USING ERRCODE = '42501';
|
|
11915
|
+
END IF;
|
|
11916
|
+
|
|
11917
|
+
SELECT coalesce(e.new_days, 30) AS new_days,
|
|
11918
|
+
coalesce(e.active_days, 90) AS active_days,
|
|
11919
|
+
coalesce(e.at_risk_days, 180) AS at_risk_days
|
|
11920
|
+
INTO v_cfg
|
|
11921
|
+
FROM public.tenants t
|
|
11922
|
+
LEFT JOIN public.plg_crm_engagement_settings e ON e.tenant_id = t.id
|
|
11923
|
+
WHERE t.id = v_tenant;
|
|
11924
|
+
|
|
11925
|
+
SELECT jsonb_build_object(
|
|
11926
|
+
'lead', count(*) FILTER (WHERE g.lifecycle = 'lead'),
|
|
11927
|
+
'prospect', count(*) FILTER (WHERE g.lifecycle = 'prospect'),
|
|
11928
|
+
'new', count(*) FILTER (WHERE g.lifecycle = 'new'),
|
|
11929
|
+
'active', count(*) FILTER (WHERE g.lifecycle = 'active'),
|
|
11930
|
+
'at_risk', count(*) FILTER (WHERE g.lifecycle = 'at_risk'),
|
|
11931
|
+
'dormant', count(*) FILTER (WHERE g.lifecycle = 'dormant'),
|
|
11932
|
+
'people', count(*),
|
|
11933
|
+
-- Reten\xE7\xE3o: dos que j\xE1 tinham aparecido ANTES da janela, quantos
|
|
11934
|
+
-- apareceram DENTRO dela. Quem veio s\xF3 uma vez n\xE3o entra no denominador \u2014
|
|
11935
|
+
-- ele n\xE3o tinha como "voltar".
|
|
11936
|
+
'returned', count(*) FILTER (WHERE g.visits > 1 AND g.days_since_last <= v_cfg.active_days),
|
|
11937
|
+
'returnable', count(*) FILTER (WHERE g.visits > 1),
|
|
11938
|
+
'settings', jsonb_build_object(
|
|
11939
|
+
'newDays', v_cfg.new_days, 'activeDays', v_cfg.active_days, 'atRiskDays', v_cfg.at_risk_days)
|
|
11940
|
+
) INTO v_out
|
|
11941
|
+
FROM public.v_crm_person_engagement g
|
|
11942
|
+
WHERE g.tenant_id = v_tenant;
|
|
11943
|
+
|
|
11944
|
+
RETURN v_out;
|
|
11945
|
+
END $$;
|
|
11946
|
+
|
|
11947
|
+
COMMENT ON FUNCTION public.crm_engagement_summary() IS
|
|
11948
|
+
'Quantos em cada degrau da escada, mais reten\xE7\xE3o. Uma chamada \u2014 o painel n\xE3o pergunta seis vezes (006).';
|
|
11949
|
+
|
|
11950
|
+
REVOKE ALL ON FUNCTION public.crm_engagement_summary() FROM PUBLIC, anon;
|
|
11951
|
+
GRANT EXECUTE ON FUNCTION public.crm_engagement_summary() TO authenticated;
|
|
11952
|
+
GRANT EXECUTE ON FUNCTION public.crm_engagement_summary() TO service_role;
|
|
11953
|
+
`;
|
|
11954
|
+
var MIGRATION_008_A_REGUA_DA_REDE_E_PUBLICA = `-- 008_a_regua_da_rede_e_publica.sql
|
|
11955
|
+
--
|
|
11956
|
+
-- O V1 tem duas telas de rede \u2014 Dashboard Operacional (ranking e indicadores
|
|
11957
|
+
-- por unidade) e Maturidade Operacional (nota 0\u2013100 por unidade). O documento
|
|
11958
|
+
-- do porte diz que o V2 "ainda n\xE3o tem o conceito de rede"; **est\xE1
|
|
11959
|
+
-- desatualizado**: as unidades existem, e o Espa\xE7o Facial tem 65 delas no
|
|
11960
|
+
-- cluster hoje.
|
|
11961
|
+
--
|
|
11962
|
+
-- O QUE VALE A PENA COPIAR DO V1, e o pr\xF3prio guia dele aponta: **a r\xE9gua \xE9
|
|
11963
|
+
-- p\xFAblica**. Os pesos de cada dimens\xE3o aparecem na mesma tela em que a nota \xE9
|
|
11964
|
+
-- mostrada. Um score comparativo s\xF3 \xE9 aceito por quem \xE9 comparado quando d\xE1
|
|
11965
|
+
-- para ler como ele foi feito.
|
|
11966
|
+
--
|
|
11967
|
+
-- O QUE N\xC3O VALE: os pesos serem FIXOS. No V1 n\xE3o h\xE1 campo para edit\xE1-los \u2014 \xE9 a
|
|
11968
|
+
-- r\xE9gua do franqueador, igual para toda a rede, e a FAQ do pr\xF3prio guia
|
|
11969
|
+
-- registra a pergunta "posso mudar os pesos?". Aqui eles s\xE3o por casa: um
|
|
11970
|
+
-- delivery e um sal\xE3o n\xE3o pesam ocupa\xE7\xE3o do mesmo jeito.
|
|
11971
|
+
--
|
|
11972
|
+
-- A DECIS\xC3O QUE MAIS MUDA O N\xDAMERO: dimens\xE3o SEM DADO n\xE3o vale zero.
|
|
11973
|
+
--
|
|
11974
|
+
-- O V1 mede sete dimens\xF5es. O V2 mede cinco com honestidade hoje \u2014 as outras
|
|
11975
|
+
-- duas (ocupa\xE7\xE3o e financeiro) dependem de fontes que este plugin n\xE3o tem. A
|
|
11976
|
+
-- sa\xEDda f\xE1cil seria cont\xE1-las como 0, e ela est\xE1 errada: uma casa sem agenda
|
|
11977
|
+
-- instalada apareceria com nota baixa por FALTA DE DADO, indistingu\xEDvel de uma
|
|
11978
|
+
-- casa com agenda vazia. Aqui a dimens\xE3o sem fonte sai do c\xE1lculo e os pesos
|
|
11979
|
+
-- restantes s\xE3o RENORMALIZADOS \u2014 a nota diz "de tudo o que d\xE1 para medir, esta
|
|
11980
|
+
-- casa est\xE1 em 72", que \xE9 uma frase verdadeira.
|
|
11981
|
+
|
|
11982
|
+
CREATE TABLE IF NOT EXISTS public.plg_crm_scorecard_weights (
|
|
11983
|
+
tenant_id uuid NOT NULL,
|
|
11984
|
+
dimension text NOT NULL,
|
|
11985
|
+
weight numeric(5,2) NOT NULL,
|
|
11986
|
+
updated_at timestamp with time zone DEFAULT now() NOT NULL,
|
|
11987
|
+
CONSTRAINT plg_crm_scorecard_weights_pkey PRIMARY KEY (tenant_id, dimension),
|
|
11988
|
+
CONSTRAINT plg_crm_scorecard_weights_dimension CHECK (
|
|
11989
|
+
dimension = ANY (ARRAY['conversion','retention','reactivation','productivity','satisfaction','speed','occupancy','financial'])),
|
|
11990
|
+
CONSTRAINT plg_crm_scorecard_weights_range CHECK (weight >= 0 AND weight <= 100)
|
|
11991
|
+
);
|
|
11992
|
+
|
|
11993
|
+
ALTER TABLE public.plg_crm_scorecard_weights FORCE ROW LEVEL SECURITY;
|
|
11994
|
+
|
|
11995
|
+
DO $$ BEGIN
|
|
11996
|
+
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'plg_crm_scorecard_weights_tenant_fkey') THEN
|
|
11997
|
+
ALTER TABLE ONLY public.plg_crm_scorecard_weights
|
|
11998
|
+
ADD CONSTRAINT plg_crm_scorecard_weights_tenant_fkey FOREIGN KEY (tenant_id)
|
|
11999
|
+
REFERENCES public.tenants(id) ON DELETE CASCADE;
|
|
12000
|
+
END IF;
|
|
12001
|
+
END $$;
|
|
12002
|
+
|
|
12003
|
+
COMMENT ON TABLE public.plg_crm_scorecard_weights IS
|
|
12004
|
+
'O peso de cada dimens\xE3o da nota, POR CASA. No V1 os pesos s\xE3o fixos e a FAQ dele registra a pergunta de quem queria mud\xE1-los (008).';
|
|
12005
|
+
|
|
12006
|
+
ALTER TABLE public.plg_crm_scorecard_weights ENABLE ROW LEVEL SECURITY;
|
|
12007
|
+
|
|
12008
|
+
DROP POLICY IF EXISTS plg_crm_scorecard_weights_authz_select ON public.plg_crm_scorecard_weights;
|
|
12009
|
+
CREATE POLICY plg_crm_scorecard_weights_authz_select ON public.plg_crm_scorecard_weights
|
|
12010
|
+
FOR SELECT TO authenticated USING (
|
|
12011
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
12012
|
+
AND (SELECT app.has_permission('sales.read', NULL::uuid)));
|
|
12013
|
+
|
|
12014
|
+
DROP POLICY IF EXISTS plg_crm_scorecard_weights_authz_write ON public.plg_crm_scorecard_weights;
|
|
12015
|
+
CREATE POLICY plg_crm_scorecard_weights_authz_write ON public.plg_crm_scorecard_weights
|
|
12016
|
+
FOR ALL TO authenticated USING (
|
|
12017
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
12018
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)))
|
|
12019
|
+
WITH CHECK (
|
|
12020
|
+
tenant_id = (SELECT app.current_tenant_id())
|
|
12021
|
+
AND (SELECT app.has_permission('sales.edit', NULL::uuid)));
|
|
12022
|
+
|
|
12023
|
+
GRANT SELECT, INSERT, UPDATE, DELETE ON public.plg_crm_scorecard_weights TO authenticated;
|
|
12024
|
+
GRANT ALL ON public.plg_crm_scorecard_weights TO service_role;
|
|
12025
|
+
|
|
12026
|
+
INSERT INTO app.scaffold_registry
|
|
12027
|
+
(table_schema, table_name, resource_type, plugin, owner_scoping, mode, previous_policies, audit_hook, scope, distributable)
|
|
12028
|
+
VALUES
|
|
12029
|
+
('public', 'plg_crm_scorecard_weights', 'crm.scorecard_weight', 'crm', false, 'enforce', ARRAY[]::text[], false, 'tenant', false)
|
|
12030
|
+
ON CONFLICT DO NOTHING;
|
|
12031
|
+
|
|
12032
|
+
-- \u2500\u2500 o placar da rede \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
12033
|
+
--
|
|
12034
|
+
-- Uma linha por unidade, com as dimens\xF5es medidas e a nota. Devolve NULO na
|
|
12035
|
+
-- dimens\xE3o sem fonte \u2014 e \xE9 o cliente que soma, com os pesos renormalizados
|
|
12036
|
+
-- sobre o que veio preenchido.
|
|
12037
|
+
--
|
|
12038
|
+
-- Cada dimens\xE3o \xE9 0\u2013100 de prop\xF3sito, inclusive satisfa\xE7\xE3o. O V1 acerta nisso:
|
|
12039
|
+
-- misturar uma escala \u2212100..100 (NPS) com percentuais na mesma linha faz a
|
|
12040
|
+
-- m\xE9dia ponderada mentir.
|
|
12041
|
+
CREATE OR REPLACE FUNCTION public.crm_unit_scorecard(
|
|
12042
|
+
p_from timestamp with time zone DEFAULT now() - interval '90 days',
|
|
12043
|
+
p_to timestamp with time zone DEFAULT now()
|
|
12044
|
+
) RETURNS TABLE(
|
|
12045
|
+
unit_id uuid,
|
|
12046
|
+
unit_name text,
|
|
12047
|
+
orders_count bigint,
|
|
12048
|
+
revenue numeric,
|
|
12049
|
+
people_count bigint,
|
|
12050
|
+
conversion numeric,
|
|
12051
|
+
retention numeric,
|
|
12052
|
+
reactivation numeric,
|
|
12053
|
+
productivity numeric,
|
|
12054
|
+
satisfaction numeric
|
|
12055
|
+
)
|
|
12056
|
+
LANGUAGE plpgsql
|
|
12057
|
+
SECURITY DEFINER
|
|
12058
|
+
STABLE
|
|
12059
|
+
SET search_path TO ''
|
|
12060
|
+
AS $$
|
|
12061
|
+
DECLARE v_tenant uuid := app.current_tenant_id();
|
|
12062
|
+
BEGIN
|
|
12063
|
+
IF v_tenant IS NULL THEN
|
|
12064
|
+
RAISE EXCEPTION 'crm_unit_scorecard: sem tenant na sess\xE3o' USING ERRCODE = '42501';
|
|
12065
|
+
END IF;
|
|
12066
|
+
IF NOT app.has_permission('sales.read', NULL::uuid) THEN
|
|
12067
|
+
RAISE EXCEPTION 'crm_unit_scorecard: exige sales.read' USING ERRCODE = '42501';
|
|
12068
|
+
END IF;
|
|
12069
|
+
|
|
12070
|
+
RETURN QUERY
|
|
12071
|
+
WITH un AS (
|
|
12072
|
+
SELECT u.id, u.name FROM app.units u WHERE u.tenant_id = v_tenant
|
|
12073
|
+
),
|
|
12074
|
+
-- PESSOA N\xC3O PERTENCE A UMA UNIDADE \u2014 ELA VISITA UNIDADES.
|
|
12075
|
+
--
|
|
12076
|
+
-- A primeira vers\xE3o desta fun\xE7\xE3o agrupava por \`people.unit_id\`, e no cluster
|
|
12077
|
+
-- ela devolveu reten\xE7\xE3o, reativa\xE7\xE3o e convers\xE3o NULAS at\xE9 para a unidade com
|
|
12078
|
+
-- 5.111 pedidos: os pedidos t\xEAm unidade, as fichas n\xE3o. N\xE3o era falta de
|
|
12079
|
+
-- dado \u2014 era o modelo errado. Numa rede, o cliente \xE9 da REDE e frequenta uma
|
|
12080
|
+
-- loja; amarr\xE1-lo a uma delas obrigaria a escolher uma resposta para quem
|
|
12081
|
+
-- passa em duas.
|
|
12082
|
+
--
|
|
12083
|
+
-- A unidade de uma pessoa \xE9, ent\xE3o, a da \xDALTIMA vez que ela apareceu. \xC9 a
|
|
12084
|
+
-- leitura que o franqueado reconhece: "esse cliente \xE9 meu porque foi aqui que
|
|
12085
|
+
-- ele veio da \xFAltima vez".
|
|
12086
|
+
person_unit AS (
|
|
12087
|
+
SELECT DISTINCT ON (o.party_id) o.party_id AS person_id, o.unit_id
|
|
12088
|
+
FROM public.orders o
|
|
12089
|
+
WHERE o.tenant_id = v_tenant AND o.status = 'completed' AND o.unit_id IS NOT NULL
|
|
12090
|
+
AND o.kind = ANY (ARRAY['sale','dine_in','takeout','delivery','appointment','service_order'])
|
|
12091
|
+
ORDER BY o.party_id, o.completed_at DESC
|
|
12092
|
+
),
|
|
12093
|
+
sales AS (
|
|
12094
|
+
-- Mesma lista de esp\xE9cies e o mesmo filtro por STATUS da 006: venda
|
|
12095
|
+
-- cancelada tem \`completed_at\` preenchido e n\xE3o pode contar.
|
|
12096
|
+
SELECT o.unit_id, count(*) AS n, sum(o.total) AS revenue,
|
|
12097
|
+
count(DISTINCT o.assignee_id) FILTER (WHERE o.assignee_id IS NOT NULL) AS people
|
|
12098
|
+
FROM public.orders o
|
|
12099
|
+
WHERE o.tenant_id = v_tenant AND o.status = 'completed'
|
|
12100
|
+
AND o.completed_at >= p_from AND o.completed_at < p_to
|
|
12101
|
+
AND o.kind = ANY (ARRAY['sale','dine_in','takeout','delivery','appointment','service_order'])
|
|
12102
|
+
GROUP BY o.unit_id
|
|
12103
|
+
),
|
|
12104
|
+
leads AS (
|
|
12105
|
+
-- A unidade da ficha quando ela tem; sen\xE3o a da \xFAltima visita. Um lead que
|
|
12106
|
+
-- nunca apareceu e n\xE3o tem unidade fica fora da convers\xE3o de todo mundo \u2014
|
|
12107
|
+
-- e \xE9 o certo: ningu\xE9m deixou de converter quem n\xE3o era de ningu\xE9m.
|
|
12108
|
+
SELECT coalesce(p.unit_id, pu.unit_id) AS unit_id, count(*) AS n
|
|
12109
|
+
FROM public.people p
|
|
12110
|
+
LEFT JOIN person_unit pu ON pu.person_id = p.id
|
|
12111
|
+
WHERE p.tenant_id = v_tenant AND p.kind = 'lead'
|
|
12112
|
+
AND p.created_at >= p_from AND p.created_at < p_to
|
|
12113
|
+
AND coalesce(p.unit_id, pu.unit_id) IS NOT NULL
|
|
12114
|
+
GROUP BY coalesce(p.unit_id, pu.unit_id)
|
|
12115
|
+
),
|
|
12116
|
+
eng AS (
|
|
12117
|
+
SELECT pu.unit_id,
|
|
12118
|
+
count(*) FILTER (WHERE g.visits > 1) AS returnable,
|
|
12119
|
+
count(*) FILTER (WHERE g.visits > 1 AND g.lifecycle IN ('active','new')) AS returned,
|
|
12120
|
+
-- Reativa\xE7\xE3o \xE9 indicador PR\xD3PRIO, e o V1 acerta ao separ\xE1-la:
|
|
12121
|
+
-- trazer de volta quem sumiu n\xE3o \xE9 a mesma coisa que manter quem j\xE1
|
|
12122
|
+
-- vem, e a a\xE7\xE3o de cada uma \xE9 diferente.
|
|
12123
|
+
count(*) FILTER (WHERE g.lifecycle IN ('at_risk','dormant')) AS lapsed
|
|
12124
|
+
FROM public.v_crm_person_engagement g
|
|
12125
|
+
JOIN person_unit pu ON pu.person_id = g.person_id
|
|
12126
|
+
WHERE g.tenant_id = v_tenant
|
|
12127
|
+
GROUP BY pu.unit_id
|
|
12128
|
+
),
|
|
12129
|
+
sat AS (
|
|
12130
|
+
SELECT r.unit_id,
|
|
12131
|
+
-- Estrelas 1\u20135 normalizadas para 0\u2013100, a r\xE9gua do painel do V1.
|
|
12132
|
+
round(avg((a.rating - 1) * 25.0), 1) AS score
|
|
12133
|
+
FROM public.plg_crm_survey_responses r
|
|
12134
|
+
JOIN public.plg_crm_survey_answers a ON a.response_id = r.id
|
|
12135
|
+
WHERE r.tenant_id = v_tenant AND a.rating IS NOT NULL
|
|
12136
|
+
AND r.submitted_at >= p_from AND r.submitted_at < p_to
|
|
12137
|
+
GROUP BY r.unit_id
|
|
12138
|
+
)
|
|
12139
|
+
SELECT
|
|
12140
|
+
un.id, un.name,
|
|
12141
|
+
coalesce(s.n, 0)::bigint,
|
|
12142
|
+
coalesce(s.revenue, 0)::numeric,
|
|
12143
|
+
coalesce(e.returnable, 0)::bigint,
|
|
12144
|
+
-- Convers\xE3o: neg\xF3cio fechado sobre lead que entrou. Sem lead no per\xEDodo a
|
|
12145
|
+
-- resposta \xE9 NULO e n\xE3o 0 \u2014 dividir por zero e chamar de "0% de convers\xE3o"
|
|
12146
|
+
-- acusa de n\xE3o converter quem n\xE3o teve o que converter.
|
|
12147
|
+
CASE WHEN coalesce(l.n, 0) > 0
|
|
12148
|
+
THEN round(least(100, coalesce(s.n, 0)::numeric * 100 / l.n), 1) END,
|
|
12149
|
+
CASE WHEN coalesce(e.returnable, 0) > 0
|
|
12150
|
+
THEN round(e.returned::numeric * 100 / e.returnable, 1) END,
|
|
12151
|
+
CASE WHEN coalesce(e.lapsed, 0) + coalesce(e.returned, 0) > 0
|
|
12152
|
+
THEN round(coalesce(e.returned, 0)::numeric * 100 / (e.lapsed + e.returned), 1) END,
|
|
12153
|
+
-- Produtividade: quanto cada pessoa que atendeu produziu, em rela\xE7\xE3o \xE0
|
|
12154
|
+
-- melhor da rede. \xC9 comparativo de prop\xF3sito \u2014 "R$ 4.200 por atendente" n\xE3o
|
|
12155
|
+
-- diz se \xE9 bom sem algu\xE9m do lado.
|
|
12156
|
+
CASE WHEN coalesce(s.people, 0) > 0 THEN round(s.revenue / s.people, 2) END,
|
|
12157
|
+
sat.score
|
|
12158
|
+
FROM un
|
|
12159
|
+
LEFT JOIN sales s ON s.unit_id = un.id
|
|
12160
|
+
LEFT JOIN leads l ON l.unit_id = un.id
|
|
12161
|
+
LEFT JOIN eng e ON e.unit_id = un.id
|
|
12162
|
+
LEFT JOIN sat ON sat.unit_id = un.id
|
|
12163
|
+
ORDER BY coalesce(s.revenue, 0) DESC, un.name;
|
|
12164
|
+
END $$;
|
|
12165
|
+
|
|
12166
|
+
COMMENT ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) IS
|
|
12167
|
+
'Uma linha por unidade com as dimens\xF5es medidas. Dimens\xE3o sem fonte volta NULO \u2014 contar como zero acusaria de mau desempenho quem s\xF3 n\xE3o tem o dado (008).';
|
|
12168
|
+
|
|
12169
|
+
REVOKE ALL ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) FROM PUBLIC, anon;
|
|
12170
|
+
GRANT EXECUTE ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) TO authenticated;
|
|
12171
|
+
GRANT EXECUTE ON FUNCTION public.crm_unit_scorecard(timestamp with time zone, timestamp with time zone) TO service_role;
|
|
12172
|
+
|
|
12173
|
+
-- \u2500\u2500 os pesos que a casa come\xE7a tendo \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
12174
|
+
--
|
|
12175
|
+
-- Os mesmos do V1, que os publica na tela: convers\xE3o 20, velocidade 15,
|
|
12176
|
+
-- reten\xE7\xE3o 15, produtividade 15, financeiro 15, follow-up 10, ocupa\xE7\xE3o 10.
|
|
12177
|
+
-- Aqui \`follow-up\` vira \`reactivation\` \u2014 no V1 ele mede se algu\xE9m retomou o
|
|
12178
|
+
-- contato, que \xE9 a mesma pergunta que reativa\xE7\xE3o responde com dado em vez de
|
|
12179
|
+
-- com tarefa marcada \u2014 e satisfa\xE7\xE3o entra porque o V2 tem a pesquisa portada.
|
|
12180
|
+
CREATE OR REPLACE FUNCTION public.crm_seed_tenant_scorecard_weights(p_tenant uuid)
|
|
12181
|
+
RETURNS jsonb
|
|
12182
|
+
LANGUAGE plpgsql
|
|
12183
|
+
SECURITY DEFINER
|
|
12184
|
+
SET search_path TO ''
|
|
12185
|
+
AS $$
|
|
12186
|
+
DECLARE v_made integer := 0;
|
|
12187
|
+
BEGIN
|
|
12188
|
+
IF p_tenant IS NULL THEN RETURN jsonb_build_object('seeded', false); END IF;
|
|
12189
|
+
INSERT INTO public.plg_crm_scorecard_weights (tenant_id, dimension, weight)
|
|
12190
|
+
SELECT p_tenant, d.dimension, d.weight
|
|
12191
|
+
FROM (VALUES
|
|
12192
|
+
('conversion', 20.0), ('retention', 15.0), ('reactivation', 10.0),
|
|
12193
|
+
('productivity', 15.0), ('satisfaction', 15.0),
|
|
12194
|
+
-- Declaradas com peso e SEM FONTE ainda. Ficam aqui de prop\xF3sito: o dia
|
|
12195
|
+
-- em que a fonte existir, o peso j\xE1 est\xE1 combinado \u2014 e at\xE9 l\xE1 a nota \xE9
|
|
12196
|
+
-- calculada sem elas, n\xE3o com zero no lugar delas.
|
|
12197
|
+
('speed', 10.0), ('occupancy', 5.0), ('financial', 10.0)
|
|
12198
|
+
) AS d(dimension, weight)
|
|
12199
|
+
WHERE NOT EXISTS (
|
|
12200
|
+
SELECT 1 FROM public.plg_crm_scorecard_weights x
|
|
12201
|
+
WHERE x.tenant_id = p_tenant AND x.dimension = d.dimension);
|
|
12202
|
+
GET DIAGNOSTICS v_made = ROW_COUNT;
|
|
12203
|
+
RETURN jsonb_build_object('seeded', true, 'weights', v_made);
|
|
12204
|
+
END $$;
|
|
12205
|
+
|
|
12206
|
+
REVOKE ALL ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) FROM PUBLIC, anon;
|
|
12207
|
+
GRANT EXECUTE ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) TO authenticated;
|
|
12208
|
+
GRANT EXECUTE ON FUNCTION public.crm_seed_tenant_scorecard_weights(uuid) TO service_role;
|
|
12209
|
+
|
|
12210
|
+
-- Entra no mesmo gatilho de tenant novo, ao lado das origens (001) e dos
|
|
12211
|
+
-- segmentos (004).
|
|
12212
|
+
CREATE OR REPLACE FUNCTION public.trg_crm_seed_new_tenant()
|
|
12213
|
+
RETURNS trigger
|
|
12214
|
+
LANGUAGE plpgsql
|
|
12215
|
+
SECURITY DEFINER
|
|
12216
|
+
SET search_path TO ''
|
|
12217
|
+
AS $$
|
|
12218
|
+
BEGIN
|
|
12219
|
+
BEGIN PERFORM public.crm_seed_tenant_lead_sources(NEW.id);
|
|
12220
|
+
EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_lead_sources % : %', NEW.id, SQLERRM; END;
|
|
12221
|
+
BEGIN PERFORM public.crm_seed_tenant_segments(NEW.id);
|
|
12222
|
+
EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_segments % : %', NEW.id, SQLERRM; END;
|
|
12223
|
+
BEGIN PERFORM public.crm_seed_tenant_scorecard_weights(NEW.id);
|
|
12224
|
+
EXCEPTION WHEN OTHERS THEN RAISE WARNING 'crm_seed_tenant_scorecard_weights % : %', NEW.id, SQLERRM; END;
|
|
12225
|
+
RETURN NEW;
|
|
12226
|
+
END $$;
|
|
12227
|
+
|
|
12228
|
+
DO $$
|
|
12229
|
+
DECLARE r record;
|
|
12230
|
+
BEGIN
|
|
12231
|
+
FOR r IN SELECT t.id FROM public.tenants t LOOP
|
|
12232
|
+
BEGIN PERFORM public.crm_seed_tenant_scorecard_weights(r.id);
|
|
12233
|
+
EXCEPTION WHEN OTHERS THEN RAISE WARNING 'backfill scorecard % : %', r.id, SQLERRM; END;
|
|
12234
|
+
END LOOP;
|
|
12235
|
+
END $$;
|
|
12236
|
+
`;
|
|
12237
|
+
var MIGRATIONS = [
|
|
12238
|
+
{ id: "000_baseline", sql: MIGRATION_000_BASELINE },
|
|
12239
|
+
{ id: "001_de_onde_veio_e_quem_indicou", sql: MIGRATION_001_DE_ONDE_VEIO_E_QUEM_INDICOU },
|
|
12240
|
+
{ id: "002_a_pergunta_que_o_cliente_responde", sql: MIGRATION_002_A_PERGUNTA_QUE_O_CLIENTE_RESPONDE },
|
|
12241
|
+
{ id: "003_o_cliente_responde_no_proprio_telefone", sql: MIGRATION_003_O_CLIENTE_RESPONDE_NO_PROPRIO_TELEFONE },
|
|
12242
|
+
{ id: "004_um_recorte_de_gente_que_tem_nome", sql: MIGRATION_004_UM_RECORTE_DE_GENTE_QUE_TEM_NOME },
|
|
12243
|
+
{ id: "005_a_etapa_ganha_um_codigo_e_um_comeco", sql: MIGRATION_005_A_ETAPA_GANHA_UM_CODIGO_E_UM_COMECO },
|
|
12244
|
+
{ id: "006_a_escada_do_relacionamento", sql: MIGRATION_006_A_ESCADA_DO_RELACIONAMENTO },
|
|
12245
|
+
{ id: "008_a_regua_da_rede_e_publica", sql: MIGRATION_008_A_REGUA_DA_REDE_E_PUBLICA }
|
|
12246
|
+
];
|
|
12247
|
+
|
|
12248
|
+
// src/locales/en.ts
|
|
12249
|
+
var en = {
|
|
12250
|
+
"crm.surveys.nps": "NPS",
|
|
12251
|
+
"crm.surveys.title": "Reviews",
|
|
12252
|
+
"crm.activities.activitiesLogged": "Activities are logged from lead and deal interactions",
|
|
12253
|
+
"crm.activities.all": "All",
|
|
12254
|
+
"crm.activities.completedFilter": "Completed",
|
|
12255
|
+
"crm.activities.done": "Done",
|
|
12256
|
+
"crm.activities.noActivities": "No activities",
|
|
12257
|
+
"crm.activities.noActivitiesOfType": 'No activities of type "{{type}}"',
|
|
12258
|
+
"crm.activities.overdue": "overdue",
|
|
12259
|
+
"crm.activities.overdueLabel": "Overdue",
|
|
12260
|
+
"crm.activities.pending": "pending",
|
|
12261
|
+
"crm.activities.pendingFilter": "Pending",
|
|
12262
|
+
"crm.activities.systemEvents": "Events",
|
|
12263
|
+
"crm.activities.typeCol": "Type",
|
|
12264
|
+
"crm.activities.titleCol": "Title",
|
|
12265
|
+
"crm.activities.dueCol": "Due",
|
|
12266
|
+
"crm.activities.title": "Activities",
|
|
12267
|
+
"crm.dashboard.activeDeals": "{{count}} active deals",
|
|
12268
|
+
"crm.dashboard.avgDealValue": "Avg deal value",
|
|
12269
|
+
"crm.dashboard.leadsCount": "{{count}} leads",
|
|
12270
|
+
"crm.dashboard.quotesCount": "{{count}} quotes",
|
|
12271
|
+
"crm.dashboard.conversionRate": "Conversion Rate",
|
|
12272
|
+
"crm.dashboard.conversionRateLabel": "Conversion rate",
|
|
12273
|
+
"crm.dashboard.createFirstLead": "Create your first lead to see the funnel",
|
|
12274
|
+
"crm.dashboard.dealsWon": "Deals won this month",
|
|
12275
|
+
"crm.dashboard.leadToDeal": "Lead to deal",
|
|
12276
|
+
"crm.dashboard.newThisMonth": "{{count}} new this month",
|
|
12277
|
+
"crm.dashboard.noLeadsYet": "No leads yet. Capture your first lead to get started.",
|
|
12278
|
+
"crm.dashboard.noPipelineData": "No pipeline data yet",
|
|
12279
|
+
"crm.dashboard.noQuotesYet": "No quotes yet.",
|
|
12280
|
+
"crm.dashboard.openPipeline": "Open Pipeline",
|
|
12281
|
+
"crm.dashboard.overdueCount": "{{count}} overdue",
|
|
12282
|
+
"crm.dashboard.pendingTasks": "Pending Tasks",
|
|
12283
|
+
"crm.dashboard.performance": "Performance",
|
|
12284
|
+
"crm.dashboard.pipelineOverview": "Pipeline Overview",
|
|
12285
|
+
"crm.dashboard.pipelineValue": "Pipeline Value",
|
|
12286
|
+
"crm.dashboard.recentLeads": "Recent Leads",
|
|
12287
|
+
"crm.dashboard.recentQuotes": "Recent Quotes",
|
|
12288
|
+
"crm.dashboard.revenueWon": "Revenue won",
|
|
12289
|
+
"crm.dashboard.totalDeals": "{{count}} total deals",
|
|
12290
|
+
"crm.dashboard.totalLeads": "Total Leads",
|
|
12291
|
+
"crm.dealSidebar.activitiesAppear": "Activities will appear here as they are logged",
|
|
12292
|
+
"crm.dealSidebar.activity": "Activity",
|
|
12293
|
+
"crm.dealSidebar.assignedTo": "Assigned to",
|
|
12294
|
+
"crm.dealSidebar.contact": "Contact",
|
|
12295
|
+
"crm.dealSidebar.created": "Created",
|
|
12296
|
+
"crm.dealSidebar.deal": "Deal",
|
|
12297
|
+
"crm.dealSidebar.dealNotFound": "Deal not found",
|
|
12298
|
+
"crm.dealSidebar.expectedClose": "Expected close",
|
|
12299
|
+
"crm.dealSidebar.noActivities": "No activities yet",
|
|
12300
|
+
"crm.dealSidebar.noQuotes": "No quotes linked",
|
|
12301
|
+
"crm.dealSidebar.notes": "Notes",
|
|
12302
|
+
"crm.dealSidebar.overview": "Overview",
|
|
12303
|
+
"crm.dealSidebar.probability": "Probability",
|
|
12304
|
+
"crm.dealSidebar.quotes": "Quotes",
|
|
12305
|
+
"crm.dealSidebar.quotesAppear": "Quotes created for this lead will appear here",
|
|
12306
|
+
"crm.dealSidebar.stage": "Stage",
|
|
12307
|
+
"crm.dealSidebar.tags": "Tags",
|
|
12308
|
+
"crm.dealSidebar.updated": "Updated",
|
|
12309
|
+
"crm.dealSidebar.value": "Value",
|
|
12310
|
+
"crm.dealSidebar.viewLeadProfile": "View Full Lead Profile",
|
|
12311
|
+
"crm.leadDetail.assignedTo": "Assigned to",
|
|
12312
|
+
"crm.leadDetail.archive": "Archive",
|
|
12313
|
+
"crm.leadDetail.backToList": "Back to list",
|
|
12314
|
+
"crm.leadDetail.formAnswers": "Form answers",
|
|
12315
|
+
"crm.leadDetail.attachments": "Attachments",
|
|
12316
|
+
"crm.leadDetail.company": "Company",
|
|
12317
|
+
"crm.leadDetail.contactInfo": "Contact Information",
|
|
12318
|
+
"crm.leadDetail.createQuote": "Create Quote",
|
|
12319
|
+
"crm.leadDetail.created": "Created",
|
|
12320
|
+
"crm.leadDetail.dealStatus": "Deal status",
|
|
12321
|
+
"crm.leadDetail.dealValue": "Deal value",
|
|
12322
|
+
"crm.leadDetail.details": "Details",
|
|
12323
|
+
"crm.leadDetail.email": "Email",
|
|
12324
|
+
"crm.leadDetail.leadNotFound": "Lead not found",
|
|
12325
|
+
"crm.leadDetail.leads": "Leads",
|
|
12326
|
+
"crm.leadDetail.loading": "Loading...",
|
|
12327
|
+
"crm.leadDetail.notFound": "Not found",
|
|
12328
|
+
"crm.leadDetail.notes": "Notes",
|
|
12329
|
+
"crm.leadDetail.phone": "Phone",
|
|
12330
|
+
"crm.leadDetail.pipeline": "Pipeline",
|
|
12331
|
+
"crm.leadDetail.probability": "Probability",
|
|
12332
|
+
"crm.leadDetail.quotes": "Quotes",
|
|
12333
|
+
"crm.leadDetail.source": "Source",
|
|
12334
|
+
"crm.leadDetail.stage": "Stage",
|
|
12335
|
+
"crm.leadDetail.tags": "Tags",
|
|
12336
|
+
"crm.leadDetail.updated": "Updated",
|
|
12337
|
+
"crm.leadDetail.value": "Value",
|
|
12338
|
+
"crm.leadForm.cancel": "Cancel",
|
|
12339
|
+
"crm.leadForm.company": "Company",
|
|
12340
|
+
"crm.leadForm.companyPlaceholder": "Company name",
|
|
12341
|
+
"crm.leadForm.email": "Email",
|
|
12342
|
+
"crm.leadForm.emailPlaceholder": "email@example.com",
|
|
12343
|
+
"crm.leadForm.name": "Name *",
|
|
12344
|
+
"crm.leadForm.namePlaceholder": "Contact name",
|
|
12345
|
+
"crm.leadForm.notes": "Notes",
|
|
12346
|
+
"crm.leadForm.notesPlaceholder": "Additional notes...",
|
|
12347
|
+
"crm.leadForm.phone": "Phone",
|
|
12348
|
+
"crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
|
|
12349
|
+
"crm.leadForm.source": "Source",
|
|
12350
|
+
"crm.leadForm.sourcePlaceholder": "Where did they come from?",
|
|
12351
|
+
"crm.leadForm.stage": "Stage",
|
|
12352
|
+
"crm.leadForm.save": "Save",
|
|
12353
|
+
"crm.leadForm.saving": "Saving...",
|
|
12354
|
+
"crm.leadForm.subtitle": "Capture a new lead",
|
|
12355
|
+
"crm.leadForm.title": "New Lead",
|
|
12356
|
+
"crm.leadSidebar.company": "Company",
|
|
12357
|
+
"crm.leadSidebar.lead": "Lead",
|
|
12358
|
+
"crm.leadSidebar.openFullProfile": "Open full profile",
|
|
12359
|
+
"crm.leadSidebar.viewDeal": "View deal",
|
|
9882
12360
|
"crm.leads.statusLost": "Lost",
|
|
9883
12361
|
"crm.leads.bulkArchive": "Archive",
|
|
9884
12362
|
"crm.leads.bulkArchiveDesc": "They leave the list and the pipeline board. This cannot be undone from here.",
|
|
@@ -10113,7 +12591,165 @@ var en = {
|
|
|
10113
12591
|
"registry.partners.description": "Benefit clubs and corporate deals: where the partnership applies and whether members book on their own.",
|
|
10114
12592
|
"crm.partners.allUnits": "All",
|
|
10115
12593
|
"crm.partners.unitCount": "{{count}} unit(s)",
|
|
10116
|
-
"crm.partners.noUnits": "No units registered. The partnership applies network-wide."
|
|
12594
|
+
"crm.partners.noUnits": "No units registered. The partnership applies network-wide.",
|
|
12595
|
+
"crm.segments.title": "Segments",
|
|
12596
|
+
"crm.segments.subtitle": "Named cuts of people \u2014 what a campaign points at, instead of a filter in the URL.",
|
|
12597
|
+
"crm.segments.new": "New segment",
|
|
12598
|
+
"crm.segments.newTitle": "New segment",
|
|
12599
|
+
"crm.segments.editTitle": "Edit segment",
|
|
12600
|
+
"crm.segments.editorDescription": "Conditions add up: someone is in the cut when ALL of them hold.",
|
|
12601
|
+
"crm.segments.name": "Name",
|
|
12602
|
+
"crm.segments.namePlaceholder": "Dormant for 90 days",
|
|
12603
|
+
"crm.segments.description": "Description",
|
|
12604
|
+
"crm.segments.descriptionPlaceholder": "What this cut is for",
|
|
12605
|
+
"crm.segments.rulesTitle": "Conditions",
|
|
12606
|
+
"crm.segments.rulesAllMustMatch": "all must hold",
|
|
12607
|
+
"crm.segments.addRule": "Add condition",
|
|
12608
|
+
"crm.segments.active": "Active",
|
|
12609
|
+
"crm.segments.people": "people",
|
|
12610
|
+
"crm.segments.days": "days",
|
|
12611
|
+
"crm.segments.daysPlaceholder": "30",
|
|
12612
|
+
"crm.segments.valuePlaceholder": "value",
|
|
12613
|
+
"crm.segments.countNow": "Count now",
|
|
12614
|
+
"crm.segments.previewSaved": "{{count}} people in the SAVED version of this cut.",
|
|
12615
|
+
"crm.segments.systemBadge": "built in",
|
|
12616
|
+
"crm.segments.systemHint": "Seeded by the system. Can be renamed and deactivated, not deleted.",
|
|
12617
|
+
"crm.segments.noRulesWarning": "No condition: matches everyone.",
|
|
12618
|
+
"crm.segments.emptyTitle": "No segments yet.",
|
|
12619
|
+
"crm.segments.emptyHint": "A segment is a cut with a name. Without one, every campaign carries its own copy of the filter and nobody can check who it went to.",
|
|
12620
|
+
"crm.segments.deleteTitle": "Delete segment",
|
|
12621
|
+
"crm.segments.deleteDescription": '"{{name}}" stops existing. People are unaffected \u2014 the cut is computed, not stored.',
|
|
12622
|
+
"crm.segments.error.nameRequired": "The segment needs a name.",
|
|
12623
|
+
"crm.segments.error.saveFailed": "Could not save the segment.",
|
|
12624
|
+
"crm.segments.error.toggleFailed": "Could not change the segment.",
|
|
12625
|
+
"crm.segments.error.deleteFailed": "Could not delete the segment.",
|
|
12626
|
+
"crm.segments.field.kind": "Record type",
|
|
12627
|
+
"crm.segments.field.tags": "Tag",
|
|
12628
|
+
"crm.segments.field.createdAt": "Joined",
|
|
12629
|
+
"crm.segments.field.updatedAt": "Last activity",
|
|
12630
|
+
"crm.segments.field.birthday": "Birthday",
|
|
12631
|
+
"crm.segments.field.email": "Email",
|
|
12632
|
+
"crm.segments.field.phone": "Phone",
|
|
12633
|
+
"crm.segments.field.city": "City",
|
|
12634
|
+
"crm.segments.field.name": "Name",
|
|
12635
|
+
"crm.segments.field.isActive": "Active",
|
|
12636
|
+
"crm.segments.op.=": "is",
|
|
12637
|
+
"crm.segments.op.<>": "is not",
|
|
12638
|
+
"crm.segments.op.>": "greater than",
|
|
12639
|
+
"crm.segments.op.<": "less than",
|
|
12640
|
+
"crm.segments.op.>=": "at least",
|
|
12641
|
+
"crm.segments.op.<=": "at most",
|
|
12642
|
+
"crm.segments.op.ilike": "contains",
|
|
12643
|
+
"crm.segments.op.in": "is one of",
|
|
12644
|
+
"crm.segments.op.not_in": "is not one of",
|
|
12645
|
+
"crm.segments.op.is_null": "has no",
|
|
12646
|
+
"crm.segments.op.not_null": "has",
|
|
12647
|
+
"crm.segments.op.has_tag": "has the tag",
|
|
12648
|
+
"crm.segments.op.within_days": "in the last N days",
|
|
12649
|
+
"crm.segments.op.older_than_days": "more than N days ago",
|
|
12650
|
+
"crm.segments.op.birthday_within_days": "in the next N days",
|
|
12651
|
+
"crm.segments.rule.isNull": "no {{field}}",
|
|
12652
|
+
"crm.segments.rule.notNull": "has {{field}}",
|
|
12653
|
+
"crm.segments.rule.hasTag": 'tag "{{value}}"',
|
|
12654
|
+
"crm.segments.rule.withinDays": "{{field}} in the last {{days}} days",
|
|
12655
|
+
"crm.segments.rule.olderThanDays": "{{field}} more than {{days}} days ago",
|
|
12656
|
+
"crm.segments.rule.birthdayWithinDays": "birthday in the next {{days}} days",
|
|
12657
|
+
"crm.segments.rule.contains": '{{field}} contains "{{value}}"',
|
|
12658
|
+
"crm.segments.rule.in": "{{field}} one of {{value}}",
|
|
12659
|
+
"crm.segments.rule.notIn": "{{field}} not one of {{value}}",
|
|
12660
|
+
"crm.pipelineSettings.role.none": "Regular stage",
|
|
12661
|
+
"crm.pipelineSettings.role.initial": "Entry",
|
|
12662
|
+
"crm.pipelineSettings.role.won": "Won",
|
|
12663
|
+
"crm.pipelineSettings.role.lost": "Lost",
|
|
12664
|
+
"crm.pipelineSettings.newStage": "New stage",
|
|
12665
|
+
"crm.pipelineSettings.newStagePlaceholder": "Stage name",
|
|
12666
|
+
"crm.pipelineSettings.cycleColor": "Change the colour",
|
|
12667
|
+
"crm.pipelineSettings.saveFailed": "Could not save the stage.",
|
|
12668
|
+
"crm.pipelineSettings.deleteTitle": "Delete stage",
|
|
12669
|
+
"crm.pipelineSettings.deleteDescription": '"{{name}}" leaves the pipeline. A stage holding deals is not deleted \u2014 move the cards first.',
|
|
12670
|
+
"crm.pipelineSettings.allZeroWarning": "Every stage sits at 0%. Without probability there is no weighted forecast, and the forecast reads zero without saying why.",
|
|
12671
|
+
"crm.pipelineSettings.noInitialWarning": "No stage is the entry. New leads land in the first open stage \u2014 which changes on its own whenever someone reorders the pipeline.",
|
|
12672
|
+
"crm.engagement.ladder": "Relationship ladder",
|
|
12673
|
+
"crm.engagement.lead": "Lead",
|
|
12674
|
+
"crm.engagement.prospect": "Never bought",
|
|
12675
|
+
"crm.engagement.new": "Newcomer",
|
|
12676
|
+
"crm.engagement.active": "Active",
|
|
12677
|
+
"crm.engagement.atRisk": "At risk",
|
|
12678
|
+
"crm.engagement.dormant": "Dormant",
|
|
12679
|
+
"crm.engagement.atRiskSub": "not seen for more than {{days}} days",
|
|
12680
|
+
"crm.engagement.retention": "Came back",
|
|
12681
|
+
"crm.engagement.retentionSub": "{{returned}} of {{base}} who had come back before",
|
|
12682
|
+
"crm.engagement.derivedNote": "The rung is computed, not typed: active up to {{active}} days away, at risk up to {{risk}}.",
|
|
12683
|
+
"crm.engagement.settingsTitle": "Ladder rungs",
|
|
12684
|
+
"crm.engagement.settingsDesc": "How many days away separate newcomer, active, at risk and dormant. The ladder is the same for every business; the rungs are not.",
|
|
12685
|
+
"crm.engagement.newDays": "Newcomer up to",
|
|
12686
|
+
"crm.engagement.newDaysDesc": "First purchase or visit inside this window.",
|
|
12687
|
+
"crm.engagement.activeDays": "Active up to",
|
|
12688
|
+
"crm.engagement.activeDaysDesc": "Showed up inside this window.",
|
|
12689
|
+
"crm.engagement.atRiskDays": "At risk up to",
|
|
12690
|
+
"crm.engagement.atRiskDaysDesc": "Past this without showing up, they are dormant.",
|
|
12691
|
+
"crm.engagement.daysUnit": "days",
|
|
12692
|
+
"crm.engagement.saveFailed": "Could not save the rungs.",
|
|
12693
|
+
"crm.capture.title": "Capture pages",
|
|
12694
|
+
"crm.capture.subtitle": "The public doors: a link to paste on your site, with the rules the house chooses.",
|
|
12695
|
+
"crm.capture.new": "New page",
|
|
12696
|
+
"crm.capture.newTitle": "New capture page",
|
|
12697
|
+
"crm.capture.editTitle": "Edit page",
|
|
12698
|
+
"crm.capture.editorDescription": "The public address never changes once created \u2014 a customer may already have it saved.",
|
|
12699
|
+
"crm.capture.name": "Name",
|
|
12700
|
+
"crm.capture.namePlaceholder": "Talk to us",
|
|
12701
|
+
"crm.capture.destination": "Where it leads",
|
|
12702
|
+
"crm.capture.dest.lead": "Captures a contact",
|
|
12703
|
+
"crm.capture.dest.booking": "Books a slot",
|
|
12704
|
+
"crm.capture.dest.reservation": "Books a table",
|
|
12705
|
+
"crm.capture.required": "What the house requires",
|
|
12706
|
+
"crm.capture.requiredHint": "Every extra required field costs conversion. Ask for the minimum you need to reply.",
|
|
12707
|
+
"crm.capture.field.name": "Name",
|
|
12708
|
+
"crm.capture.field.phone": "Phone",
|
|
12709
|
+
"crm.capture.field.email": "Email",
|
|
12710
|
+
"crm.capture.field.document": "Tax ID",
|
|
12711
|
+
"crm.capture.field.notes": "Note",
|
|
12712
|
+
"crm.capture.minAdvance": "Minimum notice (hours)",
|
|
12713
|
+
"crm.capture.minAdvanceHint": "Stops someone booking for ten minutes from now.",
|
|
12714
|
+
"crm.capture.maxAdvance": "Furthest ahead (days)",
|
|
12715
|
+
"crm.capture.maxAdvanceHint": "Stops someone booking for next year.",
|
|
12716
|
+
"crm.capture.asks": "Asks for: {{fields}}",
|
|
12717
|
+
"crm.capture.windowSummary": "from {{min}}h to {{max}} days ahead",
|
|
12718
|
+
"crm.capture.closedBadge": "closed",
|
|
12719
|
+
"crm.capture.copied": "Link copied.",
|
|
12720
|
+
"crm.capture.nameRequired": "The page needs a name.",
|
|
12721
|
+
"crm.capture.saveFailed": "Could not save the page.",
|
|
12722
|
+
"crm.capture.emptyTitle": "No door open.",
|
|
12723
|
+
"crm.capture.emptyHint": "A capture page is the address you paste on your site or send over WhatsApp. Without one, someone arriving from the site never becomes a lead on their own.",
|
|
12724
|
+
"crm.capture.deleteTitle": "Delete page",
|
|
12725
|
+
"crm.capture.deleteDescription": '"{{name}}" stops existing and the link stops answering. Anyone who saved it sees a missing page \u2014 deactivating keeps the address alive saying it is closed.',
|
|
12726
|
+
"crm.network.title": "Network",
|
|
12727
|
+
"crm.network.subtitle": "How each unit is doing \u2014 and the ruler it is measured by.",
|
|
12728
|
+
"crm.network.avgScore": "Network average",
|
|
12729
|
+
"crm.network.lastDays": "Last {{days}} days",
|
|
12730
|
+
"crm.network.unit": "Unit",
|
|
12731
|
+
"crm.network.orders": "Orders",
|
|
12732
|
+
"crm.network.revenue": "Revenue",
|
|
12733
|
+
"crm.network.score": "Score",
|
|
12734
|
+
"crm.network.measured": "Measured",
|
|
12735
|
+
"crm.network.dim.conversion": "Conversion",
|
|
12736
|
+
"crm.network.dim.retention": "Retention",
|
|
12737
|
+
"crm.network.dim.reactivation": "Reactivation",
|
|
12738
|
+
"crm.network.dim.productivity": "Productivity",
|
|
12739
|
+
"crm.network.dim.satisfaction": "Satisfaction",
|
|
12740
|
+
"crm.network.dim.speed": "Speed",
|
|
12741
|
+
"crm.network.dim.occupancy": "Occupancy",
|
|
12742
|
+
"crm.network.dim.financial": "Financial",
|
|
12743
|
+
"crm.network.weightsNote": "The weights belong to this business and you can change them. The score is computed only over dimensions that have data \u2014 the Measured column says how many.",
|
|
12744
|
+
"crm.network.unmeasuredNote": "A unit with no score is a unit with no data in the period, not a unit performing badly.",
|
|
12745
|
+
"crm.network.empty": "No units registered.",
|
|
12746
|
+
"crm.dashboard.bySource": "Conversion by source",
|
|
12747
|
+
"crm.dashboard.monthly": "Monthly trend",
|
|
12748
|
+
"crm.dashboard.leadsLabel": "Leads",
|
|
12749
|
+
"crm.dashboard.convertedLabel": "Converted",
|
|
12750
|
+
"crm.dashboard.noSources": "No lead carried a source in the period. Agree that every lead leaves with one.",
|
|
12751
|
+
"crm.dashboard.noMonthly": "No leads in the last six months.",
|
|
12752
|
+
"crm.dashboard.activeSub": "showed up in the last {{days}} days"
|
|
10117
12753
|
};
|
|
10118
12754
|
|
|
10119
12755
|
// src/locales/pt-BR.ts
|
|
@@ -10462,7 +13098,165 @@ var ptBR = {
|
|
|
10462
13098
|
"registry.partners.description": "Conv\xEAnios e clubes de benef\xEDcio: onde a parceria vale e se o conveniado agenda sozinho.",
|
|
10463
13099
|
"crm.partners.allUnits": "Todas",
|
|
10464
13100
|
"crm.partners.unitCount": "{{count}} unidade(s)",
|
|
10465
|
-
"crm.partners.noUnits": "Nenhuma unidade cadastrada. A parceria vale na rede inteira."
|
|
13101
|
+
"crm.partners.noUnits": "Nenhuma unidade cadastrada. A parceria vale na rede inteira.",
|
|
13102
|
+
"crm.segments.title": "Segmentos",
|
|
13103
|
+
"crm.segments.subtitle": "Recortes de pessoas com nome \u2014 o que uma campanha aponta, em vez de um filtro no endere\xE7o.",
|
|
13104
|
+
"crm.segments.new": "Novo segmento",
|
|
13105
|
+
"crm.segments.newTitle": "Novo segmento",
|
|
13106
|
+
"crm.segments.editTitle": "Editar segmento",
|
|
13107
|
+
"crm.segments.editorDescription": "As condi\xE7\xF5es somam: algu\xE9m entra no recorte quando atende a TODAS elas.",
|
|
13108
|
+
"crm.segments.name": "Nome",
|
|
13109
|
+
"crm.segments.namePlaceholder": "Parados h\xE1 90 dias",
|
|
13110
|
+
"crm.segments.description": "Descri\xE7\xE3o",
|
|
13111
|
+
"crm.segments.descriptionPlaceholder": "Para que serve este recorte",
|
|
13112
|
+
"crm.segments.rulesTitle": "Condi\xE7\xF5es",
|
|
13113
|
+
"crm.segments.rulesAllMustMatch": "todas precisam valer",
|
|
13114
|
+
"crm.segments.addRule": "Adicionar condi\xE7\xE3o",
|
|
13115
|
+
"crm.segments.active": "Ativo",
|
|
13116
|
+
"crm.segments.people": "pessoas",
|
|
13117
|
+
"crm.segments.days": "dias",
|
|
13118
|
+
"crm.segments.daysPlaceholder": "30",
|
|
13119
|
+
"crm.segments.valuePlaceholder": "valor",
|
|
13120
|
+
"crm.segments.countNow": "Contar agora",
|
|
13121
|
+
"crm.segments.previewSaved": "{{count}} pessoas na vers\xE3o SALVA deste recorte.",
|
|
13122
|
+
"crm.segments.systemBadge": "da casa",
|
|
13123
|
+
"crm.segments.systemHint": "Semeado pelo sistema. Pode ser renomeado e desativado, n\xE3o apagado.",
|
|
13124
|
+
"crm.segments.noRulesWarning": "Sem condi\xE7\xE3o: pega todo mundo.",
|
|
13125
|
+
"crm.segments.emptyTitle": "Nenhum segmento.",
|
|
13126
|
+
"crm.segments.emptyHint": "Um segmento \xE9 um recorte com nome. Sem ele, cada campanha carrega a pr\xF3pria c\xF3pia do filtro e ningu\xE9m consegue conferir para quem ela foi.",
|
|
13127
|
+
"crm.segments.deleteTitle": "Excluir segmento",
|
|
13128
|
+
"crm.segments.deleteDescription": '"{{name}}" deixa de existir. As pessoas n\xE3o s\xE3o afetadas \u2014 o recorte \xE9 calculado, n\xE3o guardado.',
|
|
13129
|
+
"crm.segments.error.nameRequired": "O segmento precisa de um nome.",
|
|
13130
|
+
"crm.segments.error.saveFailed": "N\xE3o foi poss\xEDvel salvar o segmento.",
|
|
13131
|
+
"crm.segments.error.toggleFailed": "N\xE3o foi poss\xEDvel alterar o segmento.",
|
|
13132
|
+
"crm.segments.error.deleteFailed": "N\xE3o foi poss\xEDvel excluir o segmento.",
|
|
13133
|
+
"crm.segments.field.kind": "Tipo de cadastro",
|
|
13134
|
+
"crm.segments.field.tags": "Etiqueta",
|
|
13135
|
+
"crm.segments.field.createdAt": "Entrou",
|
|
13136
|
+
"crm.segments.field.updatedAt": "\xDAltimo movimento",
|
|
13137
|
+
"crm.segments.field.birthday": "Anivers\xE1rio",
|
|
13138
|
+
"crm.segments.field.email": "E-mail",
|
|
13139
|
+
"crm.segments.field.phone": "Telefone",
|
|
13140
|
+
"crm.segments.field.city": "Cidade",
|
|
13141
|
+
"crm.segments.field.name": "Nome",
|
|
13142
|
+
"crm.segments.field.isActive": "Ativo",
|
|
13143
|
+
"crm.segments.op.=": "\xE9",
|
|
13144
|
+
"crm.segments.op.<>": "n\xE3o \xE9",
|
|
13145
|
+
"crm.segments.op.>": "maior que",
|
|
13146
|
+
"crm.segments.op.<": "menor que",
|
|
13147
|
+
"crm.segments.op.>=": "maior ou igual a",
|
|
13148
|
+
"crm.segments.op.<=": "menor ou igual a",
|
|
13149
|
+
"crm.segments.op.ilike": "cont\xE9m",
|
|
13150
|
+
"crm.segments.op.in": "est\xE1 entre",
|
|
13151
|
+
"crm.segments.op.not_in": "n\xE3o est\xE1 entre",
|
|
13152
|
+
"crm.segments.op.is_null": "n\xE3o tem",
|
|
13153
|
+
"crm.segments.op.not_null": "tem",
|
|
13154
|
+
"crm.segments.op.has_tag": "tem a etiqueta",
|
|
13155
|
+
"crm.segments.op.within_days": "nos \xFAltimos N dias",
|
|
13156
|
+
"crm.segments.op.older_than_days": "h\xE1 mais de N dias",
|
|
13157
|
+
"crm.segments.op.birthday_within_days": "nos pr\xF3ximos N dias",
|
|
13158
|
+
"crm.segments.rule.isNull": "sem {{field}}",
|
|
13159
|
+
"crm.segments.rule.notNull": "com {{field}}",
|
|
13160
|
+
"crm.segments.rule.hasTag": 'etiqueta "{{value}}"',
|
|
13161
|
+
"crm.segments.rule.withinDays": "{{field}} nos \xFAltimos {{days}} dias",
|
|
13162
|
+
"crm.segments.rule.olderThanDays": "{{field}} h\xE1 mais de {{days}} dias",
|
|
13163
|
+
"crm.segments.rule.birthdayWithinDays": "anivers\xE1rio nos pr\xF3ximos {{days}} dias",
|
|
13164
|
+
"crm.segments.rule.contains": '{{field}} cont\xE9m "{{value}}"',
|
|
13165
|
+
"crm.segments.rule.in": "{{field}} entre {{value}}",
|
|
13166
|
+
"crm.segments.rule.notIn": "{{field}} fora de {{value}}",
|
|
13167
|
+
"crm.pipelineSettings.role.none": "Etapa comum",
|
|
13168
|
+
"crm.pipelineSettings.role.initial": "Entrada",
|
|
13169
|
+
"crm.pipelineSettings.role.won": "Ganho",
|
|
13170
|
+
"crm.pipelineSettings.role.lost": "Perdido",
|
|
13171
|
+
"crm.pipelineSettings.newStage": "Nova etapa",
|
|
13172
|
+
"crm.pipelineSettings.newStagePlaceholder": "Nome da etapa",
|
|
13173
|
+
"crm.pipelineSettings.cycleColor": "Trocar a cor",
|
|
13174
|
+
"crm.pipelineSettings.saveFailed": "N\xE3o foi poss\xEDvel salvar a etapa.",
|
|
13175
|
+
"crm.pipelineSettings.deleteTitle": "Excluir etapa",
|
|
13176
|
+
"crm.pipelineSettings.deleteDescription": '"{{name}}" sai do funil. Etapa com neg\xF3cio dentro n\xE3o \xE9 exclu\xEDda \u2014 mova os cards antes.',
|
|
13177
|
+
"crm.pipelineSettings.allZeroWarning": "Todas as etapas est\xE3o em 0%. Sem probabilidade n\xE3o h\xE1 previs\xE3o ponderada, e o valor previsto fica zero sem dizer por qu\xEA.",
|
|
13178
|
+
"crm.pipelineSettings.noInitialWarning": "Nenhuma etapa \xE9 a entrada. O lead novo cai na primeira etapa aberta \u2014 que muda sozinha quando algu\xE9m reordena o funil.",
|
|
13179
|
+
"crm.engagement.ladder": "Escada de relacionamento",
|
|
13180
|
+
"crm.engagement.lead": "Lead",
|
|
13181
|
+
"crm.engagement.prospect": "Nunca comprou",
|
|
13182
|
+
"crm.engagement.new": "Rec\xE9m-chegado",
|
|
13183
|
+
"crm.engagement.active": "Ativo",
|
|
13184
|
+
"crm.engagement.atRisk": "Em risco",
|
|
13185
|
+
"crm.engagement.dormant": "Parado",
|
|
13186
|
+
"crm.engagement.atRiskSub": "sem aparecer h\xE1 mais de {{days}} dias",
|
|
13187
|
+
"crm.engagement.retention": "Voltaram",
|
|
13188
|
+
"crm.engagement.retentionSub": "{{returned}} de {{base}} que j\xE1 tinham voltado antes",
|
|
13189
|
+
"crm.engagement.derivedNote": "O degrau \xE9 calculado, n\xE3o digitado: ativo at\xE9 {{active}} dias sem aparecer, em risco at\xE9 {{risk}}.",
|
|
13190
|
+
"crm.engagement.settingsTitle": "Degraus da escada",
|
|
13191
|
+
"crm.engagement.settingsDesc": "Quantos dias sem aparecer separam rec\xE9m-chegado, ativo, em risco e parado. A escada \xE9 a mesma para todo neg\xF3cio; os degraus, n\xE3o.",
|
|
13192
|
+
"crm.engagement.newDays": "Rec\xE9m-chegado at\xE9",
|
|
13193
|
+
"crm.engagement.newDaysDesc": "Primeira compra ou atendimento dentro desta janela.",
|
|
13194
|
+
"crm.engagement.activeDays": "Ativo at\xE9",
|
|
13195
|
+
"crm.engagement.activeDaysDesc": "Apareceu dentro desta janela.",
|
|
13196
|
+
"crm.engagement.atRiskDays": "Em risco at\xE9",
|
|
13197
|
+
"crm.engagement.atRiskDaysDesc": "Passou disto sem aparecer, est\xE1 parado.",
|
|
13198
|
+
"crm.engagement.daysUnit": "dias",
|
|
13199
|
+
"crm.engagement.saveFailed": "N\xE3o foi poss\xEDvel salvar os degraus.",
|
|
13200
|
+
"crm.capture.title": "P\xE1ginas de captura",
|
|
13201
|
+
"crm.capture.subtitle": "As portas p\xFAblicas da casa: um link para colar no site, com as regras que a casa escolhe.",
|
|
13202
|
+
"crm.capture.new": "Nova p\xE1gina",
|
|
13203
|
+
"crm.capture.newTitle": "Nova p\xE1gina de captura",
|
|
13204
|
+
"crm.capture.editTitle": "Editar p\xE1gina",
|
|
13205
|
+
"crm.capture.editorDescription": "O endere\xE7o p\xFAblico n\xE3o muda depois de criado \u2014 o cliente pode j\xE1 t\xEA-lo salvo.",
|
|
13206
|
+
"crm.capture.name": "Nome",
|
|
13207
|
+
"crm.capture.namePlaceholder": "Fale com a gente",
|
|
13208
|
+
"crm.capture.destination": "Para onde leva",
|
|
13209
|
+
"crm.capture.dest.lead": "Captura contato",
|
|
13210
|
+
"crm.capture.dest.booking": "Marca hor\xE1rio",
|
|
13211
|
+
"crm.capture.dest.reservation": "Marca mesa",
|
|
13212
|
+
"crm.capture.required": "O que a casa exige",
|
|
13213
|
+
"crm.capture.requiredHint": "Cada campo exigido a mais derruba convers\xE3o. Pe\xE7a o m\xEDnimo para conseguir responder.",
|
|
13214
|
+
"crm.capture.field.name": "Nome",
|
|
13215
|
+
"crm.capture.field.phone": "Telefone",
|
|
13216
|
+
"crm.capture.field.email": "E-mail",
|
|
13217
|
+
"crm.capture.field.document": "CPF",
|
|
13218
|
+
"crm.capture.field.notes": "Observa\xE7\xE3o",
|
|
13219
|
+
"crm.capture.minAdvance": "Anteced\xEAncia m\xEDnima (horas)",
|
|
13220
|
+
"crm.capture.minAdvanceHint": "Impede marcar para daqui a dez minutos.",
|
|
13221
|
+
"crm.capture.maxAdvance": "Prazo m\xE1ximo (dias)",
|
|
13222
|
+
"crm.capture.maxAdvanceHint": "Impede marcar para o ano que vem.",
|
|
13223
|
+
"crm.capture.asks": "Pede: {{fields}}",
|
|
13224
|
+
"crm.capture.windowSummary": "de {{min}}h a {{max}} dias de anteced\xEAncia",
|
|
13225
|
+
"crm.capture.closedBadge": "fechada",
|
|
13226
|
+
"crm.capture.copied": "Link copiado.",
|
|
13227
|
+
"crm.capture.nameRequired": "A p\xE1gina precisa de um nome.",
|
|
13228
|
+
"crm.capture.saveFailed": "N\xE3o foi poss\xEDvel salvar a p\xE1gina.",
|
|
13229
|
+
"crm.capture.emptyTitle": "Nenhuma porta aberta.",
|
|
13230
|
+
"crm.capture.emptyHint": "Uma p\xE1gina de captura \xE9 o endere\xE7o que voc\xEA cola no site ou manda no WhatsApp. Sem ela, quem chega pelo site n\xE3o vira lead sozinho.",
|
|
13231
|
+
"crm.capture.deleteTitle": "Excluir p\xE1gina",
|
|
13232
|
+
"crm.capture.deleteDescription": '"{{name}}" deixa de existir e o link para de responder. Quem j\xE1 o tiver salvo ver\xE1 uma p\xE1gina inexistente \u2014 desativar mant\xE9m o endere\xE7o vivo avisando que est\xE1 fechado.',
|
|
13233
|
+
"crm.network.title": "Rede",
|
|
13234
|
+
"crm.network.subtitle": "Como cada unidade est\xE1 indo \u2014 e a r\xE9gua com que ela \xE9 medida.",
|
|
13235
|
+
"crm.network.avgScore": "Nota m\xE9dia da rede",
|
|
13236
|
+
"crm.network.lastDays": "\xDAltimos {{days}} dias",
|
|
13237
|
+
"crm.network.unit": "Unidade",
|
|
13238
|
+
"crm.network.orders": "Pedidos",
|
|
13239
|
+
"crm.network.revenue": "Receita",
|
|
13240
|
+
"crm.network.score": "Nota",
|
|
13241
|
+
"crm.network.measured": "Medido",
|
|
13242
|
+
"crm.network.dim.conversion": "Convers\xE3o",
|
|
13243
|
+
"crm.network.dim.retention": "Reten\xE7\xE3o",
|
|
13244
|
+
"crm.network.dim.reactivation": "Reativa\xE7\xE3o",
|
|
13245
|
+
"crm.network.dim.productivity": "Produtividade",
|
|
13246
|
+
"crm.network.dim.satisfaction": "Satisfa\xE7\xE3o",
|
|
13247
|
+
"crm.network.dim.speed": "Velocidade",
|
|
13248
|
+
"crm.network.dim.occupancy": "Ocupa\xE7\xE3o",
|
|
13249
|
+
"crm.network.dim.financial": "Financeiro",
|
|
13250
|
+
"crm.network.weightsNote": "Os pesos s\xE3o desta casa e voc\xEA pode mud\xE1-los. A nota \xE9 calculada s\xF3 sobre as dimens\xF5es que t\xEAm dado \u2014 a coluna Medido diz quantas entraram.",
|
|
13251
|
+
"crm.network.unmeasuredNote": "Unidade sem nota \xE9 unidade sem dado no per\xEDodo, n\xE3o unidade com desempenho ruim.",
|
|
13252
|
+
"crm.network.empty": "Nenhuma unidade cadastrada.",
|
|
13253
|
+
"crm.dashboard.bySource": "Convers\xE3o por origem",
|
|
13254
|
+
"crm.dashboard.monthly": "Evolu\xE7\xE3o mensal",
|
|
13255
|
+
"crm.dashboard.leadsLabel": "Leads",
|
|
13256
|
+
"crm.dashboard.convertedLabel": "Convertidos",
|
|
13257
|
+
"crm.dashboard.noSources": "Nenhum lead com origem no per\xEDodo. Combine que todo lead sai com origem.",
|
|
13258
|
+
"crm.dashboard.noMonthly": "Sem leads nos \xFAltimos seis meses.",
|
|
13259
|
+
"crm.dashboard.activeSub": "apareceram nos \xFAltimos {{days}} dias"
|
|
10466
13260
|
};
|
|
10467
13261
|
|
|
10468
13262
|
// src/locales/index.ts
|
|
@@ -10470,6 +13264,377 @@ var crmLocales = {
|
|
|
10470
13264
|
en,
|
|
10471
13265
|
"pt-BR": ptBR
|
|
10472
13266
|
};
|
|
13267
|
+
var EMPTY_RULE = { column: "kind", op: "=", value: "lead" };
|
|
13268
|
+
function SegmentEditorDialog({ open, segment, provider, onClose, onSaved }) {
|
|
13269
|
+
const t2 = useTranslation();
|
|
13270
|
+
const [name, setName] = React20.useState("");
|
|
13271
|
+
const [description, setDescription] = React20.useState("");
|
|
13272
|
+
const [isActive, setIsActive] = React20.useState(true);
|
|
13273
|
+
const [rules, setRules] = React20.useState([EMPTY_RULE]);
|
|
13274
|
+
const [saving, setSaving] = React20.useState(false);
|
|
13275
|
+
const [error, setError] = React20.useState(null);
|
|
13276
|
+
const [preview, setPreview] = React20.useState(null);
|
|
13277
|
+
const [previewing, setPreviewing] = React20.useState(false);
|
|
13278
|
+
React20.useEffect(() => {
|
|
13279
|
+
if (!open) return;
|
|
13280
|
+
setName(segment?.name ?? "");
|
|
13281
|
+
setDescription(segment?.description ?? "");
|
|
13282
|
+
setIsActive(segment?.isActive ?? true);
|
|
13283
|
+
setRules(segment?.rules?.where?.length ? segment.rules.where : [EMPTY_RULE]);
|
|
13284
|
+
setError(null);
|
|
13285
|
+
setPreview(null);
|
|
13286
|
+
}, [open, segment]);
|
|
13287
|
+
function patch(i, next) {
|
|
13288
|
+
setRules((prev) => prev.map((r, j) => j === i ? { ...r, ...next } : r));
|
|
13289
|
+
setPreview(null);
|
|
13290
|
+
}
|
|
13291
|
+
function changeColumn(i, column) {
|
|
13292
|
+
const field = segmentFieldFor(column);
|
|
13293
|
+
const op = field?.ops[0] ?? "=";
|
|
13294
|
+
patch(i, { column, op, value: defaultValueFor(op) });
|
|
13295
|
+
}
|
|
13296
|
+
function changeOp(i, op) {
|
|
13297
|
+
patch(i, { op, value: defaultValueFor(op) });
|
|
13298
|
+
}
|
|
13299
|
+
async function runPreview() {
|
|
13300
|
+
setPreviewing(true);
|
|
13301
|
+
try {
|
|
13302
|
+
if (!segment?.id) {
|
|
13303
|
+
setPreview(null);
|
|
13304
|
+
return;
|
|
13305
|
+
}
|
|
13306
|
+
const ids = await provider.resolveSegment(segment.id);
|
|
13307
|
+
setPreview(ids.length);
|
|
13308
|
+
} catch {
|
|
13309
|
+
setPreview(null);
|
|
13310
|
+
} finally {
|
|
13311
|
+
setPreviewing(false);
|
|
13312
|
+
}
|
|
13313
|
+
}
|
|
13314
|
+
async function save() {
|
|
13315
|
+
if (!name.trim()) {
|
|
13316
|
+
setError(t2("crm.segments.error.nameRequired"));
|
|
13317
|
+
return;
|
|
13318
|
+
}
|
|
13319
|
+
setSaving(true);
|
|
13320
|
+
setError(null);
|
|
13321
|
+
try {
|
|
13322
|
+
const input = {
|
|
13323
|
+
id: segment?.id,
|
|
13324
|
+
name: name.trim(),
|
|
13325
|
+
description: description.trim() || void 0,
|
|
13326
|
+
kind: "rule",
|
|
13327
|
+
isActive,
|
|
13328
|
+
rules: { where: rules.filter((r) => r.column) }
|
|
13329
|
+
};
|
|
13330
|
+
await provider.saveSegment(input);
|
|
13331
|
+
onSaved();
|
|
13332
|
+
onClose();
|
|
13333
|
+
} catch (e) {
|
|
13334
|
+
setError(e?.message ?? t2("crm.segments.error.saveFailed"));
|
|
13335
|
+
} finally {
|
|
13336
|
+
setSaving(false);
|
|
13337
|
+
}
|
|
13338
|
+
}
|
|
13339
|
+
return /* @__PURE__ */ jsx(Modal, { open, onOpenChange: (v) => {
|
|
13340
|
+
if (!v) onClose();
|
|
13341
|
+
}, children: /* @__PURE__ */ jsxs(ModalContent, { className: "sm:max-w-2xl", children: [
|
|
13342
|
+
/* @__PURE__ */ jsxs(ModalHeader, { children: [
|
|
13343
|
+
/* @__PURE__ */ jsx(ModalTitle, { children: segment ? t2("crm.segments.editTitle") : t2("crm.segments.newTitle") }),
|
|
13344
|
+
/* @__PURE__ */ jsx(ModalDescription, { children: t2("crm.segments.editorDescription") })
|
|
13345
|
+
] }),
|
|
13346
|
+
/* @__PURE__ */ jsxs(ModalBody, { className: "space-y-4", children: [
|
|
13347
|
+
/* @__PURE__ */ jsxs("div", { className: "grid gap-3 sm:grid-cols-2", children: [
|
|
13348
|
+
/* @__PURE__ */ jsxs("div", { children: [
|
|
13349
|
+
/* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: t2("crm.segments.name") }),
|
|
13350
|
+
/* @__PURE__ */ jsx(
|
|
13351
|
+
Input,
|
|
13352
|
+
{
|
|
13353
|
+
value: name,
|
|
13354
|
+
onChange: (e) => setName(e.target.value),
|
|
13355
|
+
placeholder: t2("crm.segments.namePlaceholder")
|
|
13356
|
+
}
|
|
13357
|
+
)
|
|
13358
|
+
] }),
|
|
13359
|
+
/* @__PURE__ */ jsxs("div", { children: [
|
|
13360
|
+
/* @__PURE__ */ jsx("label", { className: "text-xs font-medium", children: t2("crm.segments.description") }),
|
|
13361
|
+
/* @__PURE__ */ jsx(
|
|
13362
|
+
Input,
|
|
13363
|
+
{
|
|
13364
|
+
value: description,
|
|
13365
|
+
onChange: (e) => setDescription(e.target.value),
|
|
13366
|
+
placeholder: t2("crm.segments.descriptionPlaceholder")
|
|
13367
|
+
}
|
|
13368
|
+
)
|
|
13369
|
+
] })
|
|
13370
|
+
] }),
|
|
13371
|
+
/* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-muted/20 p-3", children: [
|
|
13372
|
+
/* @__PURE__ */ jsxs("div", { className: "mb-2 flex items-center justify-between", children: [
|
|
13373
|
+
/* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: t2("crm.segments.rulesTitle") }),
|
|
13374
|
+
/* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground", children: t2("crm.segments.rulesAllMustMatch") })
|
|
13375
|
+
] }),
|
|
13376
|
+
/* @__PURE__ */ jsx("div", { className: "space-y-2", children: rules.map((rule, i) => {
|
|
13377
|
+
const field = segmentFieldFor(rule.column);
|
|
13378
|
+
const needsValue = !VALUELESS_OPS.includes(rule.op);
|
|
13379
|
+
const isDays = DAY_OPS.includes(rule.op);
|
|
13380
|
+
return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
13381
|
+
/* @__PURE__ */ jsxs(Select, { value: rule.column, onValueChange: (v) => changeColumn(i, v), children: [
|
|
13382
|
+
/* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-[150px] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
13383
|
+
/* @__PURE__ */ jsx(SelectContent, { children: SEGMENT_FIELDS.map((f) => /* @__PURE__ */ jsx(SelectItem, { value: f.column, children: t2(f.labelKey) }, f.column)) })
|
|
13384
|
+
] }),
|
|
13385
|
+
/* @__PURE__ */ jsxs(Select, { value: rule.op, onValueChange: (v) => changeOp(i, v), children: [
|
|
13386
|
+
/* @__PURE__ */ jsx(SelectTrigger, { className: "h-8 w-[170px] text-xs", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
|
|
13387
|
+
/* @__PURE__ */ jsx(SelectContent, { children: (field?.ops ?? []).map((op) => /* @__PURE__ */ jsx(SelectItem, { value: op, children: t2(`crm.segments.op.${op}`) }, op)) })
|
|
13388
|
+
] }),
|
|
13389
|
+
needsValue && /* @__PURE__ */ jsx(
|
|
13390
|
+
Input,
|
|
13391
|
+
{
|
|
13392
|
+
className: "h-8 w-[160px] text-xs",
|
|
13393
|
+
type: isDays ? "number" : "text",
|
|
13394
|
+
value: Array.isArray(rule.value) ? rule.value.join(", ") : String(rule.value ?? ""),
|
|
13395
|
+
onChange: (e) => patch(i, {
|
|
13396
|
+
value: rule.op === "in" || rule.op === "not_in" ? e.target.value.split(",").map((x) => x.trim()).filter(Boolean) : isDays ? Number(e.target.value) : e.target.value
|
|
13397
|
+
}),
|
|
13398
|
+
placeholder: isDays ? t2("crm.segments.daysPlaceholder") : t2("crm.segments.valuePlaceholder")
|
|
13399
|
+
}
|
|
13400
|
+
),
|
|
13401
|
+
isDays && /* @__PURE__ */ jsx("span", { className: "text-[10px] text-muted-foreground", children: t2("crm.segments.days") }),
|
|
13402
|
+
/* @__PURE__ */ jsx(
|
|
13403
|
+
Button,
|
|
13404
|
+
{
|
|
13405
|
+
variant: "ghost",
|
|
13406
|
+
size: "icon",
|
|
13407
|
+
className: "h-8 w-8",
|
|
13408
|
+
disabled: rules.length === 1,
|
|
13409
|
+
onClick: () => {
|
|
13410
|
+
setRules((p) => p.filter((_, j) => j !== i));
|
|
13411
|
+
setPreview(null);
|
|
13412
|
+
},
|
|
13413
|
+
children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
|
|
13414
|
+
}
|
|
13415
|
+
)
|
|
13416
|
+
] }, i);
|
|
13417
|
+
}) }),
|
|
13418
|
+
/* @__PURE__ */ jsxs(
|
|
13419
|
+
Button,
|
|
13420
|
+
{
|
|
13421
|
+
variant: "outline",
|
|
13422
|
+
size: "sm",
|
|
13423
|
+
className: "mt-3",
|
|
13424
|
+
onClick: () => {
|
|
13425
|
+
setRules((p) => [...p, { ...EMPTY_RULE }]);
|
|
13426
|
+
setPreview(null);
|
|
13427
|
+
},
|
|
13428
|
+
children: [
|
|
13429
|
+
/* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
|
|
13430
|
+
" ",
|
|
13431
|
+
t2("crm.segments.addRule")
|
|
13432
|
+
]
|
|
13433
|
+
}
|
|
13434
|
+
)
|
|
13435
|
+
] }),
|
|
13436
|
+
segment?.id && /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
13437
|
+
/* @__PURE__ */ jsxs(Button, { variant: "outline", size: "sm", onClick: () => void runPreview(), disabled: previewing, children: [
|
|
13438
|
+
previewing ? /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }) : /* @__PURE__ */ jsx(Users, { className: "h-3.5 w-3.5" }),
|
|
13439
|
+
t2("crm.segments.countNow")
|
|
13440
|
+
] }),
|
|
13441
|
+
preview !== null && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: t2("crm.segments.previewSaved", { count: String(preview) }) })
|
|
13442
|
+
] }),
|
|
13443
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
|
|
13444
|
+
/* @__PURE__ */ jsx(Switch, { checked: isActive, onCheckedChange: setIsActive }),
|
|
13445
|
+
/* @__PURE__ */ jsx("span", { className: "text-xs", children: t2("crm.segments.active") })
|
|
13446
|
+
] }),
|
|
13447
|
+
error && /* @__PURE__ */ jsx("p", { className: "text-xs text-destructive", children: error })
|
|
13448
|
+
] }),
|
|
13449
|
+
/* @__PURE__ */ jsxs(ModalFooter, { children: [
|
|
13450
|
+
/* @__PURE__ */ jsx(Button, { variant: "ghost", onClick: onClose, children: t2("common.cancel") }),
|
|
13451
|
+
/* @__PURE__ */ jsxs(Button, { onClick: () => void save(), disabled: saving, children: [
|
|
13452
|
+
saving && /* @__PURE__ */ jsx(Loader2, { className: "h-3.5 w-3.5 animate-spin" }),
|
|
13453
|
+
t2("common.save")
|
|
13454
|
+
] })
|
|
13455
|
+
] })
|
|
13456
|
+
] }) });
|
|
13457
|
+
}
|
|
13458
|
+
function defaultValueFor(op) {
|
|
13459
|
+
if (VALUELESS_OPS.includes(op)) return void 0;
|
|
13460
|
+
if (DAY_OPS.includes(op)) return 30;
|
|
13461
|
+
if (op === "in" || op === "not_in") return [];
|
|
13462
|
+
return "";
|
|
13463
|
+
}
|
|
13464
|
+
function SegmentSkeleton() {
|
|
13465
|
+
return /* @__PURE__ */ jsx("div", { className: "space-y-3", children: [1, 2, 3].map((i) => /* @__PURE__ */ jsxs("div", { className: "rounded-card border bg-card p-4 shadow-sm", children: [
|
|
13466
|
+
/* @__PURE__ */ jsx("div", { className: "h-4 w-40 animate-pulse rounded bg-muted/40" }),
|
|
13467
|
+
/* @__PURE__ */ jsx("div", { className: "mt-2 h-3 w-64 animate-pulse rounded bg-muted/20" })
|
|
13468
|
+
] }, i)) });
|
|
13469
|
+
}
|
|
13470
|
+
function SegmentsView() {
|
|
13471
|
+
const provider = useCrmProvider();
|
|
13472
|
+
const t2 = useTranslation();
|
|
13473
|
+
const can = usePermissionOptional();
|
|
13474
|
+
const canEdit = can("sales", "edit");
|
|
13475
|
+
const canDelete = can("sales", "delete");
|
|
13476
|
+
const [segments, setSegments] = React20.useState(null);
|
|
13477
|
+
const [counts, setCounts] = React20.useState({});
|
|
13478
|
+
const [editing, setEditing] = React20.useState(void 0);
|
|
13479
|
+
const [removing, setRemoving] = React20.useState(null);
|
|
13480
|
+
const load = React20.useCallback(async () => {
|
|
13481
|
+
const list = await provider.getSegments();
|
|
13482
|
+
setSegments(list);
|
|
13483
|
+
try {
|
|
13484
|
+
const cs = await provider.getSegmentCounts();
|
|
13485
|
+
setCounts(Object.fromEntries(cs.map((c) => [c.segmentId, c.count])));
|
|
13486
|
+
} catch {
|
|
13487
|
+
setCounts({});
|
|
13488
|
+
}
|
|
13489
|
+
}, [provider]);
|
|
13490
|
+
React20.useEffect(() => {
|
|
13491
|
+
void load();
|
|
13492
|
+
}, [load]);
|
|
13493
|
+
async function toggleActive(segment, next) {
|
|
13494
|
+
try {
|
|
13495
|
+
await provider.saveSegment({
|
|
13496
|
+
id: segment.id,
|
|
13497
|
+
name: segment.name,
|
|
13498
|
+
description: segment.description,
|
|
13499
|
+
kind: segment.kind,
|
|
13500
|
+
rules: segment.rules,
|
|
13501
|
+
isActive: next
|
|
13502
|
+
});
|
|
13503
|
+
await load();
|
|
13504
|
+
} catch (e) {
|
|
13505
|
+
toast.error(e?.message ?? t2("crm.segments.error.toggleFailed"));
|
|
13506
|
+
}
|
|
13507
|
+
}
|
|
13508
|
+
async function remove(segment) {
|
|
13509
|
+
try {
|
|
13510
|
+
await provider.deleteSegment(segment.id);
|
|
13511
|
+
setRemoving(null);
|
|
13512
|
+
await load();
|
|
13513
|
+
} catch (e) {
|
|
13514
|
+
toast.error(e?.message ?? t2("crm.segments.error.deleteFailed"));
|
|
13515
|
+
}
|
|
13516
|
+
}
|
|
13517
|
+
return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
|
|
13518
|
+
/* @__PURE__ */ jsx(
|
|
13519
|
+
SubpageHeader,
|
|
13520
|
+
{
|
|
13521
|
+
title: t2("crm.segments.title"),
|
|
13522
|
+
subtitle: t2("crm.segments.subtitle"),
|
|
13523
|
+
actions: /* @__PURE__ */ jsx(
|
|
13524
|
+
PageActions,
|
|
13525
|
+
{
|
|
13526
|
+
actions: [{
|
|
13527
|
+
id: "new-segment",
|
|
13528
|
+
label: t2("crm.segments.new"),
|
|
13529
|
+
icon: Plus,
|
|
13530
|
+
intent: "primary",
|
|
13531
|
+
permission: { feature: "sales", action: "create" },
|
|
13532
|
+
onSelect: () => setEditing(null)
|
|
13533
|
+
}]
|
|
13534
|
+
}
|
|
13535
|
+
)
|
|
13536
|
+
}
|
|
13537
|
+
),
|
|
13538
|
+
segments === null ? /* @__PURE__ */ jsx(SegmentSkeleton, {}) : segments.length === 0 ? /* @__PURE__ */ jsxs("div", { className: "rounded-card border border-dashed bg-card px-6 py-10 text-center", children: [
|
|
13539
|
+
/* @__PURE__ */ jsx(Filter, { className: "mx-auto mb-3 h-8 w-8 text-muted-foreground/50" }),
|
|
13540
|
+
/* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: t2("crm.segments.emptyTitle") }),
|
|
13541
|
+
/* @__PURE__ */ jsx("p", { className: "mx-auto mt-1 max-w-md text-xs text-muted-foreground", children: t2("crm.segments.emptyHint") }),
|
|
13542
|
+
/* @__PURE__ */ jsxs(Button, { className: "mt-4", size: "sm", onClick: () => setEditing(null), children: [
|
|
13543
|
+
/* @__PURE__ */ jsx(Plus, { className: "h-3.5 w-3.5" }),
|
|
13544
|
+
" ",
|
|
13545
|
+
t2("crm.segments.new")
|
|
13546
|
+
] })
|
|
13547
|
+
] }) : /* @__PURE__ */ jsx("div", { className: "space-y-3", "data-testid": "segment-list", children: segments.map((segment) => {
|
|
13548
|
+
const count = counts[segment.id];
|
|
13549
|
+
return /* @__PURE__ */ jsx(
|
|
13550
|
+
"div",
|
|
13551
|
+
{
|
|
13552
|
+
"data-testid": "segment-row",
|
|
13553
|
+
className: `rounded-card border bg-card p-4 shadow-sm ${segment.isActive ? "" : "opacity-60"}`,
|
|
13554
|
+
children: /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-start justify-between gap-3", children: [
|
|
13555
|
+
/* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
|
|
13556
|
+
/* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
|
|
13557
|
+
segment.color && /* @__PURE__ */ jsx("span", { className: "h-2.5 w-2.5 shrink-0 rounded-full", style: { backgroundColor: segment.color } }),
|
|
13558
|
+
/* @__PURE__ */ jsx("h3", { className: "text-sm font-semibold", children: segment.name }),
|
|
13559
|
+
segment.isSystem && /* @__PURE__ */ jsx(TooltipProvider, { children: /* @__PURE__ */ jsxs(Tooltip, { children: [
|
|
13560
|
+
/* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-1 rounded-full bg-muted px-2 py-0.5 text-[10px] text-muted-foreground", children: [
|
|
13561
|
+
/* @__PURE__ */ jsx(Lock, { className: "h-2.5 w-2.5" }),
|
|
13562
|
+
" ",
|
|
13563
|
+
t2("crm.segments.systemBadge")
|
|
13564
|
+
] }) }),
|
|
13565
|
+
/* @__PURE__ */ jsx(TooltipContent, { children: t2("crm.segments.systemHint") })
|
|
13566
|
+
] }) })
|
|
13567
|
+
] }),
|
|
13568
|
+
segment.description && /* @__PURE__ */ jsx("p", { className: "mt-0.5 text-xs text-muted-foreground", children: segment.description }),
|
|
13569
|
+
/* @__PURE__ */ jsx("div", { className: "mt-2 flex flex-wrap gap-1.5", children: segment.rules.where.length === 0 ? /* @__PURE__ */ jsx("span", { className: "rounded bg-warning/10 px-2 py-0.5 text-[10px] text-foreground", children: t2("crm.segments.noRulesWarning") }) : segment.rules.where.map((rule, i) => /* @__PURE__ */ jsx("span", { className: "rounded bg-muted px-2 py-0.5 text-[10px] text-muted-foreground", children: describeRule(rule, t2) }, i)) })
|
|
13570
|
+
] }),
|
|
13571
|
+
/* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
|
|
13572
|
+
/* @__PURE__ */ jsxs("div", { className: "text-right", children: [
|
|
13573
|
+
/* @__PURE__ */ jsx("p", { className: "text-lg font-semibold leading-none", "data-testid": "segment-count", children: count === void 0 ? "\xB7" : count === null ? "\u2014" : count }),
|
|
13574
|
+
/* @__PURE__ */ jsx("p", { className: "mt-1 text-[10px] text-muted-foreground", children: t2("crm.segments.people") })
|
|
13575
|
+
] }),
|
|
13576
|
+
/* @__PURE__ */ jsx(
|
|
13577
|
+
Switch,
|
|
13578
|
+
{
|
|
13579
|
+
checked: segment.isActive,
|
|
13580
|
+
disabled: !canEdit,
|
|
13581
|
+
onCheckedChange: (v) => void toggleActive(segment, v)
|
|
13582
|
+
}
|
|
13583
|
+
),
|
|
13584
|
+
/* @__PURE__ */ jsx(
|
|
13585
|
+
Button,
|
|
13586
|
+
{
|
|
13587
|
+
variant: "ghost",
|
|
13588
|
+
size: "icon",
|
|
13589
|
+
className: "h-8 w-8",
|
|
13590
|
+
disabled: !canEdit,
|
|
13591
|
+
onClick: () => setEditing(segment),
|
|
13592
|
+
children: /* @__PURE__ */ jsx(Pencil, { className: "h-3.5 w-3.5" })
|
|
13593
|
+
}
|
|
13594
|
+
),
|
|
13595
|
+
!segment.isSystem && /* @__PURE__ */ jsx(
|
|
13596
|
+
Button,
|
|
13597
|
+
{
|
|
13598
|
+
variant: "ghost",
|
|
13599
|
+
size: "icon",
|
|
13600
|
+
className: "h-8 w-8",
|
|
13601
|
+
disabled: !canDelete,
|
|
13602
|
+
onClick: () => setRemoving(segment),
|
|
13603
|
+
children: /* @__PURE__ */ jsx(Trash2, { className: "h-3.5 w-3.5" })
|
|
13604
|
+
}
|
|
13605
|
+
)
|
|
13606
|
+
] })
|
|
13607
|
+
] })
|
|
13608
|
+
},
|
|
13609
|
+
segment.id
|
|
13610
|
+
);
|
|
13611
|
+
}) }),
|
|
13612
|
+
/* @__PURE__ */ jsx(
|
|
13613
|
+
SegmentEditorDialog,
|
|
13614
|
+
{
|
|
13615
|
+
open: editing !== void 0,
|
|
13616
|
+
segment: editing ?? null,
|
|
13617
|
+
provider,
|
|
13618
|
+
onClose: () => setEditing(void 0),
|
|
13619
|
+
onSaved: () => void load()
|
|
13620
|
+
}
|
|
13621
|
+
),
|
|
13622
|
+
/* @__PURE__ */ jsx(
|
|
13623
|
+
ConfirmDialog,
|
|
13624
|
+
{
|
|
13625
|
+
open: removing !== null,
|
|
13626
|
+
onCancel: () => setRemoving(null),
|
|
13627
|
+
title: t2("crm.segments.deleteTitle"),
|
|
13628
|
+
description: t2("crm.segments.deleteDescription", { name: removing?.name ?? "" }),
|
|
13629
|
+
confirmLabel: t2("common.delete"),
|
|
13630
|
+
variant: "destructive",
|
|
13631
|
+
onConfirm: () => {
|
|
13632
|
+
if (removing) void remove(removing);
|
|
13633
|
+
}
|
|
13634
|
+
}
|
|
13635
|
+
)
|
|
13636
|
+
] });
|
|
13637
|
+
}
|
|
10473
13638
|
function registerCrmTimelineSource() {
|
|
10474
13639
|
registerTimelineSource({
|
|
10475
13640
|
id: "activities",
|
|
@@ -10524,7 +13689,9 @@ function resolveConfig(options) {
|
|
|
10524
13689
|
quotes: options?.modules?.quotes !== false,
|
|
10525
13690
|
activities: options?.modules?.activities !== false,
|
|
10526
13691
|
pipeline: options?.modules?.pipeline !== false,
|
|
10527
|
-
surveys: options?.modules?.surveys !== false
|
|
13692
|
+
surveys: options?.modules?.surveys !== false,
|
|
13693
|
+
segments: options?.modules?.segments !== false,
|
|
13694
|
+
network: options?.modules?.network !== false
|
|
10528
13695
|
},
|
|
10529
13696
|
labels: { ...DEFAULT_LABELS, ...options?.labels },
|
|
10530
13697
|
currency: { ...DEFAULT_CURRENCY, ...options?.currency },
|
|
@@ -10546,7 +13713,7 @@ function createCrmPlugin(options) {
|
|
|
10546
13713
|
() => createMockCrmProvider({ activityTypes })
|
|
10547
13714
|
);
|
|
10548
13715
|
const store = createCrmStore(provider);
|
|
10549
|
-
const PageComponent = () =>
|
|
13716
|
+
const PageComponent = () => React20.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
|
|
10550
13717
|
const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
|
|
10551
13718
|
return {
|
|
10552
13719
|
id: "crm",
|
|
@@ -10823,12 +13990,21 @@ function createCrmPlugin(options) {
|
|
|
10823
13990
|
label: "Sales & CRM",
|
|
10824
13991
|
icon: "Filter",
|
|
10825
13992
|
component: (() => {
|
|
10826
|
-
const Tab = () =>
|
|
13993
|
+
const Tab = () => React20.createElement(
|
|
10827
13994
|
CrmContextProvider,
|
|
10828
13995
|
{ config, provider, store },
|
|
10829
|
-
|
|
13996
|
+
React20.createElement(PluginSettingsPanel, {
|
|
10830
13997
|
title: "Sales & CRM",
|
|
10831
|
-
generalSettings:
|
|
13998
|
+
generalSettings: React20.createElement(CrmGeneralSettings),
|
|
13999
|
+
// Segmento é CADASTRO, e mora onde os outros moram. Etapas do
|
|
14000
|
+
// funil, origens, parcerias e tags já estão aqui; ter o recorte
|
|
14001
|
+
// fora, no rail de trabalho diário, era a inconsistência.
|
|
14002
|
+
customTabs: [{
|
|
14003
|
+
id: "segments",
|
|
14004
|
+
label: "Segmentos",
|
|
14005
|
+
icon: "Filter",
|
|
14006
|
+
content: React20.createElement(SegmentsView)
|
|
14007
|
+
}],
|
|
10832
14008
|
registries: crmRegistries2,
|
|
10833
14009
|
hostPluginId: "crm",
|
|
10834
14010
|
routeBase: "/settings/crm"
|