@fayz-ai/plugin-crm 0.8.4 → 0.8.5

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.
Files changed (59) hide show
  1. package/dist/components/BoardFilters.d.ts +23 -0
  2. package/dist/components/BoardFilters.d.ts.map +1 -0
  3. package/dist/components/TagChips.d.ts +16 -0
  4. package/dist/components/TagChips.d.ts.map +1 -0
  5. package/dist/data/mock.d.ts.map +1 -1
  6. package/dist/data/supabase.d.ts.map +1 -1
  7. package/dist/data/types.d.ts +4 -2
  8. package/dist/data/types.d.ts.map +1 -1
  9. package/dist/index.d.ts +3 -0
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +461 -84
  12. package/dist/index.js.map +1 -1
  13. package/dist/locales/en.d.ts.map +1 -1
  14. package/dist/locales/pt-BR.d.ts.map +1 -1
  15. package/dist/migrations/index.d.ts +4 -0
  16. package/dist/migrations/index.d.ts.map +1 -1
  17. package/dist/public/context.d.ts +3 -3
  18. package/dist/public/context.d.ts.map +1 -1
  19. package/dist/public/createPublicFormsPlugin.d.ts +18 -2
  20. package/dist/public/createPublicFormsPlugin.d.ts.map +1 -1
  21. package/dist/public/data.supabase.d.ts.map +1 -1
  22. package/dist/public/index.js +29 -5
  23. package/dist/public/index.js.map +1 -1
  24. package/dist/public/types.d.ts +27 -0
  25. package/dist/public/types.d.ts.map +1 -1
  26. package/dist/registries.d.ts.map +1 -1
  27. package/dist/store.d.ts +7 -2
  28. package/dist/store.d.ts.map +1 -1
  29. package/dist/types.d.ts +37 -0
  30. package/dist/types.d.ts.map +1 -1
  31. package/dist/views/DealSidebar.d.ts.map +1 -1
  32. package/dist/views/PipelineView.d.ts.map +1 -1
  33. package/package.json +15 -14
  34. package/src/components/BoardFilters.tsx +190 -0
  35. package/src/components/TagChips.tsx +80 -0
  36. package/src/data/mock.ts +31 -4
  37. package/src/data/supabase.ts +72 -5
  38. package/src/data/types.ts +6 -3
  39. package/src/index.ts +94 -0
  40. package/src/locales/en.ts +9 -0
  41. package/src/locales/pt-BR.ts +9 -0
  42. package/src/migrations/011_agent_rpc_update_lead.sql +153 -0
  43. package/src/migrations/012_agent_rpc_create_lead.sql +128 -0
  44. package/src/migrations/013_tag_slugs.sql +177 -0
  45. package/src/migrations/014_public_lead_tags.sql +172 -0
  46. package/src/migrations/index.ts +643 -1
  47. package/src/public/context.tsx +4 -4
  48. package/src/public/createPublicFormsPlugin.ts +72 -2
  49. package/src/public/data.supabase.ts +1 -0
  50. package/src/public/types.ts +28 -0
  51. package/src/registries.ts +12 -3
  52. package/src/store.ts +78 -57
  53. package/src/types.ts +40 -0
  54. package/src/views/DealSidebar.tsx +9 -6
  55. package/src/views/PipelineView.tsx +92 -9
  56. package/dist/index.cjs +0 -5354
  57. package/dist/index.cjs.map +0 -1
  58. package/dist/public/index.cjs +0 -306
  59. package/dist/public/index.cjs.map +0 -1
package/dist/index.js CHANGED
@@ -1,9 +1,9 @@
1
- import React14, { useState, useMemo, useRef, useEffect } from 'react';
1
+ import React15, { useState, useMemo, useRef, useEffect } from 'react';
2
2
  import { createPluginContext, PluginSettingsPanel, dedup, useModuleNavigation, createViewRouter, ModuleActionBar, useTenantPluginSettings, SettingsGroup, ToggleRow, useLimitGuard, formatCurrency, PersonLink, useAccessOptional, invalidateLimit } from '@fayz-ai/saas';
3
- import { registerTranslations, createSafeDataProvider, useTranslation, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
4
- import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, DashboardCanvas, Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetBody, SheetFooter, CurrencyInput, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, ConfirmDialog, SegmentedControl, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
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, Plus, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, User, Hash, CircleCheckBig, Ban, Trash2, Receipt, CircleAlert, CircleDashed, Loader2, DollarSign } from 'lucide-react';
3
+ import { registerTranslations, createSafeDataProvider, useTranslation, useActiveTenantId, getSupabaseClientOptional, getActiveTenantId } from '@fayz-ai/core';
4
+ import { toast, defineKpiWidget, defineChartWidget, defineCustomWidget, defineTableWidget, PageTransition, ModulePage, Button, SubpageHeader, ListView, useSaveBar, SearchSelect, DatePicker, DataTable, Breadcrumb, DashboardCanvas, SegmentedControl, Sheet, SheetContent, SheetHeader, SheetTitle, SheetDescription, SheetBody, SheetFooter, CurrencyInput, Dropdown, DropdownTrigger, DropdownContent, DropdownLabel, DropdownSeparator, DropdownItem, ConfirmDialog, KpiCard, ChartWidget, Card, CardHeader, CardTitle, CardContent, TableWidget } from '@fayz-ai/ui';
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, Plus, Sparkles, Clock, Calendar, ArrowRight, ChevronDown, Printer, X, Pencil, User, Hash, CircleCheckBig, Ban, Tag, Trash2, Receipt, CircleAlert, CircleDashed, Loader2, DollarSign } from 'lucide-react';
7
7
  import { createPortal } from 'react-dom';
8
8
  import { createStore as createStore$1 } from 'zustand/vanilla';
9
9
 
@@ -272,6 +272,46 @@ function QuoteStatusDropdown({ quote, onStatusChange, size = "default" }) {
272
272
  showReject && /* @__PURE__ */ jsx(RejectModal, { onConfirm: handleReject, onCancel: () => setShowReject(false) })
273
273
  ] });
274
274
  }
275
+ function humanizeTag(slug) {
276
+ return slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
277
+ }
278
+ function chipStyle(color) {
279
+ if (!color || !/^#[0-9a-f]{6}$/i.test(color)) return void 0;
280
+ return { backgroundColor: `${color}1f`, color, borderColor: `${color}59` };
281
+ }
282
+ function TagChips({ tags, defs, max, size = "xs", className }) {
283
+ if (!tags?.length) return null;
284
+ const shown = max ? tags.slice(0, max) : tags;
285
+ const hidden = max ? tags.length - shown.length : 0;
286
+ const text = size === "xs" ? "text-[9px] px-1.5 py-px" : "text-[10px] px-2 py-0.5";
287
+ return /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-1 ${className ?? ""}`, children: [
288
+ shown.map((slug) => {
289
+ const def = defs?.get(slug);
290
+ const style = chipStyle(def?.color);
291
+ return /* @__PURE__ */ jsx(
292
+ "span",
293
+ {
294
+ title: def?.name ?? humanizeTag(slug),
295
+ className: `inline-flex max-w-[10rem] items-center truncate rounded-full border font-medium ${text} ${style ? "" : "border-border bg-muted text-muted-foreground"}`,
296
+ style,
297
+ children: def?.name ?? humanizeTag(slug)
298
+ },
299
+ slug
300
+ );
301
+ }),
302
+ hidden > 0 && /* @__PURE__ */ jsxs(
303
+ "span",
304
+ {
305
+ title: tags.slice(shown.length).map((s) => defs?.get(s)?.name ?? humanizeTag(s)).join(", "),
306
+ className: `inline-flex items-center rounded-full border border-border bg-muted font-medium text-muted-foreground ${text}`,
307
+ children: [
308
+ "+",
309
+ hidden
310
+ ]
311
+ }
312
+ )
313
+ ] });
314
+ }
275
315
 
276
316
  // src/lib/form-answers.tsx
277
317
  function humanizeKey(key) {
@@ -346,6 +386,11 @@ function FormAnswers({ lead }) {
346
386
  function OverviewTab({ deal, lead, currency }) {
347
387
  const t2 = useTranslation();
348
388
  const initial = (lead?.name ?? deal.contactName ?? deal.title).charAt(0).toUpperCase();
389
+ const tagDefs = useCrmStore((s) => s.tagDefs);
390
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
391
+ useEffect(() => {
392
+ fetchTagDefs();
393
+ }, []);
349
394
  return /* @__PURE__ */ jsxs("div", { className: "space-y-5", children: [
350
395
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3.5", children: [
351
396
  /* @__PURE__ */ jsx("div", { className: "flex h-14 w-14 shrink-0 items-center justify-center rounded-2xl bg-primary/10 text-primary text-xl font-bold", children: initial }),
@@ -411,7 +456,7 @@ function OverviewTab({ deal, lead, currency }) {
411
456
  /* @__PURE__ */ jsx(FormAnswers, { lead }),
412
457
  deal.tags && deal.tags.length > 0 && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
413
458
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.tags") }),
414
- /* @__PURE__ */ jsx("div", { className: "flex gap-1.5 flex-wrap", children: deal.tags.map((tag) => /* @__PURE__ */ jsx("span", { className: "inline-flex items-center rounded-full bg-muted px-2.5 py-0.5 text-[10px] font-medium text-muted-foreground", children: tag }, tag)) })
459
+ /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, size: "sm", className: "gap-1.5" })
415
460
  ] }),
416
461
  deal.notes && deal.notes !== deal.title && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
417
462
  /* @__PURE__ */ jsx("h4", { className: "text-[11px] font-semibold text-muted-foreground uppercase tracking-wider", children: t2("crm.dealSidebar.notes") }),
@@ -590,6 +635,145 @@ function DealSidebar({ dealId, open, onClose, onViewLead, onViewQuote }) {
590
635
  ) })
591
636
  ] }) });
592
637
  }
638
+ function periodToRange(period, customFrom, customTo) {
639
+ if (period === "all") return {};
640
+ if (period === "24h") {
641
+ return { createdFrom: new Date(Date.now() - 24 * 60 * 60 * 1e3).toISOString() };
642
+ }
643
+ if (period === "7d") {
644
+ return { createdFrom: new Date(Date.now() - 7 * 24 * 60 * 60 * 1e3).toISOString() };
645
+ }
646
+ return {
647
+ ...customFrom ? { createdFrom: (/* @__PURE__ */ new Date(`${customFrom}T00:00:00`)).toISOString() } : {},
648
+ ...customTo ? { createdTo: (/* @__PURE__ */ new Date(`${customTo}T23:59:59.999`)).toISOString() } : {}
649
+ };
650
+ }
651
+ function BoardFilters({
652
+ period,
653
+ onPeriodChange,
654
+ customFrom,
655
+ customTo,
656
+ onCustomChange,
657
+ selectedTags,
658
+ onTagsChange,
659
+ tagDefs,
660
+ availableTags,
661
+ className
662
+ }) {
663
+ const t2 = useTranslation();
664
+ const [tagsOpen, setTagsOpen] = useState(false);
665
+ const tagsRef = useRef(null);
666
+ useEffect(() => {
667
+ if (!tagsOpen) return;
668
+ const onDown = (e) => {
669
+ if (!tagsRef.current?.contains(e.target)) setTagsOpen(false);
670
+ };
671
+ document.addEventListener("mousedown", onDown);
672
+ return () => document.removeEventListener("mousedown", onDown);
673
+ }, [tagsOpen]);
674
+ const options = useMemo(() => {
675
+ const all = /* @__PURE__ */ new Set([...availableTags, ...selectedTags]);
676
+ return [...all].sort(
677
+ (a, b) => (tagDefs.get(a)?.name ?? humanizeTag(a)).localeCompare(tagDefs.get(b)?.name ?? humanizeTag(b))
678
+ );
679
+ }, [availableTags, selectedTags, tagDefs]);
680
+ const toggle = (slug) => {
681
+ onTagsChange(
682
+ selectedTags.includes(slug) ? selectedTags.filter((s) => s !== slug) : [...selectedTags, slug]
683
+ );
684
+ };
685
+ return /* @__PURE__ */ jsxs("div", { className: `flex flex-wrap items-center gap-2 ${className ?? ""}`, children: [
686
+ /* @__PURE__ */ jsx(
687
+ SegmentedControl,
688
+ {
689
+ options: [
690
+ { value: "all", label: t2("crm.filters.periodAll") },
691
+ { value: "24h", label: t2("crm.filters.period24h") },
692
+ { value: "7d", label: t2("crm.filters.period7d") },
693
+ { value: "custom", label: t2("crm.filters.periodCustom") }
694
+ ],
695
+ value: period,
696
+ onChange: onPeriodChange,
697
+ "aria-label": t2("crm.filters.period")
698
+ }
699
+ ),
700
+ period === "custom" && // As duas pontas usam a MESMA chrome do segmentado ao lado (variant
701
+ // toolbar), com a seta ligando uma à outra — antes eram dois campos de
702
+ // formulário em altura cheia no meio de uma barra de pills.
703
+ /* @__PURE__ */ jsxs("div", { className: "inline-flex items-center gap-1.5", children: [
704
+ /* @__PURE__ */ jsx(
705
+ DatePicker,
706
+ {
707
+ variant: "toolbar",
708
+ value: customFrom,
709
+ onChange: (v) => onCustomChange(v, v > customTo ? v : customTo)
710
+ }
711
+ ),
712
+ /* @__PURE__ */ jsx(ArrowRight, { className: "h-3 w-3 shrink-0 text-muted-foreground", "aria-hidden": true }),
713
+ /* @__PURE__ */ jsx(
714
+ DatePicker,
715
+ {
716
+ variant: "toolbar",
717
+ value: customTo,
718
+ onChange: (v) => onCustomChange(v < customFrom ? v : customFrom, v)
719
+ }
720
+ )
721
+ ] }),
722
+ options.length > 0 && /* @__PURE__ */ jsxs("div", { className: "relative", ref: tagsRef, children: [
723
+ /* @__PURE__ */ jsxs(
724
+ "button",
725
+ {
726
+ type: "button",
727
+ onClick: () => setTagsOpen((o) => !o),
728
+ className: `inline-flex h-[26px] items-center gap-1.5 rounded-button border px-2.5 text-xs font-medium shadow-button transition-colors ${selectedTags.length ? "border-primary/40 bg-primary/10 text-primary" : "border-border bg-card text-muted-foreground hover:bg-muted/60"}`,
729
+ children: [
730
+ /* @__PURE__ */ jsx(Tag, { className: "h-3 w-3" }),
731
+ selectedTags.length ? t2("crm.filters.tagsSelected", { count: selectedTags.length }) : t2("crm.filters.tags")
732
+ ]
733
+ }
734
+ ),
735
+ tagsOpen && /* @__PURE__ */ jsx("div", { className: "absolute left-0 z-50 mt-1 max-h-72 w-56 overflow-y-auto rounded-lg border bg-popover p-1 shadow-md", children: options.map((slug) => {
736
+ const def = tagDefs.get(slug);
737
+ const checked = selectedTags.includes(slug);
738
+ return /* @__PURE__ */ jsxs(
739
+ "button",
740
+ {
741
+ type: "button",
742
+ onClick: () => toggle(slug),
743
+ className: "flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-xs hover:bg-muted",
744
+ children: [
745
+ /* @__PURE__ */ jsx(
746
+ "span",
747
+ {
748
+ className: `flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border ${checked ? "border-primary bg-primary text-primary-foreground" : "border-border"}`,
749
+ children: checked && /* @__PURE__ */ jsx("span", { className: "text-[9px] leading-none", children: "\u2713" })
750
+ }
751
+ ),
752
+ def?.color && /* @__PURE__ */ jsx("span", { className: "h-2 w-2 shrink-0 rounded-full", style: { backgroundColor: def.color } }),
753
+ /* @__PURE__ */ jsx("span", { className: "truncate", children: def?.name ?? humanizeTag(slug) })
754
+ ]
755
+ },
756
+ slug
757
+ );
758
+ }) })
759
+ ] }),
760
+ selectedTags.length > 0 && /* @__PURE__ */ jsx(
761
+ "button",
762
+ {
763
+ type: "button",
764
+ onClick: () => onTagsChange([]),
765
+ className: "inline-flex h-[26px] items-center gap-1 rounded-md px-1.5 text-xs text-muted-foreground hover:text-foreground",
766
+ title: t2("crm.filters.clearTags"),
767
+ children: /* @__PURE__ */ jsx(X, { className: "h-3 w-3" })
768
+ }
769
+ )
770
+ ] });
771
+ }
772
+ function localDate(offsetDays = 0) {
773
+ const d = /* @__PURE__ */ new Date();
774
+ if (offsetDays) d.setDate(d.getDate() + offsetDays);
775
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
776
+ }
593
777
  function PipelineSkeleton() {
594
778
  return /* @__PURE__ */ jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: [1, 2, 3, 4, 5].map((col) => /* @__PURE__ */ jsxs("div", { className: "min-w-[240px] max-w-[280px] flex-shrink-0", children: [
595
779
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2 mb-2 px-1", children: [
@@ -607,7 +791,7 @@ function PipelineSkeleton() {
607
791
  ] }, i)) })
608
792
  ] }, col)) });
609
793
  }
610
- function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onDragEnd }) {
794
+ function DealCard({ deal, saving, currency, tagDefs, onClick, onArchive, onDragStart, onDragEnd }) {
611
795
  const t2 = useTranslation();
612
796
  return /* @__PURE__ */ jsxs(
613
797
  "div",
@@ -635,6 +819,7 @@ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onD
635
819
  )
636
820
  ] }),
637
821
  deal.contactName && /* @__PURE__ */ jsx("p", { className: "text-[10px] text-muted-foreground mt-0.5", children: deal.contactName }),
822
+ /* @__PURE__ */ jsx(TagChips, { tags: deal.tags, defs: tagDefs, max: 3, className: "mt-1.5" }),
638
823
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between mt-2", children: [
639
824
  /* @__PURE__ */ jsx("span", { className: "text-xs font-semibold", children: formatCurrency(deal.value, currency) }),
640
825
  /* @__PURE__ */ jsxs("span", { className: "text-[10px] text-muted-foreground", children: [
@@ -646,7 +831,7 @@ function DealCard({ deal, saving, currency, onClick, onArchive, onDragStart, onD
646
831
  }
647
832
  );
648
833
  }
649
- function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
834
+ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, currency, tagDefs, dragOverStageId, onDealClick, onArchiveDeal, onAddLead, onDragStart, onDragEnd, onDragOver, onDragLeave, onDrop }) {
650
835
  const t2 = useTranslation();
651
836
  const isOver = dragOverStageId === stageId;
652
837
  const [hovered, setHovered] = useState(false);
@@ -689,6 +874,7 @@ function StageColumn({ stageId, stageName, stageColor, deals, savingDealIds, cur
689
874
  deal,
690
875
  saving: savingDealIds.has(deal.id),
691
876
  currency,
877
+ tagDefs,
692
878
  onClick: () => onDealClick?.(deal.id),
693
879
  onArchive: onArchiveDeal ? () => onArchiveDeal(deal.id) : void 0,
694
880
  onDragStart: (e) => {
@@ -712,35 +898,59 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
712
898
  const dealsByStage = useCrmStore((s) => s.dealsByStage);
713
899
  const dealsLoading = useCrmStore((s) => s.dealsLoading);
714
900
  const fetchPipelines = useCrmStore((s) => s.fetchPipelines);
901
+ const tagDefs = useCrmStore((s) => s.tagDefs);
902
+ const fetchTagDefs = useCrmStore((s) => s.fetchTagDefs);
715
903
  const fetchDealsByStage = useCrmStore((s) => s.fetchDealsByStage);
904
+ const refreshBoard = useCrmStore((s) => s.refreshBoard);
716
905
  const moveDealToStage = useCrmStore((s) => s.moveDealToStage);
717
906
  const archiveDeal = useCrmStore((s) => s.archiveDeal);
718
907
  const canArchive = useCanArchive();
908
+ const [period, setPeriod] = useState("all");
909
+ const [customFrom, setCustomFrom] = useState(() => localDate(-30));
910
+ const [customTo, setCustomTo] = useState(() => localDate());
911
+ const [selectedTags, setSelectedTags] = useState([]);
719
912
  const [dragOverStageId, setDragOverStageId] = useState(null);
720
913
  const [savingDealIds, setSavingDealIds] = useState(/* @__PURE__ */ new Set());
721
914
  const [optimisticBoard, setOptimisticBoard] = useState(null);
722
915
  const t2 = useTranslation();
723
916
  const [selectedDealId, setSelectedDealId] = useState(null);
724
917
  const dragRef = useRef(null);
918
+ const savingRef = useRef(savingDealIds);
919
+ savingRef.current = savingDealIds;
920
+ const boardFilter = useMemo(() => ({
921
+ ...selectedTags.length ? { tags: selectedTags } : {},
922
+ ...periodToRange(period, customFrom, customTo)
923
+ }), [selectedTags, period, customFrom, customTo]);
924
+ const filterKey = JSON.stringify(boardFilter);
925
+ const availableTags = useMemo(() => [...tagDefs.keys()], [tagDefs]);
926
+ const tenantId = useActiveTenantId();
725
927
  useEffect(() => {
726
928
  fetchPipelines();
727
- }, []);
929
+ fetchTagDefs();
930
+ }, [tenantId]);
728
931
  useEffect(() => {
729
- if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id);
730
- }, [pipelines]);
932
+ if (pipelines.length > 0) fetchDealsByStage(pipelines[0].id, boardFilter);
933
+ }, [pipelines, filterKey]);
731
934
  const pipelineId = pipelines[0]?.id;
732
935
  useEffect(() => {
733
936
  if (!pipelineId) return;
734
937
  const supabase = getSupabaseClientOptional();
735
938
  if (!supabase) return;
939
+ let timer;
940
+ const onChange = () => {
941
+ if (savingRef.current.size > 0) return;
942
+ clearTimeout(timer);
943
+ timer = setTimeout(() => {
944
+ void refreshBoard();
945
+ }, 300);
946
+ };
736
947
  const channel = supabase.channel(`crm:board:${pipelineId}`).on(
737
948
  "postgres_changes",
738
949
  { event: "*", schema: "public", table: "plg_crm_deal_extensions" },
739
- () => {
740
- void fetchDealsByStage(pipelineId);
741
- }
950
+ onChange
742
951
  ).subscribe();
743
952
  return () => {
953
+ clearTimeout(timer);
744
954
  supabase.removeChannel(channel);
745
955
  };
746
956
  }, [pipelineId]);
@@ -804,6 +1014,23 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
804
1014
  }
805
1015
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
806
1016
  /* @__PURE__ */ jsx(SubpageHeader, { title: t2("crm.pipeline.title"), subtitle: t2("crm.pipeline.subtitle") }),
1017
+ /* @__PURE__ */ jsx(
1018
+ BoardFilters,
1019
+ {
1020
+ period,
1021
+ onPeriodChange: setPeriod,
1022
+ customFrom,
1023
+ customTo,
1024
+ onCustomChange: (from, to) => {
1025
+ setCustomFrom(from);
1026
+ setCustomTo(to);
1027
+ },
1028
+ selectedTags,
1029
+ onTagsChange: setSelectedTags,
1030
+ tagDefs,
1031
+ availableTags
1032
+ }
1033
+ ),
807
1034
  dealsLoading && dealsByStage.size === 0 ? /* @__PURE__ */ jsx(PipelineSkeleton, {}) : /* @__PURE__ */ jsx("div", { className: "flex gap-3 overflow-x-auto pb-2", children: visibleStages.map((stage) => {
808
1035
  const deals = displayBoard.get(stage.id) ?? [];
809
1036
  return /* @__PURE__ */ jsx(
@@ -815,6 +1042,7 @@ function PipelineView({ onDealClick, onViewLead, onViewQuote, onAddLead }) {
815
1042
  deals,
816
1043
  savingDealIds,
817
1044
  currency,
1045
+ tagDefs,
818
1046
  dragOverStageId,
819
1047
  onDealClick: handleDealClick,
820
1048
  onArchiveDeal: canArchive ? (id) => {
@@ -1345,7 +1573,7 @@ function QuoteFormView({ quoteId, leadId, onSaved }) {
1345
1573
  observations,
1346
1574
  items: items.map((it) => ({ itemKind: it.itemKind, description: it.description, quantity: it.quantity, unitPrice: it.unitPrice, discount: it.discount }))
1347
1575
  };
1348
- const snapshot = React14.useRef(null);
1576
+ const snapshot = React15.useRef(null);
1349
1577
  useEffect(() => {
1350
1578
  if (!loadingExisting && snapshot.current === null) snapshot.current = JSON.stringify(currentFields);
1351
1579
  }, [loadingExisting]);
@@ -2620,6 +2848,7 @@ function now() {
2620
2848
  function today() {
2621
2849
  return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2622
2850
  }
2851
+ var MOCK_TAG_COLORS = ["#6366f1", "#0ea5e9", "#10b981", "#f59e0b", "#ef4444", "#ec4899", "#8b5cf6", "#14b8a6"];
2623
2852
  function paginate(items, page, pageSize) {
2624
2853
  const p = page ?? 1;
2625
2854
  const ps = pageSize ?? 50;
@@ -2782,11 +3011,17 @@ function createMockCrmProvider(options) {
2782
3011
  async getDealById(id) {
2783
3012
  return store.deals.find((d) => d.id === id) ?? null;
2784
3013
  },
2785
- async getDealsByStage(pipelineId) {
3014
+ async getDealsByStage(pipelineId, filter) {
2786
3015
  const stages = store.stages.filter((s) => s.pipelineId === pipelineId).sort((a, b) => a.order - b.order);
3016
+ const matches = (d) => {
3017
+ if (filter?.tags?.length && !filter.tags.some((t2) => (d.tags ?? []).includes(t2))) return false;
3018
+ if (filter?.createdFrom && d.createdAt < filter.createdFrom) return false;
3019
+ if (filter?.createdTo && d.createdAt > filter.createdTo) return false;
3020
+ return true;
3021
+ };
2787
3022
  const map = /* @__PURE__ */ new Map();
2788
3023
  for (const stage of stages) {
2789
- map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open"));
3024
+ map.set(stage.id, store.deals.filter((d) => d.stageId === stage.id && d.status === "open" && matches(d)));
2790
3025
  }
2791
3026
  return map;
2792
3027
  },
@@ -2914,6 +3149,18 @@ function createMockCrmProvider(options) {
2914
3149
  ];
2915
3150
  return seed.map((t2, i) => ({ id: `at-${i}`, name: t2.label, icon: t2.icon, isActive: true }));
2916
3151
  },
3152
+ async getTagDefs() {
3153
+ const used = /* @__PURE__ */ new Set();
3154
+ for (const l of store.leads) for (const t2 of l.tags ?? []) used.add(t2);
3155
+ for (const d of store.deals) for (const t2 of d.tags ?? []) used.add(t2);
3156
+ return [...used].sort().map((slug, i) => ({
3157
+ id: `tag-${i}`,
3158
+ slug,
3159
+ name: slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase()),
3160
+ color: MOCK_TAG_COLORS[i % MOCK_TAG_COLORS.length],
3161
+ isActive: true
3162
+ }));
3163
+ },
2917
3164
  // Quotes
2918
3165
  async getQuotes(query) {
2919
3166
  let results = store.quotes.filter((q) => q.status !== "archived" || query.status && (Array.isArray(query.status) ? query.status : [query.status]).includes("archived"));
@@ -3162,6 +3409,9 @@ var T = {
3162
3409
  function getTenantId() {
3163
3410
  return getActiveTenantId();
3164
3411
  }
3412
+ function humanizeTagSlug(slug) {
3413
+ return slug.replace(/^[a-z]+:/, "").replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
3414
+ }
3165
3415
  function snakeToCamel(obj) {
3166
3416
  const result = {};
3167
3417
  for (const [key, value] of Object.entries(obj)) {
@@ -3209,6 +3459,23 @@ function createSupabaseCrmProvider(options) {
3209
3459
  { onConflict: "tenant_id,name", ignoreDuplicates: true }
3210
3460
  );
3211
3461
  }
3462
+ async function registerTags(tags) {
3463
+ const tenantId = getTenantId();
3464
+ if (!tenantId || !tags?.length) return;
3465
+ try {
3466
+ const { pub } = getClients();
3467
+ await pub.from(T.tags).upsert(
3468
+ [...new Set(tags)].map((slug) => ({
3469
+ tenant_id: tenantId,
3470
+ slug,
3471
+ name: humanizeTagSlug(slug),
3472
+ is_active: true
3473
+ })),
3474
+ { onConflict: "tenant_id,slug", ignoreDuplicates: true }
3475
+ );
3476
+ } catch {
3477
+ }
3478
+ }
3212
3479
  const provider = {
3213
3480
  // --- Pipelines (public.plg_crm_pipelines + plg_crm_pipeline_stages) ---
3214
3481
  async getPipelines() {
@@ -3297,8 +3564,9 @@ function createSupabaseCrmProvider(options) {
3297
3564
  }).select().single();
3298
3565
  if (error) throw new Error(error.message);
3299
3566
  const p = snakeToCamel(data);
3567
+ await registerTags(input.tags);
3300
3568
  await logEvent({ activityType: "lead_created", title: input.name, leadId: p.id, contactName: input.name });
3301
- return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3569
+ return { id: p.id, name: p.name, email: p.email, phone: p.phone, status: "new", tags: p.tags ?? input.tags ?? [], tenantId, createdAt: p.createdAt, updatedAt: p.updatedAt };
3302
3570
  },
3303
3571
  async updateLead(id, partial) {
3304
3572
  const { core } = getClients();
@@ -3389,10 +3657,14 @@ function createSupabaseCrmProvider(options) {
3389
3657
  updatedAt: r.updated_at
3390
3658
  };
3391
3659
  },
3392
- async getDealsByStage(pipelineId) {
3660
+ async getDealsByStage(pipelineId, filter) {
3393
3661
  const { pub } = getClients();
3394
3662
  const stages = await provider.getPipelineStages(pipelineId);
3395
- const { data } = await pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).not("status", "in", "(lost,archived)");
3663
+ let qb = pub.from("v_deals").select("*").eq("pipeline_id", pipelineId).not("status", "in", "(lost,archived)");
3664
+ if (filter?.tags?.length) qb = qb.overlaps("tags", filter.tags);
3665
+ if (filter?.createdFrom) qb = qb.gte("created_at", filter.createdFrom);
3666
+ if (filter?.createdTo) qb = qb.lte("created_at", filter.createdTo);
3667
+ const { data } = await qb;
3396
3668
  const deals = (data ?? []).map((r) => ({
3397
3669
  id: r.id,
3398
3670
  title: r.title ?? "",
@@ -3443,6 +3715,7 @@ function createSupabaseCrmProvider(options) {
3443
3715
  expected_close_date: input.expectedCloseDate,
3444
3716
  lead_id: input.leadId
3445
3717
  });
3718
+ await registerTags(input.tags);
3446
3719
  await logEvent({
3447
3720
  activityType: "deal_created",
3448
3721
  title: input.title,
@@ -3609,6 +3882,13 @@ function createSupabaseCrmProvider(options) {
3609
3882
  const { data } = await pub.from(T.activityTypes).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3610
3883
  return (data ?? []).map((r) => snakeToCamel(r));
3611
3884
  },
3885
+ async getTagDefs() {
3886
+ const { pub } = getClients();
3887
+ const tenantId = getTenantId();
3888
+ if (!tenantId) return [];
3889
+ const { data } = await pub.from(T.tags).select("*").eq("tenant_id", tenantId).eq("is_active", true).order("name");
3890
+ return (data ?? []).filter((r) => r.slug).map((r) => snakeToCamel(r));
3891
+ },
3612
3892
  // --- Quotes (public.orders kind='quote' + order_items) ---
3613
3893
  async getQuotes(query) {
3614
3894
  const { core } = getClients();
@@ -3987,6 +4267,7 @@ function createSupabaseCrmProvider(options) {
3987
4267
  }
3988
4268
  function createCrmStore(provider) {
3989
4269
  let lastActivitiesQuery = {};
4270
+ let lastBoard = null;
3990
4271
  return createStore$1((set, get) => ({
3991
4272
  pipelines: [],
3992
4273
  stages: [],
@@ -4006,6 +4287,7 @@ function createCrmStore(provider) {
4006
4287
  summary: null,
4007
4288
  summaryLoading: false,
4008
4289
  funnel: [],
4290
+ tagDefs: /* @__PURE__ */ new Map(),
4009
4291
  async fetchPipelines() {
4010
4292
  return dedup("crm:pipelines", async () => {
4011
4293
  const pipelines = await provider.getPipelines();
@@ -4013,6 +4295,15 @@ function createCrmStore(provider) {
4013
4295
  set({ pipelines, stages });
4014
4296
  });
4015
4297
  },
4298
+ async fetchTagDefs() {
4299
+ return dedup("crm:tag-defs", async () => {
4300
+ try {
4301
+ const defs = await provider.getTagDefs();
4302
+ set({ tagDefs: new Map(defs.map((d) => [d.slug, d])) });
4303
+ } catch {
4304
+ }
4305
+ });
4306
+ },
4016
4307
  async fetchSummary() {
4017
4308
  return dedup("crm:summary", async () => {
4018
4309
  set({ summaryLoading: true });
@@ -4040,13 +4331,19 @@ function createCrmStore(provider) {
4040
4331
  set({ deals: result.data, dealsTotal: result.total, dealsLoading: false });
4041
4332
  });
4042
4333
  },
4043
- async fetchDealsByStage(pipelineId) {
4044
- return dedup("crm:dealsByStage:" + pipelineId, async () => {
4334
+ async fetchDealsByStage(pipelineId, filter) {
4335
+ lastBoard = { pipelineId, filter };
4336
+ const key = "crm:dealsByStage:" + pipelineId + ":" + JSON.stringify(filter ?? {});
4337
+ return dedup(key, async () => {
4045
4338
  set({ dealsLoading: true });
4046
- const dealsByStage = await provider.getDealsByStage(pipelineId);
4339
+ const dealsByStage = await provider.getDealsByStage(pipelineId, filter);
4047
4340
  set({ dealsByStage, dealsLoading: false });
4048
4341
  });
4049
4342
  },
4343
+ async refreshBoard() {
4344
+ if (!lastBoard) return;
4345
+ return get().fetchDealsByStage(lastBoard.pipelineId, lastBoard.filter);
4346
+ },
4050
4347
  async fetchActivities(query) {
4051
4348
  lastActivitiesQuery = query;
4052
4349
  return dedup("crm:activities:" + JSON.stringify(query), async () => {
@@ -4192,12 +4489,9 @@ function createCrmStore(provider) {
4192
4489
  }
4193
4490
  }
4194
4491
  set((state) => ({ quotes: [quote, ...state.quotes], quotesTotal: state.quotesTotal + 1 }));
4195
- if (defaultPipeline) {
4196
- try {
4197
- const dealsByStage = await provider.getDealsByStage(defaultPipeline.id);
4198
- set({ dealsByStage });
4199
- } catch {
4200
- }
4492
+ try {
4493
+ await get().refreshBoard();
4494
+ } catch {
4201
4495
  }
4202
4496
  void get().refreshActivities();
4203
4497
  toast.success("Quote created");
@@ -4233,16 +4527,13 @@ function createCrmStore(provider) {
4233
4527
  async approveQuote(id) {
4234
4528
  try {
4235
4529
  const quote = await provider.approveQuote(id);
4236
- const { pipelines } = get();
4237
- if (pipelines.length > 0) {
4238
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
4239
- provider.getDealsByStage(pipelines[0].id),
4240
- provider.getSummary(),
4241
- provider.getLeads({}),
4242
- provider.getQuotes({})
4243
- ]);
4244
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4245
- }
4530
+ const [summary, leadsResult, quotesResult] = await Promise.all([
4531
+ provider.getSummary(),
4532
+ provider.getLeads({}),
4533
+ provider.getQuotes({}),
4534
+ get().refreshBoard()
4535
+ ]);
4536
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4246
4537
  void get().refreshActivities();
4247
4538
  toast.success("Quote approved \u2014 invoice created");
4248
4539
  return quote;
@@ -4254,16 +4545,13 @@ function createCrmStore(provider) {
4254
4545
  async rejectQuote(id, reason) {
4255
4546
  try {
4256
4547
  const quote = await provider.rejectQuote(id, reason);
4257
- const { pipelines } = get();
4258
- if (pipelines.length > 0) {
4259
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
4260
- provider.getDealsByStage(pipelines[0].id),
4261
- provider.getSummary(),
4262
- provider.getLeads({}),
4263
- provider.getQuotes({})
4264
- ]);
4265
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4266
- }
4548
+ const [summary, leadsResult, quotesResult] = await Promise.all([
4549
+ provider.getSummary(),
4550
+ provider.getLeads({}),
4551
+ provider.getQuotes({}),
4552
+ get().refreshBoard()
4553
+ ]);
4554
+ set({ summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4267
4555
  void get().refreshActivities();
4268
4556
  toast.success("Quote rejected");
4269
4557
  return quote;
@@ -4285,29 +4573,17 @@ function createCrmStore(provider) {
4285
4573
  },
4286
4574
  async moveDealToStage(dealId, stageId) {
4287
4575
  await provider.moveDealToStage(dealId, stageId);
4288
- const { pipelines } = get();
4289
- if (pipelines.length > 0) {
4290
- const [dealsByStage, summary, leadsResult, quotesResult] = await Promise.all([
4291
- provider.getDealsByStage(pipelines[0].id),
4292
- provider.getSummary(),
4293
- provider.getLeads({}),
4294
- provider.getQuotes({})
4295
- ]);
4296
- set({ dealsByStage, summary, leads: leadsResult.data, leadsTotal: leadsResult.total, quotes: quotesResult.data, quotesTotal: quotesResult.total });
4297
- }
4576
+ await get().refreshBoard();
4298
4577
  void get().refreshActivities();
4299
4578
  },
4300
4579
  async archiveDeal(dealId) {
4301
4580
  try {
4302
4581
  await provider.archiveDeal(dealId);
4303
- const { pipelines } = get();
4304
- if (pipelines.length > 0) {
4305
- const [dealsByStage, summary] = await Promise.all([
4306
- provider.getDealsByStage(pipelines[0].id),
4307
- provider.getSummary()
4308
- ]);
4309
- set({ dealsByStage, summary });
4310
- }
4582
+ const [, summary] = await Promise.all([
4583
+ get().refreshBoard(),
4584
+ provider.getSummary()
4585
+ ]);
4586
+ set({ summary });
4311
4587
  void get().refreshActivities();
4312
4588
  toast.success("Deal archived");
4313
4589
  } catch (err) {
@@ -4318,18 +4594,12 @@ function createCrmStore(provider) {
4318
4594
  async archiveLead(leadId) {
4319
4595
  try {
4320
4596
  await provider.archiveLead(leadId);
4321
- const { pipelines } = get();
4322
- const [leadsResult, summary, dealsByStage] = await Promise.all([
4597
+ const [leadsResult, summary] = await Promise.all([
4323
4598
  provider.getLeads({}),
4324
4599
  provider.getSummary(),
4325
- pipelines.length > 0 ? provider.getDealsByStage(pipelines[0].id) : Promise.resolve(null)
4600
+ get().refreshBoard()
4326
4601
  ]);
4327
- set({
4328
- leads: leadsResult.data,
4329
- leadsTotal: leadsResult.total,
4330
- summary,
4331
- ...dealsByStage ? { dealsByStage } : {}
4332
- });
4602
+ set({ leads: leadsResult.data, leadsTotal: leadsResult.total, summary });
4333
4603
  void get().refreshActivities();
4334
4604
  toast.success("Lead archived");
4335
4605
  } catch (err) {
@@ -4375,6 +4645,11 @@ var tagEntity = {
4375
4645
  defaultSort: "name",
4376
4646
  fields: [
4377
4647
  { key: "name", label: "Name", type: "text", required: true, showInTable: true },
4648
+ // O slug é o que vive em people.tags/orders.tags — renomear a tag NÃO o
4649
+ // muda (o trigger só o deriva quando está vazio), e é por isso que renomear
4650
+ // não órfã registro. Exposto porque, quando um chip não aparece onde
4651
+ // deveria, a resposta está sempre aqui.
4652
+ { key: "slug", label: "Slug", type: "text", showInTable: true },
4378
4653
  { key: "color", label: "Color", type: "color", showInTable: true, defaultValue: "#6366f1" },
4379
4654
  { key: "isActive", label: "Active", type: "boolean", showInTable: true, defaultValue: true }
4380
4655
  ],
@@ -4462,10 +4737,14 @@ var crmRegistries = [
4462
4737
  icon: "Tag",
4463
4738
  description: "Tags for organizing leads and deals",
4464
4739
  display: "table",
4740
+ // Só alimenta o provider MOCK (apps sem Supabase). Contra o banco, o
4741
+ // cadastro se alimenta do uso: `crm_register_tags` insere a linha quando
4742
+ // uma tag é gravada num lead. Semear vocabulário aqui encheria a tela de
4743
+ // tags que nenhum registro carrega.
4465
4744
  seedData: [
4466
- { id: "tag-vip", name: "VIP", color: "#f59e0b", isActive: true },
4467
- { id: "tag-hot", name: "Hot Lead", color: "#ef4444", isActive: true },
4468
- { id: "tag-followup", name: "Follow-up", color: "#3b82f6", isActive: true }
4745
+ { id: "tag-vip", name: "VIP", slug: "vip", color: "#f59e0b", isActive: true },
4746
+ { id: "tag-hot", name: "Hot Lead", slug: "hot-lead", color: "#ef4444", isActive: true },
4747
+ { id: "tag-followup", name: "Follow-up", slug: "follow-up", color: "#3b82f6", isActive: true }
4469
4748
  ]
4470
4749
  },
4471
4750
  {
@@ -4612,6 +4891,15 @@ var en = {
4612
4891
  "crm.page.newQuoteDesc": "Send a proposal",
4613
4892
  "crm.page.settingsSubtitle": "Configure pipeline, lead management, and registries",
4614
4893
  "crm.page.settingsTitle": "Sales & CRM Settings",
4894
+ "crm.filters.period": "Period",
4895
+ "crm.filters.periodAll": "All",
4896
+ "crm.filters.period24h": "24 hours",
4897
+ "crm.filters.period7d": "7 days",
4898
+ "crm.filters.periodCustom": "Custom",
4899
+ "crm.filters.tags": "Tags",
4900
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
4901
+ "crm.filters.clearTags": "Clear tags",
4902
+ "crm.filters.noResults": "No deals match the current filter",
4615
4903
  "crm.pipeline.dropHere": "Drop here",
4616
4904
  "crm.pipeline.archive": "Archive",
4617
4905
  "crm.pipeline.moveFailed": "Failed to move deal",
@@ -4910,6 +5198,15 @@ var ptBR = {
4910
5198
  "crm.page.newQuoteDesc": "Enviar um or\xE7amento",
4911
5199
  "crm.page.settingsSubtitle": "Configure pipeline, gest\xE3o de leads e cadastros",
4912
5200
  "crm.page.settingsTitle": "Configura\xE7\xF5es de Vendas e CRM",
5201
+ "crm.filters.period": "Per\xEDodo",
5202
+ "crm.filters.periodAll": "Tudo",
5203
+ "crm.filters.period24h": "24 horas",
5204
+ "crm.filters.period7d": "7 dias",
5205
+ "crm.filters.periodCustom": "Personalizado",
5206
+ "crm.filters.tags": "Tags",
5207
+ "crm.filters.tagsSelected": "{{count}} tag(s)",
5208
+ "crm.filters.clearTags": "Limpar tags",
5209
+ "crm.filters.noResults": "Nenhum neg\xF3cio no filtro atual",
4913
5210
  "crm.pipeline.dropHere": "Solte aqui",
4914
5211
  "crm.pipeline.archive": "Arquivar",
4915
5212
  "crm.pipeline.moveFailed": "Falha ao mover neg\xF3cio",
@@ -5141,7 +5438,7 @@ function createCrmPlugin(options) {
5141
5438
  () => createMockCrmProvider({ activityTypes })
5142
5439
  );
5143
5440
  const store = createCrmStore(provider);
5144
- const PageComponent = () => React14.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
5441
+ const PageComponent = () => React15.createElement(CrmPage, { config, provider, store, registries: crmRegistries2 });
5145
5442
  const dashboardWidgets = createCrmDashboardWidgets({ config, provider, store });
5146
5443
  return {
5147
5444
  id: "crm",
@@ -5311,6 +5608,86 @@ function createCrmPlugin(options) {
5311
5608
  { label: "Which leads need follow-up?" },
5312
5609
  { label: "What's our conversion rate?" }
5313
5610
  ]
5611
+ },
5612
+ {
5613
+ id: "crm.create-lead",
5614
+ name: "createLead",
5615
+ description: 'Opens a NEW lead. This is the ONLY way to create one \u2014 the leads entity is a read-only view, so createRecord cannot. Only `name` is required; send whatever else the user gave and omit the rest. Status defaults to "new" and belongs to a closed set: new, contacted, qualified, converted, lost. A lead whose e-mail or phone already exists is NOT duplicated \u2014 the existing one comes back with deduped:true, and changing it is updateLead. The user confirms before anything is written.',
5616
+ icon: "UserPlus",
5617
+ mode: "persist",
5618
+ limitKey: "leads",
5619
+ execution: { plane: "server", kind: "rpc", rpc: "agent_crm_create_lead" },
5620
+ category: "Sales",
5621
+ parameters: {
5622
+ type: "object",
5623
+ properties: {
5624
+ name: { type: "string", description: "The person's name" },
5625
+ email: { type: "string", description: "E-mail" },
5626
+ phone: { type: "string", description: "Phone" },
5627
+ company: { type: "string", description: "Company" },
5628
+ status: {
5629
+ type: "string",
5630
+ description: 'Funnel stage \u2014 defaults to "new"',
5631
+ enum: ["new", "contacted", "qualified", "converted", "lost"]
5632
+ },
5633
+ value: { type: "string", description: "Estimated value" },
5634
+ source_name: { type: "string", description: "Where the lead came from" },
5635
+ assigned_to_id: { type: "string", description: "Person the lead is assigned to (id)" },
5636
+ notes: { type: "string", description: "Notes" }
5637
+ },
5638
+ required: ["name"]
5639
+ },
5640
+ suggestions: [
5641
+ { label: "Cria um lead Noronha, interessado em tratamento facial" }
5642
+ ],
5643
+ permission: { feature: "sales", action: "create" }
5644
+ },
5645
+ {
5646
+ id: "crm.update-lead",
5647
+ name: "updateLead",
5648
+ description: 'Changes a lead that ALREADY EXISTS: move its status through the funnel, reassign it, or fix its data (name, email, phone, company, value, notes). This is the ONLY way to change a lead \u2014 the leads entity is a read-only view, so updateRecord cannot touch it. Status is a closed set: new (awaiting first contact), contacted, qualified, converted, lost. A proposal that went out is usually "qualified"; a closed sale is "converted". Takes the lead id from a previous search. The user confirms before anything changes.',
5649
+ icon: "UserCheck",
5650
+ mode: "persist",
5651
+ execution: { plane: "server", kind: "rpc", rpc: "agent_crm_update_lead" },
5652
+ category: "Sales",
5653
+ parameters: {
5654
+ type: "object",
5655
+ properties: {
5656
+ lead_id: { type: "string", description: "Id of the lead to change (from a search)" },
5657
+ status: {
5658
+ type: "string",
5659
+ description: "New funnel stage",
5660
+ enum: ["new", "contacted", "qualified", "converted", "lost"]
5661
+ },
5662
+ name: { type: "string", description: "Corrected name" },
5663
+ email: { type: "string", description: "Corrected e-mail" },
5664
+ phone: { type: "string", description: "Corrected phone" },
5665
+ company: { type: "string", description: "Company" },
5666
+ value: { type: "string", description: "Estimated value" },
5667
+ assigned_to_id: { type: "string", description: "Person the lead is assigned to (id)" },
5668
+ notes: { type: "string", description: "Notes" }
5669
+ },
5670
+ required: ["lead_id"]
5671
+ },
5672
+ suggestions: [
5673
+ { label: "Mandei a proposta pro Vini, atualiza o status" },
5674
+ { label: "Marca esse lead como perdido" }
5675
+ ],
5676
+ permission: { feature: "sales", action: "edit" }
5677
+ }
5678
+ ],
5679
+ declaredRpcs: [
5680
+ {
5681
+ name: "agent_crm_create_lead",
5682
+ kind: "write",
5683
+ description: "Guarded lead create: agent_guard (role\u2192plan\u2192leads cap), closed status set, e-mail/phone dedupe, audited.",
5684
+ audits: true
5685
+ },
5686
+ {
5687
+ name: "agent_crm_update_lead",
5688
+ kind: "write",
5689
+ description: "Guarded lead update: agent_guard (role\u2192plan, no cap), closed status set, tenant+kind checked, audited.",
5690
+ audits: true
5314
5691
  }
5315
5692
  ],
5316
5693
  registries: crmRegistries2,
@@ -5320,13 +5697,13 @@ function createCrmPlugin(options) {
5320
5697
  label: "Sales & CRM",
5321
5698
  icon: "Filter",
5322
5699
  component: (() => {
5323
- const Tab = () => React14.createElement(
5700
+ const Tab = () => React15.createElement(
5324
5701
  CrmContextProvider,
5325
5702
  { config, provider, store },
5326
- React14.createElement(PluginSettingsPanel, {
5703
+ React15.createElement(PluginSettingsPanel, {
5327
5704
  title: "Sales & CRM",
5328
5705
  subtitle: "Pipeline, lead management, and CRM properties",
5329
- generalSettings: React14.createElement(CrmGeneralSettings),
5706
+ generalSettings: React15.createElement(CrmGeneralSettings),
5330
5707
  registries: crmRegistries2,
5331
5708
  hostPluginId: "crm",
5332
5709
  routeBase: "/settings/crm"
@@ -5343,6 +5720,6 @@ function createCrmPlugin(options) {
5343
5720
  };
5344
5721
  }
5345
5722
 
5346
- export { createCrmPlugin };
5723
+ export { TagChips, createCrmPlugin, humanizeTag };
5347
5724
  //# sourceMappingURL=index.js.map
5348
5725
  //# sourceMappingURL=index.js.map