@lincros-ui/components 0.1.3 → 0.1.6

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,7 +1,7 @@
1
1
  import * as React36 from 'react';
2
- import React36__default, { memo, useMemo, useCallback, useState, useRef, useEffect, useContext } from 'react';
2
+ import React36__default, { memo, useMemo, useCallback, useState, useRef, useEffect } from 'react';
3
3
  import * as AccordionPrimitive from '@radix-ui/react-accordion';
4
- import { ChevronDown, ArrowLeft, ArrowRight, Check, X, Search, ChevronRight, Circle, Minimize2, Maximize2, Dot, ChevronUp, PanelLeft, Clock, AlertCircle, CheckCircle, Shield, AlertTriangle, Users, RefreshCw, Home, ExternalLink, LogIn, Server, Key, MoreHorizontal, ChevronLeft, Phone, Video, Info, MoreVertical, Paperclip, Smile, Mic, Send, GripVertical, Monitor, Navigation, Bell, BarChart3, Settings, UserCheck, UserCog, Car, Workflow, MessageCircle, Building2, Database, Bot, LogOut, Loader2, Filter, ChevronsLeft, ChevronsRight, Bold, Italic, List, ListOrdered, Quote, Code, Link2, Image, Plus, ChevronsUpDown, TestTube, Globe, Copy, Play, Pause, Square, RotateCcw, Edit, Trash2, History, CircleSlash, CircleDot, ToggleRight, ToggleLeft, MapPin, HelpCircle, Bug, StepForward, CornerDownRight, Brain, FileJson, XCircle, PauseCircle, GitBranch, Split, Layers, Gauge, PlayCircle, MessageSquare, Variable, Activity, Lightbulb, CheckCircle2, Upload, Download, Hash, StopCircle, Terminal, FileText, Zap, Eye, DollarSign, Expand, Coins, Wrench, Sparkles, Save, Inbox, TrendingUp, TrendingDown, Merge, ChevronsDownUp, PanelLeftClose, Unlock, Lock, Network, Timer, EyeOff, QrCode, User, GitMerge, Tag, Link as Link$1, Building, Box, Wifi, WifiOff, Type, Mail, File, CheckCheck } from 'lucide-react';
4
+ import { ChevronDown, ArrowLeft, ArrowRight, Check, X, Search, ChevronRight, Circle, Minimize2, Maximize2, Dot, ChevronUp, PanelLeft, Clock, AlertCircle, CheckCircle, Shield, AlertTriangle, Users, RefreshCw, Home, ExternalLink, LogIn, Server, Key, MoreHorizontal, ChevronLeft, Phone, Video, Info, MoreVertical, Paperclip, Smile, Mic, Send, GripVertical, Loader2, Filter, ChevronsLeft, ChevronsRight, Bold, Italic, List, ListOrdered, Quote, Code, Link2 as Link2$1, Image, Plus, Building2, ChevronsUpDown, TestTube, Globe, Copy, Play, Pause, Square, RotateCcw, Edit, Trash2, History, CircleSlash, CircleDot, ToggleRight, ToggleLeft, MapPin, HelpCircle, Bug, StepForward, CornerDownRight, Settings, Brain, Bot, FileJson, XCircle, PauseCircle, GitBranch, Split, Layers, Gauge, PlayCircle, MessageSquare, Database, Variable, Activity, Lightbulb, CheckCircle2, Upload, Download, Hash, StopCircle, Terminal, FileText, BarChart3, Zap, Eye, DollarSign, Expand, Coins, Wrench, Sparkles, Save, Inbox, TrendingUp, TrendingDown, MessageCircle, Merge, ChevronsDownUp, PanelLeftClose, Unlock, Lock, Network, Timer, Workflow, EyeOff, QrCode, User, GitMerge, Tag, Link as Link$1, Building, Box, Wifi, WifiOff, Type, Mail, File, CheckCheck } from 'lucide-react';
5
5
  import { clsx } from 'clsx';
6
6
  import { twMerge } from 'tailwind-merge';
7
7
  import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
@@ -41,25 +41,15 @@ import * as SwitchPrimitives from '@radix-ui/react-switch';
41
41
  import * as TabsPrimitive from '@radix-ui/react-tabs';
42
42
  import * as TogglePrimitive from '@radix-ui/react-toggle';
43
43
  import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
44
- import { sortableKeyboardCoordinates, SortableContext, verticalListSortingStrategy, arrayMove, useSortable } from '@dnd-kit/sortable';
45
- import { CSS } from '@dnd-kit/utilities';
46
- import { useQueryClient, useQuery, useMutation } from '@tanstack/react-query';
47
- import { getAllUsersUseCase, grantUserUnidadePermissionUseCase, grantBulkUserUnidadePermissionsUseCase, removeUserUnidadePermissionUseCase, getUserUnidadesUseCase, getUnidadeUsersUseCase, createUserUseCase, updateUserUseCase, deleteUserUseCase, activateUserUseCase, deactivateUserUseCase, getUserByIdUseCase } from '@/application/use-cases';
48
- import { AuthContext } from '@/presentation/providers/AuthProvider';
49
- import { TenantContext } from '@/presentation/contexts/TenantContext';
50
- import { ROUTE_PATHS } from '@/constants/routes';
51
- import { useLocation, Link, useNavigate, Navigate } from 'react-router-dom';
52
- import { MenuPermissionLevel, canAccessMenu } from '@/lib/menu-permissions';
44
+ import { useNavigate, useLocation, Navigate, Link } from 'react-router-dom';
53
45
  import { tenantService } from '@/services/api/tenant.service';
54
- import '@/types/ErrorType';
55
- import { useSensors, useSensor, PointerSensor, KeyboardSensor, DndContext, closestCenter } from '@dnd-kit/core';
56
- import { useSSOContext } from '@/presentation/contexts/SSOContext';
57
46
  import { getTenantFromSubdomain } from '@/lib/tenant-utils';
58
47
  import { useEditor, EditorContent } from '@tiptap/react';
59
48
  import StarterKit from '@tiptap/starter-kit';
60
49
  import Image2 from '@tiptap/extension-image';
61
- import Link3 from '@tiptap/extension-link';
50
+ import Link2 from '@tiptap/extension-link';
62
51
  import DOMPurify from 'dompurify';
52
+ import { useQueryClient, useQuery, useMutation } from '@tanstack/react-query';
63
53
  import { toast as toast$1 } from 'sonner';
64
54
  import { zodResolver } from '@hookform/resolvers/zod';
65
55
  import * as z2 from 'zod';
@@ -68,7 +58,9 @@ import { CreateCredentialUseCase } from '@/application/use-cases/credentials/Cre
68
58
  import { UpdateCredentialUseCase } from '@/application/use-cases/credentials/UpdateCredentialUseCase';
69
59
  import { ListCredentialsUseCase } from '@/application/use-cases/credentials/ListCredentialsUseCase';
70
60
  import { TestCredentialUseCase } from '@/application/use-cases/credentials/TestCredentialUseCase';
71
- import { authService } from '@/services/api/auth.service';
61
+ import { useSensors, useSensor, PointerSensor, KeyboardSensor, DndContext, closestCenter } from '@dnd-kit/core';
62
+ import { sortableKeyboardCoordinates, SortableContext, verticalListSortingStrategy, arrayMove, useSortable } from '@dnd-kit/sortable';
63
+ import { CSS } from '@dnd-kit/utilities';
72
64
  import { useExecutionStore } from '@/presentation/stores/execution.store';
73
65
  import { ExecutionStatus } from '@/domain/entities/flow-execution';
74
66
  import { useFlowEditorStore } from '@/presentation/stores/flow-editor.store';
@@ -86,41 +78,15 @@ import { EdgeLabelProvider, useEdgeLabels } from '@/presentation/contexts/EdgeLa
86
78
  import { flowCategoriesService } from '@/services/api/flow-categories.service';
87
79
  import { aiAgentService } from '@/services/api/ai-agent.service';
88
80
  import { mcpService } from '@/services/api/mcp.service';
89
- import { HttpWhatsAppRepository } from '@/infrastructure/repositories/HttpWhatsAppRepository';
90
- import { ListWhatsAppConfigsUseCase } from '@/application/use-cases/whatsapp/list-whatsapp-configs.use-case';
91
- import { CreateWhatsAppConfigUseCase } from '@/application/use-cases/whatsapp/create-whatsapp-config.use-case';
92
- import { ConnectWhatsAppInstanceUseCase } from '@/application/use-cases/whatsapp/connect-whatsapp-instance.use-case';
93
- import { SendWhatsAppMessageUseCase } from '@/application/use-cases/whatsapp/send-whatsapp-message.use-case';
94
- import { whatsappService } from '@/services/api/whatsapp.service';
95
- import { HttpWhatsAppTriggerRepository } from '@/infrastructure/repositories/HttpWhatsAppTriggerRepository';
96
- import { ListWhatsAppTriggersUseCase } from '@/application/use-cases/whatsapp/list-whatsapp-triggers.use-case';
97
- import { CreateWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/create-whatsapp-trigger.use-case';
98
- import { UpdateWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/update-whatsapp-trigger.use-case';
99
- import { DeleteWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/delete-whatsapp-trigger.use-case';
100
- import { TestWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/test-whatsapp-trigger.use-case';
101
- import { GetWhatsAppTriggerMetricsUseCase } from '@/application/use-cases/whatsapp/get-whatsapp-trigger-metrics.use-case';
102
- import { HttpFlowRepository } from '@/infrastructure/repositories/HttpFlowRepository';
103
81
  import { createMotoristaSchema } from '@/application/dtos/motorista/CreateMotoristaDto';
104
82
  import { updateMotoristaSchema } from '@/application/dtos/motorista/UpdateMotoristaDto';
105
- import { HttpMotoristaRepository } from '@/infrastructure/repositories/HttpMotoristaRepository';
106
- import { CreateMotoristaUseCase } from '@/application/use-cases/motorista/CreateMotoristaUseCase';
107
- import { UpdateMotoristaUseCase } from '@/application/use-cases/motorista/UpdateMotoristaUseCase';
108
- import { DeleteMotoristaUseCase } from '@/application/use-cases/motorista/DeleteMotoristaUseCase';
109
- import { ToggleBlockMotoristaUseCase } from '@/application/use-cases/motorista/ToggleBlockMotoristaUseCase';
110
83
  import { WebhookEventType, WebhookEventStatus } from '@/domain/entities/WebhookEvent';
111
84
  import { webhookService } from '@/services/api/webhook.service';
112
85
  import { flowExecutionService } from '@/services/api/flow-execution.service';
113
86
  import { useWhatsAppStore } from '@/presentation/stores/whatsapp.store';
87
+ import { whatsappService } from '@/services/api/whatsapp.service';
114
88
  import QRCode from 'qrcode';
115
89
  import { formatInTimeZone } from 'date-fns-tz';
116
- import { HttpUnidadeNegocioRepository } from '@/infrastructure/repositories/HttpUnidadeNegocioRepository';
117
- import { flowNodesService } from '@/services/api/flow-nodes.service';
118
- import { flowConnectionsService } from '@/services/api/flow-connections.service';
119
- import { compositeNodeManager } from '@/services/automation/CompositeNodeManager';
120
- import { sendMessageWhatsAppTemplate } from '@/services/automation/templates/sendMessageWhatsApp';
121
- import { perfisUsuarioService } from '@/services/api/perfis-usuario.service';
122
- import { unidadesNegocioService } from '@/services/api/unidades-negocio.service';
123
- import { httpWebhookRepository } from '@/infrastructure/repositories/HttpWebhookRepository';
124
90
 
125
91
  // src/components/ui/accordion.tsx
126
92
  function cn(...inputs) {
@@ -4399,8 +4365,8 @@ var reducer = (state, action) => {
4399
4365
  if (toastId) {
4400
4366
  addToRemoveQueue(toastId);
4401
4367
  } else {
4402
- state.toasts.forEach((toast7) => {
4403
- addToRemoveQueue(toast7.id);
4368
+ state.toasts.forEach((toast5) => {
4369
+ addToRemoveQueue(toast5.id);
4404
4370
  });
4405
4371
  }
4406
4372
  return {
@@ -4518,488 +4484,6 @@ var toastHelpers = {
4518
4484
  }
4519
4485
  };
4520
4486
  Object.assign(toast, toastHelpers);
4521
- function useAuthContext() {
4522
- const context = useContext(AuthContext);
4523
- if (context === void 0) {
4524
- throw new Error("useAuthContext must be used within an AuthProvider");
4525
- }
4526
- return context;
4527
- }
4528
- var useTenant = () => {
4529
- const context = useContext(TenantContext);
4530
- if (context === void 0) {
4531
- throw new Error("useTenant must be used within a TenantProvider");
4532
- }
4533
- return context;
4534
- };
4535
- var STORAGE_KEY = "sidebar-expanded-menus";
4536
- function useSidebarState() {
4537
- const location = useLocation();
4538
- const [expandedMenus, setExpandedMenus] = useState(() => {
4539
- try {
4540
- const saved = localStorage.getItem(STORAGE_KEY);
4541
- return saved ? JSON.parse(saved) : [];
4542
- } catch {
4543
- return [];
4544
- }
4545
- });
4546
- useEffect(() => {
4547
- const userManagementPaths = [
4548
- ROUTE_PATHS.USER_MANAGEMENT,
4549
- ROUTE_PATHS.USER_PROFILES,
4550
- ROUTE_PATHS.PERMISSIONS_MANAGEMENT
4551
- ];
4552
- const whatsAppPaths = [
4553
- ROUTE_PATHS.WHATSAPP,
4554
- ROUTE_PATHS.WHATSAPP_CONFIG,
4555
- ROUTE_PATHS.WHATSAPP_MONITORING,
4556
- ROUTE_PATHS.WHATSAPP_MESSAGES,
4557
- ROUTE_PATHS.WHATSAPP_TEMPLATES
4558
- ];
4559
- const configurationsPaths = [
4560
- ROUTE_PATHS.SETTINGS,
4561
- ROUTE_PATHS.UNIDADES_NEGOCIO,
4562
- ROUTE_PATHS.TENANT_MANAGEMENT,
4563
- ROUTE_PATHS.MOTORISTAS,
4564
- ROUTE_PATHS.CREDENTIALS
4565
- ];
4566
- const isInUsersPage = userManagementPaths.some(
4567
- (path) => location.pathname.includes(path)
4568
- );
4569
- const isInWhatsAppPage = whatsAppPaths.some(
4570
- (path) => location.pathname.includes(path)
4571
- );
4572
- const isInConfigurationsPage = configurationsPaths.some(
4573
- (path) => location.pathname.includes(path)
4574
- ) || isInUsersPage || isInWhatsAppPage;
4575
- setExpandedMenus((prev) => {
4576
- const newExpanded = [...prev];
4577
- let changed = false;
4578
- if (isInUsersPage && !prev.includes("Usu\xE1rios")) {
4579
- newExpanded.push("Usu\xE1rios");
4580
- changed = true;
4581
- }
4582
- if (isInWhatsAppPage && !prev.includes("WhatsApp")) {
4583
- newExpanded.push("WhatsApp");
4584
- changed = true;
4585
- }
4586
- if (isInConfigurationsPage && !prev.includes("Configura\xE7\xF5es")) {
4587
- newExpanded.push("Configura\xE7\xF5es");
4588
- changed = true;
4589
- }
4590
- if (changed) {
4591
- saveToStorage(newExpanded);
4592
- return newExpanded;
4593
- }
4594
- return prev;
4595
- });
4596
- }, [location.pathname]);
4597
- const saveToStorage = (menus) => {
4598
- try {
4599
- localStorage.setItem(STORAGE_KEY, JSON.stringify(menus));
4600
- } catch (error) {
4601
- console.warn("Erro ao salvar estado do menu no localStorage:", error);
4602
- }
4603
- };
4604
- const toggleSubmenu = (menuTitle) => {
4605
- setExpandedMenus((prev) => {
4606
- const newExpanded = prev.includes(menuTitle) ? prev.filter((title) => title !== menuTitle) : [...prev, menuTitle];
4607
- saveToStorage(newExpanded);
4608
- return newExpanded;
4609
- });
4610
- };
4611
- const isMenuExpanded = (menuTitle) => {
4612
- return expandedMenus.includes(menuTitle);
4613
- };
4614
- const isMenuItemActive = (url) => {
4615
- return location.pathname.includes(url);
4616
- };
4617
- const isExactMenuItemActive = (url) => {
4618
- return location.pathname === url;
4619
- };
4620
- return {
4621
- expandedMenus,
4622
- toggleSubmenu,
4623
- isMenuExpanded,
4624
- isMenuItemActive,
4625
- isExactMenuItemActive
4626
- };
4627
- }
4628
- function filterMenuItems(items, user) {
4629
- return items.filter((item) => canAccessMenu(user, item.permission)).map((item) => {
4630
- if (item.subItems) {
4631
- const filteredSubItems = filterMenuItems(
4632
- item.subItems,
4633
- user
4634
- );
4635
- if (filteredSubItems.length === 0) {
4636
- return null;
4637
- }
4638
- return {
4639
- ...item,
4640
- subItems: filteredSubItems
4641
- };
4642
- }
4643
- return item;
4644
- }).filter((item) => item !== null);
4645
- }
4646
- function RenderSubmenu({
4647
- items,
4648
- level,
4649
- isMenuExpanded,
4650
- isMenuItemActive,
4651
- toggleSubmenu
4652
- }) {
4653
- const { state } = useSidebar();
4654
- const isCollapsed = state === "collapsed";
4655
- if (!items) return null;
4656
- return /* @__PURE__ */ jsx(CustomSidebarMenuSub, { level, children: items.map((subItem) => {
4657
- const hasSubItems = subItem.subItems && subItem.subItems.length > 0;
4658
- const paddingLeft = isCollapsed ? 8 : Math.min(level * 8 + 4, 28);
4659
- return /* @__PURE__ */ jsx(CustomSidebarMenuSubItem, { children: hasSubItems ? /* @__PURE__ */ jsxs(Fragment, { children: [
4660
- /* @__PURE__ */ jsxs(Tooltip2, { children: [
4661
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
4662
- CustomSidebarMenuSubButton,
4663
- {
4664
- onClick: () => toggleSubmenu(subItem.title),
4665
- className: "w-full justify-start pr-2",
4666
- style: { paddingLeft: `${paddingLeft}px` },
4667
- children: [
4668
- subItem.icon && /* @__PURE__ */ jsx(subItem.icon, { className: "w-4 h-4 shrink-0 mr-2" }),
4669
- !isCollapsed && /* @__PURE__ */ jsxs(Fragment, { children: [
4670
- /* @__PURE__ */ jsx("span", { className: "truncate flex-1", children: subItem.title }),
4671
- /* @__PURE__ */ jsx(
4672
- ChevronRight,
4673
- {
4674
- className: `w-4 h-4 shrink-0 transition-transform ${isMenuExpanded(subItem.title) ? "rotate-90" : ""}`
4675
- }
4676
- )
4677
- ] })
4678
- ]
4679
- }
4680
- ) }),
4681
- isCollapsed && /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: subItem.title })
4682
- ] }),
4683
- isMenuExpanded(subItem.title) && /* @__PURE__ */ jsx(
4684
- RenderSubmenu,
4685
- {
4686
- items: subItem.subItems,
4687
- level: level + 1,
4688
- isMenuExpanded,
4689
- isMenuItemActive,
4690
- toggleSubmenu
4691
- }
4692
- )
4693
- ] }) : /* @__PURE__ */ jsxs(Tooltip2, { children: [
4694
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(CustomSidebarMenuSubButton, { asChild: true, children: /* @__PURE__ */ jsxs(
4695
- Link,
4696
- {
4697
- to: subItem.url || "#",
4698
- className: `justify-start pr-2 ${isMenuItemActive(subItem.url || "") ? "bg-accent text-accent-foreground" : ""}`,
4699
- style: { paddingLeft: `${paddingLeft}px` },
4700
- children: [
4701
- subItem.icon && /* @__PURE__ */ jsx(subItem.icon, { className: "w-4 h-4 shrink-0 mr-2" }),
4702
- !isCollapsed && /* @__PURE__ */ jsx("span", { className: "truncate flex-1", children: subItem.title })
4703
- ]
4704
- }
4705
- ) }) }),
4706
- isCollapsed && /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: subItem.title })
4707
- ] }) }, subItem.title);
4708
- }) });
4709
- }
4710
- function ControlTowerSidebar({
4711
- currentTime
4712
- }) {
4713
- const { user, logout, getCurrentTenantId } = useAuthContext();
4714
- const {
4715
- toggleSubmenu,
4716
- isMenuExpanded,
4717
- isMenuItemActive,
4718
- isExactMenuItemActive
4719
- } = useSidebarState();
4720
- const { state } = useSidebar();
4721
- const isCollapsed = state === "collapsed";
4722
- const [internalTime, setInternalTime] = React36__default.useState(/* @__PURE__ */ new Date());
4723
- const currentTenantId = getCurrentTenantId();
4724
- console.log(currentTenantId);
4725
- const isMasterTenant = currentTenantId === "master";
4726
- const menuItems = [
4727
- {
4728
- title: "Dashboard",
4729
- url: ROUTE_PATHS.DASHBOARD,
4730
- icon: Monitor,
4731
- permission: MenuPermissionLevel.ALL
4732
- },
4733
- {
4734
- title: "Monitoramento de Rotas",
4735
- url: ROUTE_PATHS.ROUTE_MONITORING,
4736
- icon: Navigation,
4737
- permission: MenuPermissionLevel.MASTER_TENANT_ONLY
4738
- },
4739
- {
4740
- title: "Monitoramento de Rotas",
4741
- url: ROUTE_PATHS.ROUTE_MONITORING,
4742
- icon: Navigation,
4743
- permission: MenuPermissionLevel.ADMIN_ONLY
4744
- },
4745
- {
4746
- title: "Alertas",
4747
- url: ROUTE_PATHS.ALERTS,
4748
- icon: Bell,
4749
- permission: MenuPermissionLevel.ALL
4750
- },
4751
- {
4752
- title: "Relat\xF3rios",
4753
- url: ROUTE_PATHS.REPORTS,
4754
- icon: BarChart3,
4755
- permission: MenuPermissionLevel.ALL
4756
- },
4757
- {
4758
- title: "Configura\xE7\xF5es",
4759
- icon: Settings,
4760
- permission: MenuPermissionLevel.ADMIN_ONLY,
4761
- subItems: [
4762
- {
4763
- title: "Configura\xE7\xF5es Gerais",
4764
- url: ROUTE_PATHS.SETTINGS,
4765
- icon: Settings,
4766
- permission: MenuPermissionLevel.ALL
4767
- },
4768
- {
4769
- title: "Usu\xE1rios",
4770
- icon: Users,
4771
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN,
4772
- subItems: [
4773
- {
4774
- title: "Gest\xE3o de Usu\xE1rios",
4775
- url: ROUTE_PATHS.USER_MANAGEMENT,
4776
- icon: UserCheck,
4777
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4778
- },
4779
- {
4780
- title: "Perfis de Usu\xE1rio",
4781
- url: ROUTE_PATHS.USER_PROFILES,
4782
- icon: UserCog,
4783
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4784
- },
4785
- {
4786
- title: "Permiss\xF5es",
4787
- url: ROUTE_PATHS.PERMISSIONS_MANAGEMENT,
4788
- icon: Shield,
4789
- permission: MenuPermissionLevel.ADMIN_ONLY
4790
- }
4791
- ]
4792
- },
4793
- {
4794
- title: "Motoristas",
4795
- url: ROUTE_PATHS.MOTORISTAS,
4796
- icon: Car,
4797
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4798
- },
4799
- {
4800
- title: "WhatsApp",
4801
- icon: MessageCircle,
4802
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN,
4803
- subItems: [
4804
- {
4805
- title: "Configura\xE7\xF5es",
4806
- url: ROUTE_PATHS.WHATSAPP_CONFIG,
4807
- icon: Settings,
4808
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4809
- },
4810
- {
4811
- title: "Triggers de Fluxo",
4812
- url: ROUTE_PATHS.WHATSAPP_TRIGGERS,
4813
- icon: Workflow,
4814
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4815
- },
4816
- {
4817
- title: "Monitoramento",
4818
- url: ROUTE_PATHS.WHATSAPP_MONITORING,
4819
- icon: Monitor,
4820
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4821
- }
4822
- ]
4823
- },
4824
- ...isMasterTenant ? [] : [{
4825
- title: "Unidades de Neg\xF3cio",
4826
- url: ROUTE_PATHS.UNIDADES_NEGOCIO,
4827
- icon: Building2,
4828
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4829
- }],
4830
- ...isMasterTenant ? [
4831
- {
4832
- title: "Tenants",
4833
- url: ROUTE_PATHS.TENANT_MANAGEMENT,
4834
- icon: Database,
4835
- permission: MenuPermissionLevel.ADMIN_ONLY
4836
- }
4837
- ] : []
4838
- ]
4839
- },
4840
- {
4841
- title: "Automa\xE7\xE3o",
4842
- icon: Bot,
4843
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN,
4844
- subItems: [
4845
- {
4846
- title: "Fluxos de Automa\xE7\xE3o",
4847
- url: ROUTE_PATHS.FLOWS,
4848
- icon: Workflow,
4849
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4850
- },
4851
- {
4852
- title: "Credenciais",
4853
- url: ROUTE_PATHS.CREDENTIALS,
4854
- icon: Key,
4855
- permission: MenuPermissionLevel.MANAGER_OR_ADMIN
4856
- }
4857
- ]
4858
- }
4859
- ];
4860
- React36__default.useEffect(() => {
4861
- if (!currentTime) {
4862
- const timer = setInterval(() => {
4863
- setInternalTime(/* @__PURE__ */ new Date());
4864
- }, 1e3);
4865
- return () => clearInterval(timer);
4866
- }
4867
- }, [currentTime]);
4868
- const displayTime = currentTime || internalTime;
4869
- const filteredMenuItems = filterMenuItems(menuItems, user);
4870
- return /* @__PURE__ */ jsxs(Sidebar, { className: "border-r border-gray-200", collapsible: "icon", children: [
4871
- /* @__PURE__ */ jsxs(SidebarHeader, { className: "border-b border-gray-200", children: [
4872
- /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between px-2 py-2", children: /* @__PURE__ */ jsx(SidebarTrigger, { className: "ml-auto" }) }),
4873
- !isCollapsed && /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-1 px-2 py-1", children: [
4874
- /* @__PURE__ */ jsx(
4875
- "img",
4876
- {
4877
- src: "/lovable-uploads/632ebc32-3ae3-4944-8e70-0e9c2539494a.png",
4878
- alt: "Lincros Logo",
4879
- className: "w-20 h-20 object-contain"
4880
- }
4881
- ),
4882
- /* @__PURE__ */ jsxs("div", { className: "text-center", children: [
4883
- /* @__PURE__ */ jsx("h2", { className: "font-bold text-lg text-gray-800", children: "Lincros" }),
4884
- /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500", children: "Torre de Controle 4.0" })
4885
- ] })
4886
- ] }),
4887
- isCollapsed && /* @__PURE__ */ jsx("div", { className: "flex justify-center px-2 py-2", children: /* @__PURE__ */ jsx(
4888
- "img",
4889
- {
4890
- src: "/lovable-uploads/632ebc32-3ae3-4944-8e70-0e9c2539494a.png",
4891
- alt: "Lincros Logo",
4892
- className: "w-8 h-8 object-contain"
4893
- }
4894
- ) })
4895
- ] }),
4896
- /* @__PURE__ */ jsx(SidebarContent, { children: /* @__PURE__ */ jsxs(SidebarGroup, { children: [
4897
- !isCollapsed && /* @__PURE__ */ jsx(SidebarGroupLabel, { children: "Menu Principal" }),
4898
- /* @__PURE__ */ jsx(SidebarGroupContent, { children: /* @__PURE__ */ jsx(SidebarMenu, { children: filteredMenuItems.map((item) => /* @__PURE__ */ jsx(SidebarMenuItem, { children: item.subItems ? /* @__PURE__ */ jsxs(Fragment, { children: [
4899
- /* @__PURE__ */ jsxs(Tooltip2, { children: [
4900
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxs(
4901
- SidebarMenuButton,
4902
- {
4903
- onClick: () => toggleSubmenu(item.title),
4904
- className: "w-full justify-start pr-2",
4905
- children: [
4906
- /* @__PURE__ */ jsx(item.icon, { className: "w-4 h-4 shrink-0" }),
4907
- !isCollapsed && /* @__PURE__ */ jsxs(Fragment, { children: [
4908
- /* @__PURE__ */ jsx("span", { className: "truncate flex-1", children: item.title }),
4909
- /* @__PURE__ */ jsx(
4910
- ChevronRight,
4911
- {
4912
- className: `w-4 h-4 shrink-0 transition-transform ${isMenuExpanded(item.title) ? "rotate-90" : ""}`
4913
- }
4914
- )
4915
- ] })
4916
- ]
4917
- }
4918
- ) }),
4919
- isCollapsed && /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: item.title })
4920
- ] }),
4921
- isMenuExpanded(item.title) && /* @__PURE__ */ jsx(
4922
- RenderSubmenu,
4923
- {
4924
- items: item.subItems,
4925
- level: 1,
4926
- isMenuExpanded,
4927
- isMenuItemActive,
4928
- toggleSubmenu
4929
- }
4930
- )
4931
- ] }) : /* @__PURE__ */ jsxs(Tooltip2, { children: [
4932
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(SidebarMenuButton, { asChild: true, children: /* @__PURE__ */ jsxs(
4933
- Link,
4934
- {
4935
- to: item.url || "#",
4936
- className: `justify-start pr-2 ${isExactMenuItemActive(item.url || "") ? "bg-accent text-accent-foreground" : ""}`,
4937
- children: [
4938
- /* @__PURE__ */ jsx(item.icon, { className: "w-4 h-4 shrink-0" }),
4939
- !isCollapsed && /* @__PURE__ */ jsx("span", { className: "truncate flex-1", children: item.title })
4940
- ]
4941
- }
4942
- ) }) }),
4943
- isCollapsed && /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: item.title })
4944
- ] }) }, item.title)) }) })
4945
- ] }) }),
4946
- /* @__PURE__ */ jsx(SidebarFooter, { className: "border-t border-gray-200", children: /* @__PURE__ */ jsxs("div", { className: `p-2 space-y-2 ${isCollapsed ? "px-1" : ""}`, children: [
4947
- user && /* @__PURE__ */ jsx("div", { className: "flex items-center justify-between", children: !isCollapsed ? /* @__PURE__ */ jsxs(Fragment, { children: [
4948
- /* @__PURE__ */ jsxs("div", { className: "flex flex-col min-w-0 flex-1", children: [
4949
- /* @__PURE__ */ jsx("span", { className: "text-sm font-medium text-gray-700 truncate", children: user.login }),
4950
- /* @__PURE__ */ jsx("span", { className: "text-xs text-gray-500 truncate", children: user.email })
4951
- ] }),
4952
- /* @__PURE__ */ jsx(
4953
- Button,
4954
- {
4955
- variant: "ghost",
4956
- size: "sm",
4957
- onClick: () => logout(),
4958
- className: "h-8 w-8 p-0 shrink-0 ml-2",
4959
- title: "Logout",
4960
- children: /* @__PURE__ */ jsx(LogOut, { className: "icon-size" })
4961
- }
4962
- )
4963
- ] }) : /* @__PURE__ */ jsxs(Tooltip2, { children: [
4964
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(
4965
- Button,
4966
- {
4967
- variant: "ghost",
4968
- size: "sm",
4969
- onClick: () => logout(),
4970
- className: "h-8 w-8 p-0",
4971
- children: /* @__PURE__ */ jsx(LogOut, { className: "icon-size" })
4972
- }
4973
- ) }),
4974
- /* @__PURE__ */ jsxs(TooltipContent, { side: "right", className: "font-medium", children: [
4975
- "Logout (",
4976
- user.login,
4977
- ")"
4978
- ] })
4979
- ] }) }),
4980
- !isCollapsed && /* @__PURE__ */ jsxs(Fragment, { children: [
4981
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4982
- /* @__PURE__ */ jsx("div", { className: "w-2 h-2 bg-green-500 rounded-full animate-pulse" }),
4983
- /* @__PURE__ */ jsx("span", { className: "text-xs text-gray-600 font-medium", children: "Sistema Online" })
4984
- ] }),
4985
- /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4986
- /* @__PURE__ */ jsx(Clock, { className: "w-3 h-3 text-gray-400" }),
4987
- /* @__PURE__ */ jsx("p", { className: "text-xs text-gray-500", children: displayTime.toLocaleString("pt-BR") })
4988
- ] })
4989
- ] }),
4990
- isCollapsed && /* @__PURE__ */ jsxs("div", { className: "flex flex-col items-center gap-2", children: [
4991
- /* @__PURE__ */ jsxs(Tooltip2, { children: [
4992
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx("div", { className: "w-2 h-2 bg-green-500 rounded-full animate-pulse" }) }),
4993
- /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: "Sistema Online" })
4994
- ] }),
4995
- /* @__PURE__ */ jsxs(Tooltip2, { children: [
4996
- /* @__PURE__ */ jsx(TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsx(Clock, { className: "w-4 h-4 text-gray-400" }) }),
4997
- /* @__PURE__ */ jsx(TooltipContent, { side: "right", className: "font-medium", children: displayTime.toLocaleString("pt-BR") })
4998
- ] })
4999
- ] })
5000
- ] }) })
5001
- ] });
5002
- }
5003
4487
  function EnsureTenant({ children }) {
5004
4488
  const { currentTenant, setCurrentTenant } = useTenant();
5005
4489
  const navigate = useNavigate();
@@ -5334,12 +4818,6 @@ function GenericFilterBar({
5334
4818
  ] }) })
5335
4819
  ] }) });
5336
4820
  }
5337
- function MainLayout({ children }) {
5338
- return /* @__PURE__ */ jsx(SidebarProvider, { children: /* @__PURE__ */ jsxs("div", { className: "h-screen w-full flex", children: [
5339
- /* @__PURE__ */ jsx(ControlTowerSidebar, {}),
5340
- /* @__PURE__ */ jsx("main", { className: "flex-1 overflow-hidden", children: /* @__PURE__ */ jsx("div", { className: "h-full overflow-y-auto", children }) })
5341
- ] }) });
5342
- }
5343
4821
  function PageHeader({ icon: Icon2, title, description, children }) {
5344
4822
  const scrollContainerRef = useRef(null);
5345
4823
  const headerContainerRef = useRef(null);
@@ -5588,9 +5066,6 @@ function PaginationControls({
5588
5066
  ] })
5589
5067
  ] });
5590
5068
  }
5591
- var useSSO = () => {
5592
- return useSSOContext();
5593
- };
5594
5069
  var SSOLoadingOverlay = memo(({
5595
5070
  step,
5596
5071
  progress,
@@ -5760,7 +5235,7 @@ function ProtectedRoute({ children }) {
5760
5235
  const { isAuthenticated, isLoading } = useAuthContext();
5761
5236
  const location = useLocation();
5762
5237
  const tenantId = getTenantFromSubdomain();
5763
- const sso = useSSO();
5238
+ const sso = useSSO(tenantId || void 0);
5764
5239
  useEffect(() => {
5765
5240
  if (tenantId && !isAuthenticated && !isLoading && !sso.state.loading && !sso.state.callbackProcessing && !sso.state.isAuthenticated) {
5766
5241
  console.log("[ProtectedRoute] Checking SSO status - not authenticated");
@@ -5811,7 +5286,7 @@ function RichTextEditor({ content, onChange, placeholder }) {
5811
5286
  class: "max-w-full h-auto rounded-lg my-2"
5812
5287
  }
5813
5288
  }),
5814
- Link3.configure({
5289
+ Link2.configure({
5815
5290
  openOnClick: false,
5816
5291
  HTMLAttributes: {
5817
5292
  class: "text-primary underline"
@@ -5994,7 +5469,7 @@ function RichTextEditor({ content, onChange, placeholder }) {
5994
5469
  onClick: () => setShowLinkDialog(true),
5995
5470
  className: "h-8 px-2",
5996
5471
  title: "Adicionar link",
5997
- children: /* @__PURE__ */ jsx(Link2, { className: "icon-size" })
5472
+ children: /* @__PURE__ */ jsx(Link2$1, { className: "icon-size" })
5998
5473
  }
5999
5474
  ),
6000
5475
  /* @__PURE__ */ jsx(
@@ -6993,236 +6468,6 @@ var SSOLoginButton = memo(({
6993
6468
  ] });
6994
6469
  });
6995
6470
  SSOLoginButton.displayName = "SSOLoginButton";
6996
- function useAuth() {
6997
- const [authState, setAuthState] = useState({
6998
- user: null,
6999
- isAuthenticated: false,
7000
- isLoading: true
7001
- });
7002
- useEffect(() => {
7003
- const checkAuth = async () => {
7004
- try {
7005
- if (authService.isAuthenticated()) {
7006
- const userData = authService.getCurrentUserData();
7007
- if (userData) {
7008
- if (!userData.id || !userData.login) {
7009
- try {
7010
- const token = localStorage.getItem("access_token") || localStorage.getItem("token");
7011
- if (token) {
7012
- const payload = JSON.parse(atob(token.split(".")[1]));
7013
- const userIdFromToken = payload.sub || payload.legacy_user_id || payload.user_id;
7014
- const loginFromToken = payload.login || payload.email || userData.email;
7015
- if (userIdFromToken) {
7016
- const completeUserData = {
7017
- ...userData,
7018
- id: userIdFromToken,
7019
- login: loginFromToken || userData.email || "",
7020
- legacy_user_id: userIdFromToken
7021
- };
7022
- localStorage.setItem("user_data", JSON.stringify(completeUserData));
7023
- const user2 = {
7024
- login: loginFromToken || userData.email || "",
7025
- nome: userData.nome || "",
7026
- email: userData.email || "",
7027
- empresa_id: userData.empresa_id || 0,
7028
- tenant_id: userData.tenant_id,
7029
- central_user_id: userData.central_user_id,
7030
- created_at: userData.created_at,
7031
- updated_at: userData.updated_at,
7032
- ...userData,
7033
- id: userIdFromToken,
7034
- legacy_user_id: userIdFromToken
7035
- };
7036
- setAuthState({
7037
- user: user2,
7038
- isAuthenticated: true,
7039
- isLoading: false
7040
- });
7041
- return;
7042
- }
7043
- }
7044
- } catch (error) {
7045
- console.error("Failed to extract from token:", error);
7046
- }
7047
- }
7048
- const user = {
7049
- id: userData.id,
7050
- login: userData.login,
7051
- nome: userData.nome || "",
7052
- email: userData.email || "",
7053
- empresa_id: userData.empresa_id || 0,
7054
- tenant_id: userData.tenant_id,
7055
- central_user_id: void 0,
7056
- legacy_user_id: void 0,
7057
- created_at: void 0,
7058
- updated_at: void 0,
7059
- ...userData
7060
- };
7061
- setAuthState({
7062
- user,
7063
- isAuthenticated: true,
7064
- isLoading: false
7065
- });
7066
- } else {
7067
- authService.clearAuthData();
7068
- setAuthState({
7069
- user: null,
7070
- isAuthenticated: false,
7071
- isLoading: false
7072
- });
7073
- }
7074
- } else {
7075
- setAuthState({
7076
- user: null,
7077
- isAuthenticated: false,
7078
- isLoading: false
7079
- });
7080
- }
7081
- } catch (error) {
7082
- console.error("Erro ao verificar autentica\xE7\xE3o:", error);
7083
- authService.clearAuthData();
7084
- setAuthState({
7085
- user: null,
7086
- isAuthenticated: false,
7087
- isLoading: false
7088
- });
7089
- }
7090
- };
7091
- checkAuth();
7092
- }, []);
7093
- const login = useCallback(async (credentials, tenantId) => {
7094
- setAuthState((prev) => ({ ...prev, isLoading: true }));
7095
- try {
7096
- const loginResponse = await authService.login(credentials, tenantId);
7097
- const user = {
7098
- id: loginResponse.user_id || loginResponse.user?.id,
7099
- login: loginResponse.login || loginResponse.user?.login,
7100
- nome: loginResponse.user?.nome || "",
7101
- email: loginResponse.user?.email || "",
7102
- empresa_id: loginResponse.user?.empresa_id || 0,
7103
- tenant_id: loginResponse.tenant_id,
7104
- central_user_id: loginResponse.user?.central_user_id,
7105
- legacy_user_id: loginResponse.user?.legacy_user_id,
7106
- created_at: loginResponse.user?.created_at,
7107
- updated_at: loginResponse.user?.updated_at,
7108
- is_admin: loginResponse.user?.is_admin || false,
7109
- perfil_usuario_id: loginResponse.user?.perfil_usuario_id || 0,
7110
- idioma_id: loginResponse.user?.idioma_id || 1,
7111
- tipo_usuario_id: loginResponse.user?.tipo_usuario_id || 0,
7112
- is_active: loginResponse.user?.is_active ?? true,
7113
- data_criacao: loginResponse.user?.data_criacao || null,
7114
- data_atualizacao: loginResponse.user?.data_atualizacao || null,
7115
- observacoes: loginResponse.user?.observacoes || null
7116
- };
7117
- setAuthState({
7118
- user,
7119
- isAuthenticated: true,
7120
- isLoading: false
7121
- });
7122
- return loginResponse;
7123
- } catch (error) {
7124
- setAuthState({
7125
- user: null,
7126
- isAuthenticated: false,
7127
- isLoading: false
7128
- });
7129
- throw error;
7130
- }
7131
- }, []);
7132
- const register = useCallback(async (userData) => {
7133
- setAuthState((prev) => ({ ...prev, isLoading: true }));
7134
- try {
7135
- const user = await authService.register(userData);
7136
- setAuthState({
7137
- user: null,
7138
- isAuthenticated: false,
7139
- isLoading: false
7140
- });
7141
- return user;
7142
- } catch (error) {
7143
- setAuthState((prev) => ({ ...prev, isLoading: false }));
7144
- throw error;
7145
- }
7146
- }, []);
7147
- const logout = useCallback(async () => {
7148
- setAuthState((prev) => ({ ...prev, isLoading: true }));
7149
- try {
7150
- await authService.logout();
7151
- } finally {
7152
- setAuthState({
7153
- user: null,
7154
- isAuthenticated: false,
7155
- isLoading: false
7156
- });
7157
- window.location.href = "/login";
7158
- }
7159
- }, []);
7160
- const refreshUser = useCallback(async () => {
7161
- try {
7162
- if (authService.isAuthenticated()) {
7163
- console.log("[useAuth] Refreshing user data - token found");
7164
- const userData = authService.getCurrentUserData();
7165
- if (userData) {
7166
- console.log("[useAuth] Using user data from localStorage:", userData);
7167
- const user2 = {
7168
- id: userData.id,
7169
- login: userData.login,
7170
- nome: userData.nome || userData.name || "",
7171
- email: userData.email || "",
7172
- empresa_id: userData.empresa_id || 0,
7173
- tenant_id: userData.tenant_id,
7174
- central_user_id: userData.central_user_id,
7175
- legacy_user_id: userData.legacy_user_id,
7176
- created_at: userData.created_at,
7177
- updated_at: userData.updated_at,
7178
- is_admin: userData.is_admin || false,
7179
- perfil_usuario_id: userData.perfil_usuario_id || 0,
7180
- idioma_id: userData.idioma_id || 1,
7181
- tipo_usuario_id: userData.tipo_usuario_id || 0,
7182
- is_active: userData.is_active ?? true,
7183
- data_criacao: userData.data_criacao || null,
7184
- data_atualizacao: userData.data_atualizacao || null,
7185
- observacoes: userData.observacoes || null,
7186
- ...userData
7187
- };
7188
- setAuthState({
7189
- user: user2,
7190
- isAuthenticated: true,
7191
- isLoading: false
7192
- });
7193
- console.log("[useAuth] AuthContext updated with SSO user data");
7194
- return user2;
7195
- }
7196
- const user = await authService.refreshUserData();
7197
- setAuthState((prev) => ({ ...prev, user, isAuthenticated: true }));
7198
- return user;
7199
- } else {
7200
- console.log("[useAuth] No token found during refresh");
7201
- setAuthState({
7202
- user: null,
7203
- isAuthenticated: false,
7204
- isLoading: false
7205
- });
7206
- return null;
7207
- }
7208
- } catch (error) {
7209
- console.error("Erro ao atualizar dados do usu\xE1rio:", error);
7210
- await logout();
7211
- throw error;
7212
- }
7213
- }, [logout]);
7214
- const getCurrentTenantId = useCallback(() => {
7215
- return authService.getCurrentTenantId();
7216
- }, []);
7217
- return {
7218
- ...authState,
7219
- login,
7220
- register,
7221
- logout,
7222
- refreshUser,
7223
- getCurrentTenantId
7224
- };
7225
- }
7226
6471
  var credentialRepository = new HttpCredentialRepository();
7227
6472
  var createCredentialUseCase = new CreateCredentialUseCase(credentialRepository);
7228
6473
  var updateCredentialUseCase = new UpdateCredentialUseCase(credentialRepository);
@@ -7275,7 +6520,7 @@ function SortableItem({ id, credential }) {
7275
6520
  );
7276
6521
  }
7277
6522
  function CredentialFormModal({ isOpen, onClose, credential }) {
7278
- const { toast: toast7 } = useToast();
6523
+ const { toast: toast5 } = useToast();
7279
6524
  const queryClient = useQueryClient();
7280
6525
  const { tenant } = useAuth();
7281
6526
  const [showApiKey, setShowApiKey] = useState(false);
@@ -7322,14 +6567,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
7322
6567
  mutationFn: (data) => createCredentialUseCase.execute(data),
7323
6568
  onSuccess: () => {
7324
6569
  queryClient.invalidateQueries({ queryKey: ["credentials"] });
7325
- toast7({
6570
+ toast5({
7326
6571
  title: "Credencial criada",
7327
6572
  description: "A credencial foi criada com sucesso."
7328
6573
  });
7329
6574
  onClose();
7330
6575
  },
7331
6576
  onError: (error) => {
7332
- toast7({
6577
+ toast5({
7333
6578
  title: "Erro ao criar credencial",
7334
6579
  description: error.message || "Ocorreu um erro ao criar a credencial.",
7335
6580
  variant: "destructive"
@@ -7340,14 +6585,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
7340
6585
  mutationFn: (data) => updateCredentialUseCase.execute(credential.id, data),
7341
6586
  onSuccess: () => {
7342
6587
  queryClient.invalidateQueries({ queryKey: ["credentials"] });
7343
- toast7({
6588
+ toast5({
7344
6589
  title: "Credencial atualizada",
7345
6590
  description: "A credencial foi atualizada com sucesso."
7346
6591
  });
7347
6592
  onClose();
7348
6593
  },
7349
6594
  onError: (error) => {
7350
- toast7({
6595
+ toast5({
7351
6596
  title: "Erro ao atualizar credencial",
7352
6597
  description: error.message || "Ocorreu um erro ao atualizar a credencial.",
7353
6598
  variant: "destructive"
@@ -7360,14 +6605,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
7360
6605
  return testCredentialUseCase.execute(credential.id);
7361
6606
  },
7362
6607
  onSuccess: (result) => {
7363
- toast7({
6608
+ toast5({
7364
6609
  title: result.success ? "Teste bem-sucedido" : "Teste falhou",
7365
6610
  description: result.message,
7366
6611
  variant: result.success ? "default" : "destructive"
7367
6612
  });
7368
6613
  },
7369
6614
  onError: (error) => {
7370
- toast7({
6615
+ toast5({
7371
6616
  title: "Erro ao testar credencial",
7372
6617
  description: error.message || "Ocorreu um erro ao testar a credencial.",
7373
6618
  variant: "destructive"
@@ -13054,7 +12299,7 @@ function ImportFlowFileModal({
13054
12299
  ] }) });
13055
12300
  }
13056
12301
  function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
13057
- const { toast: toast7 } = useToast();
12302
+ const { toast: toast5 } = useToast();
13058
12303
  const [loading, setLoading] = React36__default.useState(false);
13059
12304
  const [masterFlows, setMasterFlows] = React36__default.useState([]);
13060
12305
  const [selectedFlows, setSelectedFlows] = React36__default.useState([]);
@@ -13076,7 +12321,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
13076
12321
  } catch (error) {
13077
12322
  console.error("Erro ao carregar fluxos do master:", error);
13078
12323
  const errorMessage = error.response?.data?.detail || error.message || "Erro desconhecido";
13079
- toast7({
12324
+ toast5({
13080
12325
  title: "Erro ao carregar fluxos",
13081
12326
  description: `N\xE3o foi poss\xEDvel carregar os fluxos do master: ${errorMessage}`,
13082
12327
  variant: "destructive"
@@ -13084,7 +12329,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
13084
12329
  } finally {
13085
12330
  setLoading(false);
13086
12331
  }
13087
- }, [toast7]);
12332
+ }, [toast5]);
13088
12333
  React36__default.useEffect(() => {
13089
12334
  if (open) {
13090
12335
  loadMasterFlows();
@@ -13128,7 +12373,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
13128
12373
  };
13129
12374
  const showImportResult = (successCount, errorCount) => {
13130
12375
  if (successCount > 0) {
13131
- toast7({
12376
+ toast5({
13132
12377
  title: "Importa\xE7\xE3o conclu\xEDda",
13133
12378
  description: (() => {
13134
12379
  const base = `${successCount} fluxo(s) importado(s) com sucesso`;
@@ -13157,7 +12402,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
13157
12402
  }, []);
13158
12403
  const handleImport = async () => {
13159
12404
  if (selectedFlows.length === 0) {
13160
- toast7({
12405
+ toast5({
13161
12406
  title: "Nenhum fluxo selecionado",
13162
12407
  description: "Selecione pelo menos um fluxo para importar.",
13163
12408
  variant: "destructive"
@@ -14025,7 +13270,7 @@ function LoopResultsViewer({
14025
13270
  executionId,
14026
13271
  className
14027
13272
  }) {
14028
- const { toast: toast7 } = useToast();
13273
+ const { toast: toast5 } = useToast();
14029
13274
  const [activeTab, setActiveTab] = useState("table");
14030
13275
  const [filterStatus, setFilterStatus] = useState("all");
14031
13276
  const [searchQuery, setSearchQuery] = useState("");
@@ -14065,7 +13310,7 @@ function LoopResultsViewer({
14065
13310
  a.click();
14066
13311
  document.body.removeChild(a);
14067
13312
  URL.revokeObjectURL(url);
14068
- toast7({
13313
+ toast5({
14069
13314
  title: "Export conclu\xEDdo",
14070
13315
  description: "Resultados exportados para JSON com sucesso."
14071
13316
  });
@@ -14094,14 +13339,14 @@ function LoopResultsViewer({
14094
13339
  a.click();
14095
13340
  document.body.removeChild(a);
14096
13341
  URL.revokeObjectURL(url);
14097
- toast7({
13342
+ toast5({
14098
13343
  title: "Export conclu\xEDdo",
14099
13344
  description: "Resultados exportados para CSV com sucesso."
14100
13345
  });
14101
13346
  };
14102
13347
  const copyToClipboard = (data) => {
14103
13348
  navigator.clipboard.writeText(JSON.stringify(data, null, 2));
14104
- toast7({
13349
+ toast5({
14105
13350
  title: "Copiado",
14106
13351
  description: "Dados copiados para a \xE1rea de transfer\xEAncia."
14107
13352
  });
@@ -15259,20 +14504,20 @@ function PromptTestModal({
15259
14504
  tools = [],
15260
14505
  outputParser
15261
14506
  }) {
15262
- const { toast: toast7 } = useToast();
14507
+ const { toast: toast5 } = useToast();
15263
14508
  const [sampleContext, setSampleContext] = useState('{\n "input_text": "Exemplo de texto para an\xE1lise",\n "user_name": "Jo\xE3o"\n}');
15264
14509
  const [testResult, setTestResult] = useState(null);
15265
14510
  const testPromptMutation = useMutation({
15266
14511
  mutationFn: (request) => aiAgentService.testPrompt(request),
15267
14512
  onSuccess: (data) => {
15268
14513
  setTestResult(data);
15269
- toast7({
14514
+ toast5({
15270
14515
  title: "Teste executado",
15271
14516
  description: "Teste executado com sucesso!"
15272
14517
  });
15273
14518
  },
15274
14519
  onError: (error) => {
15275
- toast7({
14520
+ toast5({
15276
14521
  title: "Erro ao testar",
15277
14522
  description: `Erro ao testar prompt: ${error.message || "Erro desconhecido"}`,
15278
14523
  variant: "destructive"
@@ -15291,7 +14536,7 @@ function PromptTestModal({
15291
14536
  };
15292
14537
  testPromptMutation.mutate(request);
15293
14538
  } catch {
15294
- toast7({
14539
+ toast5({
15295
14540
  title: "Erro de valida\xE7\xE3o",
15296
14541
  description: "Contexto de teste inv\xE1lido. Verifique o JSON.",
15297
14542
  variant: "destructive"
@@ -15485,120 +14730,6 @@ function PromptTestModal({
15485
14730
  ] })
15486
14731
  ] }) });
15487
14732
  }
15488
- function useMCPTools(options = {}) {
15489
- const { category, searchTerm, enabled = true } = options;
15490
- const { toast: toast7 } = useToast();
15491
- const [filteredTools, setFilteredTools] = useState([]);
15492
- const hasToken = !!localStorage.getItem("access_token");
15493
- const shouldEnable = enabled && hasToken;
15494
- const {
15495
- data: toolsResponse,
15496
- isLoading,
15497
- error,
15498
- refetch
15499
- } = useQuery({
15500
- queryKey: ["mcp-tools", category],
15501
- queryFn: () => mcpService.listTools(category),
15502
- enabled: shouldEnable,
15503
- staleTime: 5 * 60 * 1e3,
15504
- retry: 1
15505
- });
15506
- useEffect(() => {
15507
- if (error) {
15508
- const errorMessage = error instanceof Error ? error.message : String(error);
15509
- if (!errorMessage.includes("MCP authentication failed")) {
15510
- toast7({
15511
- title: "Erro ao carregar ferramentas MCP",
15512
- description: errorMessage || "N\xE3o foi poss\xEDvel carregar as ferramentas do servidor MCP",
15513
- variant: "destructive"
15514
- });
15515
- }
15516
- }
15517
- }, [error, toast7]);
15518
- const allTools = React36__default.useMemo(() => {
15519
- if (!toolsResponse?.tools) return [];
15520
- const toolsMap = /* @__PURE__ */ new Map();
15521
- toolsResponse.tools.forEach((toolData) => {
15522
- try {
15523
- const tool = MCPTool.fromAPIResponse(toolData);
15524
- const existingTool = toolsMap.get(tool.name);
15525
- if (!existingTool || tool.description && tool.description.length > (existingTool.description?.length || 0)) {
15526
- toolsMap.set(tool.name, tool);
15527
- }
15528
- } catch (error2) {
15529
- console.error("Error processing tool:", toolData.name, error2);
15530
- }
15531
- });
15532
- return Array.from(toolsMap.values());
15533
- }, [toolsResponse]);
15534
- useEffect(() => {
15535
- if (!searchTerm) {
15536
- setFilteredTools(allTools);
15537
- return;
15538
- }
15539
- const term = searchTerm.toLowerCase();
15540
- const filtered = allTools.filter(
15541
- (tool) => tool.name.toLowerCase().includes(term) || tool.description.toLowerCase().includes(term) || tool.nodeSubtype.toLowerCase().includes(term) || tool.category.toLowerCase().includes(term)
15542
- );
15543
- setFilteredTools(filtered);
15544
- }, [searchTerm, allTools]);
15545
- const toolsByCategory = filteredTools.reduce((acc, tool) => {
15546
- if (!acc[tool.category]) {
15547
- acc[tool.category] = [];
15548
- }
15549
- acc[tool.category].push(tool);
15550
- return acc;
15551
- }, {});
15552
- const categories = Object.keys(toolsByCategory).length > 0 ? Object.keys(toolsByCategory) : toolsResponse?.categories || Object.keys(toolsResponse?.by_category || {});
15553
- if (!hasToken) {
15554
- return {
15555
- tools: [],
15556
- toolsByCategory: {},
15557
- categories: [],
15558
- isLoading: false,
15559
- error: null,
15560
- refetch: () => {
15561
- }
15562
- };
15563
- }
15564
- return {
15565
- tools: filteredTools,
15566
- toolsByCategory,
15567
- categories,
15568
- isLoading,
15569
- error,
15570
- refetch
15571
- };
15572
- }
15573
- function useMCPNodeValidation() {
15574
- const { toast: toast7 } = useToast();
15575
- const validateNode = async (nodeType, nodeSubtype, parameters) => {
15576
- try {
15577
- const response = await mcpService.validateNode({
15578
- node_type: nodeType,
15579
- node_subtype: nodeSubtype,
15580
- parameters
15581
- });
15582
- if (!response.valid && response.errors?.length) {
15583
- toast7({
15584
- title: "Valida\xE7\xE3o falhou",
15585
- description: response.errors[0],
15586
- variant: "destructive"
15587
- });
15588
- }
15589
- return response;
15590
- } catch (error) {
15591
- const errorMessage = error instanceof Error ? error.message : String(error);
15592
- toast7({
15593
- title: "Erro na valida\xE7\xE3o",
15594
- description: errorMessage || "N\xE3o foi poss\xEDvel validar a configura\xE7\xE3o",
15595
- variant: "destructive"
15596
- });
15597
- throw error;
15598
- }
15599
- };
15600
- return { validateNode };
15601
- }
15602
14733
  var aiAgentConfigSchema = z2.object({
15603
14734
  nome: z2.string().min(1, "Nome \xE9 obrigat\xF3rio").max(255),
15604
14735
  descricao: z2.string().optional(),
@@ -15647,7 +14778,7 @@ function AIAgentConfigModal({
15647
14778
  onSave,
15648
14779
  initialData
15649
14780
  }) {
15650
- const { toast: toast7 } = useToast();
14781
+ const { toast: toast5 } = useToast();
15651
14782
  const [activeTab, setActiveTab] = useState("basic");
15652
14783
  const [selectedTools, setSelectedTools] = useState([]);
15653
14784
  const [enableParser, setEnableParser] = useState(false);
@@ -15801,13 +14932,13 @@ function AIAgentConfigModal({
15801
14932
  output_parser: outputParserData
15802
14933
  };
15803
14934
  onSave(config);
15804
- toast7({
14935
+ toast5({
15805
14936
  title: "Configura\xE7\xE3o salva",
15806
14937
  description: "Configura\xE7\xE3o salva com sucesso!"
15807
14938
  });
15808
14939
  onClose();
15809
14940
  } catch {
15810
- toast7({
14941
+ toast5({
15811
14942
  title: "Erro ao salvar",
15812
14943
  description: "Erro ao salvar configura\xE7\xE3o",
15813
14944
  variant: "destructive"
@@ -15909,7 +15040,7 @@ function AIAgentConfigModal({
15909
15040
  setParserType(config.output_parser.type);
15910
15041
  form.setValue("output_parser", config.output_parser);
15911
15042
  }
15912
- toast7({
15043
+ toast5({
15913
15044
  title: "Template aplicado",
15914
15045
  description: "Template de An\xE1lise de Sentimento aplicado com sucesso"
15915
15046
  });
@@ -15934,7 +15065,7 @@ function AIAgentConfigModal({
15934
15065
  setParserType(config.output_parser.type);
15935
15066
  form.setValue("output_parser", config.output_parser);
15936
15067
  }
15937
- toast7({
15068
+ toast5({
15938
15069
  title: "Template aplicado",
15939
15070
  description: "Template de Extra\xE7\xE3o de Entidades aplicado com sucesso"
15940
15071
  });
@@ -16351,48 +15482,6 @@ function AIAgentConfigModal({
16351
15482
  )
16352
15483
  ] });
16353
15484
  }
16354
- var repository = new HttpWhatsAppRepository();
16355
- var listConfigsUseCase = new ListWhatsAppConfigsUseCase(repository);
16356
- function useWhatsAppConfigs(activeOnly = false) {
16357
- const { getCurrentTenantId } = useAuthContext();
16358
- const { toast: toast7 } = useToast();
16359
- const { data: configsData, isLoading, error } = useQuery({
16360
- queryKey: ["whatsapp-configs", getCurrentTenantId(), activeOnly],
16361
- queryFn: async () => {
16362
- try {
16363
- const result = await listConfigsUseCase.execute({ activeOnly });
16364
- return result;
16365
- } catch (err) {
16366
- console.error("[useWhatsAppConfigs] Erro na query", {
16367
- error: err,
16368
- message: err?.message,
16369
- stack: err?.stack
16370
- });
16371
- throw err;
16372
- }
16373
- },
16374
- staleTime: 5 * 60 * 1e3,
16375
- retry: 1
16376
- });
16377
- useEffect(() => {
16378
- if (error) {
16379
- console.error("[useWhatsAppConfigs] useEffect - Erro detectado", {
16380
- error,
16381
- errorMessage: error?.message
16382
- });
16383
- toast7({
16384
- title: "Erro ao carregar configura\xE7\xF5es WhatsApp",
16385
- description: "N\xE3o foi poss\xEDvel carregar as configura\xE7\xF5es do WhatsApp. Verifique se o backend est\xE1 rodando e se voc\xEA est\xE1 autenticado corretamente.",
16386
- variant: "destructive"
16387
- });
16388
- }
16389
- }, [error, toast7]);
16390
- return {
16391
- configs: configsData?.configs || [],
16392
- loading: isLoading,
16393
- error: error?.message || null
16394
- };
16395
- }
16396
15485
  var compositeNodeConfigSchema = z2.object({
16397
15486
  execution_mode: z2.enum(["full", "send_only"]).default("full"),
16398
15487
  array_field: z2.string().min(1, "Campo de dados \xE9 obrigat\xF3rio").default("messages"),
@@ -16781,7 +15870,7 @@ function LoopConfigModal({
16781
15870
  node,
16782
15871
  onSave
16783
15872
  }) {
16784
- const { toast: toast7 } = useToast();
15873
+ const { toast: toast5 } = useToast();
16785
15874
  const [activeTab, setActiveTab] = useState("config");
16786
15875
  const [previewData, setPreviewData] = useState(null);
16787
15876
  const [isMaximized, setIsMaximized] = useState(false);
@@ -16928,7 +16017,7 @@ function LoopConfigModal({
16928
16017
  try {
16929
16018
  if (!node) return;
16930
16019
  if (!data.mode) {
16931
- toast7({
16020
+ toast5({
16932
16021
  title: "Erro de valida\xE7\xE3o",
16933
16022
  description: "Modo de loop \xE9 obrigat\xF3rio",
16934
16023
  variant: "destructive"
@@ -16936,7 +16025,7 @@ function LoopConfigModal({
16936
16025
  return;
16937
16026
  }
16938
16027
  if (data.mode === "items" && !data.source_field) {
16939
- toast7({
16028
+ toast5({
16940
16029
  title: "Erro de valida\xE7\xE3o",
16941
16030
  description: "Campo de origem \xE9 obrigat\xF3rio para modo items",
16942
16031
  variant: "destructive"
@@ -16945,7 +16034,7 @@ function LoopConfigModal({
16945
16034
  }
16946
16035
  if (data.mode === "range") {
16947
16036
  if (data.start === void 0 || data.end === void 0) {
16948
- toast7({
16037
+ toast5({
16949
16038
  title: "Erro de valida\xE7\xE3o",
16950
16039
  description: "In\xEDcio e fim s\xE3o obrigat\xF3rios para modo range",
16951
16040
  variant: "destructive"
@@ -16953,7 +16042,7 @@ function LoopConfigModal({
16953
16042
  return;
16954
16043
  }
16955
16044
  if (data.start >= data.end) {
16956
- toast7({
16045
+ toast5({
16957
16046
  title: "Erro de valida\xE7\xE3o",
16958
16047
  description: "O valor inicial deve ser menor que o valor final",
16959
16048
  variant: "destructive"
@@ -16962,7 +16051,7 @@ function LoopConfigModal({
16962
16051
  }
16963
16052
  }
16964
16053
  if (data.mode === "while" && !data.condition) {
16965
- toast7({
16054
+ toast5({
16966
16055
  title: "Erro de valida\xE7\xE3o",
16967
16056
  description: "Condi\xE7\xE3o \xE9 obrigat\xF3ria para modo while",
16968
16057
  variant: "destructive"
@@ -16988,14 +16077,14 @@ function LoopConfigModal({
16988
16077
  // Enviar vazio por compatibilidade
16989
16078
  };
16990
16079
  await onSave(node.id, updatedNode);
16991
- toast7({
16080
+ toast5({
16992
16081
  title: "Configura\xE7\xE3o salva",
16993
16082
  description: "As configura\xE7\xF5es do Loop Node foram salvas com sucesso."
16994
16083
  });
16995
16084
  onClose();
16996
16085
  } catch (error) {
16997
16086
  console.error("Erro ao salvar configura\xE7\xE3o:", error);
16998
- toast7({
16087
+ toast5({
16999
16088
  title: "Erro ao salvar",
17000
16089
  description: "Ocorreu um erro ao salvar as configura\xE7\xF5es. Tente novamente.",
17001
16090
  variant: "destructive"
@@ -17340,277 +16429,6 @@ function LoopConfigModal({
17340
16429
  ] })
17341
16430
  ] }) });
17342
16431
  }
17343
- var repository2 = new HttpWhatsAppRepository();
17344
- var listConfigsUseCase2 = new ListWhatsAppConfigsUseCase(repository2);
17345
- var createConfigUseCase = new CreateWhatsAppConfigUseCase(repository2);
17346
- var connectInstanceUseCase = new ConnectWhatsAppInstanceUseCase(repository2);
17347
- var sendMessageUseCase = new SendWhatsAppMessageUseCase(repository2);
17348
- function useWhatsApp(options = {}) {
17349
- const { autoRefresh = false, refreshInterval = 3e4 } = options;
17350
- const queryClient = useQueryClient();
17351
- const { getCurrentTenantId } = useAuthContext();
17352
- const [selectedConfig, setSelectedConfig] = useState(null);
17353
- const {
17354
- data: configsData,
17355
- isLoading: isLoadingConfigs,
17356
- error: configsError,
17357
- refetch: refetchConfigs
17358
- } = useQuery({
17359
- queryKey: ["whatsapp-configs", getCurrentTenantId()],
17360
- queryFn: () => listConfigsUseCase2.execute({ limit: 50 }),
17361
- refetchInterval: autoRefresh ? refreshInterval : void 0,
17362
- staleTime: 5 * 60 * 1e3,
17363
- retry: 1,
17364
- retryDelay: 5e3,
17365
- onError: (error) => {
17366
- console.error("Erro ao carregar configura\xE7\xF5es WhatsApp:", error);
17367
- }
17368
- });
17369
- const createConfigMutation = useMutation({
17370
- mutationFn: createConfigUseCase.execute.bind(createConfigUseCase),
17371
- onSuccess: (newConfig) => {
17372
- queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
17373
- toast({
17374
- title: "Configura\xE7\xE3o criada",
17375
- description: `Inst\xE2ncia ${newConfig.instanceName} foi criada com sucesso.`
17376
- });
17377
- },
17378
- onError: (error) => {
17379
- toast({
17380
- title: "Erro ao criar configura\xE7\xE3o",
17381
- description: error.message,
17382
- variant: "destructive"
17383
- });
17384
- }
17385
- });
17386
- const connectInstanceMutation = useMutation({
17387
- mutationFn: (configId) => connectInstanceUseCase.execute({ configId }),
17388
- onSuccess: () => {
17389
- queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
17390
- },
17391
- onError: (error) => {
17392
- toast({
17393
- title: "Erro ao conectar",
17394
- description: error.message,
17395
- variant: "destructive"
17396
- });
17397
- }
17398
- });
17399
- const disconnectInstanceMutation = useMutation({
17400
- mutationFn: (configId) => connectInstanceUseCase.disconnect({ configId }),
17401
- onSuccess: () => {
17402
- queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
17403
- toast({
17404
- title: "Inst\xE2ncia desconectada",
17405
- description: "A inst\xE2ncia foi desconectada com sucesso."
17406
- });
17407
- },
17408
- onError: (error) => {
17409
- toast({
17410
- title: "Erro ao desconectar",
17411
- description: error.message,
17412
- variant: "destructive"
17413
- });
17414
- }
17415
- });
17416
- const sendMessageMutation = useMutation({
17417
- mutationFn: sendMessageUseCase.execute.bind(sendMessageUseCase),
17418
- onSuccess: () => {
17419
- toast({
17420
- title: "Mensagem enviada",
17421
- description: "Sua mensagem foi enviada com sucesso."
17422
- });
17423
- },
17424
- onError: (error) => {
17425
- toast({
17426
- title: "Erro ao enviar mensagem",
17427
- description: error.message,
17428
- variant: "destructive"
17429
- });
17430
- }
17431
- });
17432
- const deleteConfigMutation = useMutation({
17433
- mutationFn: (configId) => repository2.deleteConfig(configId),
17434
- onSuccess: () => {
17435
- queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
17436
- toast({
17437
- title: "Configura\xE7\xE3o deletada",
17438
- description: "A configura\xE7\xE3o foi removida com sucesso."
17439
- });
17440
- },
17441
- onError: (error) => {
17442
- toast({
17443
- title: "Erro ao deletar",
17444
- description: error.message,
17445
- variant: "destructive"
17446
- });
17447
- }
17448
- });
17449
- const checkHealth = useCallback(async (configId) => {
17450
- try {
17451
- const health = await connectInstanceUseCase.checkHealth({ configId });
17452
- if (health.healthy) {
17453
- toast({
17454
- title: "Inst\xE2ncia saud\xE1vel",
17455
- description: "A inst\xE2ncia est\xE1 funcionando corretamente."
17456
- });
17457
- } else {
17458
- toast({
17459
- title: "Inst\xE2ncia com problemas",
17460
- description: health.error || "Verifique a conex\xE3o.",
17461
- variant: "destructive"
17462
- });
17463
- }
17464
- return health;
17465
- } catch (error) {
17466
- toast({
17467
- title: "Erro ao verificar sa\xFAde",
17468
- description: error instanceof Error ? error.message : "Erro desconhecido",
17469
- variant: "destructive"
17470
- });
17471
- throw error;
17472
- }
17473
- }, []);
17474
- const testMessage = useCallback(async (configId, testNumber) => {
17475
- try {
17476
- const result = await repository2.testMessage(configId, testNumber);
17477
- if (result.success) {
17478
- toast({
17479
- title: "Teste bem-sucedido",
17480
- description: "Mensagem de teste enviada com sucesso."
17481
- });
17482
- } else {
17483
- toast({
17484
- title: "Teste falhou",
17485
- description: result.error || "Erro ao enviar mensagem de teste.",
17486
- variant: "destructive"
17487
- });
17488
- }
17489
- return result;
17490
- } catch (error) {
17491
- toast({
17492
- title: "Erro no teste",
17493
- description: error instanceof Error ? error.message : "Erro desconhecido",
17494
- variant: "destructive"
17495
- });
17496
- throw error;
17497
- }
17498
- }, []);
17499
- const validatePhoneNumber = useCallback((phoneNumber) => {
17500
- return whatsappService.validatePhoneNumber(phoneNumber);
17501
- }, []);
17502
- const formatPhoneNumber = useCallback((phoneNumber) => {
17503
- return whatsappService.formatPhoneForDisplay(phoneNumber);
17504
- }, []);
17505
- useEffect(() => {
17506
- if (!autoRefresh) return;
17507
- const interval = setInterval(() => {
17508
- refetchConfigs();
17509
- }, refreshInterval);
17510
- return () => clearInterval(interval);
17511
- }, [autoRefresh, refreshInterval, refetchConfigs]);
17512
- const getConnectedConfigs = useCallback(() => {
17513
- if (!configsData?.configs) return [];
17514
- return configsData.configs.filter((config) => config.isConnected());
17515
- }, [configsData]);
17516
- const getConfigByName = useCallback((instanceName) => {
17517
- if (!configsData?.configs) return null;
17518
- return configsData.configs.find((config) => config.instanceName === instanceName) || null;
17519
- }, [configsData]);
17520
- return {
17521
- // Dados
17522
- configs: configsData?.configs || [],
17523
- stats: configsData?.stats || { connected: 0, disconnected: 0, error: 0, pending: 0 },
17524
- selectedConfig,
17525
- connectedConfigs: getConnectedConfigs(),
17526
- // Estado
17527
- isLoading: isLoadingConfigs,
17528
- error: configsError,
17529
- // Mutations state
17530
- isCreating: createConfigMutation.isPending,
17531
- isConnecting: connectInstanceMutation.isPending,
17532
- isDisconnecting: disconnectInstanceMutation.isPending,
17533
- isSending: sendMessageMutation.isPending,
17534
- isDeleting: deleteConfigMutation.isPending,
17535
- // Ações
17536
- createConfig: createConfigMutation.mutate,
17537
- connectInstance: connectInstanceMutation.mutate,
17538
- disconnectInstance: disconnectInstanceMutation.mutate,
17539
- sendMessage: sendMessageMutation.mutate,
17540
- deleteConfig: deleteConfigMutation.mutate,
17541
- checkHealth,
17542
- testMessage,
17543
- refetchConfigs,
17544
- setSelectedConfig,
17545
- // Utilidades
17546
- validatePhoneNumber,
17547
- formatPhoneNumber,
17548
- getConfigByName
17549
- };
17550
- }
17551
- function useWhatsAppHealthMonitor(configId, interval = 6e4) {
17552
- const [health, setHealth] = useState(null);
17553
- useEffect(() => {
17554
- if (!configId) return;
17555
- const checkHealth = async () => {
17556
- try {
17557
- const useCase = new ConnectWhatsAppInstanceUseCase(repository2);
17558
- const result = await useCase.checkHealth({ configId });
17559
- setHealth({
17560
- ...result,
17561
- lastCheck: /* @__PURE__ */ new Date()
17562
- });
17563
- } catch (error) {
17564
- setHealth({
17565
- healthy: false,
17566
- connected: false,
17567
- status: "error",
17568
- error: error instanceof Error ? error.message : "Erro desconhecido",
17569
- lastCheck: /* @__PURE__ */ new Date()
17570
- });
17571
- }
17572
- };
17573
- checkHealth();
17574
- const intervalId = setInterval(checkHealth, interval);
17575
- return () => clearInterval(intervalId);
17576
- }, [configId, interval]);
17577
- return health;
17578
- }
17579
- function useWhatsAppQRCode(configId) {
17580
- const [qrCode, setQrCode] = useState(null);
17581
- const [loading, setLoading] = useState(false);
17582
- const [error, setError] = useState(null);
17583
- const connect = useCallback(async () => {
17584
- if (!configId) {
17585
- setError("ID da configura\xE7\xE3o n\xE3o fornecido");
17586
- return;
17587
- }
17588
- setLoading(true);
17589
- setError(null);
17590
- try {
17591
- const response = await repository2.connectInstance(configId);
17592
- setQrCode(response);
17593
- return response;
17594
- } catch (err) {
17595
- const errorMessage = err instanceof Error ? err.message : "Erro ao gerar QR Code";
17596
- setError(errorMessage);
17597
- throw err;
17598
- } finally {
17599
- setLoading(false);
17600
- }
17601
- }, [configId]);
17602
- const reset = useCallback(() => {
17603
- setQrCode(null);
17604
- setError(null);
17605
- }, []);
17606
- return {
17607
- qrCode,
17608
- loading,
17609
- error,
17610
- connect,
17611
- reset
17612
- };
17613
- }
17614
16432
  var mcpVerificationCache = /* @__PURE__ */ new Map();
17615
16433
  var WEBHOOK_EVENT_TYPES = [
17616
16434
  { value: "messages.upsert", label: "messages.upsert - Nova mensagem recebida", icon: "\u{1F4E8}" },
@@ -18737,7 +17555,7 @@ function SplitConfigModal({
18737
17555
  node,
18738
17556
  onSave
18739
17557
  }) {
18740
- const { toast: toast7 } = useToast();
17558
+ const { toast: toast5 } = useToast();
18741
17559
  const [activeTab, setActiveTab] = useState("config");
18742
17560
  const [previewData, setPreviewData] = useState(null);
18743
17561
  const [isMaximized, setIsMaximized] = useState(false);
@@ -18856,7 +17674,7 @@ function SplitConfigModal({
18856
17674
  try {
18857
17675
  if (!node) return;
18858
17676
  if (!data.split_mode) {
18859
- toast7({
17677
+ toast5({
18860
17678
  title: "Erro de valida\xE7\xE3o",
18861
17679
  description: "Modo de divis\xE3o \xE9 obrigat\xF3rio",
18862
17680
  variant: "destructive"
@@ -18864,7 +17682,7 @@ function SplitConfigModal({
18864
17682
  return;
18865
17683
  }
18866
17684
  if (!data.field_name && data.split_mode !== "properties") {
18867
- toast7({
17685
+ toast5({
18868
17686
  title: "Erro de valida\xE7\xE3o",
18869
17687
  description: "Nome do campo \xE9 obrigat\xF3rio para este modo",
18870
17688
  variant: "destructive"
@@ -18890,14 +17708,14 @@ function SplitConfigModal({
18890
17708
  // Enviar vazio por compatibilidade
18891
17709
  };
18892
17710
  await onSave(node.id, updatedNode);
18893
- toast7({
17711
+ toast5({
18894
17712
  title: "Configura\xE7\xE3o salva",
18895
17713
  description: "As configura\xE7\xF5es do nodo Split foram salvas com sucesso."
18896
17714
  });
18897
17715
  onClose();
18898
17716
  } catch (error) {
18899
17717
  console.error("Erro ao salvar configura\xE7\xE3o:", error);
18900
- toast7({
17718
+ toast5({
18901
17719
  title: "Erro ao salvar",
18902
17720
  description: "Ocorreu um erro ao salvar as configura\xE7\xF5es. Tente novamente.",
18903
17721
  variant: "destructive"
@@ -19195,7 +18013,7 @@ function WhatsAppTriggerConfigModal({
19195
18013
  flowId,
19196
18014
  onSave
19197
18015
  }) {
19198
- const { toast: toast7 } = useToast();
18016
+ const { toast: toast5 } = useToast();
19199
18017
  const { configs, loading: loadingConfigs } = useWhatsAppConfigs();
19200
18018
  const availableInstances = configs?.filter((config) => config.isConnected()) || [];
19201
18019
  const [activeTab, setActiveTab] = useState("basic");
@@ -19267,7 +18085,7 @@ function WhatsAppTriggerConfigModal({
19267
18085
  };
19268
18086
  const onFormError = (errors2) => {
19269
18087
  const errorMessages = Object.entries(errors2).map(([field, error]) => `${field}: ${error?.message || "erro desconhecido"}`).join("\n");
19270
- toast7({
18088
+ toast5({
19271
18089
  title: "Erro de valida\xE7\xE3o",
19272
18090
  description: errorMessages || "Verifique os campos do formul\xE1rio",
19273
18091
  variant: "destructive"
@@ -19560,184 +18378,6 @@ function WhatsAppTriggerConfigModal({
19560
18378
  ] })
19561
18379
  ] }) });
19562
18380
  }
19563
- var triggerRepository = new HttpWhatsAppTriggerRepository();
19564
- var flowRepository = new HttpFlowRepository();
19565
- var whatsappRepository = new HttpWhatsAppRepository();
19566
- var listTriggersUseCase = new ListWhatsAppTriggersUseCase(triggerRepository);
19567
- var createTriggerUseCase = new CreateWhatsAppTriggerUseCase(
19568
- triggerRepository,
19569
- flowRepository,
19570
- whatsappRepository
19571
- );
19572
- var updateTriggerUseCase = new UpdateWhatsAppTriggerUseCase(triggerRepository);
19573
- var deleteTriggerUseCase = new DeleteWhatsAppTriggerUseCase(triggerRepository);
19574
- var testTriggerUseCase = new TestWhatsAppTriggerUseCase(triggerRepository);
19575
- var getMetricsUseCase = new GetWhatsAppTriggerMetricsUseCase(triggerRepository);
19576
- function useWhatsAppTriggers(flowId, instanceName) {
19577
- const queryClient = useQueryClient();
19578
- const { toast: toast7 } = useToast();
19579
- const { data: triggersData, isLoading, error, refetch } = useQuery({
19580
- queryKey: ["whatsapp-triggers", flowId, instanceName],
19581
- queryFn: async () => {
19582
- if (flowId) {
19583
- const triggers = await listTriggersUseCase.getByFlow(flowId);
19584
- return triggers;
19585
- }
19586
- if (instanceName) {
19587
- const triggers = await listTriggersUseCase.getByInstance(instanceName);
19588
- return triggers;
19589
- }
19590
- const result = await listTriggersUseCase.execute();
19591
- return result.triggers;
19592
- },
19593
- refetchInterval: 3e4
19594
- });
19595
- const createTriggerMutation = useMutation({
19596
- mutationFn: (data) => createTriggerUseCase.execute(data),
19597
- onSuccess: () => {
19598
- queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
19599
- toast7({
19600
- title: "Sucesso",
19601
- description: "Trigger criado com sucesso"
19602
- });
19603
- },
19604
- onError: (error2) => {
19605
- toast7({
19606
- title: "Erro",
19607
- description: `Erro ao criar trigger: ${error2.message}`,
19608
- variant: "destructive"
19609
- });
19610
- }
19611
- });
19612
- const updateTriggerMutation = useMutation({
19613
- mutationFn: ({ id, data }) => updateTriggerUseCase.execute(id, data),
19614
- onSuccess: () => {
19615
- queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
19616
- toast7({
19617
- title: "Sucesso",
19618
- description: "Trigger atualizado com sucesso"
19619
- });
19620
- },
19621
- onError: (error2) => {
19622
- toast7({
19623
- title: "Erro",
19624
- description: `Erro ao atualizar trigger: ${error2.message}`,
19625
- variant: "destructive"
19626
- });
19627
- }
19628
- });
19629
- const deleteTriggerMutation = useMutation({
19630
- mutationFn: (id) => deleteTriggerUseCase.execute(id),
19631
- onSuccess: () => {
19632
- queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
19633
- toast7({
19634
- title: "Sucesso",
19635
- description: "Trigger exclu\xEDdo com sucesso"
19636
- });
19637
- },
19638
- onError: (error2) => {
19639
- toast7({
19640
- title: "Erro",
19641
- description: `Erro ao excluir trigger: ${error2.message}`,
19642
- variant: "destructive"
19643
- });
19644
- }
19645
- });
19646
- const toggleActiveMutation = useMutation({
19647
- mutationFn: (id) => updateTriggerUseCase.toggleActive(id),
19648
- onSuccess: () => {
19649
- queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
19650
- toast7({
19651
- title: "Sucesso",
19652
- description: "Status do trigger alterado"
19653
- });
19654
- },
19655
- onError: (error2) => {
19656
- toast7({
19657
- title: "Erro",
19658
- description: `Erro ao alterar status: ${error2.message}`,
19659
- variant: "destructive"
19660
- });
19661
- }
19662
- });
19663
- const testTriggerMutation = useMutation({
19664
- mutationFn: (data) => testTriggerUseCase.execute(data),
19665
- onSuccess: (result) => {
19666
- if (result && result.matched) {
19667
- toast7({
19668
- title: "Teste bem-sucedido",
19669
- description: "A mensagem corresponde ao trigger"
19670
- });
19671
- } else if (result) {
19672
- toast7({
19673
- title: "Teste falhado",
19674
- description: result.error || "A mensagem n\xE3o corresponde ao trigger",
19675
- variant: "destructive"
19676
- });
19677
- } else {
19678
- toast7({
19679
- title: "Erro",
19680
- description: "Resposta inv\xE1lida do servidor",
19681
- variant: "destructive"
19682
- });
19683
- }
19684
- },
19685
- onError: (error2) => {
19686
- toast7({
19687
- title: "Erro",
19688
- description: `Erro ao testar trigger: ${error2.message}`,
19689
- variant: "destructive"
19690
- });
19691
- }
19692
- });
19693
- return {
19694
- triggers: triggersData || [],
19695
- loading: isLoading,
19696
- error: error?.message || null,
19697
- refetch,
19698
- createTrigger: createTriggerMutation.mutate,
19699
- updateTrigger: updateTriggerMutation.mutate,
19700
- deleteTrigger: deleteTriggerMutation.mutate,
19701
- toggleActive: toggleActiveMutation.mutate,
19702
- testTrigger: testTriggerMutation.mutate,
19703
- isCreating: createTriggerMutation.isPending,
19704
- isUpdating: updateTriggerMutation.isPending,
19705
- isDeleting: deleteTriggerMutation.isPending,
19706
- isTesting: testTriggerMutation.isPending
19707
- };
19708
- }
19709
- function useWhatsAppTriggerMetrics(triggerId) {
19710
- const { data, isLoading, error, refetch } = useQuery({
19711
- queryKey: ["whatsapp-trigger-metrics", triggerId],
19712
- queryFn: () => getMetricsUseCase.execute(triggerId),
19713
- enabled: !!triggerId,
19714
- refetchInterval: 1e4
19715
- // Atualizar a cada 10 segundos
19716
- });
19717
- return {
19718
- metrics: data?.metrics,
19719
- trigger: data?.trigger,
19720
- recentExecutions: data?.recentExecutions || [],
19721
- loading: isLoading,
19722
- error: error?.message || null,
19723
- refetch
19724
- };
19725
- }
19726
- function useWhatsAppTriggerExecutions(triggerId, limit = 50) {
19727
- const { data, isLoading, error, refetch } = useQuery({
19728
- queryKey: ["whatsapp-trigger-executions", triggerId, limit],
19729
- queryFn: () => getMetricsUseCase.getExecutions(triggerId, limit),
19730
- enabled: !!triggerId,
19731
- refetchInterval: 5e3
19732
- // Atualizar a cada 5 segundos
19733
- });
19734
- return {
19735
- executions: data || [],
19736
- loading: isLoading,
19737
- error: error?.message || null,
19738
- refetch
19739
- };
19740
- }
19741
18381
  function WhatsAppTriggerMetricsModal({
19742
18382
  open,
19743
18383
  onClose,
@@ -21405,61 +20045,6 @@ function MotoristaStatusBadge({ motorista }) {
21405
20045
  }
21406
20046
  return /* @__PURE__ */ jsx(Badge, { variant: "default", children: "Ativo" });
21407
20047
  }
21408
- var repository3 = new HttpMotoristaRepository();
21409
- function useMotoristaMutations() {
21410
- const queryClient = useQueryClient();
21411
- const createMutation = useMutation({
21412
- mutationFn: async (data) => {
21413
- const useCase = new CreateMotoristaUseCase(repository3);
21414
- return await useCase.execute(data);
21415
- },
21416
- onSuccess: () => {
21417
- queryClient.invalidateQueries({ queryKey: ["motoristas"] });
21418
- }
21419
- });
21420
- const updateMutation = useMutation({
21421
- mutationFn: async ({ cd_motorista, data }) => {
21422
- const useCase = new UpdateMotoristaUseCase(repository3);
21423
- return await useCase.execute(cd_motorista, data);
21424
- },
21425
- onSuccess: (_, variables) => {
21426
- queryClient.invalidateQueries({ queryKey: ["motorista", variables.cd_motorista] });
21427
- queryClient.invalidateQueries({ queryKey: ["motoristas"] });
21428
- }
21429
- });
21430
- const deleteMutation = useMutation({
21431
- mutationFn: async (cd_motorista) => {
21432
- const useCase = new DeleteMotoristaUseCase(repository3);
21433
- return await useCase.execute(cd_motorista);
21434
- },
21435
- onSuccess: (_, cd_motorista) => {
21436
- queryClient.invalidateQueries({ queryKey: ["motorista", cd_motorista] });
21437
- queryClient.invalidateQueries({ queryKey: ["motoristas"] });
21438
- }
21439
- });
21440
- const toggleBlockMutation = useMutation({
21441
- mutationFn: async ({ cd_motorista, bloqueado }) => {
21442
- const useCase = new ToggleBlockMotoristaUseCase(repository3);
21443
- return await useCase.execute(cd_motorista, bloqueado);
21444
- },
21445
- onSuccess: (_, variables) => {
21446
- queryClient.invalidateQueries({ queryKey: ["motorista", variables.cd_motorista] });
21447
- queryClient.invalidateQueries({ queryKey: ["motoristas"] });
21448
- }
21449
- });
21450
- const verifyPasswordMutation = useMutation({
21451
- mutationFn: async ({ cd_motorista, senha }) => {
21452
- return await repository3.verifyPassword(cd_motorista, senha);
21453
- }
21454
- });
21455
- return {
21456
- createMutation,
21457
- updateMutation,
21458
- deleteMutation,
21459
- toggleBlockMutation,
21460
- verifyPasswordMutation
21461
- };
21462
- }
21463
20048
  function MotoristaTable({
21464
20049
  motoristas,
21465
20050
  isLoading,
@@ -21608,7 +20193,7 @@ function MotoristaTable({
21608
20193
  ] }) }) });
21609
20194
  }
21610
20195
  function EventInspector({ event, onRetry, className }) {
21611
- const { toast: toast7 } = useToast();
20196
+ const { toast: toast5 } = useToast();
21612
20197
  const [expandedSections, setExpandedSections] = useState(/* @__PURE__ */ new Set(["overview"]));
21613
20198
  const [copiedField, setCopiedField] = useState(null);
21614
20199
  const retryMutation = useMutation({
@@ -21616,14 +20201,14 @@ function EventInspector({ event, onRetry, className }) {
21616
20201
  return await webhookService.retryEvent(eventId);
21617
20202
  },
21618
20203
  onSuccess: () => {
21619
- toast7({
20204
+ toast5({
21620
20205
  title: "Reprocessamento iniciado",
21621
20206
  description: "O evento ser\xE1 reprocessado em breve"
21622
20207
  });
21623
20208
  onRetry?.(event.id);
21624
20209
  },
21625
20210
  onError: (error) => {
21626
- toast7({
20211
+ toast5({
21627
20212
  title: "Erro ao reprocessar",
21628
20213
  description: error.message,
21629
20214
  variant: "destructive"
@@ -21663,7 +20248,7 @@ function EventInspector({ event, onRetry, className }) {
21663
20248
  await navigator.clipboard.writeText(text);
21664
20249
  setCopiedField(field);
21665
20250
  setTimeout(() => setCopiedField(null), 2e3);
21666
- toast7({
20251
+ toast5({
21667
20252
  title: "Copiado!",
21668
20253
  description: "Conte\xFAdo copiado para a \xE1rea de transfer\xEAncia"
21669
20254
  });
@@ -22686,7 +21271,7 @@ function WebhookFlowLink({
22686
21271
  showDetails = true,
22687
21272
  onReExecute
22688
21273
  }) {
22689
- const { toast: toast7 } = useToast();
21274
+ const { toast: toast5 } = useToast();
22690
21275
  const { data: flowExecution, isLoading, refetch } = useQuery({
22691
21276
  queryKey: ["flow-execution", event.metadata.sessionId],
22692
21277
  queryFn: async () => {
@@ -22745,7 +21330,7 @@ function WebhookFlowLink({
22745
21330
  return execution;
22746
21331
  },
22747
21332
  onSuccess: (execution) => {
22748
- toast7({
21333
+ toast5({
22749
21334
  title: "Fluxo re-executado",
22750
21335
  description: `Nova execu\xE7\xE3o iniciada: ${execution.id}`
22751
21336
  });
@@ -22753,7 +21338,7 @@ function WebhookFlowLink({
22753
21338
  refetch();
22754
21339
  },
22755
21340
  onError: (error) => {
22756
- toast7({
21341
+ toast5({
22757
21342
  title: "Erro ao re-executar fluxo",
22758
21343
  description: error.message,
22759
21344
  variant: "destructive"
@@ -22978,7 +21563,7 @@ function WebhookLogsViewer({
22978
21563
  maxLogs = 500,
22979
21564
  className
22980
21565
  }) {
22981
- const { toast: toast7 } = useToast();
21566
+ const { toast: toast5 } = useToast();
22982
21567
  const scrollAreaRef = useRef(null);
22983
21568
  const [searchTerm, setSearchTerm] = useState("");
22984
21569
  const [selectedLevel, setSelectedLevel] = useState("all");
@@ -23047,7 +21632,7 @@ function WebhookLogsViewer({
23047
21632
  });
23048
21633
  const handleExport = (format8) => {
23049
21634
  if (!filteredLogs || filteredLogs.length === 0) {
23050
- toast7({
21635
+ toast5({
23051
21636
  title: "Nenhum log para exportar",
23052
21637
  description: "N\xE3o h\xE1 logs dispon\xEDveis para exporta\xE7\xE3o",
23053
21638
  variant: "destructive"
@@ -23083,7 +21668,7 @@ function WebhookLogsViewer({
23083
21668
  linkElement.setAttribute("download", exportFileDefaultName);
23084
21669
  linkElement.click();
23085
21670
  }
23086
- toast7({
21671
+ toast5({
23087
21672
  title: "Logs exportados",
23088
21673
  description: `${selectedToExport.length} logs exportados com sucesso`
23089
21674
  });
@@ -23109,7 +21694,7 @@ function WebhookLogsViewer({
23109
21694
  const copyLogToClipboard = (log) => {
23110
21695
  const logText = `[${format(log.timestamp, "yyyy-MM-dd HH:mm:ss.SSS")}] [${log.level.toUpperCase()}] ${log.message}`;
23111
21696
  navigator.clipboard.writeText(logText);
23112
- toast7({
21697
+ toast5({
23113
21698
  title: "Log copiado",
23114
21699
  description: "Conte\xFAdo do log copiado para a \xE1rea de transfer\xEAncia"
23115
21700
  });
@@ -23835,7 +22420,7 @@ function WebhookTestModal({
23835
22420
  defaultUrl = "",
23836
22421
  defaultEventType = WebhookEventType.MESSAGE_RECEIVED
23837
22422
  }) {
23838
- const { toast: toast7 } = useToast();
22423
+ const { toast: toast5 } = useToast();
23839
22424
  const [testHistory, setTestHistory] = useState([]);
23840
22425
  const [selectedTemplate, setSelectedTemplate] = useState(defaultEventType);
23841
22426
  const [activeTab, setActiveTab] = useState("test");
@@ -23880,12 +22465,12 @@ function WebhookTestModal({
23880
22465
  };
23881
22466
  setTestHistory((prev) => [historyItem, ...prev].slice(0, 10));
23882
22467
  if (response.success) {
23883
- toast7({
22468
+ toast5({
23884
22469
  title: "Teste bem-sucedido",
23885
22470
  description: `Webhook respondeu com status ${response.status_code} em ${duration}ms`
23886
22471
  });
23887
22472
  } else {
23888
- toast7({
22473
+ toast5({
23889
22474
  title: "Teste falhou",
23890
22475
  description: response.error || `Status: ${response.status_code}`,
23891
22476
  variant: "destructive"
@@ -23893,7 +22478,7 @@ function WebhookTestModal({
23893
22478
  }
23894
22479
  },
23895
22480
  onError: (error) => {
23896
- toast7({
22481
+ toast5({
23897
22482
  title: "Erro ao testar webhook",
23898
22483
  description: error.message,
23899
22484
  variant: "destructive"
@@ -23911,7 +22496,7 @@ function WebhookTestModal({
23911
22496
  };
23912
22497
  const copyToClipboard = (text) => {
23913
22498
  navigator.clipboard.writeText(text);
23914
- toast7({
22499
+ toast5({
23915
22500
  title: "Copiado!",
23916
22501
  description: "Conte\xFAdo copiado para a \xE1rea de transfer\xEAncia"
23917
22502
  });
@@ -24949,7 +23534,7 @@ var QRCodeModal = ({
24949
23534
  configId,
24950
23535
  onConnectionSuccess
24951
23536
  }) => {
24952
- const { toast: toast7 } = useToast();
23537
+ const { toast: toast5 } = useToast();
24953
23538
  const [qrCodeUrl, setQrCodeUrl] = useState("");
24954
23539
  const [timeRemaining, setTimeRemaining] = useState(180);
24955
23540
  const [isExpired, setIsExpired] = useState(false);
@@ -25030,7 +23615,7 @@ var QRCodeModal = ({
25030
23615
  if (health.connected || health.status === "connected") {
25031
23616
  setIsConnected(true);
25032
23617
  setCurrentStatus("connected");
25033
- toast7({
23618
+ toast5({
25034
23619
  title: "WhatsApp Conectado!",
25035
23620
  description: `A inst\xE2ncia ${instanceName} foi conectada com sucesso.`,
25036
23621
  variant: "default"
@@ -25049,7 +23634,7 @@ var QRCodeModal = ({
25049
23634
  } finally {
25050
23635
  setCheckingStatus(false);
25051
23636
  }
25052
- }, [configId, checkingStatus, isConnected, isExpired, instanceName, onConnectionSuccess, onClose, toast7]);
23637
+ }, [configId, checkingStatus, isConnected, isExpired, instanceName, onConnectionSuccess, onClose, toast5]);
25053
23638
  useEffect(() => {
25054
23639
  if (!open || !configId || isConnected || isExpired) return;
25055
23640
  const interval = setInterval(() => {
@@ -25981,1471 +24566,6 @@ function getNodeIconTextColor({
25981
24566
  };
25982
24567
  return colorMap[status] || "text-purple-600";
25983
24568
  }
25984
- var repository4 = new HttpUnidadeNegocioRepository();
25985
- function useEmpresasForSelect() {
25986
- return useQuery({
25987
- queryKey: ["empresas", "select"],
25988
- queryFn: async () => {
25989
- const response = await repository4.getAll();
25990
- return response.data.map((unidade) => ({
25991
- value: unidade.cd_unidade_negocio,
25992
- label: unidade.nome
25993
- }));
25994
- },
25995
- staleTime: 5 * 60 * 1e3
25996
- // Cache for 5 minutes
25997
- });
25998
- }
25999
- function useFlowEditor({ flowId, onHistorySave }) {
26000
- const { toast: toast7 } = useToast();
26001
- const [data, setData] = useState(null);
26002
- const [loading, setLoading] = useState(true);
26003
- const [error, setError] = useState(null);
26004
- const [nodes, setNodes] = useState([]);
26005
- const [connections, setConnections] = useState([]);
26006
- const [composites, setComposites] = useState([]);
26007
- const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
26008
- const [saving, setSaving] = useState(false);
26009
- const [selectedNodeId, setSelectedNodeId] = useState(null);
26010
- const [showPropertiesPanel, setShowPropertiesPanel] = useState(false);
26011
- const [showAIAgentModal, setShowAIAgentModal] = useState(false);
26012
- const [aiAgentNodeToEdit, setAIAgentNodeToEdit] = useState(null);
26013
- const [showSplitModal, setShowSplitModal] = useState(false);
26014
- const [splitNodeToEdit, setSplitNodeToEdit] = useState(null);
26015
- const [showLoopModal, setShowLoopModal] = useState(false);
26016
- const [loopNodeToEdit, setLoopNodeToEdit] = useState(null);
26017
- const [showCompositeModal, setShowCompositeModal] = useState(false);
26018
- const [compositeToEdit, setCompositeToEdit] = useState(null);
26019
- useEffect(() => {
26020
- compositeNodeManager.registerTemplate(sendMessageWhatsAppTemplate);
26021
- }, []);
26022
- useEffect(() => {
26023
- const fetchFlowDetails = async () => {
26024
- try {
26025
- setLoading(true);
26026
- setError(null);
26027
- const flowDetails = await flowsService.getFlowWithDetails(flowId);
26028
- const flow = {
26029
- id: flowDetails.id,
26030
- nome: flowDetails.nome,
26031
- descricao: flowDetails.descricao,
26032
- ativo: flowDetails.ativo,
26033
- versao: flowDetails.versao,
26034
- configuracoes: flowDetails.configuracoes || {},
26035
- created_at: new Date(flowDetails.created_at),
26036
- updated_at: new Date(flowDetails.updated_at)
26037
- };
26038
- const nodes2 = flowDetails.nodes.map((n) => {
26039
- const baseNode = {
26040
- id: n.id,
26041
- flow_id: n.flow_id,
26042
- tipo: n.tipo,
26043
- subtipo: n.subtipo,
26044
- nome: n.nome,
26045
- descricao: n.descricao,
26046
- parametros: n.parametros || {},
26047
- configuracoes: n.configuracoes || {},
26048
- posicao: n.posicao,
26049
- desabilitado: n.desabilitado || false
26050
- };
26051
- if (n.tipo === "send_whatsapp_message" && n.subtipo) {
26052
- return {
26053
- ...baseNode,
26054
- data: {
26055
- compositeType: n.subtipo,
26056
- compositeConfig: n.parametros?.config || n.parametros || n.configuracoes || {}
26057
- }
26058
- };
26059
- }
26060
- return baseNode;
26061
- });
26062
- const connections2 = flowDetails.connections.map((c) => ({
26063
- id: c.id,
26064
- flow_id: c.flow_id,
26065
- node_origem_id: c.node_origem_id,
26066
- porta_saida: c.porta_saida,
26067
- node_destino_id: c.node_destino_id,
26068
- porta_entrada: c.porta_entrada,
26069
- condicoes: c.condicoes,
26070
- mapeamento_dados: c.mapeamento_dados
26071
- }));
26072
- setData({ flow, nodes: nodes2, connections: connections2 });
26073
- } catch (err) {
26074
- console.error("Erro ao carregar fluxo:", err);
26075
- setError("Erro ao carregar os detalhes do fluxo");
26076
- } finally {
26077
- setLoading(false);
26078
- }
26079
- };
26080
- if (flowId) {
26081
- fetchFlowDetails();
26082
- }
26083
- }, [flowId]);
26084
- useEffect(() => {
26085
- if (data) {
26086
- const compositeNodes = data.nodes.filter(
26087
- (node) => node.tipo === "send_whatsapp_message" && node.subtipo
26088
- );
26089
- const regularNodes = data.nodes.filter((node) => node.tipo !== "send_whatsapp_message");
26090
- const detectedComposites = compositeNodes.map((node) => ({
26091
- compositeId: node.id,
26092
- templateId: node.subtipo,
26093
- config: node.parametros?.config || node.parametros || node.configuracoes || {},
26094
- nodeIds: [],
26095
- position: node.posicao
26096
- }));
26097
- setComposites(detectedComposites);
26098
- setNodes(regularNodes);
26099
- setConnections(data.connections);
26100
- }
26101
- }, [data]);
26102
- const selectedNode = selectedNodeId ? nodes.find((n) => n.id === selectedNodeId) : null;
26103
- const compositesAsNodes = useMemo(() => {
26104
- return composites.map((composite) => {
26105
- const template = compositeNodeManager.getTemplate(composite.templateId);
26106
- return {
26107
- id: composite.compositeId,
26108
- flow_id: flowId,
26109
- tipo: "send_whatsapp_message",
26110
- subtipo: composite.templateId,
26111
- nome: template?.displayName || "N\xF3 Composto",
26112
- descricao: template?.description,
26113
- parametros: composite.config,
26114
- configuracoes: composite.config,
26115
- posicao: composite.position,
26116
- desabilitado: false
26117
- };
26118
- });
26119
- }, [composites, flowId]);
26120
- const saveFlowData = async () => {
26121
- if (!data) return;
26122
- await flowsService.updateFlow(flowId, {
26123
- nome: data.flow.nome,
26124
- descricao: data.flow.descricao,
26125
- ativo: data.flow.ativo,
26126
- configuracoes: data.flow.configuracoes
26127
- });
26128
- };
26129
- const getChangeSets = (existingNodes, existingConnections) => {
26130
- const compositeFlowNodes = composites.map((composite) => {
26131
- const template = compositeNodeManager.getTemplate(composite.templateId);
26132
- return {
26133
- id: composite.compositeId,
26134
- flow_id: flowId,
26135
- tipo: "send_whatsapp_message",
26136
- subtipo: composite.templateId,
26137
- nome: template?.displayName || "Composite Node",
26138
- descricao: template?.description,
26139
- parametros: {
26140
- config: composite.config
26141
- },
26142
- configuracoes: {},
26143
- posicao: composite.position,
26144
- desabilitado: false,
26145
- metadata: {
26146
- compositeType: composite.templateId,
26147
- compositeId: composite.compositeId
26148
- }
26149
- };
26150
- });
26151
- const expandedNodes = [...nodes, ...compositeFlowNodes];
26152
- const expandedConnections = connections;
26153
- const existingNodeIds = new Set(existingNodes.map((n) => n.id));
26154
- const existingConnectionIds = new Set(existingConnections.map((c) => c.id));
26155
- return {
26156
- nodesToCreate: expandedNodes.filter((n) => !existingNodeIds.has(n.id)),
26157
- nodesToUpdate: expandedNodes.filter((n) => existingNodeIds.has(n.id)),
26158
- nodeIdsToDelete: existingNodes.filter((n) => !expandedNodes.find((localNode) => localNode.id === n.id)).map((n) => n.id),
26159
- connectionsToCreate: expandedConnections.filter((c) => !existingConnectionIds.has(c.id)),
26160
- connectionsToUpdate: expandedConnections.filter((c) => existingConnectionIds.has(c.id)),
26161
- connectionIdsToDelete: existingConnections.filter((c) => !expandedConnections.find((localConn) => localConn.id === c.id)).map((c) => c.id)
26162
- };
26163
- };
26164
- const createConnectionData = (connection) => {
26165
- const connectionData = {
26166
- node_origem_id: connection.node_origem_id,
26167
- node_destino_id: connection.node_destino_id
26168
- };
26169
- const optionalFields = ["porta_saida", "porta_entrada", "condicoes", "mapeamento_dados"];
26170
- optionalFields.forEach((field) => {
26171
- if (connection[field] !== void 0) {
26172
- connectionData[field] = connection[field];
26173
- }
26174
- });
26175
- return connectionData;
26176
- };
26177
- const handleSave = async () => {
26178
- if (!data) return;
26179
- try {
26180
- setSaving(true);
26181
- toast7({
26182
- title: "Salvando fluxo",
26183
- description: "Aguarde enquanto o fluxo est\xE1 sendo salvo..."
26184
- });
26185
- await saveFlowData();
26186
- const existingNodes = await flowNodesService.getFlowNodes(flowId);
26187
- const existingConnections = await flowConnectionsService.getFlowConnections(flowId);
26188
- const {
26189
- nodesToCreate,
26190
- nodesToUpdate,
26191
- nodeIdsToDelete,
26192
- connectionsToCreate,
26193
- connectionsToUpdate,
26194
- connectionIdsToDelete
26195
- } = getChangeSets(existingNodes, existingConnections);
26196
- await Promise.all(
26197
- connectionIdsToDelete.map((connId) => flowConnectionsService.deleteFlowConnection(connId))
26198
- );
26199
- await Promise.all(
26200
- nodeIdsToDelete.map((nodeId) => flowNodesService.deleteFlowNode(nodeId))
26201
- );
26202
- const createdNodesResults = await Promise.all(
26203
- nodesToCreate.map((node) => flowNodesService.createFlowNode({
26204
- flow_id: node.flow_id,
26205
- tipo: node.tipo,
26206
- subtipo: node.subtipo,
26207
- nome: node.nome,
26208
- descricao: node.descricao,
26209
- parametros: node.parametros,
26210
- configuracoes: node.configuracoes,
26211
- posicao: node.posicao,
26212
- desabilitado: node.desabilitado
26213
- }))
26214
- );
26215
- const tempIdToRealIdMap = /* @__PURE__ */ new Map();
26216
- nodesToCreate.forEach((node, index) => {
26217
- if (node.id.startsWith("temp-") && createdNodesResults[index]) {
26218
- tempIdToRealIdMap.set(node.id, createdNodesResults[index].id);
26219
- }
26220
- });
26221
- if (tempIdToRealIdMap.size > 0) {
26222
- setNodes((prev) => prev.map((node) => {
26223
- const realId = tempIdToRealIdMap.get(node.id);
26224
- return realId ? { ...node, id: realId } : node;
26225
- }));
26226
- setConnections((prev) => prev.map((conn) => ({
26227
- ...conn,
26228
- node_origem_id: tempIdToRealIdMap.get(conn.node_origem_id) || conn.node_origem_id,
26229
- node_destino_id: tempIdToRealIdMap.get(conn.node_destino_id) || conn.node_destino_id
26230
- })));
26231
- }
26232
- await Promise.all(
26233
- nodesToUpdate.map((node) => flowNodesService.updateFlowNode(node.id, {
26234
- tipo: node.tipo,
26235
- subtipo: node.subtipo,
26236
- nome: node.nome,
26237
- descricao: node.descricao,
26238
- parametros: node.parametros,
26239
- configuracoes: node.configuracoes,
26240
- posicao: node.posicao,
26241
- desabilitado: node.desabilitado
26242
- }))
26243
- );
26244
- const mappedConnectionsToCreate = connectionsToCreate.map((conn) => ({
26245
- ...conn,
26246
- node_origem_id: tempIdToRealIdMap.get(conn.node_origem_id) || conn.node_origem_id,
26247
- node_destino_id: tempIdToRealIdMap.get(conn.node_destino_id) || conn.node_destino_id
26248
- }));
26249
- const createdConnectionsResults = await Promise.all(
26250
- mappedConnectionsToCreate.map(
26251
- (conn) => flowConnectionsService.createFlowConnection(createConnectionData(conn))
26252
- )
26253
- );
26254
- if (createdConnectionsResults.length > 0) {
26255
- const tempConnIdToRealIdMap = /* @__PURE__ */ new Map();
26256
- connectionsToCreate.forEach((conn, index) => {
26257
- if (conn.id.startsWith("temp-conn-") && createdConnectionsResults[index]) {
26258
- tempConnIdToRealIdMap.set(conn.id, createdConnectionsResults[index].id);
26259
- }
26260
- });
26261
- if (tempConnIdToRealIdMap.size > 0) {
26262
- setConnections((prev) => prev.map((conn) => {
26263
- const realConnId = tempConnIdToRealIdMap.get(conn.id);
26264
- return realConnId ? { ...conn, id: realConnId } : conn;
26265
- }));
26266
- }
26267
- }
26268
- await Promise.all(
26269
- connectionsToUpdate.map((conn) => flowConnectionsService.updateFlowConnection(conn.id, {
26270
- porta_saida: conn.porta_saida,
26271
- porta_entrada: conn.porta_entrada,
26272
- condicoes: conn.condicoes,
26273
- mapeamento_dados: conn.mapeamento_dados
26274
- }))
26275
- );
26276
- toast7({
26277
- title: "Fluxo salvo",
26278
- description: "O fluxo foi salvo com sucesso."
26279
- });
26280
- setHasUnsavedChanges(false);
26281
- } catch (error2) {
26282
- console.error("Erro ao salvar fluxo:", error2);
26283
- toast7({
26284
- title: "Erro ao salvar",
26285
- description: "Ocorreu um erro ao salvar o fluxo. Verifique o console para mais detalhes.",
26286
- variant: "destructive"
26287
- });
26288
- } finally {
26289
- setSaving(false);
26290
- }
26291
- };
26292
- const handleNodeAdd = async (newNode) => {
26293
- if (newNode.tipo === "send_whatsapp_message") {
26294
- const template = compositeNodeManager.getTemplate(newNode.subtipo);
26295
- if (template) {
26296
- try {
26297
- const createdNode = await flowNodesService.createFlowNode({
26298
- flow_id: flowId,
26299
- tipo: newNode.tipo,
26300
- subtipo: newNode.subtipo,
26301
- nome: newNode.nome || template.displayName,
26302
- descricao: newNode.descricao || template.description,
26303
- parametros: newNode.parametros || {},
26304
- configuracoes: newNode.configuracoes || {},
26305
- posicao: newNode.posicao,
26306
- desabilitado: newNode.desabilitado || false
26307
- });
26308
- const composite = {
26309
- compositeId: createdNode.id,
26310
- templateId: newNode.subtipo,
26311
- config: {},
26312
- nodeIds: [],
26313
- position: newNode.posicao
26314
- };
26315
- setCompositeToEdit(composite);
26316
- setShowCompositeModal(true);
26317
- setComposites((prev) => [...prev, composite]);
26318
- setHasUnsavedChanges(true);
26319
- onHistorySave?.();
26320
- } catch (error2) {
26321
- console.error("Erro ao criar n\xF3 composto:", error2);
26322
- toast7({
26323
- title: "Erro ao criar n\xF3",
26324
- description: "N\xE3o foi poss\xEDvel criar o n\xF3 composto.",
26325
- variant: "destructive"
26326
- });
26327
- }
26328
- }
26329
- return;
26330
- }
26331
- try {
26332
- const createdNode = await flowNodesService.createFlowNode({
26333
- flow_id: flowId,
26334
- tipo: newNode.tipo,
26335
- subtipo: newNode.subtipo,
26336
- nome: newNode.nome || "Novo N\xF3",
26337
- descricao: newNode.descricao,
26338
- parametros: newNode.parametros || {},
26339
- configuracoes: newNode.configuracoes || {},
26340
- posicao: newNode.posicao,
26341
- desabilitado: newNode.desabilitado || false
26342
- });
26343
- const node = {
26344
- id: createdNode.id,
26345
- flow_id: flowId,
26346
- tipo: createdNode.tipo,
26347
- subtipo: createdNode.subtipo,
26348
- nome: createdNode.nome,
26349
- descricao: createdNode.descricao,
26350
- parametros: createdNode.parametros,
26351
- configuracoes: createdNode.configuracoes,
26352
- posicao: createdNode.posicao,
26353
- desabilitado: createdNode.desabilitado
26354
- };
26355
- if (node.tipo === "ai_agent" && node.subtipo === "langchain_agent") {
26356
- setNodes((prev) => [...prev, node]);
26357
- setHasUnsavedChanges(true);
26358
- setAIAgentNodeToEdit(node);
26359
- setShowAIAgentModal(true);
26360
- } else if (node.tipo === "split") {
26361
- setNodes((prev) => [...prev, node]);
26362
- setHasUnsavedChanges(true);
26363
- setSplitNodeToEdit(node);
26364
- setShowSplitModal(true);
26365
- } else {
26366
- setNodes((prev) => [...prev, node]);
26367
- setHasUnsavedChanges(true);
26368
- }
26369
- onHistorySave?.();
26370
- } catch (error2) {
26371
- console.error("Erro ao criar n\xF3:", error2);
26372
- toast7({
26373
- title: "Erro ao criar n\xF3",
26374
- description: "N\xE3o foi poss\xEDvel criar o n\xF3.",
26375
- variant: "destructive"
26376
- });
26377
- }
26378
- };
26379
- const handleNodeDelete = (nodeId) => {
26380
- const isComposite = composites.some((c) => c.compositeId === nodeId);
26381
- if (isComposite) {
26382
- setComposites((prev) => prev.filter((c) => c.compositeId !== nodeId));
26383
- setHasUnsavedChanges(true);
26384
- if (selectedNodeId === nodeId) {
26385
- setSelectedNodeId(null);
26386
- }
26387
- onHistorySave?.();
26388
- return;
26389
- }
26390
- setNodes((prev) => prev.filter((n) => n.id !== nodeId));
26391
- setConnections((prev) => prev.filter(
26392
- (c) => c.node_origem_id !== nodeId && c.node_destino_id !== nodeId
26393
- ));
26394
- setHasUnsavedChanges(true);
26395
- if (selectedNodeId === nodeId) {
26396
- setSelectedNodeId(null);
26397
- }
26398
- onHistorySave?.();
26399
- };
26400
- const handleNodeEdit = (nodeId) => {
26401
- const composite = composites.find((c) => c.compositeId === nodeId);
26402
- if (composite) {
26403
- setCompositeToEdit(composite);
26404
- setShowCompositeModal(true);
26405
- return;
26406
- }
26407
- const node = nodes.find((n) => n.id === nodeId);
26408
- if (node && node.tipo === "ai_agent" && node.subtipo === "langchain_agent") {
26409
- setAIAgentNodeToEdit(node);
26410
- setShowAIAgentModal(true);
26411
- } else if (node && node.tipo === "split") {
26412
- setSplitNodeToEdit(node);
26413
- setShowSplitModal(true);
26414
- } else if (node && node.tipo === "loop") {
26415
- setLoopNodeToEdit(node);
26416
- setShowLoopModal(true);
26417
- } else {
26418
- setSelectedNodeId(nodeId);
26419
- setShowPropertiesPanel(true);
26420
- }
26421
- };
26422
- const handleNodeUpdate = (nodeId, updates) => {
26423
- setNodes((prev) => prev.map(
26424
- (node) => node.id === nodeId ? { ...node, ...updates } : node
26425
- ));
26426
- setHasUnsavedChanges(true);
26427
- };
26428
- const handleConnectionAdd = async (newConnection) => {
26429
- const isSourceTemp = newConnection.node_origem_id?.startsWith("temp-");
26430
- const isTargetTemp = newConnection.node_destino_id?.startsWith("temp-");
26431
- if (isSourceTemp || isTargetTemp) {
26432
- const tempConnection = {
26433
- id: `temp-conn-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
26434
- flow_id: flowId,
26435
- node_origem_id: newConnection.node_origem_id,
26436
- node_destino_id: newConnection.node_destino_id,
26437
- porta_saida: newConnection.porta_saida,
26438
- porta_entrada: newConnection.porta_entrada,
26439
- condicoes: newConnection.condicoes,
26440
- mapeamento_dados: newConnection.mapeamento_dados
26441
- };
26442
- setConnections((prev) => [...prev, tempConnection]);
26443
- setHasUnsavedChanges(true);
26444
- return;
26445
- }
26446
- try {
26447
- const createdConnection = await flowConnectionsService.createFlowConnection({
26448
- node_origem_id: newConnection.node_origem_id,
26449
- node_destino_id: newConnection.node_destino_id,
26450
- porta_saida: newConnection.porta_saida,
26451
- porta_entrada: newConnection.porta_entrada,
26452
- condicoes: newConnection.condicoes,
26453
- mapeamento_dados: newConnection.mapeamento_dados
26454
- });
26455
- const connection = {
26456
- id: createdConnection.id,
26457
- flow_id: flowId,
26458
- node_origem_id: createdConnection.node_origem_id,
26459
- porta_saida: createdConnection.porta_saida,
26460
- node_destino_id: createdConnection.node_destino_id,
26461
- porta_entrada: createdConnection.porta_entrada,
26462
- condicoes: createdConnection.condicoes,
26463
- mapeamento_dados: createdConnection.mapeamento_dados
26464
- };
26465
- setConnections((prev) => [...prev, connection]);
26466
- setHasUnsavedChanges(true);
26467
- } catch (error2) {
26468
- console.error("Erro ao criar conex\xE3o:", error2);
26469
- toast7({
26470
- title: "Erro ao criar conex\xE3o",
26471
- description: "N\xE3o foi poss\xEDvel criar a conex\xE3o.",
26472
- variant: "destructive"
26473
- });
26474
- }
26475
- };
26476
- const handleConnectionDelete = (connectionId) => {
26477
- setConnections((prev) => prev.filter((conn) => conn.id !== connectionId));
26478
- setHasUnsavedChanges(true);
26479
- };
26480
- const handleNodesChange = (updatedNodes) => {
26481
- if (Array.isArray(updatedNodes) && updatedNodes.length === nodes.length) {
26482
- setNodes(updatedNodes);
26483
- setHasUnsavedChanges(true);
26484
- }
26485
- };
26486
- const handleCompositeNodeSave = (config) => {
26487
- if (compositeToEdit) {
26488
- setComposites(
26489
- (prev) => prev.map(
26490
- (c) => c.compositeId === compositeToEdit.compositeId ? { ...c, config } : c
26491
- )
26492
- );
26493
- setHasUnsavedChanges(true);
26494
- }
26495
- };
26496
- const handleAIAgentSave = async (config) => {
26497
- try {
26498
- if (aiAgentNodeToEdit) {
26499
- const existingNodes = await flowNodesService.getFlowNodes(flowId);
26500
- const isNewNode = !existingNodes.find((n) => n.id === aiAgentNodeToEdit.id);
26501
- if (isNewNode) {
26502
- await aiAgentService.createNode(flowId, {
26503
- ...config,
26504
- posicao: aiAgentNodeToEdit.posicao
26505
- });
26506
- } else {
26507
- await aiAgentService.updateNode(aiAgentNodeToEdit.id, {
26508
- nome: config.nome,
26509
- descricao: config.descricao,
26510
- prompt_template: config.prompt_template,
26511
- llm_config: config.llm_config,
26512
- tools: config.tools,
26513
- output_parser: config.output_parser,
26514
- context_window: config.context_window,
26515
- retry_on_error: config.retry_on_error,
26516
- timeout_seconds: config.timeout_seconds
26517
- });
26518
- }
26519
- handleNodeUpdate(aiAgentNodeToEdit.id, {
26520
- nome: config.nome,
26521
- descricao: config.descricao,
26522
- parametros: {
26523
- ...aiAgentNodeToEdit.parametros,
26524
- nome: config.nome,
26525
- descricao: config.descricao,
26526
- prompt_template: config.prompt_template,
26527
- llm_config: config.llm_config,
26528
- tools: config.tools,
26529
- output_parser: config.output_parser,
26530
- context_window: config.context_window,
26531
- retry_on_error: config.retry_on_error,
26532
- timeout_seconds: config.timeout_seconds
26533
- }
26534
- });
26535
- toast7({
26536
- title: isNewNode ? "N\xF3 AI Agent criado" : "N\xF3 AI Agent atualizado",
26537
- description: "As configura\xE7\xF5es foram salvas com sucesso."
26538
- });
26539
- }
26540
- } catch (error2) {
26541
- console.error("Erro ao salvar AI Agent:", error2);
26542
- toast7({
26543
- title: "Erro ao salvar",
26544
- description: "N\xE3o foi poss\xEDvel salvar as configura\xE7\xF5es do AI Agent.",
26545
- variant: "destructive"
26546
- });
26547
- }
26548
- };
26549
- return {
26550
- data,
26551
- loading,
26552
- error,
26553
- nodes,
26554
- connections,
26555
- composites,
26556
- compositesAsNodes,
26557
- hasUnsavedChanges,
26558
- saving,
26559
- selectedNode,
26560
- selectedNodeId,
26561
- showPropertiesPanel,
26562
- showAIAgentModal,
26563
- aiAgentNodeToEdit,
26564
- showSplitModal,
26565
- splitNodeToEdit,
26566
- showLoopModal,
26567
- loopNodeToEdit,
26568
- showCompositeModal,
26569
- compositeToEdit,
26570
- setSelectedNodeId,
26571
- setShowPropertiesPanel,
26572
- setShowAIAgentModal,
26573
- setAIAgentNodeToEdit,
26574
- setShowSplitModal,
26575
- setSplitNodeToEdit,
26576
- setShowLoopModal,
26577
- setLoopNodeToEdit,
26578
- setShowCompositeModal,
26579
- setCompositeToEdit,
26580
- setNodes,
26581
- setConnections,
26582
- setComposites,
26583
- handleSave,
26584
- handleNodeAdd,
26585
- handleNodeDelete,
26586
- handleNodeEdit,
26587
- handleNodeUpdate,
26588
- handleConnectionAdd,
26589
- handleConnectionDelete,
26590
- handleNodesChange,
26591
- handleCompositeNodeSave,
26592
- handleAIAgentSave
26593
- };
26594
- }
26595
- function useFlows() {
26596
- const [flows, setFlows] = useState([]);
26597
- const [loading, setLoading] = useState(true);
26598
- const [error, setError] = useState(null);
26599
- const loadFlows = async () => {
26600
- try {
26601
- setLoading(true);
26602
- setError(null);
26603
- const [flowsData, categoriesData] = await Promise.all([
26604
- flowsService.listFlows(),
26605
- flowCategoriesService.listFlowCategories()
26606
- ]);
26607
- const categoriesMap = /* @__PURE__ */ new Map();
26608
- categoriesData.forEach((category) => {
26609
- categoriesMap.set(category.id, {
26610
- id: category.id,
26611
- nome: category.nome,
26612
- descricao: category.descricao,
26613
- icone: category.icone,
26614
- created_at: new Date(category.created_at),
26615
- updated_at: new Date(category.updated_at)
26616
- });
26617
- });
26618
- const domainFlows = flowsData.map((flow) => ({
26619
- id: flow.id,
26620
- nome: flow.nome,
26621
- descricao: flow.descricao,
26622
- category_id: flow.category_id,
26623
- category: flow.category_id ? categoriesMap.get(flow.category_id) : void 0,
26624
- ativo: flow.ativo,
26625
- versao: flow.versao,
26626
- configuracoes: flow.configuracoes,
26627
- variaveis_globais: flow.variaveis_globais,
26628
- created_at: new Date(flow.created_at),
26629
- updated_at: new Date(flow.updated_at)
26630
- }));
26631
- setFlows(domainFlows);
26632
- } catch (err) {
26633
- console.error("Erro ao carregar flows:", err);
26634
- setError(err instanceof Error ? err.message : "Erro desconhecido");
26635
- } finally {
26636
- setLoading(false);
26637
- }
26638
- };
26639
- useEffect(() => {
26640
- loadFlows();
26641
- }, []);
26642
- return {
26643
- flows,
26644
- loading,
26645
- error,
26646
- refetch: loadFlows
26647
- };
26648
- }
26649
- var repository5 = new HttpMotoristaRepository();
26650
- function useMotorista(cd_motorista, options) {
26651
- return useQuery({
26652
- queryKey: ["motorista", cd_motorista],
26653
- queryFn: () => repository5.getById(cd_motorista),
26654
- enabled: options?.enabled !== false && !!cd_motorista && cd_motorista > 0
26655
- });
26656
- }
26657
- function useMotoristaByCpf(cpf) {
26658
- return useQuery({
26659
- queryKey: ["motorista", "cpf", cpf],
26660
- queryFn: () => repository5.searchByCpf(cpf),
26661
- enabled: !!cpf && cpf.length >= 11
26662
- });
26663
- }
26664
- var repository6 = new HttpMotoristaRepository();
26665
- function useMotoristas(params) {
26666
- return useQuery({
26667
- queryKey: ["motoristas", params],
26668
- queryFn: () => repository6.getAll(params),
26669
- keepPreviousData: true
26670
- });
26671
- }
26672
- function useMotoristasbyEmpresa(cd_empresa, params) {
26673
- return useQuery({
26674
- queryKey: ["motoristas", "empresa", cd_empresa, params],
26675
- queryFn: () => repository6.getByEmpresa(cd_empresa, params),
26676
- enabled: !!cd_empresa,
26677
- keepPreviousData: true
26678
- });
26679
- }
26680
- function useSearchMotoristas(params) {
26681
- return useQuery({
26682
- queryKey: ["motoristas", "search", params],
26683
- queryFn: () => repository6.search(params),
26684
- enabled: !!params.query || !!params.filters,
26685
- keepPreviousData: true
26686
- });
26687
- }
26688
- function usePaginatedUsers({
26689
- initialPageSize = 20,
26690
- enablePagination = true
26691
- } = {}) {
26692
- const { isAuthenticated, user } = useAuthContext();
26693
- const { currentTenant } = useTenant();
26694
- const [currentPage, setCurrentPage] = useState(1);
26695
- const [pageSize, setPageSize] = useState(initialPageSize);
26696
- const isReady = Boolean(isAuthenticated && user && currentTenant);
26697
- const { data: allUsers = [], isLoading, error, refetch } = useQuery({
26698
- queryKey: ["users-all"],
26699
- queryFn: async () => {
26700
- return await getAllUsersUseCase.execute({ limit: 1e3 });
26701
- },
26702
- enabled: isReady
26703
- });
26704
- const totalItems = allUsers.length;
26705
- const totalPages = enablePagination ? Math.ceil(totalItems / pageSize) : 1;
26706
- const paginatedUsers = enablePagination ? allUsers.slice((currentPage - 1) * pageSize, currentPage * pageSize) : allUsers;
26707
- const hasNextPage = enablePagination && currentPage < totalPages;
26708
- const hasPreviousPage = enablePagination && currentPage > 1;
26709
- const goToPage = useCallback((page) => {
26710
- if (page >= 1 && page <= totalPages) {
26711
- setCurrentPage(page);
26712
- }
26713
- }, [totalPages]);
26714
- const nextPage = useCallback(() => {
26715
- if (hasNextPage) {
26716
- setCurrentPage((prev) => prev + 1);
26717
- }
26718
- }, [hasNextPage]);
26719
- const previousPage = useCallback(() => {
26720
- if (hasPreviousPage) {
26721
- setCurrentPage((prev) => prev - 1);
26722
- }
26723
- }, [hasPreviousPage]);
26724
- const setPageSizeCallback = useCallback((size) => {
26725
- setPageSize(size);
26726
- setCurrentPage(1);
26727
- }, []);
26728
- const refresh = useCallback(() => {
26729
- refetch();
26730
- }, [refetch]);
26731
- return {
26732
- users: paginatedUsers,
26733
- loading: isLoading,
26734
- error,
26735
- // Pagination state
26736
- currentPage,
26737
- pageSize,
26738
- totalItems,
26739
- totalPages,
26740
- hasNextPage,
26741
- hasPreviousPage,
26742
- // Pagination actions
26743
- goToPage,
26744
- nextPage,
26745
- previousPage,
26746
- setPageSize: setPageSizeCallback,
26747
- // Data actions
26748
- refresh
26749
- };
26750
- }
26751
- function usePerfilUsuario() {
26752
- const [perfis, setPerfis] = useState([]);
26753
- const [loading, setLoading] = useState(false);
26754
- const [error, setError] = useState(null);
26755
- const refreshPerfis = useCallback(async (filters) => {
26756
- try {
26757
- setLoading(true);
26758
- setError(null);
26759
- const data = await perfisUsuarioService.listPerfis(filters);
26760
- setPerfis(data);
26761
- } catch (err) {
26762
- const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
26763
- setError(errorMessage);
26764
- toast$1.error(`Erro ao carregar perfis: ${errorMessage}`);
26765
- } finally {
26766
- setLoading(false);
26767
- }
26768
- }, []);
26769
- const criarPerfil = useCallback(async (data) => {
26770
- try {
26771
- const novoPerfil = await perfisUsuarioService.createPerfil(data);
26772
- setPerfis((prev) => [...prev, novoPerfil]);
26773
- toast$1.success("Perfil criado com sucesso!");
26774
- return novoPerfil;
26775
- } catch (err) {
26776
- const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
26777
- toast$1.error(`Erro ao criar perfil: ${errorMessage}`);
26778
- return null;
26779
- }
26780
- }, []);
26781
- const atualizarPerfil = useCallback(async (id, data) => {
26782
- try {
26783
- const perfilAtualizado = await perfisUsuarioService.updatePerfil(id, data);
26784
- setPerfis((prev) => prev.map(
26785
- (perfil) => perfil.id === id ? perfilAtualizado : perfil
26786
- ));
26787
- toast$1.success("Perfil atualizado com sucesso!");
26788
- return perfilAtualizado;
26789
- } catch (err) {
26790
- const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
26791
- toast$1.error(`Erro ao atualizar perfil: ${errorMessage}`);
26792
- return null;
26793
- }
26794
- }, []);
26795
- const removerPerfil = useCallback(async (id) => {
26796
- try {
26797
- await perfisUsuarioService.deletePerfil(id);
26798
- setPerfis((prev) => prev.filter((perfil) => perfil.id !== id));
26799
- toast$1.success("Perfil removido com sucesso!");
26800
- return true;
26801
- } catch (err) {
26802
- const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
26803
- toast$1.error(`Erro ao remover perfil: ${errorMessage}`);
26804
- return false;
26805
- }
26806
- }, []);
26807
- useEffect(() => {
26808
- }, []);
26809
- return {
26810
- perfis,
26811
- loading,
26812
- error,
26813
- refreshPerfis,
26814
- criarPerfil,
26815
- atualizarPerfil,
26816
- removerPerfil
26817
- };
26818
- }
26819
- function usePersistedFilters({ key, defaultFilters = {} }) {
26820
- const [filters, setFilters] = useState(defaultFilters);
26821
- const [isLoaded, setIsLoaded] = useState(false);
26822
- useEffect(() => {
26823
- try {
26824
- const savedFilters = localStorage.getItem(`filters_${key}`);
26825
- if (savedFilters) {
26826
- const parsedFilters = JSON.parse(savedFilters);
26827
- const mergedFilters = { ...defaultFilters, ...parsedFilters };
26828
- setFilters(mergedFilters);
26829
- } else {
26830
- setFilters(defaultFilters);
26831
- }
26832
- } catch (error) {
26833
- console.warn(`Erro ao carregar filtros salvos para ${key}:`, error);
26834
- setFilters(defaultFilters);
26835
- } finally {
26836
- setIsLoaded(true);
26837
- }
26838
- }, [key, defaultFilters]);
26839
- const updateFilters = useCallback((newFilters) => {
26840
- setFilters(newFilters);
26841
- try {
26842
- localStorage.setItem(`filters_${key}`, JSON.stringify(newFilters));
26843
- } catch (error) {
26844
- console.warn(`Erro ao salvar filtros para ${key}:`, error);
26845
- }
26846
- }, [key]);
26847
- const clearFilters = useCallback(() => {
26848
- setFilters(defaultFilters);
26849
- try {
26850
- localStorage.removeItem(`filters_${key}`);
26851
- } catch (error) {
26852
- console.warn(`Erro ao limpar filtros salvos para ${key}:`, error);
26853
- }
26854
- }, [key, defaultFilters]);
26855
- const updateFilter = useCallback((filterKey, value) => {
26856
- const newFilters = { ...filters, [filterKey]: value };
26857
- updateFilters(newFilters);
26858
- }, [filters, updateFilters]);
26859
- const removeFilter = useCallback((filterKey) => {
26860
- const newFilters = { ...filters };
26861
- delete newFilters[filterKey];
26862
- updateFilters(newFilters);
26863
- }, [filters, updateFilters]);
26864
- return {
26865
- filters,
26866
- isLoaded,
26867
- updateFilters,
26868
- updateFilter,
26869
- removeFilter,
26870
- clearFilters
26871
- };
26872
- }
26873
-
26874
- // src/hooks/usePerfilUsuarioFilters.ts
26875
- var DEFAULT_FILTERS = {
26876
- nome: ""
26877
- };
26878
- function usePerfilUsuarioFilters() {
26879
- const {
26880
- filters,
26881
- updateFilter,
26882
- clearFilters,
26883
- isLoaded
26884
- } = usePersistedFilters({
26885
- key: "perfil-usuario-filters",
26886
- defaultFilters: DEFAULT_FILTERS
26887
- });
26888
- const toApiFilters = useCallback((uiFilters) => {
26889
- const apiFilters = {};
26890
- if (uiFilters.nome.trim()) {
26891
- apiFilters.nome = uiFilters.nome.trim();
26892
- }
26893
- return apiFilters;
26894
- }, []);
26895
- const activeFiltersCount = Object.values(filters).filter((value) => {
26896
- if (typeof value === "string") {
26897
- return value.trim() !== "";
26898
- }
26899
- return false;
26900
- }).length;
26901
- const hasActiveFilters = activeFiltersCount > 0;
26902
- const typedFilters = {
26903
- nome: String(filters.nome || "")
26904
- };
26905
- return {
26906
- filters: typedFilters,
26907
- isLoaded,
26908
- updateFilter,
26909
- clearFilters,
26910
- hasActiveFilters,
26911
- activeFiltersCount,
26912
- toApiFilters,
26913
- defaultFilters: DEFAULT_FILTERS
26914
- };
26915
- }
26916
- function usePermissions() {
26917
- const [loading, setLoading] = useState(false);
26918
- const [error, setError] = useState(null);
26919
- const clearError = () => setError(null);
26920
- const grantPermission = useCallback(async (permissionData) => {
26921
- try {
26922
- setLoading(true);
26923
- clearError();
26924
- const result = await grantUserUnidadePermissionUseCase.execute(permissionData);
26925
- return result;
26926
- } catch (err) {
26927
- const errorMessage = err instanceof Error ? err.message : "Erro ao conceder permiss\xE3o";
26928
- setError(errorMessage);
26929
- console.error("Error granting permission:", err);
26930
- return null;
26931
- } finally {
26932
- setLoading(false);
26933
- }
26934
- }, []);
26935
- const grantBulkPermissions = useCallback(async (permissionsData) => {
26936
- try {
26937
- setLoading(true);
26938
- clearError();
26939
- const result = await grantBulkUserUnidadePermissionsUseCase.execute(permissionsData);
26940
- return result;
26941
- } catch (err) {
26942
- const errorMessage = err instanceof Error ? err.message : "Erro ao conceder permiss\xF5es em lote";
26943
- setError(errorMessage);
26944
- console.error("Error granting bulk permissions:", err);
26945
- return null;
26946
- } finally {
26947
- setLoading(false);
26948
- }
26949
- }, []);
26950
- const removeUserUnidadePermission = useCallback(async (userId, unidadeCodigo) => {
26951
- try {
26952
- setLoading(true);
26953
- clearError();
26954
- await removeUserUnidadePermissionUseCase.execute(userId, unidadeCodigo);
26955
- return true;
26956
- } catch (err) {
26957
- const errorMessage = err instanceof Error ? err.message : "Erro ao remover permiss\xE3o usu\xE1rio-unidade";
26958
- setError(errorMessage);
26959
- console.error("Error removing user-unidade permission:", err);
26960
- return false;
26961
- } finally {
26962
- setLoading(false);
26963
- }
26964
- }, []);
26965
- const getUserUnidades = useCallback(async (userId) => {
26966
- try {
26967
- setLoading(true);
26968
- clearError();
26969
- const userPermissions = await getUserUnidadesUseCase.execute(userId);
26970
- return userPermissions;
26971
- } catch (err) {
26972
- const errorMessage = err instanceof Error ? err.message : "Erro ao carregar unidades do usu\xE1rio";
26973
- setError(errorMessage);
26974
- console.error("Error loading user unidades:", err);
26975
- return null;
26976
- } finally {
26977
- setLoading(false);
26978
- }
26979
- }, []);
26980
- const getUnidadeUsers = useCallback(async (unidadeCodigo) => {
26981
- try {
26982
- setLoading(true);
26983
- clearError();
26984
- const unidadeUsers = await getUnidadeUsersUseCase.execute(unidadeCodigo);
26985
- return unidadeUsers;
26986
- } catch (err) {
26987
- const errorMessage = err instanceof Error ? err.message : "Erro ao carregar usu\xE1rios da unidade";
26988
- setError(errorMessage);
26989
- console.error("Error loading unidade users:", err);
26990
- return null;
26991
- } finally {
26992
- setLoading(false);
26993
- }
26994
- }, []);
26995
- return {
26996
- loading,
26997
- error,
26998
- grantPermission,
26999
- grantBulkPermissions,
27000
- removeUserUnidadePermission,
27001
- getUserUnidades,
27002
- getUnidadeUsers,
27003
- clearError
27004
- };
27005
- }
27006
- function useUnidadesNegocio(filters) {
27007
- const queryClient = useQueryClient();
27008
- const { isAuthenticated, user } = useAuthContext();
27009
- const { currentTenant } = useTenant();
27010
- const isReady = Boolean(isAuthenticated && user && currentTenant);
27011
- const {
27012
- data: response,
27013
- isLoading: loading,
27014
- isFetching,
27015
- error,
27016
- refetch: refreshUnidades
27017
- } = useQuery({
27018
- queryKey: ["unidades-negocio", filters],
27019
- queryFn: () => unidadesNegocioService.listUnidadesNegocio({
27020
- limit: 100,
27021
- ...filters
27022
- }),
27023
- enabled: isReady,
27024
- staleTime: 0,
27025
- // Sempre recarregar após login
27026
- gcTime: 10 * 60 * 1e3,
27027
- // 10 minutos
27028
- refetchOnMount: "always"
27029
- });
27030
- const criarUnidadeMutation = useMutation({
27031
- mutationFn: (data) => unidadesNegocioService.createUnidadeNegocio(data),
27032
- onSuccess: () => {
27033
- queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
27034
- }
27035
- });
27036
- const atualizarUnidadeMutation = useMutation({
27037
- mutationFn: ({ codigo, data }) => unidadesNegocioService.updateUnidadeNegocio(codigo, data),
27038
- onSuccess: () => {
27039
- queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
27040
- }
27041
- });
27042
- const removerUnidadeMutation = useMutation({
27043
- mutationFn: (codigo) => unidadesNegocioService.deleteUnidadeNegocio(codigo),
27044
- onSuccess: () => {
27045
- queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
27046
- }
27047
- });
27048
- const criarUnidade = useCallback(
27049
- async (data) => {
27050
- await criarUnidadeMutation.mutateAsync(data);
27051
- },
27052
- [criarUnidadeMutation]
27053
- );
27054
- const atualizarUnidade = useCallback(
27055
- async (codigo, data) => {
27056
- await atualizarUnidadeMutation.mutateAsync({ codigo, data });
27057
- },
27058
- [atualizarUnidadeMutation]
27059
- );
27060
- const removerUnidade = useCallback(
27061
- async (codigo) => {
27062
- await removerUnidadeMutation.mutateAsync(codigo);
27063
- },
27064
- [removerUnidadeMutation]
27065
- );
27066
- const isLoadingOrFetching = loading || isFetching && !response;
27067
- return {
27068
- unidades: response?.items || [],
27069
- loading: isLoadingOrFetching,
27070
- error: error ? error instanceof Error ? error.message : "Erro ao carregar unidades de neg\xF3cio" : null,
27071
- total: response?.total || 0,
27072
- refreshUnidades,
27073
- criarUnidade,
27074
- atualizarUnidade,
27075
- removerUnidade
27076
- };
27077
- }
27078
- var DEFAULT_FILTERS2 = {
27079
- nome: "",
27080
- email: "",
27081
- login: "",
27082
- ativo: "todos",
27083
- perfil_ids: "",
27084
- tipo_usuario_ids: ""
27085
- };
27086
- function useUserFilters() {
27087
- const {
27088
- filters,
27089
- updateFilter,
27090
- updateFilters,
27091
- clearFilters,
27092
- isLoaded
27093
- } = usePersistedFilters({
27094
- key: "user-management-filters",
27095
- defaultFilters: DEFAULT_FILTERS2
27096
- });
27097
- const toApiFilters = useCallback((uiFilters) => {
27098
- const apiFilters = {};
27099
- if (uiFilters.nome.trim()) {
27100
- apiFilters.nome = uiFilters.nome.trim();
27101
- }
27102
- if (uiFilters.email.trim()) {
27103
- apiFilters.email = uiFilters.email.trim();
27104
- }
27105
- if (uiFilters.login.trim()) {
27106
- apiFilters.login = uiFilters.login.trim();
27107
- }
27108
- if (uiFilters.ativo !== "todos") {
27109
- apiFilters.ativo = uiFilters.ativo === "true";
27110
- }
27111
- if (uiFilters.perfil_ids.trim()) {
27112
- const perfilIds = uiFilters.perfil_ids.split(",").map((id) => parseInt(id.trim())).filter((id) => !isNaN(id));
27113
- if (perfilIds.length > 0) {
27114
- apiFilters.perfil_ids = perfilIds;
27115
- }
27116
- }
27117
- if (uiFilters.tipo_usuario_ids.trim()) {
27118
- const tipoUsuarioIds = uiFilters.tipo_usuario_ids.split(",").map((id) => parseInt(id.trim())).filter((id) => !isNaN(id));
27119
- if (tipoUsuarioIds.length > 0) {
27120
- apiFilters.tipo_usuario_ids = tipoUsuarioIds;
27121
- }
27122
- }
27123
- return apiFilters;
27124
- }, []);
27125
- const activeFiltersCount = Object.values(filters).filter((value) => {
27126
- if (typeof value === "string") {
27127
- return value.trim() !== "" && value !== "todos";
27128
- }
27129
- return false;
27130
- }).length;
27131
- const hasActiveFilters = activeFiltersCount > 0;
27132
- const typedFilters = {
27133
- nome: String(filters.nome || ""),
27134
- email: String(filters.email || ""),
27135
- login: String(filters.login || ""),
27136
- ativo: String(filters.ativo || "todos"),
27137
- perfil_ids: String(filters.perfil_ids || ""),
27138
- tipo_usuario_ids: String(filters.tipo_usuario_ids || "")
27139
- };
27140
- return {
27141
- filters: typedFilters,
27142
- updateFilter,
27143
- updateFilters,
27144
- clearFilters,
27145
- toApiFilters,
27146
- activeFiltersCount,
27147
- hasActiveFilters,
27148
- isLoaded
27149
- };
27150
- }
27151
- function useUserUnidades() {
27152
- const { user, isAuthenticated } = useAuthContext();
27153
- const { currentTenant } = useTenant();
27154
- const getUserId = () => {
27155
- if (user?.id && user.id > 0) return user.id;
27156
- if (user?.legacy_user_id && user.legacy_user_id > 0) return user.legacy_user_id;
27157
- try {
27158
- const token = localStorage.getItem("access_token") || localStorage.getItem("token");
27159
- if (token) {
27160
- const payload = JSON.parse(atob(token.split(".")[1]));
27161
- const tokenUserId = payload.sub || payload.legacy_user_id || payload.user_id;
27162
- if (tokenUserId && tokenUserId > 0) {
27163
- return tokenUserId;
27164
- }
27165
- }
27166
- } catch (error2) {
27167
- console.error("Error extracting user ID from token:", error2);
27168
- }
27169
- return 0;
27170
- };
27171
- const userId = getUserId();
27172
- const isReady = Boolean(isAuthenticated && user && userId && userId > 0 && currentTenant);
27173
- const { unidades: allUnidades, loading: loadingAllUnidades } = useUnidadesNegocio();
27174
- const {
27175
- data: userPermissions,
27176
- isLoading: loadingPermissions,
27177
- isFetching: fetchingPermissions,
27178
- error: permissionsError,
27179
- refetch: refreshPermissions
27180
- } = useQuery({
27181
- queryKey: ["user-unidades", userId],
27182
- queryFn: () => getUserUnidadesUseCase.execute(userId),
27183
- enabled: isReady && userId > 0,
27184
- staleTime: 0,
27185
- // Sempre recarregar após login
27186
- gcTime: 10 * 60 * 1e3,
27187
- // 10 minutos
27188
- retry: 2,
27189
- refetchOnMount: "always"
27190
- });
27191
- const userUnidades = useMemo(() => {
27192
- if (!userPermissions || !allUnidades.length) {
27193
- return [];
27194
- }
27195
- if (userPermissions.has_full_access) {
27196
- return allUnidades;
27197
- }
27198
- const allowedUnidadesCodigos = userPermissions.unidades.map((u) => u.codigo);
27199
- const filteredUnidades = allUnidades.filter(
27200
- (unidade) => allowedUnidadesCodigos.includes(unidade.codigo)
27201
- );
27202
- const mappedUnidades = filteredUnidades.map((unidade) => ({
27203
- codigo: unidade.codigo,
27204
- cnpj: unidade.cnpj,
27205
- descricao: unidade.descricao,
27206
- ativo: unidade.ativo
27207
- }));
27208
- return mappedUnidades;
27209
- }, [userPermissions, allUnidades]);
27210
- const isInitialState = isReady && !userPermissions && !allUnidades.length && !permissionsError;
27211
- const loading = loadingAllUnidades || loadingPermissions || fetchingPermissions || isInitialState;
27212
- const error = permissionsError ? permissionsError instanceof Error ? permissionsError.message : "Erro ao carregar permiss\xF5es" : null;
27213
- return {
27214
- unidades: userUnidades,
27215
- loading,
27216
- error,
27217
- refreshUserUnidades: refreshPermissions
27218
- };
27219
- }
27220
- var useUsers = () => {
27221
- const queryClient = useQueryClient();
27222
- const { isAuthenticated, user } = useAuthContext();
27223
- const { currentTenant } = useTenant();
27224
- const isReady = Boolean(isAuthenticated && user && currentTenant);
27225
- const getAllUsers = useQuery({
27226
- queryKey: ["users"],
27227
- queryFn: async () => {
27228
- return await getAllUsersUseCase.execute({ limit: 1e3 });
27229
- },
27230
- enabled: isReady
27231
- });
27232
- const createUser = useMutation({
27233
- mutationFn: async (userData) => {
27234
- return await createUserUseCase.execute(userData);
27235
- },
27236
- onSuccess: () => {
27237
- queryClient.invalidateQueries({ queryKey: ["users"] });
27238
- }
27239
- });
27240
- const updateUser = useMutation({
27241
- mutationFn: async ({ id, userData }) => {
27242
- return await updateUserUseCase.execute(id, userData);
27243
- },
27244
- onSuccess: (_, { id }) => {
27245
- queryClient.invalidateQueries({ queryKey: ["users"] });
27246
- queryClient.invalidateQueries({ queryKey: ["user", id] });
27247
- }
27248
- });
27249
- const deleteUser = useMutation({
27250
- mutationFn: async (id) => {
27251
- return await deleteUserUseCase.execute(id);
27252
- },
27253
- onSuccess: () => {
27254
- queryClient.invalidateQueries({ queryKey: ["users"] });
27255
- }
27256
- });
27257
- const activateUser = useMutation({
27258
- mutationFn: async (id) => {
27259
- return await activateUserUseCase.execute(id);
27260
- },
27261
- onSuccess: (_, id) => {
27262
- queryClient.invalidateQueries({ queryKey: ["users"] });
27263
- queryClient.invalidateQueries({ queryKey: ["user", id] });
27264
- }
27265
- });
27266
- const deactivateUser = useMutation({
27267
- mutationFn: async (id) => {
27268
- return await deactivateUserUseCase.execute(id);
27269
- },
27270
- onSuccess: (_, id) => {
27271
- queryClient.invalidateQueries({ queryKey: ["users"] });
27272
- queryClient.invalidateQueries({ queryKey: ["user", id] });
27273
- }
27274
- });
27275
- return {
27276
- // Queries
27277
- getAllUsers,
27278
- // Mutations
27279
- createUser,
27280
- updateUser,
27281
- deleteUser,
27282
- activateUser,
27283
- deactivateUser,
27284
- // Derived data for compatibility
27285
- users: getAllUsers.data || [],
27286
- loading: getAllUsers.isLoading || createUser.isPending || updateUser.isPending || deleteUser.isPending || activateUser.isPending || deactivateUser.isPending,
27287
- error: getAllUsers.error || createUser.error || updateUser.error || deleteUser.error || activateUser.error || deactivateUser.error,
27288
- clearError: () => {
27289
- queryClient.resetQueries({ queryKey: ["users"] });
27290
- }
27291
- };
27292
- };
27293
- var useUserById = (id) => {
27294
- const { isAuthenticated, user } = useAuthContext();
27295
- const { currentTenant } = useTenant();
27296
- const isReady = Boolean(isAuthenticated && user && currentTenant);
27297
- return useQuery({
27298
- queryKey: ["user", id],
27299
- queryFn: async () => {
27300
- return await getUserByIdUseCase.execute(id);
27301
- },
27302
- enabled: isReady && !!id
27303
- });
27304
- };
27305
- function useWebhookEvents(options = {}) {
27306
- const { filter: initialFilter, pollingInterval = 5e3, enabled = true } = options;
27307
- const queryClient = useQueryClient();
27308
- const [filter, setFilter] = useState(initialFilter || {});
27309
- const [events, setEvents] = useState([]);
27310
- const [isLoadingMore, setIsLoadingMore] = useState(false);
27311
- const queryKey = ["webhookEvents", filter];
27312
- const { data, isLoading, isError, error, refetch } = useQuery({
27313
- queryKey,
27314
- queryFn: () => httpWebhookRepository.getEvents(filter),
27315
- enabled,
27316
- refetchInterval: pollingInterval,
27317
- staleTime: 2e3
27318
- });
27319
- useEffect(() => {
27320
- if (data?.events) {
27321
- if (filter.offset === 0 || !filter.offset) {
27322
- setEvents(data.events);
27323
- } else {
27324
- setEvents((prev) => [...prev, ...data.events]);
27325
- }
27326
- }
27327
- }, [data, filter.offset]);
27328
- const retryMutation = useMutation({
27329
- mutationFn: (eventId) => httpWebhookRepository.retryEvent(eventId),
27330
- onSuccess: (updatedEvent) => {
27331
- queryClient.invalidateQueries({ queryKey });
27332
- toast$1.success("Evento reenviado com sucesso");
27333
- setEvents((prev) => prev.map(
27334
- (event) => event.id === updatedEvent.id ? updatedEvent : event
27335
- ));
27336
- },
27337
- onError: (error2) => {
27338
- toast$1.error("Erro ao reenviar evento: " + error2.message);
27339
- }
27340
- });
27341
- const cancelMutation = useMutation({
27342
- mutationFn: (eventId) => httpWebhookRepository.cancelEvent(eventId),
27343
- onSuccess: (_, eventId) => {
27344
- queryClient.invalidateQueries({ queryKey });
27345
- toast$1.success("Evento cancelado com sucesso");
27346
- setEvents((prev) => prev.filter((event) => event.id !== eventId));
27347
- },
27348
- onError: (error2) => {
27349
- toast$1.error("Erro ao cancelar evento: " + error2.message);
27350
- }
27351
- });
27352
- const retryEvent = useCallback(async (eventId) => {
27353
- await retryMutation.mutateAsync(eventId);
27354
- }, [retryMutation]);
27355
- const cancelEvent = useCallback(async (eventId) => {
27356
- await cancelMutation.mutateAsync(eventId);
27357
- }, [cancelMutation]);
27358
- const loadMore = useCallback(() => {
27359
- if (!isLoadingMore && data?.hasMore) {
27360
- setIsLoadingMore(true);
27361
- const newFilter = {
27362
- ...filter,
27363
- offset: (filter.offset || 0) + (filter.limit || 20)
27364
- };
27365
- setFilter(newFilter);
27366
- setIsLoadingMore(false);
27367
- }
27368
- }, [filter, data?.hasMore, isLoadingMore]);
27369
- const updateFilter = useCallback((newFilter) => {
27370
- setFilter(newFilter);
27371
- setEvents([]);
27372
- }, []);
27373
- return {
27374
- events,
27375
- total: data?.total || 0,
27376
- hasMore: data?.hasMore || false,
27377
- isLoading,
27378
- isError,
27379
- error,
27380
- refetch,
27381
- retryEvent,
27382
- cancelEvent,
27383
- loadMore,
27384
- isLoadingMore,
27385
- updateFilter
27386
- };
27387
- }
27388
- function useWebhookEventDetails(eventId) {
27389
- return useQuery({
27390
- queryKey: ["webhookEvent", eventId],
27391
- queryFn: () => eventId ? httpWebhookRepository.getEventById(eventId) : null,
27392
- enabled: !!eventId,
27393
- staleTime: 1e4
27394
- });
27395
- }
27396
- function useWebhookEventMetrics(instanceId, startDate, endDate) {
27397
- return useQuery({
27398
- queryKey: ["webhookMetrics", instanceId, startDate, endDate],
27399
- queryFn: () => httpWebhookRepository.getMetrics(instanceId, startDate, endDate),
27400
- refetchInterval: 3e4,
27401
- staleTime: 1e4
27402
- });
27403
- }
27404
- function useWebhookSubscriptions() {
27405
- const queryClient = useQueryClient();
27406
- const { data: subscriptions, ...query } = useQuery({
27407
- queryKey: ["webhookSubscriptions"],
27408
- queryFn: () => httpWebhookRepository.getSubscriptions(),
27409
- staleTime: 3e4
27410
- });
27411
- const createMutation = useMutation({
27412
- mutationFn: httpWebhookRepository.createSubscription,
27413
- onSuccess: () => {
27414
- queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
27415
- toast$1.success("Inscri\xE7\xE3o criada com sucesso");
27416
- },
27417
- onError: (error) => {
27418
- toast$1.error("Erro ao criar inscri\xE7\xE3o: " + error.message);
27419
- }
27420
- });
27421
- const updateMutation = useMutation({
27422
- mutationFn: ({ id, updates }) => httpWebhookRepository.updateSubscription(id, updates),
27423
- onSuccess: () => {
27424
- queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
27425
- toast$1.success("Inscri\xE7\xE3o atualizada com sucesso");
27426
- },
27427
- onError: (error) => {
27428
- toast$1.error("Erro ao atualizar inscri\xE7\xE3o: " + error.message);
27429
- }
27430
- });
27431
- const deleteMutation = useMutation({
27432
- mutationFn: httpWebhookRepository.deleteSubscription,
27433
- onSuccess: () => {
27434
- queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
27435
- toast$1.success("Inscri\xE7\xE3o removida com sucesso");
27436
- },
27437
- onError: (error) => {
27438
- toast$1.error("Erro ao remover inscri\xE7\xE3o: " + error.message);
27439
- }
27440
- });
27441
- return {
27442
- subscriptions: subscriptions || [],
27443
- ...query,
27444
- createSubscription: createMutation.mutate,
27445
- updateSubscription: updateMutation.mutate,
27446
- deleteSubscription: deleteMutation.mutate
27447
- };
27448
- }
27449
24569
 
27450
24570
  // src/types/mcp.types.ts
27451
24571
  var MCPCategoryToNodeType = {
@@ -27594,6 +24714,6 @@ var WebhookMetricsMapper = class {
27594
24714
  }
27595
24715
  };
27596
24716
 
27597
- export { AIAgentConfigModal, AIAgentNode, Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionNode, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, AspectRatio, Avatar, AvatarFallback, AvatarImage, Badge, BadgeGroup, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, BreakpointIndicator, BreakpointsPanel, Button, Calendar, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, CardWithIcon, Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, ChatContainer, ChatHeader, ChatInput, ChatLayout, ChatMessages, Checkbox, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, CompositeNode, CompositeNodeConfigModal, ConditionNode, ConditionalBreakpointModal, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, ControlTowerSidebar, CountBadge, CredentialFormModal, CredentialSelector, CustomEdge, CustomEdgeWithTooltip, CustomSidebarMenuSub, CustomSidebarMenuSubButton, CustomSidebarMenuSubItem, DEFAULT_WEBHOOK_CONFIG, DebugControlPanel, DebugModeToggle, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogMaximizableContent, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerOverlay, DrawerPortal, DrawerTitle, DrawerTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, EdgeLabel, EnsureTenant, EventInspector, ExecutableNode, ExecuteFlowModal, ExecutionDataNode, ExecutionDataNodeForm, ExecutionHistorySidebar, ExecutionProgress, ExpandableText, FlowEditor, FlowExecutionPanel, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, GenericFilterBar, HoverCard, HoverCardContent, HoverCardTrigger, ImportErrorDisplay, ImportFlowFileModal, ImportFlowsModal, Input, InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, InputWithLabel, JSONSchemaEditor, Label3 as Label, LoopConfigModal, LoopExecutionMonitor, LoopNode, LoopResultsViewer, MCPCategoryToNodeType, MCPSubtypeToIcon, MCPToolNode, MainLayout, Menubar, MenubarCheckboxItem, MenubarContent, MenubarGroup, MenubarItem, MenubarLabel, MenubarMenu, MenubarPortal, MenubarRadioGroup, MenubarRadioItem, MenubarSeparator, MenubarShortcut, MenubarSub, MenubarSubContent, MenubarSubTrigger, MenubarTrigger, MergeNode, MessageBubble, MessageHistory, MessageInput, ModelSelector, MotoristaFilters, MotoristaForm, MotoristaStatusBadge, MotoristaTable, NavigationMenu, NavigationMenuContent, NavigationMenuIndicator, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, NavigationMenuViewport, NodeLibraryPanel, NodeOutputViewer, NodePropertiesModal, NotificationBadge, PageHeader, Pagination, PaginationContent, PaginationControls, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, ParameterInput, Popover, PopoverContent, PopoverTrigger, Progress, PromptEditor, PromptTestModal, ProtectedRoute, QRCodeModal, RadioGroup4 as RadioGroup, RadioGroupItem, ResizableHandle, ResizablePanel, ResizablePanelGroup, RichTextEditor, RichTextRenderer, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SendMessageModal, Separator5 as Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, Skeleton, Slider, SplitConfigModal, SplitNode, StandardPageLayout, StatusBadge, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TenantSelectorLazy, Textarea, Toggle, ToggleGroup, ToggleGroupItem, Tooltip2 as Tooltip, TooltipButton, TooltipContent, TooltipProvider, TooltipTrigger, TriggerNode, TypingIndicator, UnidadeNegocioCombobox, UserCombobox, VariablePicker, WEBHOOK_TEST_EVENTS, WebhookConfigModal, WebhookConfigPanel, WebhookEventCard, WebhookEventMapper, WebhookFlowLink, WebhookLogsViewer, WebhookMetricsChart, WebhookMetricsMapper, WebhookSubscriptionMapper, WebhookTestModal, WebhookTimeline, WebhookTokenManager, WhatsAppHealthMonitor, WhatsAppTriggerConfigModal, WhatsAppTriggerMetricsModal, WhatsAppTriggerNode, WhatsAppTriggerTestModal, badgeVariants, beautifyString, buttonVariants, calculateProcessingTime, capitalizeFirst, cn, formatDate, formatDateTime, formatEventType, formatLocalDate, formatLocalDateTime, formatLocalTime, formatStatus, formatTime, getEventTypeVariant, getMetricColor, getNodeBorderStyles, getNodeIconColor, getNodeIconTextColor, getStatusVariant, getTimelineColor, isValidWebhookPayload, navigationMenuTriggerStyle, sanitizeWebhookUrl, toCamelCase, toSnakeCase, toast, toggleVariants, useAuth, useAuthContext, useEmpresasForSelect, useFlowEditor, useFlows, useFormField, useIsMobile, useMCPNodeValidation, useMCPTools, useMotorista, useMotoristaByCpf, useMotoristaMutations, useMotoristas, useMotoristasbyEmpresa, usePaginatedUsers, usePerfilUsuario, usePerfilUsuarioFilters, usePermissions, usePersistedFilters, useSSO, useSearchMotoristas, useSidebar, useSidebarState, useTenant, useToast, useUnidadesNegocio, useUserById, useUserFilters, useUserUnidades, useUsers, useWebhookEventDetails, useWebhookEventMetrics, useWebhookEvents, useWebhookSubscriptions, useWhatsApp, useWhatsAppConfigs, useWhatsAppHealthMonitor, useWhatsAppQRCode, useWhatsAppTriggerExecutions, useWhatsAppTriggerMetrics, useWhatsAppTriggers, validateUrl };
24717
+ export { AIAgentConfigModal, AIAgentNode, Accordion, AccordionContent, AccordionItem, AccordionTrigger, ActionNode, Alert, AlertDescription, AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogOverlay, AlertDialogPortal, AlertDialogTitle, AlertDialogTrigger, AlertTitle, AspectRatio, Avatar, AvatarFallback, AvatarImage, Badge, BadgeGroup, Breadcrumb, BreadcrumbEllipsis, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator, BreakpointIndicator, BreakpointsPanel, Button, Calendar, Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle, CardWithIcon, Carousel, CarouselContent, CarouselItem, CarouselNext, CarouselPrevious, ChartContainer, ChartLegend, ChartLegendContent, ChartStyle, ChartTooltip, ChartTooltipContent, ChatContainer, ChatHeader, ChatInput, ChatLayout, ChatMessages, Checkbox, Collapsible, CollapsibleContent2 as CollapsibleContent, CollapsibleTrigger2 as CollapsibleTrigger, Command, CommandDialog, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator, CommandShortcut, CompositeNode, CompositeNodeConfigModal, ConditionNode, ConditionalBreakpointModal, ContextMenu, ContextMenuCheckboxItem, ContextMenuContent, ContextMenuGroup, ContextMenuItem, ContextMenuLabel, ContextMenuPortal, ContextMenuRadioGroup, ContextMenuRadioItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger, CountBadge, CredentialFormModal, CredentialSelector, CustomEdge, CustomEdgeWithTooltip, CustomSidebarMenuSub, CustomSidebarMenuSubButton, CustomSidebarMenuSubItem, DEFAULT_WEBHOOK_CONFIG, DebugControlPanel, DebugModeToggle, Dialog, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogMaximizableContent, DialogOverlay, DialogPortal, DialogTitle, DialogTrigger, Drawer, DrawerClose, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerOverlay, DrawerPortal, DrawerTitle, DrawerTrigger, DropdownMenu, DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, EdgeLabel, EnsureTenant, EventInspector, ExecutableNode, ExecuteFlowModal, ExecutionDataNode, ExecutionDataNodeForm, ExecutionHistorySidebar, ExecutionProgress, ExpandableText, FlowEditor, FlowExecutionPanel, Form, FormControl, FormDescription, FormField, FormItem, FormLabel, FormMessage, GenericFilterBar, HoverCard, HoverCardContent, HoverCardTrigger, ImportErrorDisplay, ImportFlowFileModal, ImportFlowsModal, Input, InputOTP, InputOTPGroup, InputOTPSeparator, InputOTPSlot, InputWithLabel, JSONSchemaEditor, Label3 as Label, LoopConfigModal, LoopExecutionMonitor, LoopNode, LoopResultsViewer, MCPCategoryToNodeType, MCPSubtypeToIcon, MCPToolNode, Menubar, MenubarCheckboxItem, MenubarContent, MenubarGroup, MenubarItem, MenubarLabel, MenubarMenu, MenubarPortal, MenubarRadioGroup, MenubarRadioItem, MenubarSeparator, MenubarShortcut, MenubarSub, MenubarSubContent, MenubarSubTrigger, MenubarTrigger, MergeNode, MessageBubble, MessageHistory, MessageInput, ModelSelector, MotoristaFilters, MotoristaForm, MotoristaStatusBadge, MotoristaTable, NavigationMenu, NavigationMenuContent, NavigationMenuIndicator, NavigationMenuItem, NavigationMenuLink, NavigationMenuList, NavigationMenuTrigger, NavigationMenuViewport, NodeLibraryPanel, NodeOutputViewer, NodePropertiesModal, NotificationBadge, PageHeader, Pagination, PaginationContent, PaginationControls, PaginationEllipsis, PaginationItem, PaginationLink, PaginationNext, PaginationPrevious, ParameterInput, Popover, PopoverContent, PopoverTrigger, Progress, PromptEditor, PromptTestModal, ProtectedRoute, QRCodeModal, RadioGroup4 as RadioGroup, RadioGroupItem, ResizableHandle, ResizablePanel, ResizablePanelGroup, RichTextEditor, RichTextRenderer, ScrollArea, ScrollBar, Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectScrollDownButton, SelectScrollUpButton, SelectSeparator, SelectTrigger, SelectValue, SendMessageModal, Separator5 as Separator, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetOverlay, SheetPortal, SheetTitle, SheetTrigger, Sidebar, SidebarContent, SidebarFooter, SidebarGroup, SidebarGroupAction, SidebarGroupContent, SidebarGroupLabel, SidebarHeader, SidebarInput, SidebarInset, SidebarMenu, SidebarMenuAction, SidebarMenuBadge, SidebarMenuButton, SidebarMenuItem, SidebarMenuSkeleton, SidebarMenuSub, SidebarMenuSubButton, SidebarMenuSubItem, SidebarProvider, SidebarRail, SidebarSeparator, SidebarTrigger, Skeleton, Slider, SplitConfigModal, SplitNode, StandardPageLayout, StatusBadge, Switch, Table, TableBody, TableCaption, TableCell, TableFooter, TableHead, TableHeader, TableRow, Tabs, TabsContent, TabsList, TabsTrigger, TenantSelectorLazy, Textarea, Toggle, ToggleGroup, ToggleGroupItem, Tooltip2 as Tooltip, TooltipButton, TooltipContent, TooltipProvider, TooltipTrigger, TriggerNode, TypingIndicator, UnidadeNegocioCombobox, UserCombobox, VariablePicker, WEBHOOK_TEST_EVENTS, WebhookConfigModal, WebhookConfigPanel, WebhookEventCard, WebhookEventMapper, WebhookFlowLink, WebhookLogsViewer, WebhookMetricsChart, WebhookMetricsMapper, WebhookSubscriptionMapper, WebhookTestModal, WebhookTimeline, WebhookTokenManager, WhatsAppHealthMonitor, WhatsAppTriggerConfigModal, WhatsAppTriggerMetricsModal, WhatsAppTriggerNode, WhatsAppTriggerTestModal, badgeVariants, beautifyString, buttonVariants, calculateProcessingTime, capitalizeFirst, cn, formatDate, formatDateTime, formatEventType, formatLocalDate, formatLocalDateTime, formatLocalTime, formatStatus, formatTime, getEventTypeVariant, getMetricColor, getNodeBorderStyles, getNodeIconColor, getNodeIconTextColor, getStatusVariant, getTimelineColor, isValidWebhookPayload, navigationMenuTriggerStyle, sanitizeWebhookUrl, toCamelCase, toSnakeCase, toast, toggleVariants, useFormField, useIsMobile, useSidebar, useToast, validateUrl };
27598
24718
  //# sourceMappingURL=index.js.map
27599
24719
  //# sourceMappingURL=index.js.map