@fayz-ai/plugin-crm 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import React17, { useState, useEffect, useMemo, useRef, useCallback } from 'react';
2
- import { registerTranslations, registerMessageDefaults, createSafeDataProvider, getSupabaseClientOptional, usePluginRuntimeOptional, useTranslation, useActiveTenantId, getActiveTenantId, loadMessageOverrides, resolveMessages } from '@fayz-ai/core';
3
- import { createPluginContext, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, usePermissionOptional, useLimitGuard, RightRailPage, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, useAccessOptional, invalidateLimit, useOrganizationStore, getRailPage } from '@fayz-ai/admin';
4
- import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, ConfirmDialog, SheetBody, SheetFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, DashboardCanvas, PageToolbar, ToolbarButton, RangeControl, HeaderTabs, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, normalizePhone, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
2
+ import { tl, registerTranslations, registerMessageDefaults, createSafeDataProvider, getSupabaseClientOptional, usePluginRuntimeOptional, useTranslation, useActiveTenantId, exportCSV, getActiveTenantId, loadMessageOverrides, resolveMessages } from '@fayz-ai/core';
3
+ import { createPluginContext, PluginSettingsPanel, registerTimelineSource, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, adminNavigateTo, PageActions, usePermissionOptional, useLimitGuard, RightRailPage, OrderFormSkeleton, OrderFormBlock, OrderFormView, OrderFormItemsCard, OrderFormItemRow, OrderFormAddItemStep, formatCurrency, OrderDetailSkeleton, OrderDetailBlock, OrderDetailView, PersonLink, useAccessOptional, invalidateLimit, useOrganizationStore, getRailPage } from '@fayz-ai/admin';
4
+ import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, useIsWide, SubpageHeader, PageHeaderActions, ListView, ConfirmDialog, SheetBody, Select, SelectTrigger, SelectValue, SelectContent, SelectItem, SheetFooter, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, PhoneLink, DashboardCanvas, 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 { jsxs, jsx, 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, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Tag, Plus, Zap, Paperclip, ImageOff, CircleAlert, CircleDashed, Loader2, DollarSign, User, Building2 } from 'lucide-react';
6
+ import { Archive, FileX2, FileCheck2, Send, FilePlus2, XCircle, Trophy, MoveRight, Target, ArrowRightLeft, UserPlus, MessageCircle, CheckSquare, FileText, Users, Mail, Phone, Filter, Globe, Check, ChevronRight, Plus, Settings, Download, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, CircleCheckBig, Ban, Receipt, Package, CalendarClock, Tag, Zap, Paperclip, ImageOff, CircleAlert, CircleDashed, Loader2, DollarSign, User, Building2 } from 'lucide-react';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
9
9
 
@@ -1332,6 +1332,7 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead, onOpenS
1332
1332
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
1333
1333
  const [optimisticBoard, setOptimisticBoard] = useState(null);
1334
1334
  const t2 = useTranslation();
1335
+ const isWide = useIsWide();
1335
1336
  const [selectedDealId, setSelectedDealId] = useState(null);
1336
1337
  const dragRef = useRef(null);
1337
1338
  const savingRef = useRef(savingDealIds);
@@ -1434,6 +1435,28 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead, onOpenS
1434
1435
  }
1435
1436
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1436
1437
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.pipeline.title"), subtitle: t2("crm.pipeline.subtitle") }),
1438
+ !isWide && /* @__PURE__ */ jsx(PageHeaderActions, { children: /* @__PURE__ */ jsx(
1439
+ PageActions,
1440
+ {
1441
+ actions: [
1442
+ ...onAddLead ? [{
1443
+ id: "new-deal",
1444
+ label: t2("crm.quickActions.newDeal"),
1445
+ icon: Plus,
1446
+ intent: "primary",
1447
+ creates: true,
1448
+ onSelect: onAddLead
1449
+ }] : [],
1450
+ ...onOpenSettings ? [{
1451
+ id: "pipeline-stages",
1452
+ label: t2("crm.pipeline.setupStages"),
1453
+ icon: Settings,
1454
+ intent: "utility",
1455
+ onSelect: onOpenSettings
1456
+ }] : []
1457
+ ]
1458
+ }
1459
+ ) }),
1437
1460
  /* @__PURE__ */ jsx(
1438
1461
  BoardFilters,
1439
1462
  {
@@ -1558,6 +1581,27 @@ var columns = [
1558
1581
  }
1559
1582
  }
1560
1583
  ];
1584
+ function formAnswerColumns(leads) {
1585
+ const keys = [];
1586
+ for (const lead of leads) {
1587
+ for (const [key] of answerEntries(lead.metadata?.fields)) {
1588
+ if (!keys.includes(key)) keys.push(key);
1589
+ }
1590
+ }
1591
+ return keys.map((key) => ({
1592
+ key: `field:${key}`,
1593
+ label: humanizeKey(key),
1594
+ format: (_value, row) => {
1595
+ const fields = row.metadata?.fields;
1596
+ const value = fields?.[key];
1597
+ if (value === null || value === void 0 || value === "") return "";
1598
+ if (Array.isArray(value)) return value.join(", ");
1599
+ if (typeof value === "boolean") return value ? "Sim" : "N\xE3o";
1600
+ if (typeof value === "object") return JSON.stringify(value);
1601
+ return String(value);
1602
+ }
1603
+ }));
1604
+ }
1561
1605
  function LeadListView({ onNew, onEdit }) {
1562
1606
  const t2 = useTranslation();
1563
1607
  const can = usePermissionOptional();
@@ -1627,6 +1671,33 @@ function LeadListView({ onNew, onEdit }) {
1627
1671
  }] : []
1628
1672
  ];
1629
1673
  }, [can, bulkBusy, runBulk, updateLead, t2]);
1674
+ const exportRows = useCallback(() => {
1675
+ exportCSV(
1676
+ [
1677
+ { key: "createdAt", label: t2("crm.leads.receivedCol"), format: (v) => {
1678
+ const at = v ? new Date(String(v)) : null;
1679
+ return at && !Number.isNaN(at.getTime()) ? at.toLocaleString() : "";
1680
+ } },
1681
+ { key: "name", label: t2("crm.leads.name") },
1682
+ { key: "email", label: t2("crm.leadForm.email") },
1683
+ { key: "phone", label: t2("crm.leadForm.phone") },
1684
+ { key: "company", label: t2("crm.leadForm.company") },
1685
+ { key: "sourceName", label: t2("crm.leads.source") },
1686
+ { key: "status", label: t2("crm.leads.statusCol"), format: (v) => {
1687
+ const opt = LEAD_STATUS_OPTIONS.find((o) => o.value === v);
1688
+ return opt ? t2(opt.labelKey) : String(v ?? "");
1689
+ } },
1690
+ { key: "notes", label: t2("crm.leadDetail.notes") },
1691
+ // O que a landing page perguntou vira uma coluna POR PERGUNTA, com as
1692
+ // chaves descobertas nas linhas — cada campanha pergunta outra coisa, e
1693
+ // declarar as colunas aqui tornaria o próximo formulário invisível.
1694
+ ...formAnswerColumns(leads)
1695
+ ],
1696
+ leads,
1697
+ "leads"
1698
+ );
1699
+ toast.success(t2("crud.export.toastSuccess", { count: String(leads.length) }));
1700
+ }, [leads, t2]);
1630
1701
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1631
1702
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.leads.title") }),
1632
1703
  /* @__PURE__ */ jsx(
@@ -1644,6 +1715,8 @@ function LeadListView({ onNew, onEdit }) {
1644
1715
  onTagChange: (v) => setStatusFilter(v ? [v] : []),
1645
1716
  newLabel: t2("crm.leads.newLead"),
1646
1717
  onNew,
1718
+ onExport: leads.length > 0 ? exportRows : void 0,
1719
+ exportLabel: t2("crud.export.action"),
1647
1720
  bulkActions,
1648
1721
  onRowClick: (row) => onEdit?.(row.id),
1649
1722
  emptyIcon: UserPlus,
@@ -1679,17 +1752,27 @@ function LeadFormView({ onSaved }) {
1679
1752
  const t2 = useTranslation();
1680
1753
  const createLead = useCrmStore((s) => s.createLead);
1681
1754
  const guardLeads = useLimitGuard("leads");
1682
- const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
1683
- const pipelines = useCrmStore((s) => s.pipelines);
1684
- useEffect(() => {
1685
- if (pipelines.length === 0) fetchPipelines();
1686
- }, []);
1755
+ const resolveEntryPipeline = useCrmStore((s) => s.resolveEntryPipeline);
1687
1756
  const [name, setName] = useState("");
1688
1757
  const [email, setEmail] = useState("");
1689
1758
  const [phone, setPhone] = useState("");
1690
1759
  const [company, setCompany] = useState("");
1691
1760
  const [notes, setNotes] = useState("");
1692
1761
  const [saving, setSaving] = useState(false);
1762
+ const [stages, setStages] = useState([]);
1763
+ const [stageId, setStageId] = useState("");
1764
+ useEffect(() => {
1765
+ let cancelled = false;
1766
+ void resolveEntryPipeline().then(({ stages: entry }) => {
1767
+ if (cancelled) return;
1768
+ const open = entry.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order);
1769
+ setStages(open);
1770
+ setStageId((current) => current || open[0]?.id || "");
1771
+ });
1772
+ return () => {
1773
+ cancelled = true;
1774
+ };
1775
+ }, []);
1693
1776
  async function handleSave() {
1694
1777
  if (!name.trim()) {
1695
1778
  toast.error(t2("common.formIncomplete"));
@@ -1698,7 +1781,7 @@ function LeadFormView({ onSaved }) {
1698
1781
  if (await guardLeads() === "blocked") return;
1699
1782
  setSaving(true);
1700
1783
  try {
1701
- const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0 });
1784
+ const lead = await createLead({ name, email: email || void 0, phone: phone || void 0, company: company || void 0, notes: notes || void 0, stageId: stageId || void 0 });
1702
1785
  invalidateLimit("leads");
1703
1786
  invalidateLimit("deals");
1704
1787
  onSaved?.(lead.id);
@@ -1737,6 +1820,13 @@ function LeadFormView({ onSaved }) {
1737
1820
  /* @__PURE__ */ jsxs("div", { children: [
1738
1821
  /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.notes") }),
1739
1822
  /* @__PURE__ */ jsx("textarea", { value: notes, onChange: (e) => setNotes(e.target.value), rows: 2, placeholder: t2("crm.leadForm.notesPlaceholder"), className: "w-full mt-1 rounded-input border border-input bg-card shadow-[inset_0_1px_0_rgb(0_0_0_/0.06)] px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring resize-none" })
1823
+ ] }),
1824
+ stages.length > 1 && /* @__PURE__ */ jsxs("div", { children: [
1825
+ /* @__PURE__ */ jsx("label", { className: "text-xs font-medium text-muted-foreground", children: t2("crm.leadForm.stage") }),
1826
+ /* @__PURE__ */ jsxs(Select, { value: stageId, onValueChange: setStageId, children: [
1827
+ /* @__PURE__ */ jsx(SelectTrigger, { className: "mt-1", children: /* @__PURE__ */ jsx(SelectValue, {}) }),
1828
+ /* @__PURE__ */ jsx(SelectContent, { children: stages.map((s) => /* @__PURE__ */ jsx(SelectItem, { value: s.id, children: s.name }, s.id)) })
1829
+ ] })
1740
1830
  ] })
1741
1831
  ] }),
1742
1832
  /* @__PURE__ */ jsx(SheetFooter, { children: /* @__PURE__ */ jsx(Button, { className: "flex-1", onClick: () => void handleSave(), disabled: saving || !name.trim(), children: saving ? t2("common.saving") : t2("crm.leadForm.save") }) })
@@ -1825,16 +1915,37 @@ function QuoteListView({ onNew, onEdit, onEditQuote }) {
1825
1915
  const columns2 = useQuoteColumns(currency, onEditQuote, canArchive ? (id) => {
1826
1916
  void archiveQuote(id);
1827
1917
  } : void 0);
1918
+ const exportRows = useCallback(() => {
1919
+ exportCSV(
1920
+ [
1921
+ { key: "quoteNumber", label: "#" },
1922
+ { key: "quoteDate", label: t2("crm.quotes.date") },
1923
+ { key: "contactName", label: t2("crm.quotes.contact") },
1924
+ { key: "totalAmount", label: t2("crm.quotes.amount"), format: (v) => formatCurrency(Number(v) || 0, currency) },
1925
+ { key: "status", label: t2("crm.quotes.status") },
1926
+ { key: "validUntil", label: t2("crm.quoteForm.validUntil") }
1927
+ ],
1928
+ quotes,
1929
+ "orcamentos"
1930
+ );
1931
+ toast.success(t2("crud.export.toastSuccess", { count: String(quotes.length) }));
1932
+ }, [quotes, currency, t2]);
1828
1933
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
1829
1934
  /* @__PURE__ */ jsx(
1830
1935
  SubpageHeader,
1831
1936
  {
1832
1937
  title: t2("crm.quotes.title"),
1833
- actions: onNew && /* @__PURE__ */ jsxs("button", { onClick: onNew, className: "inline-flex items-center gap-1.5 rounded-button bg-primary border border-primary px-3 py-2 text-sm font-medium text-primary-foreground hover:bg-primary/90 shadow-button-primary active:shadow-button-inset transition-colors", children: [
1834
- /* @__PURE__ */ jsx("span", { className: "h-3.5 w-3.5 inline-flex items-center justify-center", children: "+" }),
1835
- " ",
1836
- t2("crm.quotes.newQuote")
1837
- ] })
1938
+ actions: (onNew || quotes.length > 0) && /* @__PURE__ */ jsx(
1939
+ PageActions,
1940
+ {
1941
+ actions: [
1942
+ ...onNew ? [{ id: "new-quote", label: t2("crm.quotes.newQuote"), icon: Plus, intent: "primary", onSelect: onNew }] : [],
1943
+ // 'utility': ícone só, ao lado do primário — o mesmo lugar que o
1944
+ // exportar ocupa em toda lista de CRUD.
1945
+ ...quotes.length > 0 ? [{ id: "export", label: t2("crud.export.action"), icon: Download, intent: "utility", onSelect: exportRows }] : []
1946
+ ]
1947
+ }
1948
+ )
1838
1949
  }
1839
1950
  ),
1840
1951
  /* @__PURE__ */ jsx(
@@ -2904,8 +3015,38 @@ function ActivityListView({ onOpenLead, onOpenQuote } = {}) {
2904
3015
  }, [typeFilter, showCompleted]);
2905
3016
  const filtered = eventsFilter ? activities.filter((a) => SYSTEM_TYPES.has(a.activityType)) : activities;
2906
3017
  const messages = useActivityAutomations();
3018
+ const exportRows = useCallback(() => {
3019
+ exportCSV(
3020
+ [
3021
+ { key: "createdAt", label: t2("crm.leads.receivedCol"), format: (v) => {
3022
+ const at = v ? new Date(String(v)) : null;
3023
+ return at && !Number.isNaN(at.getTime()) ? at.toLocaleString() : "";
3024
+ } },
3025
+ { key: "activityType", label: t2("crm.activities.typeCol"), format: (v) => TYPE_CONFIG[String(v)]?.label ?? String(v ?? "") },
3026
+ { key: "title", label: t2("crm.activities.titleCol") },
3027
+ { key: "description", label: t2("crm.leadDetail.notes") },
3028
+ { key: "contactName", label: t2("crm.quotes.contact") },
3029
+ { key: "dueDate", label: t2("crm.activities.dueCol") },
3030
+ { key: "completedAt", label: t2("crm.activities.done") }
3031
+ ],
3032
+ filtered,
3033
+ "atividades"
3034
+ );
3035
+ toast.success(t2("crud.export.toastSuccess", { count: String(filtered.length) }));
3036
+ }, [filtered, t2]);
2907
3037
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
2908
- /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.activities.title") }),
3038
+ /* @__PURE__ */ jsx(
3039
+ SubpageHeader,
3040
+ {
3041
+ title: t2("crm.activities.title"),
3042
+ actions: filtered.length > 0 && /* @__PURE__ */ jsx(
3043
+ PageActions,
3044
+ {
3045
+ actions: [{ id: "export", label: t2("crud.export.action"), icon: Download, intent: "utility", onSelect: exportRows }]
3046
+ }
3047
+ )
3048
+ }
3049
+ ),
2909
3050
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col sm:flex-row gap-3 sm:items-center", children: [
2910
3051
  /* @__PURE__ */ jsxs("div", { className: "flex gap-1.5 flex-wrap", children: [
2911
3052
  /* @__PURE__ */ jsx(
@@ -3215,8 +3356,7 @@ function CrmPage({ config, provider, store, registries }) {
3215
3356
  ModuleActionBar,
3216
3357
  {
3217
3358
  quickActions,
3218
- settingsPath: registries && registries.length > 0 ? "/settings/crm" : void 0,
3219
- settingsLabel: "CRM Settings"
3359
+ settingsPath: registries && registries.length > 0 ? "/settings/crm" : void 0
3220
3360
  }
3221
3361
  ),
3222
3362
  children: renderView(view)
@@ -4121,6 +4261,15 @@ function createSupabaseCrmProvider(options) {
4121
4261
  value: r.lead_value ? Number(r.lead_value) : void 0,
4122
4262
  tags: r.tags ?? [],
4123
4263
  notes: r.notes,
4264
+ // As respostas do formulário vinham só no getLeadById, embora o
4265
+ // select('*') já as trouxesse aqui: a lista tinha a informação na mão
4266
+ // e a jogava fora, então exportar os leads perdia justamente o que a
4267
+ // campanha perguntou.
4268
+ metadata: {
4269
+ formId: r.form_id ?? void 0,
4270
+ fields: r.custom_fields ?? {},
4271
+ utm: r.utm ?? {}
4272
+ },
4124
4273
  tenantId: r.tenant_id,
4125
4274
  createdAt: r.created_at,
4126
4275
  updatedAt: r.updated_at
@@ -4985,25 +5134,33 @@ function createCrmStore(provider) {
4985
5134
  set({ quotes: result.data, quotesTotal: result.total, quotesLoading: false });
4986
5135
  });
4987
5136
  },
5137
+ async resolveEntryPipeline() {
5138
+ let { pipelines, stages } = get();
5139
+ if (pipelines.length === 0) {
5140
+ pipelines = await provider.getPipelines();
5141
+ stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
5142
+ set({ pipelines, stages });
5143
+ }
5144
+ const pipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
5145
+ if (!pipeline) return { pipeline: void 0, stages: [] };
5146
+ const own = pipeline.id === pipelines[0]?.id && stages.length > 0 ? stages : await provider.getPipelineStages(pipeline.id);
5147
+ return { pipeline, stages: own };
5148
+ },
4988
5149
  async createLead(input) {
4989
5150
  try {
4990
5151
  const lead = await provider.createLead(input);
4991
- let { pipelines, stages } = get();
4992
- if (pipelines.length === 0) {
4993
- pipelines = await provider.getPipelines();
4994
- stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
4995
- set({ pipelines, stages });
4996
- }
4997
- const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
4998
- const firstStage = stages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order)[0];
4999
- if (defaultPipeline && firstStage) {
5152
+ const { pipeline, stages: entryStages } = await get().resolveEntryPipeline();
5153
+ const open = entryStages.filter((s) => !s.isWon && !s.isLost).sort((a, b) => a.order - b.order);
5154
+ const chosen = input.stageId ? entryStages.find((s) => s.id === input.stageId) : void 0;
5155
+ const stage = chosen ?? open[0];
5156
+ if (pipeline && stage) {
5000
5157
  try {
5001
5158
  await provider.createDeal({
5002
5159
  leadId: lead.id,
5003
5160
  title: lead.name,
5004
5161
  value: input.value ?? 0,
5005
- pipelineId: defaultPipeline.id,
5006
- stageId: firstStage.id,
5162
+ pipelineId: pipeline.id,
5163
+ stageId: stage.id,
5007
5164
  contactName: lead.name
5008
5165
  });
5009
5166
  } catch {
@@ -5056,13 +5213,7 @@ function createCrmStore(provider) {
5056
5213
  },
5057
5214
  async createQuote(input) {
5058
5215
  try {
5059
- let { pipelines, stages } = get();
5060
- if (pipelines.length === 0) {
5061
- pipelines = await provider.getPipelines();
5062
- stages = pipelines.length > 0 ? await provider.getPipelineStages(pipelines[0].id) : [];
5063
- set({ pipelines, stages });
5064
- }
5065
- const defaultPipeline = pipelines.find((p) => p.isDefault) ?? pipelines[0];
5216
+ const { pipeline: defaultPipeline, stages } = await get().resolveEntryPipeline();
5066
5217
  let leadId = input.leadId;
5067
5218
  let dealId = input.dealId;
5068
5219
  const contactId = input.contactId;
@@ -5254,6 +5405,275 @@ function createCrmStore(provider) {
5254
5405
  }
5255
5406
  }));
5256
5407
  }
5408
+ var LEADS = "plg_crm_rep_leads";
5409
+ var DEALS = "plg_crm_rep_deals";
5410
+ var CAT_LEADS = tl("Leads", "Leads");
5411
+ var CAT_DEALS = tl("Deals", "Neg\xF3cios");
5412
+ var LEAD_STATUS_LABELS = {
5413
+ new: tl("New", "Novo"),
5414
+ contacted: tl("Contacted", "Contatado"),
5415
+ qualified: tl("Qualified", "Qualificado"),
5416
+ unqualified: tl("Unqualified", "Desqualificado"),
5417
+ converted: tl("Converted", "Convertido"),
5418
+ lost: tl("Lost", "Perdido")
5419
+ };
5420
+ var DEAL_STATUS_LABELS = {
5421
+ open: tl("Open", "Aberto"),
5422
+ won: tl("Won", "Ganho"),
5423
+ lost: tl("Lost", "Perdido")
5424
+ };
5425
+ var leadStatusFilter = {
5426
+ key: "status",
5427
+ label: tl("Lead status", "Situa\xE7\xE3o do lead"),
5428
+ type: "multiselect",
5429
+ group: CAT_LEADS,
5430
+ options: [
5431
+ { label: tl("New", "Novo"), value: "new" },
5432
+ { label: tl("Contacted", "Contatado"), value: "contacted" },
5433
+ { label: tl("Qualified", "Qualificado"), value: "qualified" },
5434
+ { label: tl("Unqualified", "Desqualificado"), value: "unqualified" },
5435
+ { label: tl("Converted", "Convertido"), value: "converted" },
5436
+ { label: tl("Lost", "Perdido"), value: "lost" }
5437
+ ]
5438
+ };
5439
+ var dealStatusFilter = {
5440
+ key: "status",
5441
+ label: tl("Deal status", "Situa\xE7\xE3o do neg\xF3cio"),
5442
+ type: "multiselect",
5443
+ group: CAT_DEALS,
5444
+ options: [
5445
+ { label: tl("Open", "Aberto"), value: "open" },
5446
+ { label: tl("Won", "Ganho"), value: "won" },
5447
+ { label: tl("Lost", "Perdido"), value: "lost" }
5448
+ ]
5449
+ };
5450
+ function buildCrmAnalyticsCards() {
5451
+ const base = { domain: "crm", compare: true };
5452
+ return [
5453
+ // -----------------------------------------------------------------------
5454
+ // Leads
5455
+ // -----------------------------------------------------------------------
5456
+ {
5457
+ ...base,
5458
+ id: "crm.leads",
5459
+ name: tl("Leads", "Leads"),
5460
+ description: tl(
5461
+ "Leads that came in during the period.",
5462
+ "Leads que entraram no per\xEDodo."
5463
+ ),
5464
+ icon: "UserPlus",
5465
+ category: CAT_LEADS,
5466
+ grain: "lead",
5467
+ canonicalOwner: "public.v_leads",
5468
+ query: {
5469
+ source: { kind: "view", name: LEADS },
5470
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5471
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5472
+ filters: [leadStatusFilter]
5473
+ },
5474
+ viz: { type: "kpi", spark: true },
5475
+ dashboard: { span: 1, order: 20 }
5476
+ },
5477
+ {
5478
+ ...base,
5479
+ id: "crm.leads-by-source",
5480
+ name: tl("Leads by source", "Leads por origem"),
5481
+ description: tl(
5482
+ 'Where the enquiries came from \u2014 the answer to "is the campaign working".',
5483
+ 'De onde vieram os contatos \u2014 a resposta para "a campanha est\xE1 funcionando".'
5484
+ ),
5485
+ icon: "Share2",
5486
+ category: CAT_LEADS,
5487
+ grain: "lead",
5488
+ query: {
5489
+ source: { kind: "view", name: LEADS },
5490
+ dimensions: [{ key: "source_name", label: tl("Source", "Origem") }],
5491
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5492
+ filters: [leadStatusFilter],
5493
+ defaultSort: "leads",
5494
+ defaultSortDir: "desc"
5495
+ },
5496
+ viz: { type: "breakdown", limit: 8 },
5497
+ dashboard: { span: 1, order: 21 }
5498
+ },
5499
+ {
5500
+ ...base,
5501
+ id: "crm.leads-by-status",
5502
+ name: tl("Leads by status", "Leads por situa\xE7\xE3o"),
5503
+ description: tl(
5504
+ "How the period\u2019s enquiries are spread across the funnel.",
5505
+ "Como os contatos do per\xEDodo est\xE3o distribu\xEDdos no funil."
5506
+ ),
5507
+ icon: "Filter",
5508
+ category: CAT_LEADS,
5509
+ grain: "lead",
5510
+ query: {
5511
+ source: { kind: "view", name: LEADS },
5512
+ dimensions: [{ key: "status", label: tl("Status", "Situa\xE7\xE3o") }],
5513
+ measures: [{ key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" }],
5514
+ defaultSort: "leads",
5515
+ defaultSortDir: "desc"
5516
+ },
5517
+ viz: { type: "donut" }
5518
+ },
5519
+ {
5520
+ // Converted over total, computed after aggregation: a ratio of sums, not
5521
+ // an average of per-row ratios, which would answer a different question.
5522
+ ...base,
5523
+ id: "crm.lead-conversion",
5524
+ name: tl("Lead conversion", "Convers\xE3o de leads"),
5525
+ description: tl(
5526
+ "Share of the period\u2019s leads that became a customer.",
5527
+ "Parte dos leads do per\xEDodo que virou cliente."
5528
+ ),
5529
+ icon: "TrendingUp",
5530
+ category: CAT_LEADS,
5531
+ grain: "lead",
5532
+ query: {
5533
+ source: { kind: "view", name: LEADS },
5534
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5535
+ measures: [
5536
+ { key: "leads", label: tl("Leads", "Leads"), agg: "count", format: "number" },
5537
+ { key: "converted", label: tl("Converted", "Convertidos"), agg: "sum", column: "is_converted", format: "number" },
5538
+ {
5539
+ key: "conversion",
5540
+ label: tl("Conversion", "Convers\xE3o"),
5541
+ agg: "ratio",
5542
+ ratioOf: ["converted", "leads"],
5543
+ scale: 100,
5544
+ format: "percent"
5545
+ }
5546
+ ]
5547
+ },
5548
+ viz: { type: "kpi", measures: ["conversion"], spark: true }
5549
+ },
5550
+ {
5551
+ // The one the CRM never had: every lead, in a table, exportable. No
5552
+ // measures, so it is a plain select over the read model rather than an
5553
+ // aggregate — the rows themselves ARE the report.
5554
+ ...base,
5555
+ id: "crm.leads-list",
5556
+ name: tl("Lead list", "Lista de leads"),
5557
+ description: tl(
5558
+ "Every lead in the period with contact details, source and status \u2014 ready to export.",
5559
+ "Todo lead do per\xEDodo com contato, origem e situa\xE7\xE3o \u2014 pronto para exportar."
5560
+ ),
5561
+ icon: "Users",
5562
+ category: CAT_LEADS,
5563
+ grain: "lead",
5564
+ canonicalOwner: "public.v_leads",
5565
+ query: {
5566
+ source: { kind: "view", name: LEADS },
5567
+ filters: [leadStatusFilter],
5568
+ defaultSort: "created_at",
5569
+ defaultSortDir: "desc"
5570
+ },
5571
+ columns: [
5572
+ { key: "created_at", label: tl("Received", "Entrada"), type: "date", sortable: true },
5573
+ { key: "lead_name", label: tl("Name", "Nome"), type: "text", sortable: true },
5574
+ { key: "email", label: tl("E-mail", "E-mail"), type: "email" },
5575
+ { key: "phone", label: tl("Phone", "Telefone"), type: "text" },
5576
+ { key: "company", label: tl("Company", "Empresa"), type: "text" },
5577
+ { key: "source_name", label: tl("Source", "Origem"), type: "text" },
5578
+ { key: "status", label: tl("Status", "Situa\xE7\xE3o"), type: "text", valueMap: LEAD_STATUS_LABELS },
5579
+ // O que a landing page perguntou — estilo, perfil, "tem WhatsApp?".
5580
+ // Uma coluna na tela (as perguntas mudam a cada campanha, e declarar
5581
+ // uma coluna por pergunta tornaria o PRÓXIMO formulário invisível) e,
5582
+ // na planilha, uma coluna por pergunta: é `expand` quem faz isso, com
5583
+ // as chaves descobertas nas linhas exportadas.
5584
+ {
5585
+ key: "custom_fields",
5586
+ label: tl("Form answers", "Dados do formul\xE1rio"),
5587
+ type: "text",
5588
+ expand: true,
5589
+ sortable: false
5590
+ },
5591
+ // Export-only: useful in the spreadsheet, noise in a table already
5592
+ // carrying seven columns.
5593
+ { key: "utm_source", label: tl("UTM source", "UTM origem"), type: "text", visible: false },
5594
+ { key: "utm_campaign", label: tl("UTM campaign", "UTM campanha"), type: "text", visible: false },
5595
+ { key: "lead_value", label: tl("Value", "Valor"), type: "currency", visible: false }
5596
+ ],
5597
+ viz: { type: "table" }
5598
+ },
5599
+ // -----------------------------------------------------------------------
5600
+ // Deals
5601
+ // -----------------------------------------------------------------------
5602
+ {
5603
+ ...base,
5604
+ id: "crm.deals-won",
5605
+ name: tl("Won deals", "Neg\xF3cios ganhos"),
5606
+ description: tl(
5607
+ "Value of the deals closed as won in the period.",
5608
+ "Valor dos neg\xF3cios fechados como ganhos no per\xEDodo."
5609
+ ),
5610
+ icon: "Trophy",
5611
+ category: CAT_DEALS,
5612
+ grain: "deal",
5613
+ canonicalOwner: "public.v_deals",
5614
+ query: {
5615
+ source: { kind: "view", name: DEALS },
5616
+ dimensions: [{ key: "created_at", label: tl("Date", "Data"), grain: "auto" }],
5617
+ measures: [{ key: "won_value", label: tl("Won", "Ganho"), agg: "sum", format: "currency" }]
5618
+ },
5619
+ viz: { type: "kpi", spark: true }
5620
+ },
5621
+ {
5622
+ ...base,
5623
+ id: "crm.deals-by-stage",
5624
+ name: tl("Pipeline by stage", "Funil por etapa"),
5625
+ description: tl(
5626
+ "What is sitting in each stage of the board, and what it is worth.",
5627
+ "O que est\xE1 parado em cada etapa do quadro, e quanto vale."
5628
+ ),
5629
+ icon: "Columns3",
5630
+ category: CAT_DEALS,
5631
+ grain: "deal",
5632
+ query: {
5633
+ source: { kind: "view", name: DEALS },
5634
+ dimensions: [{ key: "stage_name", label: tl("Stage", "Etapa") }],
5635
+ measures: [
5636
+ { key: "deals", label: tl("Deals", "Neg\xF3cios"), agg: "count", format: "number" },
5637
+ { key: "value", label: tl("Value", "Valor"), agg: "sum", format: "currency" }
5638
+ ],
5639
+ filters: [dealStatusFilter],
5640
+ defaultSort: "value",
5641
+ defaultSortDir: "desc"
5642
+ },
5643
+ viz: { type: "bar", measures: ["value"] }
5644
+ },
5645
+ {
5646
+ ...base,
5647
+ id: "crm.deals-list",
5648
+ name: tl("Deal list", "Lista de neg\xF3cios"),
5649
+ description: tl(
5650
+ "Every deal in the period with its stage, value and owner \u2014 ready to export.",
5651
+ "Todo neg\xF3cio do per\xEDodo com etapa, valor e respons\xE1vel \u2014 pronto para exportar."
5652
+ ),
5653
+ icon: "Handshake",
5654
+ category: CAT_DEALS,
5655
+ grain: "deal",
5656
+ canonicalOwner: "public.v_deals",
5657
+ query: {
5658
+ source: { kind: "view", name: DEALS },
5659
+ filters: [dealStatusFilter],
5660
+ defaultSort: "created_at",
5661
+ defaultSortDir: "desc"
5662
+ },
5663
+ columns: [
5664
+ { key: "created_at", label: tl("Opened", "Aberto em"), type: "date", sortable: true },
5665
+ { key: "title", label: tl("Deal", "Neg\xF3cio"), type: "text" },
5666
+ { key: "contact_name", label: tl("Contact", "Contato"), type: "text" },
5667
+ { key: "stage_name", label: tl("Stage", "Etapa"), type: "text" },
5668
+ { key: "status", label: tl("Status", "Situa\xE7\xE3o"), type: "text", valueMap: DEAL_STATUS_LABELS },
5669
+ { key: "value", label: tl("Value", "Valor"), type: "currency", sortable: true, aggregate: "sum" },
5670
+ { key: "expected_close_date", label: tl("Expected close", "Previs\xE3o"), type: "date", visible: false },
5671
+ { key: "lost_reason", label: tl("Lost reason", "Motivo da perda"), type: "text", visible: false }
5672
+ ],
5673
+ viz: { type: "table" }
5674
+ }
5675
+ ];
5676
+ }
5257
5677
 
5258
5678
  // src/data/registries.ts
5259
5679
  var leadSourceEntity = {
@@ -5417,6 +5837,9 @@ var en = {
5417
5837
  "crm.activities.pending": "pending",
5418
5838
  "crm.activities.pendingFilter": "Pending",
5419
5839
  "crm.activities.systemEvents": "Events",
5840
+ "crm.activities.typeCol": "Type",
5841
+ "crm.activities.titleCol": "Title",
5842
+ "crm.activities.dueCol": "Due",
5420
5843
  "crm.activities.title": "Activities",
5421
5844
  "crm.dashboard.activeDeals": "{{count}} active deals",
5422
5845
  "crm.dashboard.avgDealValue": "Avg deal value",
@@ -5500,6 +5923,7 @@ var en = {
5500
5923
  "crm.leadForm.notesPlaceholder": "Additional notes...",
5501
5924
  "crm.leadForm.phone": "Phone",
5502
5925
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
5926
+ "crm.leadForm.stage": "Stage",
5503
5927
  "crm.leadForm.save": "Save",
5504
5928
  "crm.leadForm.saving": "Saving...",
5505
5929
  "crm.leadForm.subtitle": "Capture a new lead",
@@ -5529,6 +5953,7 @@ var en = {
5529
5953
  "crm.leads.name": "Name",
5530
5954
  "crm.leads.newLead": "New Lead",
5531
5955
  "crm.leads.noLeads": "No leads yet",
5956
+ "crm.leads.receivedCol": "Received",
5532
5957
  "crm.leads.searchPlaceholder": "Search leads...",
5533
5958
  "crm.leads.source": "Source",
5534
5959
  "crm.leads.statusCol": "Status",
@@ -5749,6 +6174,9 @@ var ptBR = {
5749
6174
  "crm.activities.pending": "pendente",
5750
6175
  "crm.activities.pendingFilter": "Pendentes",
5751
6176
  "crm.activities.systemEvents": "Eventos",
6177
+ "crm.activities.typeCol": "Tipo",
6178
+ "crm.activities.titleCol": "T\xEDtulo",
6179
+ "crm.activities.dueCol": "Vencimento",
5752
6180
  "crm.activities.title": "Atividades",
5753
6181
  "crm.dashboard.activeDeals": "{{count}} neg\xF3cios ativos",
5754
6182
  "crm.dashboard.avgDealValue": "Valor m\xE9dio do neg\xF3cio",
@@ -5832,6 +6260,7 @@ var ptBR = {
5832
6260
  "crm.leadForm.notesPlaceholder": "Observa\xE7\xF5es adicionais...",
5833
6261
  "crm.leadForm.phone": "Telefone",
5834
6262
  "crm.leadForm.phonePlaceholder": "+55 11 99999-9999",
6263
+ "crm.leadForm.stage": "Etapa",
5835
6264
  "crm.leadForm.save": "Salvar",
5836
6265
  "crm.leadForm.saving": "Salvando...",
5837
6266
  "crm.leadForm.subtitle": "Capturar um novo lead",
@@ -5861,6 +6290,7 @@ var ptBR = {
5861
6290
  "crm.leads.name": "Nome",
5862
6291
  "crm.leads.newLead": "Novo Lead",
5863
6292
  "crm.leads.noLeads": "Nenhum lead ainda",
6293
+ "crm.leads.receivedCol": "Entrada",
5864
6294
  "crm.leads.searchPlaceholder": "Buscar leads...",
5865
6295
  "crm.leads.source": "Origem",
5866
6296
  "crm.leads.statusCol": "Status",
@@ -6162,12 +6592,23 @@ function createCrmPlugin(options) {
6162
6592
  // saas/admin Panel world, not the ecommerce storefront.
6163
6593
  scaffolds: ["saas"],
6164
6594
  defaultEnabled: true,
6595
+ // The parts a plan can permit separately (#281, ADR 0025). A contact list
6596
+ // is table stakes; a pipeline that automates itself is not.
6597
+ facets: [
6598
+ { id: "contacts", label: "Contatos e leads", description: "Cadastro, tags e hist\xF3rico.", includedWithPlugin: true },
6599
+ { id: "pipeline", label: "Funil de vendas", description: "Board de neg\xF3cios, etapas e previs\xE3o." },
6600
+ { id: "automation", label: "Automa\xE7\xF5es de funil", description: "Regras que movem o card e disparam a pr\xF3xima a\xE7\xE3o." }
6601
+ ],
6165
6602
  dependencies: [],
6166
6603
  // Os FATOS do funil. Vão no manifesto (e não num registro à parte) para que
6167
6604
  // o runtime só os exponha enquanto o CRM está ATIVO — automações, webhooks
6168
6605
  // e auditoria leem todos daqui. Sem esta linha os textos existiam mas não
6169
6606
  // tinham evento a que se ligar, e a lista de automações saía vazia.
6170
6607
  events: buildCrmDomainEvents(),
6608
+ // Leads e negócios em /analytics: o mesmo card é bloco do painel, linha da
6609
+ // lista de relatórios e o relatório inteiro — que é onde alguém finalmente
6610
+ // exporta os leads para uma planilha. Read models na migration 017.
6611
+ analyticsCards: options?.analyticsCards === false ? [] : buildCrmAnalyticsCards(),
6171
6612
  declaredFeatures: [
6172
6613
  { id: "sales", label: config.labels.pageTitle, group: config.labels.pageTitle },
6173
6614
  { id: "crm.leads", label: config.labels.leads, group: config.labels.pageTitle },