@lincros-ui/components 0.1.5 → 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 +65 -2468
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import * as React36 from 'react';
|
|
2
|
-
import React36__default, { memo, useMemo, useCallback, useState, useRef, useEffect
|
|
2
|
+
import React36__default, { memo, useMemo, useCallback, useState, useRef, useEffect } from 'react';
|
|
3
3
|
import * as AccordionPrimitive from '@radix-ui/react-accordion';
|
|
4
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';
|
|
@@ -42,10 +42,7 @@ 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
44
|
import { useNavigate, useLocation, Navigate, Link } from 'react-router-dom';
|
|
45
|
-
import { TenantContext } from '@/presentation/contexts/TenantContext';
|
|
46
45
|
import { tenantService } from '@/services/api/tenant.service';
|
|
47
|
-
import { AuthContext } from '@/presentation/providers/AuthProvider';
|
|
48
|
-
import { useSSOContext } from '@/presentation/contexts/SSOContext';
|
|
49
46
|
import { getTenantFromSubdomain } from '@/lib/tenant-utils';
|
|
50
47
|
import { useEditor, EditorContent } from '@tiptap/react';
|
|
51
48
|
import StarterKit from '@tiptap/starter-kit';
|
|
@@ -61,7 +58,6 @@ import { CreateCredentialUseCase } from '@/application/use-cases/credentials/Cre
|
|
|
61
58
|
import { UpdateCredentialUseCase } from '@/application/use-cases/credentials/UpdateCredentialUseCase';
|
|
62
59
|
import { ListCredentialsUseCase } from '@/application/use-cases/credentials/ListCredentialsUseCase';
|
|
63
60
|
import { TestCredentialUseCase } from '@/application/use-cases/credentials/TestCredentialUseCase';
|
|
64
|
-
import { authService } from '@/services/api/auth.service';
|
|
65
61
|
import { useSensors, useSensor, PointerSensor, KeyboardSensor, DndContext, closestCenter } from '@dnd-kit/core';
|
|
66
62
|
import { sortableKeyboardCoordinates, SortableContext, verticalListSortingStrategy, arrayMove, useSortable } from '@dnd-kit/sortable';
|
|
67
63
|
import { CSS } from '@dnd-kit/utilities';
|
|
@@ -82,42 +78,15 @@ import { EdgeLabelProvider, useEdgeLabels } from '@/presentation/contexts/EdgeLa
|
|
|
82
78
|
import { flowCategoriesService } from '@/services/api/flow-categories.service';
|
|
83
79
|
import { aiAgentService } from '@/services/api/ai-agent.service';
|
|
84
80
|
import { mcpService } from '@/services/api/mcp.service';
|
|
85
|
-
import { HttpWhatsAppRepository } from '@/infrastructure/repositories/HttpWhatsAppRepository';
|
|
86
|
-
import { ListWhatsAppConfigsUseCase } from '@/application/use-cases/whatsapp/list-whatsapp-configs.use-case';
|
|
87
|
-
import { CreateWhatsAppConfigUseCase } from '@/application/use-cases/whatsapp/create-whatsapp-config.use-case';
|
|
88
|
-
import { ConnectWhatsAppInstanceUseCase } from '@/application/use-cases/whatsapp/connect-whatsapp-instance.use-case';
|
|
89
|
-
import { SendWhatsAppMessageUseCase } from '@/application/use-cases/whatsapp/send-whatsapp-message.use-case';
|
|
90
|
-
import { whatsappService } from '@/services/api/whatsapp.service';
|
|
91
|
-
import { HttpWhatsAppTriggerRepository } from '@/infrastructure/repositories/HttpWhatsAppTriggerRepository';
|
|
92
|
-
import { ListWhatsAppTriggersUseCase } from '@/application/use-cases/whatsapp/list-whatsapp-triggers.use-case';
|
|
93
|
-
import { CreateWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/create-whatsapp-trigger.use-case';
|
|
94
|
-
import { UpdateWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/update-whatsapp-trigger.use-case';
|
|
95
|
-
import { DeleteWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/delete-whatsapp-trigger.use-case';
|
|
96
|
-
import { TestWhatsAppTriggerUseCase } from '@/application/use-cases/whatsapp/test-whatsapp-trigger.use-case';
|
|
97
|
-
import { GetWhatsAppTriggerMetricsUseCase } from '@/application/use-cases/whatsapp/get-whatsapp-trigger-metrics.use-case';
|
|
98
|
-
import { HttpFlowRepository } from '@/infrastructure/repositories/HttpFlowRepository';
|
|
99
81
|
import { createMotoristaSchema } from '@/application/dtos/motorista/CreateMotoristaDto';
|
|
100
82
|
import { updateMotoristaSchema } from '@/application/dtos/motorista/UpdateMotoristaDto';
|
|
101
|
-
import { HttpMotoristaRepository } from '@/infrastructure/repositories/HttpMotoristaRepository';
|
|
102
|
-
import { CreateMotoristaUseCase } from '@/application/use-cases/motorista/CreateMotoristaUseCase';
|
|
103
|
-
import { UpdateMotoristaUseCase } from '@/application/use-cases/motorista/UpdateMotoristaUseCase';
|
|
104
|
-
import { DeleteMotoristaUseCase } from '@/application/use-cases/motorista/DeleteMotoristaUseCase';
|
|
105
|
-
import { ToggleBlockMotoristaUseCase } from '@/application/use-cases/motorista/ToggleBlockMotoristaUseCase';
|
|
106
83
|
import { WebhookEventType, WebhookEventStatus } from '@/domain/entities/WebhookEvent';
|
|
107
84
|
import { webhookService } from '@/services/api/webhook.service';
|
|
108
85
|
import { flowExecutionService } from '@/services/api/flow-execution.service';
|
|
109
86
|
import { useWhatsAppStore } from '@/presentation/stores/whatsapp.store';
|
|
87
|
+
import { whatsappService } from '@/services/api/whatsapp.service';
|
|
110
88
|
import QRCode from 'qrcode';
|
|
111
89
|
import { formatInTimeZone } from 'date-fns-tz';
|
|
112
|
-
import { HttpUnidadeNegocioRepository } from '@/infrastructure/repositories/HttpUnidadeNegocioRepository';
|
|
113
|
-
import { flowNodesService } from '@/services/api/flow-nodes.service';
|
|
114
|
-
import { flowConnectionsService } from '@/services/api/flow-connections.service';
|
|
115
|
-
import { compositeNodeManager } from '@/services/automation/CompositeNodeManager';
|
|
116
|
-
import { sendMessageWhatsAppTemplate } from '@/services/automation/templates/sendMessageWhatsApp';
|
|
117
|
-
import { getAllUsersUseCase, grantUserUnidadePermissionUseCase, grantBulkUserUnidadePermissionsUseCase, removeUserUnidadePermissionUseCase, getUserUnidadesUseCase, getUnidadeUsersUseCase, createUserUseCase, updateUserUseCase, deleteUserUseCase, activateUserUseCase, deactivateUserUseCase, getUserByIdUseCase } from '@/application/use-cases';
|
|
118
|
-
import { perfisUsuarioService } from '@/services/api/perfis-usuario.service';
|
|
119
|
-
import { unidadesNegocioService } from '@/services/api/unidades-negocio.service';
|
|
120
|
-
import { httpWebhookRepository } from '@/infrastructure/repositories/HttpWebhookRepository';
|
|
121
90
|
|
|
122
91
|
// src/components/ui/accordion.tsx
|
|
123
92
|
function cn(...inputs) {
|
|
@@ -4396,8 +4365,8 @@ var reducer = (state, action) => {
|
|
|
4396
4365
|
if (toastId) {
|
|
4397
4366
|
addToRemoveQueue(toastId);
|
|
4398
4367
|
} else {
|
|
4399
|
-
state.toasts.forEach((
|
|
4400
|
-
addToRemoveQueue(
|
|
4368
|
+
state.toasts.forEach((toast5) => {
|
|
4369
|
+
addToRemoveQueue(toast5.id);
|
|
4401
4370
|
});
|
|
4402
4371
|
}
|
|
4403
4372
|
return {
|
|
@@ -4515,13 +4484,6 @@ var toastHelpers = {
|
|
|
4515
4484
|
}
|
|
4516
4485
|
};
|
|
4517
4486
|
Object.assign(toast, toastHelpers);
|
|
4518
|
-
var useTenant = () => {
|
|
4519
|
-
const context = useContext(TenantContext);
|
|
4520
|
-
if (context === void 0) {
|
|
4521
|
-
throw new Error("useTenant must be used within a TenantProvider");
|
|
4522
|
-
}
|
|
4523
|
-
return context;
|
|
4524
|
-
};
|
|
4525
4487
|
function EnsureTenant({ children }) {
|
|
4526
4488
|
const { currentTenant, setCurrentTenant } = useTenant();
|
|
4527
4489
|
const navigate = useNavigate();
|
|
@@ -5104,16 +5066,6 @@ function PaginationControls({
|
|
|
5104
5066
|
] })
|
|
5105
5067
|
] });
|
|
5106
5068
|
}
|
|
5107
|
-
function useAuthContext() {
|
|
5108
|
-
const context = useContext(AuthContext);
|
|
5109
|
-
if (context === void 0) {
|
|
5110
|
-
throw new Error("useAuthContext must be used within an AuthProvider");
|
|
5111
|
-
}
|
|
5112
|
-
return context;
|
|
5113
|
-
}
|
|
5114
|
-
var useSSO = () => {
|
|
5115
|
-
return useSSOContext();
|
|
5116
|
-
};
|
|
5117
5069
|
var SSOLoadingOverlay = memo(({
|
|
5118
5070
|
step,
|
|
5119
5071
|
progress,
|
|
@@ -5283,7 +5235,7 @@ function ProtectedRoute({ children }) {
|
|
|
5283
5235
|
const { isAuthenticated, isLoading } = useAuthContext();
|
|
5284
5236
|
const location = useLocation();
|
|
5285
5237
|
const tenantId = getTenantFromSubdomain();
|
|
5286
|
-
const sso = useSSO();
|
|
5238
|
+
const sso = useSSO(tenantId || void 0);
|
|
5287
5239
|
useEffect(() => {
|
|
5288
5240
|
if (tenantId && !isAuthenticated && !isLoading && !sso.state.loading && !sso.state.callbackProcessing && !sso.state.isAuthenticated) {
|
|
5289
5241
|
console.log("[ProtectedRoute] Checking SSO status - not authenticated");
|
|
@@ -6516,236 +6468,6 @@ var SSOLoginButton = memo(({
|
|
|
6516
6468
|
] });
|
|
6517
6469
|
});
|
|
6518
6470
|
SSOLoginButton.displayName = "SSOLoginButton";
|
|
6519
|
-
function useAuth() {
|
|
6520
|
-
const [authState, setAuthState] = useState({
|
|
6521
|
-
user: null,
|
|
6522
|
-
isAuthenticated: false,
|
|
6523
|
-
isLoading: true
|
|
6524
|
-
});
|
|
6525
|
-
useEffect(() => {
|
|
6526
|
-
const checkAuth = async () => {
|
|
6527
|
-
try {
|
|
6528
|
-
if (authService.isAuthenticated()) {
|
|
6529
|
-
const userData = authService.getCurrentUserData();
|
|
6530
|
-
if (userData) {
|
|
6531
|
-
if (!userData.id || !userData.login) {
|
|
6532
|
-
try {
|
|
6533
|
-
const token = localStorage.getItem("access_token") || localStorage.getItem("token");
|
|
6534
|
-
if (token) {
|
|
6535
|
-
const payload = JSON.parse(atob(token.split(".")[1]));
|
|
6536
|
-
const userIdFromToken = payload.sub || payload.legacy_user_id || payload.user_id;
|
|
6537
|
-
const loginFromToken = payload.login || payload.email || userData.email;
|
|
6538
|
-
if (userIdFromToken) {
|
|
6539
|
-
const completeUserData = {
|
|
6540
|
-
...userData,
|
|
6541
|
-
id: userIdFromToken,
|
|
6542
|
-
login: loginFromToken || userData.email || "",
|
|
6543
|
-
legacy_user_id: userIdFromToken
|
|
6544
|
-
};
|
|
6545
|
-
localStorage.setItem("user_data", JSON.stringify(completeUserData));
|
|
6546
|
-
const user2 = {
|
|
6547
|
-
login: loginFromToken || userData.email || "",
|
|
6548
|
-
nome: userData.nome || "",
|
|
6549
|
-
email: userData.email || "",
|
|
6550
|
-
empresa_id: userData.empresa_id || 0,
|
|
6551
|
-
tenant_id: userData.tenant_id,
|
|
6552
|
-
central_user_id: userData.central_user_id,
|
|
6553
|
-
created_at: userData.created_at,
|
|
6554
|
-
updated_at: userData.updated_at,
|
|
6555
|
-
...userData,
|
|
6556
|
-
id: userIdFromToken,
|
|
6557
|
-
legacy_user_id: userIdFromToken
|
|
6558
|
-
};
|
|
6559
|
-
setAuthState({
|
|
6560
|
-
user: user2,
|
|
6561
|
-
isAuthenticated: true,
|
|
6562
|
-
isLoading: false
|
|
6563
|
-
});
|
|
6564
|
-
return;
|
|
6565
|
-
}
|
|
6566
|
-
}
|
|
6567
|
-
} catch (error) {
|
|
6568
|
-
console.error("Failed to extract from token:", error);
|
|
6569
|
-
}
|
|
6570
|
-
}
|
|
6571
|
-
const user = {
|
|
6572
|
-
id: userData.id,
|
|
6573
|
-
login: userData.login,
|
|
6574
|
-
nome: userData.nome || "",
|
|
6575
|
-
email: userData.email || "",
|
|
6576
|
-
empresa_id: userData.empresa_id || 0,
|
|
6577
|
-
tenant_id: userData.tenant_id,
|
|
6578
|
-
central_user_id: void 0,
|
|
6579
|
-
legacy_user_id: void 0,
|
|
6580
|
-
created_at: void 0,
|
|
6581
|
-
updated_at: void 0,
|
|
6582
|
-
...userData
|
|
6583
|
-
};
|
|
6584
|
-
setAuthState({
|
|
6585
|
-
user,
|
|
6586
|
-
isAuthenticated: true,
|
|
6587
|
-
isLoading: false
|
|
6588
|
-
});
|
|
6589
|
-
} else {
|
|
6590
|
-
authService.clearAuthData();
|
|
6591
|
-
setAuthState({
|
|
6592
|
-
user: null,
|
|
6593
|
-
isAuthenticated: false,
|
|
6594
|
-
isLoading: false
|
|
6595
|
-
});
|
|
6596
|
-
}
|
|
6597
|
-
} else {
|
|
6598
|
-
setAuthState({
|
|
6599
|
-
user: null,
|
|
6600
|
-
isAuthenticated: false,
|
|
6601
|
-
isLoading: false
|
|
6602
|
-
});
|
|
6603
|
-
}
|
|
6604
|
-
} catch (error) {
|
|
6605
|
-
console.error("Erro ao verificar autentica\xE7\xE3o:", error);
|
|
6606
|
-
authService.clearAuthData();
|
|
6607
|
-
setAuthState({
|
|
6608
|
-
user: null,
|
|
6609
|
-
isAuthenticated: false,
|
|
6610
|
-
isLoading: false
|
|
6611
|
-
});
|
|
6612
|
-
}
|
|
6613
|
-
};
|
|
6614
|
-
checkAuth();
|
|
6615
|
-
}, []);
|
|
6616
|
-
const login = useCallback(async (credentials, tenantId) => {
|
|
6617
|
-
setAuthState((prev) => ({ ...prev, isLoading: true }));
|
|
6618
|
-
try {
|
|
6619
|
-
const loginResponse = await authService.login(credentials, tenantId);
|
|
6620
|
-
const user = {
|
|
6621
|
-
id: loginResponse.user_id || loginResponse.user?.id,
|
|
6622
|
-
login: loginResponse.login || loginResponse.user?.login,
|
|
6623
|
-
nome: loginResponse.user?.nome || "",
|
|
6624
|
-
email: loginResponse.user?.email || "",
|
|
6625
|
-
empresa_id: loginResponse.user?.empresa_id || 0,
|
|
6626
|
-
tenant_id: loginResponse.tenant_id,
|
|
6627
|
-
central_user_id: loginResponse.user?.central_user_id,
|
|
6628
|
-
legacy_user_id: loginResponse.user?.legacy_user_id,
|
|
6629
|
-
created_at: loginResponse.user?.created_at,
|
|
6630
|
-
updated_at: loginResponse.user?.updated_at,
|
|
6631
|
-
is_admin: loginResponse.user?.is_admin || false,
|
|
6632
|
-
perfil_usuario_id: loginResponse.user?.perfil_usuario_id || 0,
|
|
6633
|
-
idioma_id: loginResponse.user?.idioma_id || 1,
|
|
6634
|
-
tipo_usuario_id: loginResponse.user?.tipo_usuario_id || 0,
|
|
6635
|
-
is_active: loginResponse.user?.is_active ?? true,
|
|
6636
|
-
data_criacao: loginResponse.user?.data_criacao || null,
|
|
6637
|
-
data_atualizacao: loginResponse.user?.data_atualizacao || null,
|
|
6638
|
-
observacoes: loginResponse.user?.observacoes || null
|
|
6639
|
-
};
|
|
6640
|
-
setAuthState({
|
|
6641
|
-
user,
|
|
6642
|
-
isAuthenticated: true,
|
|
6643
|
-
isLoading: false
|
|
6644
|
-
});
|
|
6645
|
-
return loginResponse;
|
|
6646
|
-
} catch (error) {
|
|
6647
|
-
setAuthState({
|
|
6648
|
-
user: null,
|
|
6649
|
-
isAuthenticated: false,
|
|
6650
|
-
isLoading: false
|
|
6651
|
-
});
|
|
6652
|
-
throw error;
|
|
6653
|
-
}
|
|
6654
|
-
}, []);
|
|
6655
|
-
const register = useCallback(async (userData) => {
|
|
6656
|
-
setAuthState((prev) => ({ ...prev, isLoading: true }));
|
|
6657
|
-
try {
|
|
6658
|
-
const user = await authService.register(userData);
|
|
6659
|
-
setAuthState({
|
|
6660
|
-
user: null,
|
|
6661
|
-
isAuthenticated: false,
|
|
6662
|
-
isLoading: false
|
|
6663
|
-
});
|
|
6664
|
-
return user;
|
|
6665
|
-
} catch (error) {
|
|
6666
|
-
setAuthState((prev) => ({ ...prev, isLoading: false }));
|
|
6667
|
-
throw error;
|
|
6668
|
-
}
|
|
6669
|
-
}, []);
|
|
6670
|
-
const logout = useCallback(async () => {
|
|
6671
|
-
setAuthState((prev) => ({ ...prev, isLoading: true }));
|
|
6672
|
-
try {
|
|
6673
|
-
await authService.logout();
|
|
6674
|
-
} finally {
|
|
6675
|
-
setAuthState({
|
|
6676
|
-
user: null,
|
|
6677
|
-
isAuthenticated: false,
|
|
6678
|
-
isLoading: false
|
|
6679
|
-
});
|
|
6680
|
-
window.location.href = "/login";
|
|
6681
|
-
}
|
|
6682
|
-
}, []);
|
|
6683
|
-
const refreshUser = useCallback(async () => {
|
|
6684
|
-
try {
|
|
6685
|
-
if (authService.isAuthenticated()) {
|
|
6686
|
-
console.log("[useAuth] Refreshing user data - token found");
|
|
6687
|
-
const userData = authService.getCurrentUserData();
|
|
6688
|
-
if (userData) {
|
|
6689
|
-
console.log("[useAuth] Using user data from localStorage:", userData);
|
|
6690
|
-
const user2 = {
|
|
6691
|
-
id: userData.id,
|
|
6692
|
-
login: userData.login,
|
|
6693
|
-
nome: userData.nome || userData.name || "",
|
|
6694
|
-
email: userData.email || "",
|
|
6695
|
-
empresa_id: userData.empresa_id || 0,
|
|
6696
|
-
tenant_id: userData.tenant_id,
|
|
6697
|
-
central_user_id: userData.central_user_id,
|
|
6698
|
-
legacy_user_id: userData.legacy_user_id,
|
|
6699
|
-
created_at: userData.created_at,
|
|
6700
|
-
updated_at: userData.updated_at,
|
|
6701
|
-
is_admin: userData.is_admin || false,
|
|
6702
|
-
perfil_usuario_id: userData.perfil_usuario_id || 0,
|
|
6703
|
-
idioma_id: userData.idioma_id || 1,
|
|
6704
|
-
tipo_usuario_id: userData.tipo_usuario_id || 0,
|
|
6705
|
-
is_active: userData.is_active ?? true,
|
|
6706
|
-
data_criacao: userData.data_criacao || null,
|
|
6707
|
-
data_atualizacao: userData.data_atualizacao || null,
|
|
6708
|
-
observacoes: userData.observacoes || null,
|
|
6709
|
-
...userData
|
|
6710
|
-
};
|
|
6711
|
-
setAuthState({
|
|
6712
|
-
user: user2,
|
|
6713
|
-
isAuthenticated: true,
|
|
6714
|
-
isLoading: false
|
|
6715
|
-
});
|
|
6716
|
-
console.log("[useAuth] AuthContext updated with SSO user data");
|
|
6717
|
-
return user2;
|
|
6718
|
-
}
|
|
6719
|
-
const user = await authService.refreshUserData();
|
|
6720
|
-
setAuthState((prev) => ({ ...prev, user, isAuthenticated: true }));
|
|
6721
|
-
return user;
|
|
6722
|
-
} else {
|
|
6723
|
-
console.log("[useAuth] No token found during refresh");
|
|
6724
|
-
setAuthState({
|
|
6725
|
-
user: null,
|
|
6726
|
-
isAuthenticated: false,
|
|
6727
|
-
isLoading: false
|
|
6728
|
-
});
|
|
6729
|
-
return null;
|
|
6730
|
-
}
|
|
6731
|
-
} catch (error) {
|
|
6732
|
-
console.error("Erro ao atualizar dados do usu\xE1rio:", error);
|
|
6733
|
-
await logout();
|
|
6734
|
-
throw error;
|
|
6735
|
-
}
|
|
6736
|
-
}, [logout]);
|
|
6737
|
-
const getCurrentTenantId = useCallback(() => {
|
|
6738
|
-
return authService.getCurrentTenantId();
|
|
6739
|
-
}, []);
|
|
6740
|
-
return {
|
|
6741
|
-
...authState,
|
|
6742
|
-
login,
|
|
6743
|
-
register,
|
|
6744
|
-
logout,
|
|
6745
|
-
refreshUser,
|
|
6746
|
-
getCurrentTenantId
|
|
6747
|
-
};
|
|
6748
|
-
}
|
|
6749
6471
|
var credentialRepository = new HttpCredentialRepository();
|
|
6750
6472
|
var createCredentialUseCase = new CreateCredentialUseCase(credentialRepository);
|
|
6751
6473
|
var updateCredentialUseCase = new UpdateCredentialUseCase(credentialRepository);
|
|
@@ -6798,7 +6520,7 @@ function SortableItem({ id, credential }) {
|
|
|
6798
6520
|
);
|
|
6799
6521
|
}
|
|
6800
6522
|
function CredentialFormModal({ isOpen, onClose, credential }) {
|
|
6801
|
-
const { toast:
|
|
6523
|
+
const { toast: toast5 } = useToast();
|
|
6802
6524
|
const queryClient = useQueryClient();
|
|
6803
6525
|
const { tenant } = useAuth();
|
|
6804
6526
|
const [showApiKey, setShowApiKey] = useState(false);
|
|
@@ -6845,14 +6567,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
|
|
|
6845
6567
|
mutationFn: (data) => createCredentialUseCase.execute(data),
|
|
6846
6568
|
onSuccess: () => {
|
|
6847
6569
|
queryClient.invalidateQueries({ queryKey: ["credentials"] });
|
|
6848
|
-
|
|
6570
|
+
toast5({
|
|
6849
6571
|
title: "Credencial criada",
|
|
6850
6572
|
description: "A credencial foi criada com sucesso."
|
|
6851
6573
|
});
|
|
6852
6574
|
onClose();
|
|
6853
6575
|
},
|
|
6854
6576
|
onError: (error) => {
|
|
6855
|
-
|
|
6577
|
+
toast5({
|
|
6856
6578
|
title: "Erro ao criar credencial",
|
|
6857
6579
|
description: error.message || "Ocorreu um erro ao criar a credencial.",
|
|
6858
6580
|
variant: "destructive"
|
|
@@ -6863,14 +6585,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
|
|
|
6863
6585
|
mutationFn: (data) => updateCredentialUseCase.execute(credential.id, data),
|
|
6864
6586
|
onSuccess: () => {
|
|
6865
6587
|
queryClient.invalidateQueries({ queryKey: ["credentials"] });
|
|
6866
|
-
|
|
6588
|
+
toast5({
|
|
6867
6589
|
title: "Credencial atualizada",
|
|
6868
6590
|
description: "A credencial foi atualizada com sucesso."
|
|
6869
6591
|
});
|
|
6870
6592
|
onClose();
|
|
6871
6593
|
},
|
|
6872
6594
|
onError: (error) => {
|
|
6873
|
-
|
|
6595
|
+
toast5({
|
|
6874
6596
|
title: "Erro ao atualizar credencial",
|
|
6875
6597
|
description: error.message || "Ocorreu um erro ao atualizar a credencial.",
|
|
6876
6598
|
variant: "destructive"
|
|
@@ -6883,14 +6605,14 @@ function CredentialFormModal({ isOpen, onClose, credential }) {
|
|
|
6883
6605
|
return testCredentialUseCase.execute(credential.id);
|
|
6884
6606
|
},
|
|
6885
6607
|
onSuccess: (result) => {
|
|
6886
|
-
|
|
6608
|
+
toast5({
|
|
6887
6609
|
title: result.success ? "Teste bem-sucedido" : "Teste falhou",
|
|
6888
6610
|
description: result.message,
|
|
6889
6611
|
variant: result.success ? "default" : "destructive"
|
|
6890
6612
|
});
|
|
6891
6613
|
},
|
|
6892
6614
|
onError: (error) => {
|
|
6893
|
-
|
|
6615
|
+
toast5({
|
|
6894
6616
|
title: "Erro ao testar credencial",
|
|
6895
6617
|
description: error.message || "Ocorreu um erro ao testar a credencial.",
|
|
6896
6618
|
variant: "destructive"
|
|
@@ -12577,7 +12299,7 @@ function ImportFlowFileModal({
|
|
|
12577
12299
|
] }) });
|
|
12578
12300
|
}
|
|
12579
12301
|
function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
|
|
12580
|
-
const { toast:
|
|
12302
|
+
const { toast: toast5 } = useToast();
|
|
12581
12303
|
const [loading, setLoading] = React36__default.useState(false);
|
|
12582
12304
|
const [masterFlows, setMasterFlows] = React36__default.useState([]);
|
|
12583
12305
|
const [selectedFlows, setSelectedFlows] = React36__default.useState([]);
|
|
@@ -12599,7 +12321,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
|
|
|
12599
12321
|
} catch (error) {
|
|
12600
12322
|
console.error("Erro ao carregar fluxos do master:", error);
|
|
12601
12323
|
const errorMessage = error.response?.data?.detail || error.message || "Erro desconhecido";
|
|
12602
|
-
|
|
12324
|
+
toast5({
|
|
12603
12325
|
title: "Erro ao carregar fluxos",
|
|
12604
12326
|
description: `N\xE3o foi poss\xEDvel carregar os fluxos do master: ${errorMessage}`,
|
|
12605
12327
|
variant: "destructive"
|
|
@@ -12607,7 +12329,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
|
|
|
12607
12329
|
} finally {
|
|
12608
12330
|
setLoading(false);
|
|
12609
12331
|
}
|
|
12610
|
-
}, [
|
|
12332
|
+
}, [toast5]);
|
|
12611
12333
|
React36__default.useEffect(() => {
|
|
12612
12334
|
if (open) {
|
|
12613
12335
|
loadMasterFlows();
|
|
@@ -12651,7 +12373,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
|
|
|
12651
12373
|
};
|
|
12652
12374
|
const showImportResult = (successCount, errorCount) => {
|
|
12653
12375
|
if (successCount > 0) {
|
|
12654
|
-
|
|
12376
|
+
toast5({
|
|
12655
12377
|
title: "Importa\xE7\xE3o conclu\xEDda",
|
|
12656
12378
|
description: (() => {
|
|
12657
12379
|
const base = `${successCount} fluxo(s) importado(s) com sucesso`;
|
|
@@ -12680,7 +12402,7 @@ function ImportFlowsModal({ open, onOpenChange, onImportSuccess }) {
|
|
|
12680
12402
|
}, []);
|
|
12681
12403
|
const handleImport = async () => {
|
|
12682
12404
|
if (selectedFlows.length === 0) {
|
|
12683
|
-
|
|
12405
|
+
toast5({
|
|
12684
12406
|
title: "Nenhum fluxo selecionado",
|
|
12685
12407
|
description: "Selecione pelo menos um fluxo para importar.",
|
|
12686
12408
|
variant: "destructive"
|
|
@@ -13548,7 +13270,7 @@ function LoopResultsViewer({
|
|
|
13548
13270
|
executionId,
|
|
13549
13271
|
className
|
|
13550
13272
|
}) {
|
|
13551
|
-
const { toast:
|
|
13273
|
+
const { toast: toast5 } = useToast();
|
|
13552
13274
|
const [activeTab, setActiveTab] = useState("table");
|
|
13553
13275
|
const [filterStatus, setFilterStatus] = useState("all");
|
|
13554
13276
|
const [searchQuery, setSearchQuery] = useState("");
|
|
@@ -13588,7 +13310,7 @@ function LoopResultsViewer({
|
|
|
13588
13310
|
a.click();
|
|
13589
13311
|
document.body.removeChild(a);
|
|
13590
13312
|
URL.revokeObjectURL(url);
|
|
13591
|
-
|
|
13313
|
+
toast5({
|
|
13592
13314
|
title: "Export conclu\xEDdo",
|
|
13593
13315
|
description: "Resultados exportados para JSON com sucesso."
|
|
13594
13316
|
});
|
|
@@ -13617,14 +13339,14 @@ function LoopResultsViewer({
|
|
|
13617
13339
|
a.click();
|
|
13618
13340
|
document.body.removeChild(a);
|
|
13619
13341
|
URL.revokeObjectURL(url);
|
|
13620
|
-
|
|
13342
|
+
toast5({
|
|
13621
13343
|
title: "Export conclu\xEDdo",
|
|
13622
13344
|
description: "Resultados exportados para CSV com sucesso."
|
|
13623
13345
|
});
|
|
13624
13346
|
};
|
|
13625
13347
|
const copyToClipboard = (data) => {
|
|
13626
13348
|
navigator.clipboard.writeText(JSON.stringify(data, null, 2));
|
|
13627
|
-
|
|
13349
|
+
toast5({
|
|
13628
13350
|
title: "Copiado",
|
|
13629
13351
|
description: "Dados copiados para a \xE1rea de transfer\xEAncia."
|
|
13630
13352
|
});
|
|
@@ -14782,20 +14504,20 @@ function PromptTestModal({
|
|
|
14782
14504
|
tools = [],
|
|
14783
14505
|
outputParser
|
|
14784
14506
|
}) {
|
|
14785
|
-
const { toast:
|
|
14507
|
+
const { toast: toast5 } = useToast();
|
|
14786
14508
|
const [sampleContext, setSampleContext] = useState('{\n "input_text": "Exemplo de texto para an\xE1lise",\n "user_name": "Jo\xE3o"\n}');
|
|
14787
14509
|
const [testResult, setTestResult] = useState(null);
|
|
14788
14510
|
const testPromptMutation = useMutation({
|
|
14789
14511
|
mutationFn: (request) => aiAgentService.testPrompt(request),
|
|
14790
14512
|
onSuccess: (data) => {
|
|
14791
14513
|
setTestResult(data);
|
|
14792
|
-
|
|
14514
|
+
toast5({
|
|
14793
14515
|
title: "Teste executado",
|
|
14794
14516
|
description: "Teste executado com sucesso!"
|
|
14795
14517
|
});
|
|
14796
14518
|
},
|
|
14797
14519
|
onError: (error) => {
|
|
14798
|
-
|
|
14520
|
+
toast5({
|
|
14799
14521
|
title: "Erro ao testar",
|
|
14800
14522
|
description: `Erro ao testar prompt: ${error.message || "Erro desconhecido"}`,
|
|
14801
14523
|
variant: "destructive"
|
|
@@ -14814,7 +14536,7 @@ function PromptTestModal({
|
|
|
14814
14536
|
};
|
|
14815
14537
|
testPromptMutation.mutate(request);
|
|
14816
14538
|
} catch {
|
|
14817
|
-
|
|
14539
|
+
toast5({
|
|
14818
14540
|
title: "Erro de valida\xE7\xE3o",
|
|
14819
14541
|
description: "Contexto de teste inv\xE1lido. Verifique o JSON.",
|
|
14820
14542
|
variant: "destructive"
|
|
@@ -15008,120 +14730,6 @@ function PromptTestModal({
|
|
|
15008
14730
|
] })
|
|
15009
14731
|
] }) });
|
|
15010
14732
|
}
|
|
15011
|
-
function useMCPTools(options = {}) {
|
|
15012
|
-
const { category, searchTerm, enabled = true } = options;
|
|
15013
|
-
const { toast: toast7 } = useToast();
|
|
15014
|
-
const [filteredTools, setFilteredTools] = useState([]);
|
|
15015
|
-
const hasToken = !!localStorage.getItem("access_token");
|
|
15016
|
-
const shouldEnable = enabled && hasToken;
|
|
15017
|
-
const {
|
|
15018
|
-
data: toolsResponse,
|
|
15019
|
-
isLoading,
|
|
15020
|
-
error,
|
|
15021
|
-
refetch
|
|
15022
|
-
} = useQuery({
|
|
15023
|
-
queryKey: ["mcp-tools", category],
|
|
15024
|
-
queryFn: () => mcpService.listTools(category),
|
|
15025
|
-
enabled: shouldEnable,
|
|
15026
|
-
staleTime: 5 * 60 * 1e3,
|
|
15027
|
-
retry: 1
|
|
15028
|
-
});
|
|
15029
|
-
useEffect(() => {
|
|
15030
|
-
if (error) {
|
|
15031
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
15032
|
-
if (!errorMessage.includes("MCP authentication failed")) {
|
|
15033
|
-
toast7({
|
|
15034
|
-
title: "Erro ao carregar ferramentas MCP",
|
|
15035
|
-
description: errorMessage || "N\xE3o foi poss\xEDvel carregar as ferramentas do servidor MCP",
|
|
15036
|
-
variant: "destructive"
|
|
15037
|
-
});
|
|
15038
|
-
}
|
|
15039
|
-
}
|
|
15040
|
-
}, [error, toast7]);
|
|
15041
|
-
const allTools = React36__default.useMemo(() => {
|
|
15042
|
-
if (!toolsResponse?.tools) return [];
|
|
15043
|
-
const toolsMap = /* @__PURE__ */ new Map();
|
|
15044
|
-
toolsResponse.tools.forEach((toolData) => {
|
|
15045
|
-
try {
|
|
15046
|
-
const tool = MCPTool.fromAPIResponse(toolData);
|
|
15047
|
-
const existingTool = toolsMap.get(tool.name);
|
|
15048
|
-
if (!existingTool || tool.description && tool.description.length > (existingTool.description?.length || 0)) {
|
|
15049
|
-
toolsMap.set(tool.name, tool);
|
|
15050
|
-
}
|
|
15051
|
-
} catch (error2) {
|
|
15052
|
-
console.error("Error processing tool:", toolData.name, error2);
|
|
15053
|
-
}
|
|
15054
|
-
});
|
|
15055
|
-
return Array.from(toolsMap.values());
|
|
15056
|
-
}, [toolsResponse]);
|
|
15057
|
-
useEffect(() => {
|
|
15058
|
-
if (!searchTerm) {
|
|
15059
|
-
setFilteredTools(allTools);
|
|
15060
|
-
return;
|
|
15061
|
-
}
|
|
15062
|
-
const term = searchTerm.toLowerCase();
|
|
15063
|
-
const filtered = allTools.filter(
|
|
15064
|
-
(tool) => tool.name.toLowerCase().includes(term) || tool.description.toLowerCase().includes(term) || tool.nodeSubtype.toLowerCase().includes(term) || tool.category.toLowerCase().includes(term)
|
|
15065
|
-
);
|
|
15066
|
-
setFilteredTools(filtered);
|
|
15067
|
-
}, [searchTerm, allTools]);
|
|
15068
|
-
const toolsByCategory = filteredTools.reduce((acc, tool) => {
|
|
15069
|
-
if (!acc[tool.category]) {
|
|
15070
|
-
acc[tool.category] = [];
|
|
15071
|
-
}
|
|
15072
|
-
acc[tool.category].push(tool);
|
|
15073
|
-
return acc;
|
|
15074
|
-
}, {});
|
|
15075
|
-
const categories = Object.keys(toolsByCategory).length > 0 ? Object.keys(toolsByCategory) : toolsResponse?.categories || Object.keys(toolsResponse?.by_category || {});
|
|
15076
|
-
if (!hasToken) {
|
|
15077
|
-
return {
|
|
15078
|
-
tools: [],
|
|
15079
|
-
toolsByCategory: {},
|
|
15080
|
-
categories: [],
|
|
15081
|
-
isLoading: false,
|
|
15082
|
-
error: null,
|
|
15083
|
-
refetch: () => {
|
|
15084
|
-
}
|
|
15085
|
-
};
|
|
15086
|
-
}
|
|
15087
|
-
return {
|
|
15088
|
-
tools: filteredTools,
|
|
15089
|
-
toolsByCategory,
|
|
15090
|
-
categories,
|
|
15091
|
-
isLoading,
|
|
15092
|
-
error,
|
|
15093
|
-
refetch
|
|
15094
|
-
};
|
|
15095
|
-
}
|
|
15096
|
-
function useMCPNodeValidation() {
|
|
15097
|
-
const { toast: toast7 } = useToast();
|
|
15098
|
-
const validateNode = async (nodeType, nodeSubtype, parameters) => {
|
|
15099
|
-
try {
|
|
15100
|
-
const response = await mcpService.validateNode({
|
|
15101
|
-
node_type: nodeType,
|
|
15102
|
-
node_subtype: nodeSubtype,
|
|
15103
|
-
parameters
|
|
15104
|
-
});
|
|
15105
|
-
if (!response.valid && response.errors?.length) {
|
|
15106
|
-
toast7({
|
|
15107
|
-
title: "Valida\xE7\xE3o falhou",
|
|
15108
|
-
description: response.errors[0],
|
|
15109
|
-
variant: "destructive"
|
|
15110
|
-
});
|
|
15111
|
-
}
|
|
15112
|
-
return response;
|
|
15113
|
-
} catch (error) {
|
|
15114
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
15115
|
-
toast7({
|
|
15116
|
-
title: "Erro na valida\xE7\xE3o",
|
|
15117
|
-
description: errorMessage || "N\xE3o foi poss\xEDvel validar a configura\xE7\xE3o",
|
|
15118
|
-
variant: "destructive"
|
|
15119
|
-
});
|
|
15120
|
-
throw error;
|
|
15121
|
-
}
|
|
15122
|
-
};
|
|
15123
|
-
return { validateNode };
|
|
15124
|
-
}
|
|
15125
14733
|
var aiAgentConfigSchema = z2.object({
|
|
15126
14734
|
nome: z2.string().min(1, "Nome \xE9 obrigat\xF3rio").max(255),
|
|
15127
14735
|
descricao: z2.string().optional(),
|
|
@@ -15170,7 +14778,7 @@ function AIAgentConfigModal({
|
|
|
15170
14778
|
onSave,
|
|
15171
14779
|
initialData
|
|
15172
14780
|
}) {
|
|
15173
|
-
const { toast:
|
|
14781
|
+
const { toast: toast5 } = useToast();
|
|
15174
14782
|
const [activeTab, setActiveTab] = useState("basic");
|
|
15175
14783
|
const [selectedTools, setSelectedTools] = useState([]);
|
|
15176
14784
|
const [enableParser, setEnableParser] = useState(false);
|
|
@@ -15324,13 +14932,13 @@ function AIAgentConfigModal({
|
|
|
15324
14932
|
output_parser: outputParserData
|
|
15325
14933
|
};
|
|
15326
14934
|
onSave(config);
|
|
15327
|
-
|
|
14935
|
+
toast5({
|
|
15328
14936
|
title: "Configura\xE7\xE3o salva",
|
|
15329
14937
|
description: "Configura\xE7\xE3o salva com sucesso!"
|
|
15330
14938
|
});
|
|
15331
14939
|
onClose();
|
|
15332
14940
|
} catch {
|
|
15333
|
-
|
|
14941
|
+
toast5({
|
|
15334
14942
|
title: "Erro ao salvar",
|
|
15335
14943
|
description: "Erro ao salvar configura\xE7\xE3o",
|
|
15336
14944
|
variant: "destructive"
|
|
@@ -15432,7 +15040,7 @@ function AIAgentConfigModal({
|
|
|
15432
15040
|
setParserType(config.output_parser.type);
|
|
15433
15041
|
form.setValue("output_parser", config.output_parser);
|
|
15434
15042
|
}
|
|
15435
|
-
|
|
15043
|
+
toast5({
|
|
15436
15044
|
title: "Template aplicado",
|
|
15437
15045
|
description: "Template de An\xE1lise de Sentimento aplicado com sucesso"
|
|
15438
15046
|
});
|
|
@@ -15457,7 +15065,7 @@ function AIAgentConfigModal({
|
|
|
15457
15065
|
setParserType(config.output_parser.type);
|
|
15458
15066
|
form.setValue("output_parser", config.output_parser);
|
|
15459
15067
|
}
|
|
15460
|
-
|
|
15068
|
+
toast5({
|
|
15461
15069
|
title: "Template aplicado",
|
|
15462
15070
|
description: "Template de Extra\xE7\xE3o de Entidades aplicado com sucesso"
|
|
15463
15071
|
});
|
|
@@ -15874,48 +15482,6 @@ function AIAgentConfigModal({
|
|
|
15874
15482
|
)
|
|
15875
15483
|
] });
|
|
15876
15484
|
}
|
|
15877
|
-
var repository = new HttpWhatsAppRepository();
|
|
15878
|
-
var listConfigsUseCase = new ListWhatsAppConfigsUseCase(repository);
|
|
15879
|
-
function useWhatsAppConfigs(activeOnly = false) {
|
|
15880
|
-
const { getCurrentTenantId } = useAuthContext();
|
|
15881
|
-
const { toast: toast7 } = useToast();
|
|
15882
|
-
const { data: configsData, isLoading, error } = useQuery({
|
|
15883
|
-
queryKey: ["whatsapp-configs", getCurrentTenantId(), activeOnly],
|
|
15884
|
-
queryFn: async () => {
|
|
15885
|
-
try {
|
|
15886
|
-
const result = await listConfigsUseCase.execute({ activeOnly });
|
|
15887
|
-
return result;
|
|
15888
|
-
} catch (err) {
|
|
15889
|
-
console.error("[useWhatsAppConfigs] Erro na query", {
|
|
15890
|
-
error: err,
|
|
15891
|
-
message: err?.message,
|
|
15892
|
-
stack: err?.stack
|
|
15893
|
-
});
|
|
15894
|
-
throw err;
|
|
15895
|
-
}
|
|
15896
|
-
},
|
|
15897
|
-
staleTime: 5 * 60 * 1e3,
|
|
15898
|
-
retry: 1
|
|
15899
|
-
});
|
|
15900
|
-
useEffect(() => {
|
|
15901
|
-
if (error) {
|
|
15902
|
-
console.error("[useWhatsAppConfigs] useEffect - Erro detectado", {
|
|
15903
|
-
error,
|
|
15904
|
-
errorMessage: error?.message
|
|
15905
|
-
});
|
|
15906
|
-
toast7({
|
|
15907
|
-
title: "Erro ao carregar configura\xE7\xF5es WhatsApp",
|
|
15908
|
-
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.",
|
|
15909
|
-
variant: "destructive"
|
|
15910
|
-
});
|
|
15911
|
-
}
|
|
15912
|
-
}, [error, toast7]);
|
|
15913
|
-
return {
|
|
15914
|
-
configs: configsData?.configs || [],
|
|
15915
|
-
loading: isLoading,
|
|
15916
|
-
error: error?.message || null
|
|
15917
|
-
};
|
|
15918
|
-
}
|
|
15919
15485
|
var compositeNodeConfigSchema = z2.object({
|
|
15920
15486
|
execution_mode: z2.enum(["full", "send_only"]).default("full"),
|
|
15921
15487
|
array_field: z2.string().min(1, "Campo de dados \xE9 obrigat\xF3rio").default("messages"),
|
|
@@ -16304,7 +15870,7 @@ function LoopConfigModal({
|
|
|
16304
15870
|
node,
|
|
16305
15871
|
onSave
|
|
16306
15872
|
}) {
|
|
16307
|
-
const { toast:
|
|
15873
|
+
const { toast: toast5 } = useToast();
|
|
16308
15874
|
const [activeTab, setActiveTab] = useState("config");
|
|
16309
15875
|
const [previewData, setPreviewData] = useState(null);
|
|
16310
15876
|
const [isMaximized, setIsMaximized] = useState(false);
|
|
@@ -16451,7 +16017,7 @@ function LoopConfigModal({
|
|
|
16451
16017
|
try {
|
|
16452
16018
|
if (!node) return;
|
|
16453
16019
|
if (!data.mode) {
|
|
16454
|
-
|
|
16020
|
+
toast5({
|
|
16455
16021
|
title: "Erro de valida\xE7\xE3o",
|
|
16456
16022
|
description: "Modo de loop \xE9 obrigat\xF3rio",
|
|
16457
16023
|
variant: "destructive"
|
|
@@ -16459,7 +16025,7 @@ function LoopConfigModal({
|
|
|
16459
16025
|
return;
|
|
16460
16026
|
}
|
|
16461
16027
|
if (data.mode === "items" && !data.source_field) {
|
|
16462
|
-
|
|
16028
|
+
toast5({
|
|
16463
16029
|
title: "Erro de valida\xE7\xE3o",
|
|
16464
16030
|
description: "Campo de origem \xE9 obrigat\xF3rio para modo items",
|
|
16465
16031
|
variant: "destructive"
|
|
@@ -16468,7 +16034,7 @@ function LoopConfigModal({
|
|
|
16468
16034
|
}
|
|
16469
16035
|
if (data.mode === "range") {
|
|
16470
16036
|
if (data.start === void 0 || data.end === void 0) {
|
|
16471
|
-
|
|
16037
|
+
toast5({
|
|
16472
16038
|
title: "Erro de valida\xE7\xE3o",
|
|
16473
16039
|
description: "In\xEDcio e fim s\xE3o obrigat\xF3rios para modo range",
|
|
16474
16040
|
variant: "destructive"
|
|
@@ -16476,7 +16042,7 @@ function LoopConfigModal({
|
|
|
16476
16042
|
return;
|
|
16477
16043
|
}
|
|
16478
16044
|
if (data.start >= data.end) {
|
|
16479
|
-
|
|
16045
|
+
toast5({
|
|
16480
16046
|
title: "Erro de valida\xE7\xE3o",
|
|
16481
16047
|
description: "O valor inicial deve ser menor que o valor final",
|
|
16482
16048
|
variant: "destructive"
|
|
@@ -16485,7 +16051,7 @@ function LoopConfigModal({
|
|
|
16485
16051
|
}
|
|
16486
16052
|
}
|
|
16487
16053
|
if (data.mode === "while" && !data.condition) {
|
|
16488
|
-
|
|
16054
|
+
toast5({
|
|
16489
16055
|
title: "Erro de valida\xE7\xE3o",
|
|
16490
16056
|
description: "Condi\xE7\xE3o \xE9 obrigat\xF3ria para modo while",
|
|
16491
16057
|
variant: "destructive"
|
|
@@ -16511,14 +16077,14 @@ function LoopConfigModal({
|
|
|
16511
16077
|
// Enviar vazio por compatibilidade
|
|
16512
16078
|
};
|
|
16513
16079
|
await onSave(node.id, updatedNode);
|
|
16514
|
-
|
|
16080
|
+
toast5({
|
|
16515
16081
|
title: "Configura\xE7\xE3o salva",
|
|
16516
16082
|
description: "As configura\xE7\xF5es do Loop Node foram salvas com sucesso."
|
|
16517
16083
|
});
|
|
16518
16084
|
onClose();
|
|
16519
16085
|
} catch (error) {
|
|
16520
16086
|
console.error("Erro ao salvar configura\xE7\xE3o:", error);
|
|
16521
|
-
|
|
16087
|
+
toast5({
|
|
16522
16088
|
title: "Erro ao salvar",
|
|
16523
16089
|
description: "Ocorreu um erro ao salvar as configura\xE7\xF5es. Tente novamente.",
|
|
16524
16090
|
variant: "destructive"
|
|
@@ -16863,277 +16429,6 @@ function LoopConfigModal({
|
|
|
16863
16429
|
] })
|
|
16864
16430
|
] }) });
|
|
16865
16431
|
}
|
|
16866
|
-
var repository2 = new HttpWhatsAppRepository();
|
|
16867
|
-
var listConfigsUseCase2 = new ListWhatsAppConfigsUseCase(repository2);
|
|
16868
|
-
var createConfigUseCase = new CreateWhatsAppConfigUseCase(repository2);
|
|
16869
|
-
var connectInstanceUseCase = new ConnectWhatsAppInstanceUseCase(repository2);
|
|
16870
|
-
var sendMessageUseCase = new SendWhatsAppMessageUseCase(repository2);
|
|
16871
|
-
function useWhatsApp(options = {}) {
|
|
16872
|
-
const { autoRefresh = false, refreshInterval = 3e4 } = options;
|
|
16873
|
-
const queryClient = useQueryClient();
|
|
16874
|
-
const { getCurrentTenantId } = useAuthContext();
|
|
16875
|
-
const [selectedConfig, setSelectedConfig] = useState(null);
|
|
16876
|
-
const {
|
|
16877
|
-
data: configsData,
|
|
16878
|
-
isLoading: isLoadingConfigs,
|
|
16879
|
-
error: configsError,
|
|
16880
|
-
refetch: refetchConfigs
|
|
16881
|
-
} = useQuery({
|
|
16882
|
-
queryKey: ["whatsapp-configs", getCurrentTenantId()],
|
|
16883
|
-
queryFn: () => listConfigsUseCase2.execute({ limit: 50 }),
|
|
16884
|
-
refetchInterval: autoRefresh ? refreshInterval : void 0,
|
|
16885
|
-
staleTime: 5 * 60 * 1e3,
|
|
16886
|
-
retry: 1,
|
|
16887
|
-
retryDelay: 5e3,
|
|
16888
|
-
onError: (error) => {
|
|
16889
|
-
console.error("Erro ao carregar configura\xE7\xF5es WhatsApp:", error);
|
|
16890
|
-
}
|
|
16891
|
-
});
|
|
16892
|
-
const createConfigMutation = useMutation({
|
|
16893
|
-
mutationFn: createConfigUseCase.execute.bind(createConfigUseCase),
|
|
16894
|
-
onSuccess: (newConfig) => {
|
|
16895
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
|
|
16896
|
-
toast({
|
|
16897
|
-
title: "Configura\xE7\xE3o criada",
|
|
16898
|
-
description: `Inst\xE2ncia ${newConfig.instanceName} foi criada com sucesso.`
|
|
16899
|
-
});
|
|
16900
|
-
},
|
|
16901
|
-
onError: (error) => {
|
|
16902
|
-
toast({
|
|
16903
|
-
title: "Erro ao criar configura\xE7\xE3o",
|
|
16904
|
-
description: error.message,
|
|
16905
|
-
variant: "destructive"
|
|
16906
|
-
});
|
|
16907
|
-
}
|
|
16908
|
-
});
|
|
16909
|
-
const connectInstanceMutation = useMutation({
|
|
16910
|
-
mutationFn: (configId) => connectInstanceUseCase.execute({ configId }),
|
|
16911
|
-
onSuccess: () => {
|
|
16912
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
|
|
16913
|
-
},
|
|
16914
|
-
onError: (error) => {
|
|
16915
|
-
toast({
|
|
16916
|
-
title: "Erro ao conectar",
|
|
16917
|
-
description: error.message,
|
|
16918
|
-
variant: "destructive"
|
|
16919
|
-
});
|
|
16920
|
-
}
|
|
16921
|
-
});
|
|
16922
|
-
const disconnectInstanceMutation = useMutation({
|
|
16923
|
-
mutationFn: (configId) => connectInstanceUseCase.disconnect({ configId }),
|
|
16924
|
-
onSuccess: () => {
|
|
16925
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
|
|
16926
|
-
toast({
|
|
16927
|
-
title: "Inst\xE2ncia desconectada",
|
|
16928
|
-
description: "A inst\xE2ncia foi desconectada com sucesso."
|
|
16929
|
-
});
|
|
16930
|
-
},
|
|
16931
|
-
onError: (error) => {
|
|
16932
|
-
toast({
|
|
16933
|
-
title: "Erro ao desconectar",
|
|
16934
|
-
description: error.message,
|
|
16935
|
-
variant: "destructive"
|
|
16936
|
-
});
|
|
16937
|
-
}
|
|
16938
|
-
});
|
|
16939
|
-
const sendMessageMutation = useMutation({
|
|
16940
|
-
mutationFn: sendMessageUseCase.execute.bind(sendMessageUseCase),
|
|
16941
|
-
onSuccess: () => {
|
|
16942
|
-
toast({
|
|
16943
|
-
title: "Mensagem enviada",
|
|
16944
|
-
description: "Sua mensagem foi enviada com sucesso."
|
|
16945
|
-
});
|
|
16946
|
-
},
|
|
16947
|
-
onError: (error) => {
|
|
16948
|
-
toast({
|
|
16949
|
-
title: "Erro ao enviar mensagem",
|
|
16950
|
-
description: error.message,
|
|
16951
|
-
variant: "destructive"
|
|
16952
|
-
});
|
|
16953
|
-
}
|
|
16954
|
-
});
|
|
16955
|
-
const deleteConfigMutation = useMutation({
|
|
16956
|
-
mutationFn: (configId) => repository2.deleteConfig(configId),
|
|
16957
|
-
onSuccess: () => {
|
|
16958
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-configs"] });
|
|
16959
|
-
toast({
|
|
16960
|
-
title: "Configura\xE7\xE3o deletada",
|
|
16961
|
-
description: "A configura\xE7\xE3o foi removida com sucesso."
|
|
16962
|
-
});
|
|
16963
|
-
},
|
|
16964
|
-
onError: (error) => {
|
|
16965
|
-
toast({
|
|
16966
|
-
title: "Erro ao deletar",
|
|
16967
|
-
description: error.message,
|
|
16968
|
-
variant: "destructive"
|
|
16969
|
-
});
|
|
16970
|
-
}
|
|
16971
|
-
});
|
|
16972
|
-
const checkHealth = useCallback(async (configId) => {
|
|
16973
|
-
try {
|
|
16974
|
-
const health = await connectInstanceUseCase.checkHealth({ configId });
|
|
16975
|
-
if (health.healthy) {
|
|
16976
|
-
toast({
|
|
16977
|
-
title: "Inst\xE2ncia saud\xE1vel",
|
|
16978
|
-
description: "A inst\xE2ncia est\xE1 funcionando corretamente."
|
|
16979
|
-
});
|
|
16980
|
-
} else {
|
|
16981
|
-
toast({
|
|
16982
|
-
title: "Inst\xE2ncia com problemas",
|
|
16983
|
-
description: health.error || "Verifique a conex\xE3o.",
|
|
16984
|
-
variant: "destructive"
|
|
16985
|
-
});
|
|
16986
|
-
}
|
|
16987
|
-
return health;
|
|
16988
|
-
} catch (error) {
|
|
16989
|
-
toast({
|
|
16990
|
-
title: "Erro ao verificar sa\xFAde",
|
|
16991
|
-
description: error instanceof Error ? error.message : "Erro desconhecido",
|
|
16992
|
-
variant: "destructive"
|
|
16993
|
-
});
|
|
16994
|
-
throw error;
|
|
16995
|
-
}
|
|
16996
|
-
}, []);
|
|
16997
|
-
const testMessage = useCallback(async (configId, testNumber) => {
|
|
16998
|
-
try {
|
|
16999
|
-
const result = await repository2.testMessage(configId, testNumber);
|
|
17000
|
-
if (result.success) {
|
|
17001
|
-
toast({
|
|
17002
|
-
title: "Teste bem-sucedido",
|
|
17003
|
-
description: "Mensagem de teste enviada com sucesso."
|
|
17004
|
-
});
|
|
17005
|
-
} else {
|
|
17006
|
-
toast({
|
|
17007
|
-
title: "Teste falhou",
|
|
17008
|
-
description: result.error || "Erro ao enviar mensagem de teste.",
|
|
17009
|
-
variant: "destructive"
|
|
17010
|
-
});
|
|
17011
|
-
}
|
|
17012
|
-
return result;
|
|
17013
|
-
} catch (error) {
|
|
17014
|
-
toast({
|
|
17015
|
-
title: "Erro no teste",
|
|
17016
|
-
description: error instanceof Error ? error.message : "Erro desconhecido",
|
|
17017
|
-
variant: "destructive"
|
|
17018
|
-
});
|
|
17019
|
-
throw error;
|
|
17020
|
-
}
|
|
17021
|
-
}, []);
|
|
17022
|
-
const validatePhoneNumber = useCallback((phoneNumber) => {
|
|
17023
|
-
return whatsappService.validatePhoneNumber(phoneNumber);
|
|
17024
|
-
}, []);
|
|
17025
|
-
const formatPhoneNumber = useCallback((phoneNumber) => {
|
|
17026
|
-
return whatsappService.formatPhoneForDisplay(phoneNumber);
|
|
17027
|
-
}, []);
|
|
17028
|
-
useEffect(() => {
|
|
17029
|
-
if (!autoRefresh) return;
|
|
17030
|
-
const interval = setInterval(() => {
|
|
17031
|
-
refetchConfigs();
|
|
17032
|
-
}, refreshInterval);
|
|
17033
|
-
return () => clearInterval(interval);
|
|
17034
|
-
}, [autoRefresh, refreshInterval, refetchConfigs]);
|
|
17035
|
-
const getConnectedConfigs = useCallback(() => {
|
|
17036
|
-
if (!configsData?.configs) return [];
|
|
17037
|
-
return configsData.configs.filter((config) => config.isConnected());
|
|
17038
|
-
}, [configsData]);
|
|
17039
|
-
const getConfigByName = useCallback((instanceName) => {
|
|
17040
|
-
if (!configsData?.configs) return null;
|
|
17041
|
-
return configsData.configs.find((config) => config.instanceName === instanceName) || null;
|
|
17042
|
-
}, [configsData]);
|
|
17043
|
-
return {
|
|
17044
|
-
// Dados
|
|
17045
|
-
configs: configsData?.configs || [],
|
|
17046
|
-
stats: configsData?.stats || { connected: 0, disconnected: 0, error: 0, pending: 0 },
|
|
17047
|
-
selectedConfig,
|
|
17048
|
-
connectedConfigs: getConnectedConfigs(),
|
|
17049
|
-
// Estado
|
|
17050
|
-
isLoading: isLoadingConfigs,
|
|
17051
|
-
error: configsError,
|
|
17052
|
-
// Mutations state
|
|
17053
|
-
isCreating: createConfigMutation.isPending,
|
|
17054
|
-
isConnecting: connectInstanceMutation.isPending,
|
|
17055
|
-
isDisconnecting: disconnectInstanceMutation.isPending,
|
|
17056
|
-
isSending: sendMessageMutation.isPending,
|
|
17057
|
-
isDeleting: deleteConfigMutation.isPending,
|
|
17058
|
-
// Ações
|
|
17059
|
-
createConfig: createConfigMutation.mutate,
|
|
17060
|
-
connectInstance: connectInstanceMutation.mutate,
|
|
17061
|
-
disconnectInstance: disconnectInstanceMutation.mutate,
|
|
17062
|
-
sendMessage: sendMessageMutation.mutate,
|
|
17063
|
-
deleteConfig: deleteConfigMutation.mutate,
|
|
17064
|
-
checkHealth,
|
|
17065
|
-
testMessage,
|
|
17066
|
-
refetchConfigs,
|
|
17067
|
-
setSelectedConfig,
|
|
17068
|
-
// Utilidades
|
|
17069
|
-
validatePhoneNumber,
|
|
17070
|
-
formatPhoneNumber,
|
|
17071
|
-
getConfigByName
|
|
17072
|
-
};
|
|
17073
|
-
}
|
|
17074
|
-
function useWhatsAppHealthMonitor(configId, interval = 6e4) {
|
|
17075
|
-
const [health, setHealth] = useState(null);
|
|
17076
|
-
useEffect(() => {
|
|
17077
|
-
if (!configId) return;
|
|
17078
|
-
const checkHealth = async () => {
|
|
17079
|
-
try {
|
|
17080
|
-
const useCase = new ConnectWhatsAppInstanceUseCase(repository2);
|
|
17081
|
-
const result = await useCase.checkHealth({ configId });
|
|
17082
|
-
setHealth({
|
|
17083
|
-
...result,
|
|
17084
|
-
lastCheck: /* @__PURE__ */ new Date()
|
|
17085
|
-
});
|
|
17086
|
-
} catch (error) {
|
|
17087
|
-
setHealth({
|
|
17088
|
-
healthy: false,
|
|
17089
|
-
connected: false,
|
|
17090
|
-
status: "error",
|
|
17091
|
-
error: error instanceof Error ? error.message : "Erro desconhecido",
|
|
17092
|
-
lastCheck: /* @__PURE__ */ new Date()
|
|
17093
|
-
});
|
|
17094
|
-
}
|
|
17095
|
-
};
|
|
17096
|
-
checkHealth();
|
|
17097
|
-
const intervalId = setInterval(checkHealth, interval);
|
|
17098
|
-
return () => clearInterval(intervalId);
|
|
17099
|
-
}, [configId, interval]);
|
|
17100
|
-
return health;
|
|
17101
|
-
}
|
|
17102
|
-
function useWhatsAppQRCode(configId) {
|
|
17103
|
-
const [qrCode, setQrCode] = useState(null);
|
|
17104
|
-
const [loading, setLoading] = useState(false);
|
|
17105
|
-
const [error, setError] = useState(null);
|
|
17106
|
-
const connect = useCallback(async () => {
|
|
17107
|
-
if (!configId) {
|
|
17108
|
-
setError("ID da configura\xE7\xE3o n\xE3o fornecido");
|
|
17109
|
-
return;
|
|
17110
|
-
}
|
|
17111
|
-
setLoading(true);
|
|
17112
|
-
setError(null);
|
|
17113
|
-
try {
|
|
17114
|
-
const response = await repository2.connectInstance(configId);
|
|
17115
|
-
setQrCode(response);
|
|
17116
|
-
return response;
|
|
17117
|
-
} catch (err) {
|
|
17118
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao gerar QR Code";
|
|
17119
|
-
setError(errorMessage);
|
|
17120
|
-
throw err;
|
|
17121
|
-
} finally {
|
|
17122
|
-
setLoading(false);
|
|
17123
|
-
}
|
|
17124
|
-
}, [configId]);
|
|
17125
|
-
const reset = useCallback(() => {
|
|
17126
|
-
setQrCode(null);
|
|
17127
|
-
setError(null);
|
|
17128
|
-
}, []);
|
|
17129
|
-
return {
|
|
17130
|
-
qrCode,
|
|
17131
|
-
loading,
|
|
17132
|
-
error,
|
|
17133
|
-
connect,
|
|
17134
|
-
reset
|
|
17135
|
-
};
|
|
17136
|
-
}
|
|
17137
16432
|
var mcpVerificationCache = /* @__PURE__ */ new Map();
|
|
17138
16433
|
var WEBHOOK_EVENT_TYPES = [
|
|
17139
16434
|
{ value: "messages.upsert", label: "messages.upsert - Nova mensagem recebida", icon: "\u{1F4E8}" },
|
|
@@ -18260,7 +17555,7 @@ function SplitConfigModal({
|
|
|
18260
17555
|
node,
|
|
18261
17556
|
onSave
|
|
18262
17557
|
}) {
|
|
18263
|
-
const { toast:
|
|
17558
|
+
const { toast: toast5 } = useToast();
|
|
18264
17559
|
const [activeTab, setActiveTab] = useState("config");
|
|
18265
17560
|
const [previewData, setPreviewData] = useState(null);
|
|
18266
17561
|
const [isMaximized, setIsMaximized] = useState(false);
|
|
@@ -18379,7 +17674,7 @@ function SplitConfigModal({
|
|
|
18379
17674
|
try {
|
|
18380
17675
|
if (!node) return;
|
|
18381
17676
|
if (!data.split_mode) {
|
|
18382
|
-
|
|
17677
|
+
toast5({
|
|
18383
17678
|
title: "Erro de valida\xE7\xE3o",
|
|
18384
17679
|
description: "Modo de divis\xE3o \xE9 obrigat\xF3rio",
|
|
18385
17680
|
variant: "destructive"
|
|
@@ -18387,7 +17682,7 @@ function SplitConfigModal({
|
|
|
18387
17682
|
return;
|
|
18388
17683
|
}
|
|
18389
17684
|
if (!data.field_name && data.split_mode !== "properties") {
|
|
18390
|
-
|
|
17685
|
+
toast5({
|
|
18391
17686
|
title: "Erro de valida\xE7\xE3o",
|
|
18392
17687
|
description: "Nome do campo \xE9 obrigat\xF3rio para este modo",
|
|
18393
17688
|
variant: "destructive"
|
|
@@ -18413,14 +17708,14 @@ function SplitConfigModal({
|
|
|
18413
17708
|
// Enviar vazio por compatibilidade
|
|
18414
17709
|
};
|
|
18415
17710
|
await onSave(node.id, updatedNode);
|
|
18416
|
-
|
|
17711
|
+
toast5({
|
|
18417
17712
|
title: "Configura\xE7\xE3o salva",
|
|
18418
17713
|
description: "As configura\xE7\xF5es do nodo Split foram salvas com sucesso."
|
|
18419
17714
|
});
|
|
18420
17715
|
onClose();
|
|
18421
17716
|
} catch (error) {
|
|
18422
17717
|
console.error("Erro ao salvar configura\xE7\xE3o:", error);
|
|
18423
|
-
|
|
17718
|
+
toast5({
|
|
18424
17719
|
title: "Erro ao salvar",
|
|
18425
17720
|
description: "Ocorreu um erro ao salvar as configura\xE7\xF5es. Tente novamente.",
|
|
18426
17721
|
variant: "destructive"
|
|
@@ -18718,7 +18013,7 @@ function WhatsAppTriggerConfigModal({
|
|
|
18718
18013
|
flowId,
|
|
18719
18014
|
onSave
|
|
18720
18015
|
}) {
|
|
18721
|
-
const { toast:
|
|
18016
|
+
const { toast: toast5 } = useToast();
|
|
18722
18017
|
const { configs, loading: loadingConfigs } = useWhatsAppConfigs();
|
|
18723
18018
|
const availableInstances = configs?.filter((config) => config.isConnected()) || [];
|
|
18724
18019
|
const [activeTab, setActiveTab] = useState("basic");
|
|
@@ -18790,7 +18085,7 @@ function WhatsAppTriggerConfigModal({
|
|
|
18790
18085
|
};
|
|
18791
18086
|
const onFormError = (errors2) => {
|
|
18792
18087
|
const errorMessages = Object.entries(errors2).map(([field, error]) => `${field}: ${error?.message || "erro desconhecido"}`).join("\n");
|
|
18793
|
-
|
|
18088
|
+
toast5({
|
|
18794
18089
|
title: "Erro de valida\xE7\xE3o",
|
|
18795
18090
|
description: errorMessages || "Verifique os campos do formul\xE1rio",
|
|
18796
18091
|
variant: "destructive"
|
|
@@ -19083,184 +18378,6 @@ function WhatsAppTriggerConfigModal({
|
|
|
19083
18378
|
] })
|
|
19084
18379
|
] }) });
|
|
19085
18380
|
}
|
|
19086
|
-
var triggerRepository = new HttpWhatsAppTriggerRepository();
|
|
19087
|
-
var flowRepository = new HttpFlowRepository();
|
|
19088
|
-
var whatsappRepository = new HttpWhatsAppRepository();
|
|
19089
|
-
var listTriggersUseCase = new ListWhatsAppTriggersUseCase(triggerRepository);
|
|
19090
|
-
var createTriggerUseCase = new CreateWhatsAppTriggerUseCase(
|
|
19091
|
-
triggerRepository,
|
|
19092
|
-
flowRepository,
|
|
19093
|
-
whatsappRepository
|
|
19094
|
-
);
|
|
19095
|
-
var updateTriggerUseCase = new UpdateWhatsAppTriggerUseCase(triggerRepository);
|
|
19096
|
-
var deleteTriggerUseCase = new DeleteWhatsAppTriggerUseCase(triggerRepository);
|
|
19097
|
-
var testTriggerUseCase = new TestWhatsAppTriggerUseCase(triggerRepository);
|
|
19098
|
-
var getMetricsUseCase = new GetWhatsAppTriggerMetricsUseCase(triggerRepository);
|
|
19099
|
-
function useWhatsAppTriggers(flowId, instanceName) {
|
|
19100
|
-
const queryClient = useQueryClient();
|
|
19101
|
-
const { toast: toast7 } = useToast();
|
|
19102
|
-
const { data: triggersData, isLoading, error, refetch } = useQuery({
|
|
19103
|
-
queryKey: ["whatsapp-triggers", flowId, instanceName],
|
|
19104
|
-
queryFn: async () => {
|
|
19105
|
-
if (flowId) {
|
|
19106
|
-
const triggers = await listTriggersUseCase.getByFlow(flowId);
|
|
19107
|
-
return triggers;
|
|
19108
|
-
}
|
|
19109
|
-
if (instanceName) {
|
|
19110
|
-
const triggers = await listTriggersUseCase.getByInstance(instanceName);
|
|
19111
|
-
return triggers;
|
|
19112
|
-
}
|
|
19113
|
-
const result = await listTriggersUseCase.execute();
|
|
19114
|
-
return result.triggers;
|
|
19115
|
-
},
|
|
19116
|
-
refetchInterval: 3e4
|
|
19117
|
-
});
|
|
19118
|
-
const createTriggerMutation = useMutation({
|
|
19119
|
-
mutationFn: (data) => createTriggerUseCase.execute(data),
|
|
19120
|
-
onSuccess: () => {
|
|
19121
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
|
|
19122
|
-
toast7({
|
|
19123
|
-
title: "Sucesso",
|
|
19124
|
-
description: "Trigger criado com sucesso"
|
|
19125
|
-
});
|
|
19126
|
-
},
|
|
19127
|
-
onError: (error2) => {
|
|
19128
|
-
toast7({
|
|
19129
|
-
title: "Erro",
|
|
19130
|
-
description: `Erro ao criar trigger: ${error2.message}`,
|
|
19131
|
-
variant: "destructive"
|
|
19132
|
-
});
|
|
19133
|
-
}
|
|
19134
|
-
});
|
|
19135
|
-
const updateTriggerMutation = useMutation({
|
|
19136
|
-
mutationFn: ({ id, data }) => updateTriggerUseCase.execute(id, data),
|
|
19137
|
-
onSuccess: () => {
|
|
19138
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
|
|
19139
|
-
toast7({
|
|
19140
|
-
title: "Sucesso",
|
|
19141
|
-
description: "Trigger atualizado com sucesso"
|
|
19142
|
-
});
|
|
19143
|
-
},
|
|
19144
|
-
onError: (error2) => {
|
|
19145
|
-
toast7({
|
|
19146
|
-
title: "Erro",
|
|
19147
|
-
description: `Erro ao atualizar trigger: ${error2.message}`,
|
|
19148
|
-
variant: "destructive"
|
|
19149
|
-
});
|
|
19150
|
-
}
|
|
19151
|
-
});
|
|
19152
|
-
const deleteTriggerMutation = useMutation({
|
|
19153
|
-
mutationFn: (id) => deleteTriggerUseCase.execute(id),
|
|
19154
|
-
onSuccess: () => {
|
|
19155
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
|
|
19156
|
-
toast7({
|
|
19157
|
-
title: "Sucesso",
|
|
19158
|
-
description: "Trigger exclu\xEDdo com sucesso"
|
|
19159
|
-
});
|
|
19160
|
-
},
|
|
19161
|
-
onError: (error2) => {
|
|
19162
|
-
toast7({
|
|
19163
|
-
title: "Erro",
|
|
19164
|
-
description: `Erro ao excluir trigger: ${error2.message}`,
|
|
19165
|
-
variant: "destructive"
|
|
19166
|
-
});
|
|
19167
|
-
}
|
|
19168
|
-
});
|
|
19169
|
-
const toggleActiveMutation = useMutation({
|
|
19170
|
-
mutationFn: (id) => updateTriggerUseCase.toggleActive(id),
|
|
19171
|
-
onSuccess: () => {
|
|
19172
|
-
queryClient.invalidateQueries({ queryKey: ["whatsapp-triggers"] });
|
|
19173
|
-
toast7({
|
|
19174
|
-
title: "Sucesso",
|
|
19175
|
-
description: "Status do trigger alterado"
|
|
19176
|
-
});
|
|
19177
|
-
},
|
|
19178
|
-
onError: (error2) => {
|
|
19179
|
-
toast7({
|
|
19180
|
-
title: "Erro",
|
|
19181
|
-
description: `Erro ao alterar status: ${error2.message}`,
|
|
19182
|
-
variant: "destructive"
|
|
19183
|
-
});
|
|
19184
|
-
}
|
|
19185
|
-
});
|
|
19186
|
-
const testTriggerMutation = useMutation({
|
|
19187
|
-
mutationFn: (data) => testTriggerUseCase.execute(data),
|
|
19188
|
-
onSuccess: (result) => {
|
|
19189
|
-
if (result && result.matched) {
|
|
19190
|
-
toast7({
|
|
19191
|
-
title: "Teste bem-sucedido",
|
|
19192
|
-
description: "A mensagem corresponde ao trigger"
|
|
19193
|
-
});
|
|
19194
|
-
} else if (result) {
|
|
19195
|
-
toast7({
|
|
19196
|
-
title: "Teste falhado",
|
|
19197
|
-
description: result.error || "A mensagem n\xE3o corresponde ao trigger",
|
|
19198
|
-
variant: "destructive"
|
|
19199
|
-
});
|
|
19200
|
-
} else {
|
|
19201
|
-
toast7({
|
|
19202
|
-
title: "Erro",
|
|
19203
|
-
description: "Resposta inv\xE1lida do servidor",
|
|
19204
|
-
variant: "destructive"
|
|
19205
|
-
});
|
|
19206
|
-
}
|
|
19207
|
-
},
|
|
19208
|
-
onError: (error2) => {
|
|
19209
|
-
toast7({
|
|
19210
|
-
title: "Erro",
|
|
19211
|
-
description: `Erro ao testar trigger: ${error2.message}`,
|
|
19212
|
-
variant: "destructive"
|
|
19213
|
-
});
|
|
19214
|
-
}
|
|
19215
|
-
});
|
|
19216
|
-
return {
|
|
19217
|
-
triggers: triggersData || [],
|
|
19218
|
-
loading: isLoading,
|
|
19219
|
-
error: error?.message || null,
|
|
19220
|
-
refetch,
|
|
19221
|
-
createTrigger: createTriggerMutation.mutate,
|
|
19222
|
-
updateTrigger: updateTriggerMutation.mutate,
|
|
19223
|
-
deleteTrigger: deleteTriggerMutation.mutate,
|
|
19224
|
-
toggleActive: toggleActiveMutation.mutate,
|
|
19225
|
-
testTrigger: testTriggerMutation.mutate,
|
|
19226
|
-
isCreating: createTriggerMutation.isPending,
|
|
19227
|
-
isUpdating: updateTriggerMutation.isPending,
|
|
19228
|
-
isDeleting: deleteTriggerMutation.isPending,
|
|
19229
|
-
isTesting: testTriggerMutation.isPending
|
|
19230
|
-
};
|
|
19231
|
-
}
|
|
19232
|
-
function useWhatsAppTriggerMetrics(triggerId) {
|
|
19233
|
-
const { data, isLoading, error, refetch } = useQuery({
|
|
19234
|
-
queryKey: ["whatsapp-trigger-metrics", triggerId],
|
|
19235
|
-
queryFn: () => getMetricsUseCase.execute(triggerId),
|
|
19236
|
-
enabled: !!triggerId,
|
|
19237
|
-
refetchInterval: 1e4
|
|
19238
|
-
// Atualizar a cada 10 segundos
|
|
19239
|
-
});
|
|
19240
|
-
return {
|
|
19241
|
-
metrics: data?.metrics,
|
|
19242
|
-
trigger: data?.trigger,
|
|
19243
|
-
recentExecutions: data?.recentExecutions || [],
|
|
19244
|
-
loading: isLoading,
|
|
19245
|
-
error: error?.message || null,
|
|
19246
|
-
refetch
|
|
19247
|
-
};
|
|
19248
|
-
}
|
|
19249
|
-
function useWhatsAppTriggerExecutions(triggerId, limit = 50) {
|
|
19250
|
-
const { data, isLoading, error, refetch } = useQuery({
|
|
19251
|
-
queryKey: ["whatsapp-trigger-executions", triggerId, limit],
|
|
19252
|
-
queryFn: () => getMetricsUseCase.getExecutions(triggerId, limit),
|
|
19253
|
-
enabled: !!triggerId,
|
|
19254
|
-
refetchInterval: 5e3
|
|
19255
|
-
// Atualizar a cada 5 segundos
|
|
19256
|
-
});
|
|
19257
|
-
return {
|
|
19258
|
-
executions: data || [],
|
|
19259
|
-
loading: isLoading,
|
|
19260
|
-
error: error?.message || null,
|
|
19261
|
-
refetch
|
|
19262
|
-
};
|
|
19263
|
-
}
|
|
19264
18381
|
function WhatsAppTriggerMetricsModal({
|
|
19265
18382
|
open,
|
|
19266
18383
|
onClose,
|
|
@@ -20928,61 +20045,6 @@ function MotoristaStatusBadge({ motorista }) {
|
|
|
20928
20045
|
}
|
|
20929
20046
|
return /* @__PURE__ */ jsx(Badge, { variant: "default", children: "Ativo" });
|
|
20930
20047
|
}
|
|
20931
|
-
var repository3 = new HttpMotoristaRepository();
|
|
20932
|
-
function useMotoristaMutations() {
|
|
20933
|
-
const queryClient = useQueryClient();
|
|
20934
|
-
const createMutation = useMutation({
|
|
20935
|
-
mutationFn: async (data) => {
|
|
20936
|
-
const useCase = new CreateMotoristaUseCase(repository3);
|
|
20937
|
-
return await useCase.execute(data);
|
|
20938
|
-
},
|
|
20939
|
-
onSuccess: () => {
|
|
20940
|
-
queryClient.invalidateQueries({ queryKey: ["motoristas"] });
|
|
20941
|
-
}
|
|
20942
|
-
});
|
|
20943
|
-
const updateMutation = useMutation({
|
|
20944
|
-
mutationFn: async ({ cd_motorista, data }) => {
|
|
20945
|
-
const useCase = new UpdateMotoristaUseCase(repository3);
|
|
20946
|
-
return await useCase.execute(cd_motorista, data);
|
|
20947
|
-
},
|
|
20948
|
-
onSuccess: (_, variables) => {
|
|
20949
|
-
queryClient.invalidateQueries({ queryKey: ["motorista", variables.cd_motorista] });
|
|
20950
|
-
queryClient.invalidateQueries({ queryKey: ["motoristas"] });
|
|
20951
|
-
}
|
|
20952
|
-
});
|
|
20953
|
-
const deleteMutation = useMutation({
|
|
20954
|
-
mutationFn: async (cd_motorista) => {
|
|
20955
|
-
const useCase = new DeleteMotoristaUseCase(repository3);
|
|
20956
|
-
return await useCase.execute(cd_motorista);
|
|
20957
|
-
},
|
|
20958
|
-
onSuccess: (_, cd_motorista) => {
|
|
20959
|
-
queryClient.invalidateQueries({ queryKey: ["motorista", cd_motorista] });
|
|
20960
|
-
queryClient.invalidateQueries({ queryKey: ["motoristas"] });
|
|
20961
|
-
}
|
|
20962
|
-
});
|
|
20963
|
-
const toggleBlockMutation = useMutation({
|
|
20964
|
-
mutationFn: async ({ cd_motorista, bloqueado }) => {
|
|
20965
|
-
const useCase = new ToggleBlockMotoristaUseCase(repository3);
|
|
20966
|
-
return await useCase.execute(cd_motorista, bloqueado);
|
|
20967
|
-
},
|
|
20968
|
-
onSuccess: (_, variables) => {
|
|
20969
|
-
queryClient.invalidateQueries({ queryKey: ["motorista", variables.cd_motorista] });
|
|
20970
|
-
queryClient.invalidateQueries({ queryKey: ["motoristas"] });
|
|
20971
|
-
}
|
|
20972
|
-
});
|
|
20973
|
-
const verifyPasswordMutation = useMutation({
|
|
20974
|
-
mutationFn: async ({ cd_motorista, senha }) => {
|
|
20975
|
-
return await repository3.verifyPassword(cd_motorista, senha);
|
|
20976
|
-
}
|
|
20977
|
-
});
|
|
20978
|
-
return {
|
|
20979
|
-
createMutation,
|
|
20980
|
-
updateMutation,
|
|
20981
|
-
deleteMutation,
|
|
20982
|
-
toggleBlockMutation,
|
|
20983
|
-
verifyPasswordMutation
|
|
20984
|
-
};
|
|
20985
|
-
}
|
|
20986
20048
|
function MotoristaTable({
|
|
20987
20049
|
motoristas,
|
|
20988
20050
|
isLoading,
|
|
@@ -21131,7 +20193,7 @@ function MotoristaTable({
|
|
|
21131
20193
|
] }) }) });
|
|
21132
20194
|
}
|
|
21133
20195
|
function EventInspector({ event, onRetry, className }) {
|
|
21134
|
-
const { toast:
|
|
20196
|
+
const { toast: toast5 } = useToast();
|
|
21135
20197
|
const [expandedSections, setExpandedSections] = useState(/* @__PURE__ */ new Set(["overview"]));
|
|
21136
20198
|
const [copiedField, setCopiedField] = useState(null);
|
|
21137
20199
|
const retryMutation = useMutation({
|
|
@@ -21139,14 +20201,14 @@ function EventInspector({ event, onRetry, className }) {
|
|
|
21139
20201
|
return await webhookService.retryEvent(eventId);
|
|
21140
20202
|
},
|
|
21141
20203
|
onSuccess: () => {
|
|
21142
|
-
|
|
20204
|
+
toast5({
|
|
21143
20205
|
title: "Reprocessamento iniciado",
|
|
21144
20206
|
description: "O evento ser\xE1 reprocessado em breve"
|
|
21145
20207
|
});
|
|
21146
20208
|
onRetry?.(event.id);
|
|
21147
20209
|
},
|
|
21148
20210
|
onError: (error) => {
|
|
21149
|
-
|
|
20211
|
+
toast5({
|
|
21150
20212
|
title: "Erro ao reprocessar",
|
|
21151
20213
|
description: error.message,
|
|
21152
20214
|
variant: "destructive"
|
|
@@ -21186,7 +20248,7 @@ function EventInspector({ event, onRetry, className }) {
|
|
|
21186
20248
|
await navigator.clipboard.writeText(text);
|
|
21187
20249
|
setCopiedField(field);
|
|
21188
20250
|
setTimeout(() => setCopiedField(null), 2e3);
|
|
21189
|
-
|
|
20251
|
+
toast5({
|
|
21190
20252
|
title: "Copiado!",
|
|
21191
20253
|
description: "Conte\xFAdo copiado para a \xE1rea de transfer\xEAncia"
|
|
21192
20254
|
});
|
|
@@ -22209,7 +21271,7 @@ function WebhookFlowLink({
|
|
|
22209
21271
|
showDetails = true,
|
|
22210
21272
|
onReExecute
|
|
22211
21273
|
}) {
|
|
22212
|
-
const { toast:
|
|
21274
|
+
const { toast: toast5 } = useToast();
|
|
22213
21275
|
const { data: flowExecution, isLoading, refetch } = useQuery({
|
|
22214
21276
|
queryKey: ["flow-execution", event.metadata.sessionId],
|
|
22215
21277
|
queryFn: async () => {
|
|
@@ -22268,7 +21330,7 @@ function WebhookFlowLink({
|
|
|
22268
21330
|
return execution;
|
|
22269
21331
|
},
|
|
22270
21332
|
onSuccess: (execution) => {
|
|
22271
|
-
|
|
21333
|
+
toast5({
|
|
22272
21334
|
title: "Fluxo re-executado",
|
|
22273
21335
|
description: `Nova execu\xE7\xE3o iniciada: ${execution.id}`
|
|
22274
21336
|
});
|
|
@@ -22276,7 +21338,7 @@ function WebhookFlowLink({
|
|
|
22276
21338
|
refetch();
|
|
22277
21339
|
},
|
|
22278
21340
|
onError: (error) => {
|
|
22279
|
-
|
|
21341
|
+
toast5({
|
|
22280
21342
|
title: "Erro ao re-executar fluxo",
|
|
22281
21343
|
description: error.message,
|
|
22282
21344
|
variant: "destructive"
|
|
@@ -22501,7 +21563,7 @@ function WebhookLogsViewer({
|
|
|
22501
21563
|
maxLogs = 500,
|
|
22502
21564
|
className
|
|
22503
21565
|
}) {
|
|
22504
|
-
const { toast:
|
|
21566
|
+
const { toast: toast5 } = useToast();
|
|
22505
21567
|
const scrollAreaRef = useRef(null);
|
|
22506
21568
|
const [searchTerm, setSearchTerm] = useState("");
|
|
22507
21569
|
const [selectedLevel, setSelectedLevel] = useState("all");
|
|
@@ -22570,7 +21632,7 @@ function WebhookLogsViewer({
|
|
|
22570
21632
|
});
|
|
22571
21633
|
const handleExport = (format8) => {
|
|
22572
21634
|
if (!filteredLogs || filteredLogs.length === 0) {
|
|
22573
|
-
|
|
21635
|
+
toast5({
|
|
22574
21636
|
title: "Nenhum log para exportar",
|
|
22575
21637
|
description: "N\xE3o h\xE1 logs dispon\xEDveis para exporta\xE7\xE3o",
|
|
22576
21638
|
variant: "destructive"
|
|
@@ -22606,7 +21668,7 @@ function WebhookLogsViewer({
|
|
|
22606
21668
|
linkElement.setAttribute("download", exportFileDefaultName);
|
|
22607
21669
|
linkElement.click();
|
|
22608
21670
|
}
|
|
22609
|
-
|
|
21671
|
+
toast5({
|
|
22610
21672
|
title: "Logs exportados",
|
|
22611
21673
|
description: `${selectedToExport.length} logs exportados com sucesso`
|
|
22612
21674
|
});
|
|
@@ -22632,7 +21694,7 @@ function WebhookLogsViewer({
|
|
|
22632
21694
|
const copyLogToClipboard = (log) => {
|
|
22633
21695
|
const logText = `[${format(log.timestamp, "yyyy-MM-dd HH:mm:ss.SSS")}] [${log.level.toUpperCase()}] ${log.message}`;
|
|
22634
21696
|
navigator.clipboard.writeText(logText);
|
|
22635
|
-
|
|
21697
|
+
toast5({
|
|
22636
21698
|
title: "Log copiado",
|
|
22637
21699
|
description: "Conte\xFAdo do log copiado para a \xE1rea de transfer\xEAncia"
|
|
22638
21700
|
});
|
|
@@ -23358,7 +22420,7 @@ function WebhookTestModal({
|
|
|
23358
22420
|
defaultUrl = "",
|
|
23359
22421
|
defaultEventType = WebhookEventType.MESSAGE_RECEIVED
|
|
23360
22422
|
}) {
|
|
23361
|
-
const { toast:
|
|
22423
|
+
const { toast: toast5 } = useToast();
|
|
23362
22424
|
const [testHistory, setTestHistory] = useState([]);
|
|
23363
22425
|
const [selectedTemplate, setSelectedTemplate] = useState(defaultEventType);
|
|
23364
22426
|
const [activeTab, setActiveTab] = useState("test");
|
|
@@ -23403,12 +22465,12 @@ function WebhookTestModal({
|
|
|
23403
22465
|
};
|
|
23404
22466
|
setTestHistory((prev) => [historyItem, ...prev].slice(0, 10));
|
|
23405
22467
|
if (response.success) {
|
|
23406
|
-
|
|
22468
|
+
toast5({
|
|
23407
22469
|
title: "Teste bem-sucedido",
|
|
23408
22470
|
description: `Webhook respondeu com status ${response.status_code} em ${duration}ms`
|
|
23409
22471
|
});
|
|
23410
22472
|
} else {
|
|
23411
|
-
|
|
22473
|
+
toast5({
|
|
23412
22474
|
title: "Teste falhou",
|
|
23413
22475
|
description: response.error || `Status: ${response.status_code}`,
|
|
23414
22476
|
variant: "destructive"
|
|
@@ -23416,7 +22478,7 @@ function WebhookTestModal({
|
|
|
23416
22478
|
}
|
|
23417
22479
|
},
|
|
23418
22480
|
onError: (error) => {
|
|
23419
|
-
|
|
22481
|
+
toast5({
|
|
23420
22482
|
title: "Erro ao testar webhook",
|
|
23421
22483
|
description: error.message,
|
|
23422
22484
|
variant: "destructive"
|
|
@@ -23434,7 +22496,7 @@ function WebhookTestModal({
|
|
|
23434
22496
|
};
|
|
23435
22497
|
const copyToClipboard = (text) => {
|
|
23436
22498
|
navigator.clipboard.writeText(text);
|
|
23437
|
-
|
|
22499
|
+
toast5({
|
|
23438
22500
|
title: "Copiado!",
|
|
23439
22501
|
description: "Conte\xFAdo copiado para a \xE1rea de transfer\xEAncia"
|
|
23440
22502
|
});
|
|
@@ -24472,7 +23534,7 @@ var QRCodeModal = ({
|
|
|
24472
23534
|
configId,
|
|
24473
23535
|
onConnectionSuccess
|
|
24474
23536
|
}) => {
|
|
24475
|
-
const { toast:
|
|
23537
|
+
const { toast: toast5 } = useToast();
|
|
24476
23538
|
const [qrCodeUrl, setQrCodeUrl] = useState("");
|
|
24477
23539
|
const [timeRemaining, setTimeRemaining] = useState(180);
|
|
24478
23540
|
const [isExpired, setIsExpired] = useState(false);
|
|
@@ -24553,7 +23615,7 @@ var QRCodeModal = ({
|
|
|
24553
23615
|
if (health.connected || health.status === "connected") {
|
|
24554
23616
|
setIsConnected(true);
|
|
24555
23617
|
setCurrentStatus("connected");
|
|
24556
|
-
|
|
23618
|
+
toast5({
|
|
24557
23619
|
title: "WhatsApp Conectado!",
|
|
24558
23620
|
description: `A inst\xE2ncia ${instanceName} foi conectada com sucesso.`,
|
|
24559
23621
|
variant: "default"
|
|
@@ -24572,7 +23634,7 @@ var QRCodeModal = ({
|
|
|
24572
23634
|
} finally {
|
|
24573
23635
|
setCheckingStatus(false);
|
|
24574
23636
|
}
|
|
24575
|
-
}, [configId, checkingStatus, isConnected, isExpired, instanceName, onConnectionSuccess, onClose,
|
|
23637
|
+
}, [configId, checkingStatus, isConnected, isExpired, instanceName, onConnectionSuccess, onClose, toast5]);
|
|
24576
23638
|
useEffect(() => {
|
|
24577
23639
|
if (!open || !configId || isConnected || isExpired) return;
|
|
24578
23640
|
const interval = setInterval(() => {
|
|
@@ -25504,1471 +24566,6 @@ function getNodeIconTextColor({
|
|
|
25504
24566
|
};
|
|
25505
24567
|
return colorMap[status] || "text-purple-600";
|
|
25506
24568
|
}
|
|
25507
|
-
var repository4 = new HttpUnidadeNegocioRepository();
|
|
25508
|
-
function useEmpresasForSelect() {
|
|
25509
|
-
return useQuery({
|
|
25510
|
-
queryKey: ["empresas", "select"],
|
|
25511
|
-
queryFn: async () => {
|
|
25512
|
-
const response = await repository4.getAll();
|
|
25513
|
-
return response.data.map((unidade) => ({
|
|
25514
|
-
value: unidade.cd_unidade_negocio,
|
|
25515
|
-
label: unidade.nome
|
|
25516
|
-
}));
|
|
25517
|
-
},
|
|
25518
|
-
staleTime: 5 * 60 * 1e3
|
|
25519
|
-
// Cache for 5 minutes
|
|
25520
|
-
});
|
|
25521
|
-
}
|
|
25522
|
-
function useFlowEditor({ flowId, onHistorySave }) {
|
|
25523
|
-
const { toast: toast7 } = useToast();
|
|
25524
|
-
const [data, setData] = useState(null);
|
|
25525
|
-
const [loading, setLoading] = useState(true);
|
|
25526
|
-
const [error, setError] = useState(null);
|
|
25527
|
-
const [nodes, setNodes] = useState([]);
|
|
25528
|
-
const [connections, setConnections] = useState([]);
|
|
25529
|
-
const [composites, setComposites] = useState([]);
|
|
25530
|
-
const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
|
|
25531
|
-
const [saving, setSaving] = useState(false);
|
|
25532
|
-
const [selectedNodeId, setSelectedNodeId] = useState(null);
|
|
25533
|
-
const [showPropertiesPanel, setShowPropertiesPanel] = useState(false);
|
|
25534
|
-
const [showAIAgentModal, setShowAIAgentModal] = useState(false);
|
|
25535
|
-
const [aiAgentNodeToEdit, setAIAgentNodeToEdit] = useState(null);
|
|
25536
|
-
const [showSplitModal, setShowSplitModal] = useState(false);
|
|
25537
|
-
const [splitNodeToEdit, setSplitNodeToEdit] = useState(null);
|
|
25538
|
-
const [showLoopModal, setShowLoopModal] = useState(false);
|
|
25539
|
-
const [loopNodeToEdit, setLoopNodeToEdit] = useState(null);
|
|
25540
|
-
const [showCompositeModal, setShowCompositeModal] = useState(false);
|
|
25541
|
-
const [compositeToEdit, setCompositeToEdit] = useState(null);
|
|
25542
|
-
useEffect(() => {
|
|
25543
|
-
compositeNodeManager.registerTemplate(sendMessageWhatsAppTemplate);
|
|
25544
|
-
}, []);
|
|
25545
|
-
useEffect(() => {
|
|
25546
|
-
const fetchFlowDetails = async () => {
|
|
25547
|
-
try {
|
|
25548
|
-
setLoading(true);
|
|
25549
|
-
setError(null);
|
|
25550
|
-
const flowDetails = await flowsService.getFlowWithDetails(flowId);
|
|
25551
|
-
const flow = {
|
|
25552
|
-
id: flowDetails.id,
|
|
25553
|
-
nome: flowDetails.nome,
|
|
25554
|
-
descricao: flowDetails.descricao,
|
|
25555
|
-
ativo: flowDetails.ativo,
|
|
25556
|
-
versao: flowDetails.versao,
|
|
25557
|
-
configuracoes: flowDetails.configuracoes || {},
|
|
25558
|
-
created_at: new Date(flowDetails.created_at),
|
|
25559
|
-
updated_at: new Date(flowDetails.updated_at)
|
|
25560
|
-
};
|
|
25561
|
-
const nodes2 = flowDetails.nodes.map((n) => {
|
|
25562
|
-
const baseNode = {
|
|
25563
|
-
id: n.id,
|
|
25564
|
-
flow_id: n.flow_id,
|
|
25565
|
-
tipo: n.tipo,
|
|
25566
|
-
subtipo: n.subtipo,
|
|
25567
|
-
nome: n.nome,
|
|
25568
|
-
descricao: n.descricao,
|
|
25569
|
-
parametros: n.parametros || {},
|
|
25570
|
-
configuracoes: n.configuracoes || {},
|
|
25571
|
-
posicao: n.posicao,
|
|
25572
|
-
desabilitado: n.desabilitado || false
|
|
25573
|
-
};
|
|
25574
|
-
if (n.tipo === "send_whatsapp_message" && n.subtipo) {
|
|
25575
|
-
return {
|
|
25576
|
-
...baseNode,
|
|
25577
|
-
data: {
|
|
25578
|
-
compositeType: n.subtipo,
|
|
25579
|
-
compositeConfig: n.parametros?.config || n.parametros || n.configuracoes || {}
|
|
25580
|
-
}
|
|
25581
|
-
};
|
|
25582
|
-
}
|
|
25583
|
-
return baseNode;
|
|
25584
|
-
});
|
|
25585
|
-
const connections2 = flowDetails.connections.map((c) => ({
|
|
25586
|
-
id: c.id,
|
|
25587
|
-
flow_id: c.flow_id,
|
|
25588
|
-
node_origem_id: c.node_origem_id,
|
|
25589
|
-
porta_saida: c.porta_saida,
|
|
25590
|
-
node_destino_id: c.node_destino_id,
|
|
25591
|
-
porta_entrada: c.porta_entrada,
|
|
25592
|
-
condicoes: c.condicoes,
|
|
25593
|
-
mapeamento_dados: c.mapeamento_dados
|
|
25594
|
-
}));
|
|
25595
|
-
setData({ flow, nodes: nodes2, connections: connections2 });
|
|
25596
|
-
} catch (err) {
|
|
25597
|
-
console.error("Erro ao carregar fluxo:", err);
|
|
25598
|
-
setError("Erro ao carregar os detalhes do fluxo");
|
|
25599
|
-
} finally {
|
|
25600
|
-
setLoading(false);
|
|
25601
|
-
}
|
|
25602
|
-
};
|
|
25603
|
-
if (flowId) {
|
|
25604
|
-
fetchFlowDetails();
|
|
25605
|
-
}
|
|
25606
|
-
}, [flowId]);
|
|
25607
|
-
useEffect(() => {
|
|
25608
|
-
if (data) {
|
|
25609
|
-
const compositeNodes = data.nodes.filter(
|
|
25610
|
-
(node) => node.tipo === "send_whatsapp_message" && node.subtipo
|
|
25611
|
-
);
|
|
25612
|
-
const regularNodes = data.nodes.filter((node) => node.tipo !== "send_whatsapp_message");
|
|
25613
|
-
const detectedComposites = compositeNodes.map((node) => ({
|
|
25614
|
-
compositeId: node.id,
|
|
25615
|
-
templateId: node.subtipo,
|
|
25616
|
-
config: node.parametros?.config || node.parametros || node.configuracoes || {},
|
|
25617
|
-
nodeIds: [],
|
|
25618
|
-
position: node.posicao
|
|
25619
|
-
}));
|
|
25620
|
-
setComposites(detectedComposites);
|
|
25621
|
-
setNodes(regularNodes);
|
|
25622
|
-
setConnections(data.connections);
|
|
25623
|
-
}
|
|
25624
|
-
}, [data]);
|
|
25625
|
-
const selectedNode = selectedNodeId ? nodes.find((n) => n.id === selectedNodeId) : null;
|
|
25626
|
-
const compositesAsNodes = useMemo(() => {
|
|
25627
|
-
return composites.map((composite) => {
|
|
25628
|
-
const template = compositeNodeManager.getTemplate(composite.templateId);
|
|
25629
|
-
return {
|
|
25630
|
-
id: composite.compositeId,
|
|
25631
|
-
flow_id: flowId,
|
|
25632
|
-
tipo: "send_whatsapp_message",
|
|
25633
|
-
subtipo: composite.templateId,
|
|
25634
|
-
nome: template?.displayName || "N\xF3 Composto",
|
|
25635
|
-
descricao: template?.description,
|
|
25636
|
-
parametros: composite.config,
|
|
25637
|
-
configuracoes: composite.config,
|
|
25638
|
-
posicao: composite.position,
|
|
25639
|
-
desabilitado: false
|
|
25640
|
-
};
|
|
25641
|
-
});
|
|
25642
|
-
}, [composites, flowId]);
|
|
25643
|
-
const saveFlowData = async () => {
|
|
25644
|
-
if (!data) return;
|
|
25645
|
-
await flowsService.updateFlow(flowId, {
|
|
25646
|
-
nome: data.flow.nome,
|
|
25647
|
-
descricao: data.flow.descricao,
|
|
25648
|
-
ativo: data.flow.ativo,
|
|
25649
|
-
configuracoes: data.flow.configuracoes
|
|
25650
|
-
});
|
|
25651
|
-
};
|
|
25652
|
-
const getChangeSets = (existingNodes, existingConnections) => {
|
|
25653
|
-
const compositeFlowNodes = composites.map((composite) => {
|
|
25654
|
-
const template = compositeNodeManager.getTemplate(composite.templateId);
|
|
25655
|
-
return {
|
|
25656
|
-
id: composite.compositeId,
|
|
25657
|
-
flow_id: flowId,
|
|
25658
|
-
tipo: "send_whatsapp_message",
|
|
25659
|
-
subtipo: composite.templateId,
|
|
25660
|
-
nome: template?.displayName || "Composite Node",
|
|
25661
|
-
descricao: template?.description,
|
|
25662
|
-
parametros: {
|
|
25663
|
-
config: composite.config
|
|
25664
|
-
},
|
|
25665
|
-
configuracoes: {},
|
|
25666
|
-
posicao: composite.position,
|
|
25667
|
-
desabilitado: false,
|
|
25668
|
-
metadata: {
|
|
25669
|
-
compositeType: composite.templateId,
|
|
25670
|
-
compositeId: composite.compositeId
|
|
25671
|
-
}
|
|
25672
|
-
};
|
|
25673
|
-
});
|
|
25674
|
-
const expandedNodes = [...nodes, ...compositeFlowNodes];
|
|
25675
|
-
const expandedConnections = connections;
|
|
25676
|
-
const existingNodeIds = new Set(existingNodes.map((n) => n.id));
|
|
25677
|
-
const existingConnectionIds = new Set(existingConnections.map((c) => c.id));
|
|
25678
|
-
return {
|
|
25679
|
-
nodesToCreate: expandedNodes.filter((n) => !existingNodeIds.has(n.id)),
|
|
25680
|
-
nodesToUpdate: expandedNodes.filter((n) => existingNodeIds.has(n.id)),
|
|
25681
|
-
nodeIdsToDelete: existingNodes.filter((n) => !expandedNodes.find((localNode) => localNode.id === n.id)).map((n) => n.id),
|
|
25682
|
-
connectionsToCreate: expandedConnections.filter((c) => !existingConnectionIds.has(c.id)),
|
|
25683
|
-
connectionsToUpdate: expandedConnections.filter((c) => existingConnectionIds.has(c.id)),
|
|
25684
|
-
connectionIdsToDelete: existingConnections.filter((c) => !expandedConnections.find((localConn) => localConn.id === c.id)).map((c) => c.id)
|
|
25685
|
-
};
|
|
25686
|
-
};
|
|
25687
|
-
const createConnectionData = (connection) => {
|
|
25688
|
-
const connectionData = {
|
|
25689
|
-
node_origem_id: connection.node_origem_id,
|
|
25690
|
-
node_destino_id: connection.node_destino_id
|
|
25691
|
-
};
|
|
25692
|
-
const optionalFields = ["porta_saida", "porta_entrada", "condicoes", "mapeamento_dados"];
|
|
25693
|
-
optionalFields.forEach((field) => {
|
|
25694
|
-
if (connection[field] !== void 0) {
|
|
25695
|
-
connectionData[field] = connection[field];
|
|
25696
|
-
}
|
|
25697
|
-
});
|
|
25698
|
-
return connectionData;
|
|
25699
|
-
};
|
|
25700
|
-
const handleSave = async () => {
|
|
25701
|
-
if (!data) return;
|
|
25702
|
-
try {
|
|
25703
|
-
setSaving(true);
|
|
25704
|
-
toast7({
|
|
25705
|
-
title: "Salvando fluxo",
|
|
25706
|
-
description: "Aguarde enquanto o fluxo est\xE1 sendo salvo..."
|
|
25707
|
-
});
|
|
25708
|
-
await saveFlowData();
|
|
25709
|
-
const existingNodes = await flowNodesService.getFlowNodes(flowId);
|
|
25710
|
-
const existingConnections = await flowConnectionsService.getFlowConnections(flowId);
|
|
25711
|
-
const {
|
|
25712
|
-
nodesToCreate,
|
|
25713
|
-
nodesToUpdate,
|
|
25714
|
-
nodeIdsToDelete,
|
|
25715
|
-
connectionsToCreate,
|
|
25716
|
-
connectionsToUpdate,
|
|
25717
|
-
connectionIdsToDelete
|
|
25718
|
-
} = getChangeSets(existingNodes, existingConnections);
|
|
25719
|
-
await Promise.all(
|
|
25720
|
-
connectionIdsToDelete.map((connId) => flowConnectionsService.deleteFlowConnection(connId))
|
|
25721
|
-
);
|
|
25722
|
-
await Promise.all(
|
|
25723
|
-
nodeIdsToDelete.map((nodeId) => flowNodesService.deleteFlowNode(nodeId))
|
|
25724
|
-
);
|
|
25725
|
-
const createdNodesResults = await Promise.all(
|
|
25726
|
-
nodesToCreate.map((node) => flowNodesService.createFlowNode({
|
|
25727
|
-
flow_id: node.flow_id,
|
|
25728
|
-
tipo: node.tipo,
|
|
25729
|
-
subtipo: node.subtipo,
|
|
25730
|
-
nome: node.nome,
|
|
25731
|
-
descricao: node.descricao,
|
|
25732
|
-
parametros: node.parametros,
|
|
25733
|
-
configuracoes: node.configuracoes,
|
|
25734
|
-
posicao: node.posicao,
|
|
25735
|
-
desabilitado: node.desabilitado
|
|
25736
|
-
}))
|
|
25737
|
-
);
|
|
25738
|
-
const tempIdToRealIdMap = /* @__PURE__ */ new Map();
|
|
25739
|
-
nodesToCreate.forEach((node, index) => {
|
|
25740
|
-
if (node.id.startsWith("temp-") && createdNodesResults[index]) {
|
|
25741
|
-
tempIdToRealIdMap.set(node.id, createdNodesResults[index].id);
|
|
25742
|
-
}
|
|
25743
|
-
});
|
|
25744
|
-
if (tempIdToRealIdMap.size > 0) {
|
|
25745
|
-
setNodes((prev) => prev.map((node) => {
|
|
25746
|
-
const realId = tempIdToRealIdMap.get(node.id);
|
|
25747
|
-
return realId ? { ...node, id: realId } : node;
|
|
25748
|
-
}));
|
|
25749
|
-
setConnections((prev) => prev.map((conn) => ({
|
|
25750
|
-
...conn,
|
|
25751
|
-
node_origem_id: tempIdToRealIdMap.get(conn.node_origem_id) || conn.node_origem_id,
|
|
25752
|
-
node_destino_id: tempIdToRealIdMap.get(conn.node_destino_id) || conn.node_destino_id
|
|
25753
|
-
})));
|
|
25754
|
-
}
|
|
25755
|
-
await Promise.all(
|
|
25756
|
-
nodesToUpdate.map((node) => flowNodesService.updateFlowNode(node.id, {
|
|
25757
|
-
tipo: node.tipo,
|
|
25758
|
-
subtipo: node.subtipo,
|
|
25759
|
-
nome: node.nome,
|
|
25760
|
-
descricao: node.descricao,
|
|
25761
|
-
parametros: node.parametros,
|
|
25762
|
-
configuracoes: node.configuracoes,
|
|
25763
|
-
posicao: node.posicao,
|
|
25764
|
-
desabilitado: node.desabilitado
|
|
25765
|
-
}))
|
|
25766
|
-
);
|
|
25767
|
-
const mappedConnectionsToCreate = connectionsToCreate.map((conn) => ({
|
|
25768
|
-
...conn,
|
|
25769
|
-
node_origem_id: tempIdToRealIdMap.get(conn.node_origem_id) || conn.node_origem_id,
|
|
25770
|
-
node_destino_id: tempIdToRealIdMap.get(conn.node_destino_id) || conn.node_destino_id
|
|
25771
|
-
}));
|
|
25772
|
-
const createdConnectionsResults = await Promise.all(
|
|
25773
|
-
mappedConnectionsToCreate.map(
|
|
25774
|
-
(conn) => flowConnectionsService.createFlowConnection(createConnectionData(conn))
|
|
25775
|
-
)
|
|
25776
|
-
);
|
|
25777
|
-
if (createdConnectionsResults.length > 0) {
|
|
25778
|
-
const tempConnIdToRealIdMap = /* @__PURE__ */ new Map();
|
|
25779
|
-
connectionsToCreate.forEach((conn, index) => {
|
|
25780
|
-
if (conn.id.startsWith("temp-conn-") && createdConnectionsResults[index]) {
|
|
25781
|
-
tempConnIdToRealIdMap.set(conn.id, createdConnectionsResults[index].id);
|
|
25782
|
-
}
|
|
25783
|
-
});
|
|
25784
|
-
if (tempConnIdToRealIdMap.size > 0) {
|
|
25785
|
-
setConnections((prev) => prev.map((conn) => {
|
|
25786
|
-
const realConnId = tempConnIdToRealIdMap.get(conn.id);
|
|
25787
|
-
return realConnId ? { ...conn, id: realConnId } : conn;
|
|
25788
|
-
}));
|
|
25789
|
-
}
|
|
25790
|
-
}
|
|
25791
|
-
await Promise.all(
|
|
25792
|
-
connectionsToUpdate.map((conn) => flowConnectionsService.updateFlowConnection(conn.id, {
|
|
25793
|
-
porta_saida: conn.porta_saida,
|
|
25794
|
-
porta_entrada: conn.porta_entrada,
|
|
25795
|
-
condicoes: conn.condicoes,
|
|
25796
|
-
mapeamento_dados: conn.mapeamento_dados
|
|
25797
|
-
}))
|
|
25798
|
-
);
|
|
25799
|
-
toast7({
|
|
25800
|
-
title: "Fluxo salvo",
|
|
25801
|
-
description: "O fluxo foi salvo com sucesso."
|
|
25802
|
-
});
|
|
25803
|
-
setHasUnsavedChanges(false);
|
|
25804
|
-
} catch (error2) {
|
|
25805
|
-
console.error("Erro ao salvar fluxo:", error2);
|
|
25806
|
-
toast7({
|
|
25807
|
-
title: "Erro ao salvar",
|
|
25808
|
-
description: "Ocorreu um erro ao salvar o fluxo. Verifique o console para mais detalhes.",
|
|
25809
|
-
variant: "destructive"
|
|
25810
|
-
});
|
|
25811
|
-
} finally {
|
|
25812
|
-
setSaving(false);
|
|
25813
|
-
}
|
|
25814
|
-
};
|
|
25815
|
-
const handleNodeAdd = async (newNode) => {
|
|
25816
|
-
if (newNode.tipo === "send_whatsapp_message") {
|
|
25817
|
-
const template = compositeNodeManager.getTemplate(newNode.subtipo);
|
|
25818
|
-
if (template) {
|
|
25819
|
-
try {
|
|
25820
|
-
const createdNode = await flowNodesService.createFlowNode({
|
|
25821
|
-
flow_id: flowId,
|
|
25822
|
-
tipo: newNode.tipo,
|
|
25823
|
-
subtipo: newNode.subtipo,
|
|
25824
|
-
nome: newNode.nome || template.displayName,
|
|
25825
|
-
descricao: newNode.descricao || template.description,
|
|
25826
|
-
parametros: newNode.parametros || {},
|
|
25827
|
-
configuracoes: newNode.configuracoes || {},
|
|
25828
|
-
posicao: newNode.posicao,
|
|
25829
|
-
desabilitado: newNode.desabilitado || false
|
|
25830
|
-
});
|
|
25831
|
-
const composite = {
|
|
25832
|
-
compositeId: createdNode.id,
|
|
25833
|
-
templateId: newNode.subtipo,
|
|
25834
|
-
config: {},
|
|
25835
|
-
nodeIds: [],
|
|
25836
|
-
position: newNode.posicao
|
|
25837
|
-
};
|
|
25838
|
-
setCompositeToEdit(composite);
|
|
25839
|
-
setShowCompositeModal(true);
|
|
25840
|
-
setComposites((prev) => [...prev, composite]);
|
|
25841
|
-
setHasUnsavedChanges(true);
|
|
25842
|
-
onHistorySave?.();
|
|
25843
|
-
} catch (error2) {
|
|
25844
|
-
console.error("Erro ao criar n\xF3 composto:", error2);
|
|
25845
|
-
toast7({
|
|
25846
|
-
title: "Erro ao criar n\xF3",
|
|
25847
|
-
description: "N\xE3o foi poss\xEDvel criar o n\xF3 composto.",
|
|
25848
|
-
variant: "destructive"
|
|
25849
|
-
});
|
|
25850
|
-
}
|
|
25851
|
-
}
|
|
25852
|
-
return;
|
|
25853
|
-
}
|
|
25854
|
-
try {
|
|
25855
|
-
const createdNode = await flowNodesService.createFlowNode({
|
|
25856
|
-
flow_id: flowId,
|
|
25857
|
-
tipo: newNode.tipo,
|
|
25858
|
-
subtipo: newNode.subtipo,
|
|
25859
|
-
nome: newNode.nome || "Novo N\xF3",
|
|
25860
|
-
descricao: newNode.descricao,
|
|
25861
|
-
parametros: newNode.parametros || {},
|
|
25862
|
-
configuracoes: newNode.configuracoes || {},
|
|
25863
|
-
posicao: newNode.posicao,
|
|
25864
|
-
desabilitado: newNode.desabilitado || false
|
|
25865
|
-
});
|
|
25866
|
-
const node = {
|
|
25867
|
-
id: createdNode.id,
|
|
25868
|
-
flow_id: flowId,
|
|
25869
|
-
tipo: createdNode.tipo,
|
|
25870
|
-
subtipo: createdNode.subtipo,
|
|
25871
|
-
nome: createdNode.nome,
|
|
25872
|
-
descricao: createdNode.descricao,
|
|
25873
|
-
parametros: createdNode.parametros,
|
|
25874
|
-
configuracoes: createdNode.configuracoes,
|
|
25875
|
-
posicao: createdNode.posicao,
|
|
25876
|
-
desabilitado: createdNode.desabilitado
|
|
25877
|
-
};
|
|
25878
|
-
if (node.tipo === "ai_agent" && node.subtipo === "langchain_agent") {
|
|
25879
|
-
setNodes((prev) => [...prev, node]);
|
|
25880
|
-
setHasUnsavedChanges(true);
|
|
25881
|
-
setAIAgentNodeToEdit(node);
|
|
25882
|
-
setShowAIAgentModal(true);
|
|
25883
|
-
} else if (node.tipo === "split") {
|
|
25884
|
-
setNodes((prev) => [...prev, node]);
|
|
25885
|
-
setHasUnsavedChanges(true);
|
|
25886
|
-
setSplitNodeToEdit(node);
|
|
25887
|
-
setShowSplitModal(true);
|
|
25888
|
-
} else {
|
|
25889
|
-
setNodes((prev) => [...prev, node]);
|
|
25890
|
-
setHasUnsavedChanges(true);
|
|
25891
|
-
}
|
|
25892
|
-
onHistorySave?.();
|
|
25893
|
-
} catch (error2) {
|
|
25894
|
-
console.error("Erro ao criar n\xF3:", error2);
|
|
25895
|
-
toast7({
|
|
25896
|
-
title: "Erro ao criar n\xF3",
|
|
25897
|
-
description: "N\xE3o foi poss\xEDvel criar o n\xF3.",
|
|
25898
|
-
variant: "destructive"
|
|
25899
|
-
});
|
|
25900
|
-
}
|
|
25901
|
-
};
|
|
25902
|
-
const handleNodeDelete = (nodeId) => {
|
|
25903
|
-
const isComposite = composites.some((c) => c.compositeId === nodeId);
|
|
25904
|
-
if (isComposite) {
|
|
25905
|
-
setComposites((prev) => prev.filter((c) => c.compositeId !== nodeId));
|
|
25906
|
-
setHasUnsavedChanges(true);
|
|
25907
|
-
if (selectedNodeId === nodeId) {
|
|
25908
|
-
setSelectedNodeId(null);
|
|
25909
|
-
}
|
|
25910
|
-
onHistorySave?.();
|
|
25911
|
-
return;
|
|
25912
|
-
}
|
|
25913
|
-
setNodes((prev) => prev.filter((n) => n.id !== nodeId));
|
|
25914
|
-
setConnections((prev) => prev.filter(
|
|
25915
|
-
(c) => c.node_origem_id !== nodeId && c.node_destino_id !== nodeId
|
|
25916
|
-
));
|
|
25917
|
-
setHasUnsavedChanges(true);
|
|
25918
|
-
if (selectedNodeId === nodeId) {
|
|
25919
|
-
setSelectedNodeId(null);
|
|
25920
|
-
}
|
|
25921
|
-
onHistorySave?.();
|
|
25922
|
-
};
|
|
25923
|
-
const handleNodeEdit = (nodeId) => {
|
|
25924
|
-
const composite = composites.find((c) => c.compositeId === nodeId);
|
|
25925
|
-
if (composite) {
|
|
25926
|
-
setCompositeToEdit(composite);
|
|
25927
|
-
setShowCompositeModal(true);
|
|
25928
|
-
return;
|
|
25929
|
-
}
|
|
25930
|
-
const node = nodes.find((n) => n.id === nodeId);
|
|
25931
|
-
if (node && node.tipo === "ai_agent" && node.subtipo === "langchain_agent") {
|
|
25932
|
-
setAIAgentNodeToEdit(node);
|
|
25933
|
-
setShowAIAgentModal(true);
|
|
25934
|
-
} else if (node && node.tipo === "split") {
|
|
25935
|
-
setSplitNodeToEdit(node);
|
|
25936
|
-
setShowSplitModal(true);
|
|
25937
|
-
} else if (node && node.tipo === "loop") {
|
|
25938
|
-
setLoopNodeToEdit(node);
|
|
25939
|
-
setShowLoopModal(true);
|
|
25940
|
-
} else {
|
|
25941
|
-
setSelectedNodeId(nodeId);
|
|
25942
|
-
setShowPropertiesPanel(true);
|
|
25943
|
-
}
|
|
25944
|
-
};
|
|
25945
|
-
const handleNodeUpdate = (nodeId, updates) => {
|
|
25946
|
-
setNodes((prev) => prev.map(
|
|
25947
|
-
(node) => node.id === nodeId ? { ...node, ...updates } : node
|
|
25948
|
-
));
|
|
25949
|
-
setHasUnsavedChanges(true);
|
|
25950
|
-
};
|
|
25951
|
-
const handleConnectionAdd = async (newConnection) => {
|
|
25952
|
-
const isSourceTemp = newConnection.node_origem_id?.startsWith("temp-");
|
|
25953
|
-
const isTargetTemp = newConnection.node_destino_id?.startsWith("temp-");
|
|
25954
|
-
if (isSourceTemp || isTargetTemp) {
|
|
25955
|
-
const tempConnection = {
|
|
25956
|
-
id: `temp-conn-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,
|
|
25957
|
-
flow_id: flowId,
|
|
25958
|
-
node_origem_id: newConnection.node_origem_id,
|
|
25959
|
-
node_destino_id: newConnection.node_destino_id,
|
|
25960
|
-
porta_saida: newConnection.porta_saida,
|
|
25961
|
-
porta_entrada: newConnection.porta_entrada,
|
|
25962
|
-
condicoes: newConnection.condicoes,
|
|
25963
|
-
mapeamento_dados: newConnection.mapeamento_dados
|
|
25964
|
-
};
|
|
25965
|
-
setConnections((prev) => [...prev, tempConnection]);
|
|
25966
|
-
setHasUnsavedChanges(true);
|
|
25967
|
-
return;
|
|
25968
|
-
}
|
|
25969
|
-
try {
|
|
25970
|
-
const createdConnection = await flowConnectionsService.createFlowConnection({
|
|
25971
|
-
node_origem_id: newConnection.node_origem_id,
|
|
25972
|
-
node_destino_id: newConnection.node_destino_id,
|
|
25973
|
-
porta_saida: newConnection.porta_saida,
|
|
25974
|
-
porta_entrada: newConnection.porta_entrada,
|
|
25975
|
-
condicoes: newConnection.condicoes,
|
|
25976
|
-
mapeamento_dados: newConnection.mapeamento_dados
|
|
25977
|
-
});
|
|
25978
|
-
const connection = {
|
|
25979
|
-
id: createdConnection.id,
|
|
25980
|
-
flow_id: flowId,
|
|
25981
|
-
node_origem_id: createdConnection.node_origem_id,
|
|
25982
|
-
porta_saida: createdConnection.porta_saida,
|
|
25983
|
-
node_destino_id: createdConnection.node_destino_id,
|
|
25984
|
-
porta_entrada: createdConnection.porta_entrada,
|
|
25985
|
-
condicoes: createdConnection.condicoes,
|
|
25986
|
-
mapeamento_dados: createdConnection.mapeamento_dados
|
|
25987
|
-
};
|
|
25988
|
-
setConnections((prev) => [...prev, connection]);
|
|
25989
|
-
setHasUnsavedChanges(true);
|
|
25990
|
-
} catch (error2) {
|
|
25991
|
-
console.error("Erro ao criar conex\xE3o:", error2);
|
|
25992
|
-
toast7({
|
|
25993
|
-
title: "Erro ao criar conex\xE3o",
|
|
25994
|
-
description: "N\xE3o foi poss\xEDvel criar a conex\xE3o.",
|
|
25995
|
-
variant: "destructive"
|
|
25996
|
-
});
|
|
25997
|
-
}
|
|
25998
|
-
};
|
|
25999
|
-
const handleConnectionDelete = (connectionId) => {
|
|
26000
|
-
setConnections((prev) => prev.filter((conn) => conn.id !== connectionId));
|
|
26001
|
-
setHasUnsavedChanges(true);
|
|
26002
|
-
};
|
|
26003
|
-
const handleNodesChange = (updatedNodes) => {
|
|
26004
|
-
if (Array.isArray(updatedNodes) && updatedNodes.length === nodes.length) {
|
|
26005
|
-
setNodes(updatedNodes);
|
|
26006
|
-
setHasUnsavedChanges(true);
|
|
26007
|
-
}
|
|
26008
|
-
};
|
|
26009
|
-
const handleCompositeNodeSave = (config) => {
|
|
26010
|
-
if (compositeToEdit) {
|
|
26011
|
-
setComposites(
|
|
26012
|
-
(prev) => prev.map(
|
|
26013
|
-
(c) => c.compositeId === compositeToEdit.compositeId ? { ...c, config } : c
|
|
26014
|
-
)
|
|
26015
|
-
);
|
|
26016
|
-
setHasUnsavedChanges(true);
|
|
26017
|
-
}
|
|
26018
|
-
};
|
|
26019
|
-
const handleAIAgentSave = async (config) => {
|
|
26020
|
-
try {
|
|
26021
|
-
if (aiAgentNodeToEdit) {
|
|
26022
|
-
const existingNodes = await flowNodesService.getFlowNodes(flowId);
|
|
26023
|
-
const isNewNode = !existingNodes.find((n) => n.id === aiAgentNodeToEdit.id);
|
|
26024
|
-
if (isNewNode) {
|
|
26025
|
-
await aiAgentService.createNode(flowId, {
|
|
26026
|
-
...config,
|
|
26027
|
-
posicao: aiAgentNodeToEdit.posicao
|
|
26028
|
-
});
|
|
26029
|
-
} else {
|
|
26030
|
-
await aiAgentService.updateNode(aiAgentNodeToEdit.id, {
|
|
26031
|
-
nome: config.nome,
|
|
26032
|
-
descricao: config.descricao,
|
|
26033
|
-
prompt_template: config.prompt_template,
|
|
26034
|
-
llm_config: config.llm_config,
|
|
26035
|
-
tools: config.tools,
|
|
26036
|
-
output_parser: config.output_parser,
|
|
26037
|
-
context_window: config.context_window,
|
|
26038
|
-
retry_on_error: config.retry_on_error,
|
|
26039
|
-
timeout_seconds: config.timeout_seconds
|
|
26040
|
-
});
|
|
26041
|
-
}
|
|
26042
|
-
handleNodeUpdate(aiAgentNodeToEdit.id, {
|
|
26043
|
-
nome: config.nome,
|
|
26044
|
-
descricao: config.descricao,
|
|
26045
|
-
parametros: {
|
|
26046
|
-
...aiAgentNodeToEdit.parametros,
|
|
26047
|
-
nome: config.nome,
|
|
26048
|
-
descricao: config.descricao,
|
|
26049
|
-
prompt_template: config.prompt_template,
|
|
26050
|
-
llm_config: config.llm_config,
|
|
26051
|
-
tools: config.tools,
|
|
26052
|
-
output_parser: config.output_parser,
|
|
26053
|
-
context_window: config.context_window,
|
|
26054
|
-
retry_on_error: config.retry_on_error,
|
|
26055
|
-
timeout_seconds: config.timeout_seconds
|
|
26056
|
-
}
|
|
26057
|
-
});
|
|
26058
|
-
toast7({
|
|
26059
|
-
title: isNewNode ? "N\xF3 AI Agent criado" : "N\xF3 AI Agent atualizado",
|
|
26060
|
-
description: "As configura\xE7\xF5es foram salvas com sucesso."
|
|
26061
|
-
});
|
|
26062
|
-
}
|
|
26063
|
-
} catch (error2) {
|
|
26064
|
-
console.error("Erro ao salvar AI Agent:", error2);
|
|
26065
|
-
toast7({
|
|
26066
|
-
title: "Erro ao salvar",
|
|
26067
|
-
description: "N\xE3o foi poss\xEDvel salvar as configura\xE7\xF5es do AI Agent.",
|
|
26068
|
-
variant: "destructive"
|
|
26069
|
-
});
|
|
26070
|
-
}
|
|
26071
|
-
};
|
|
26072
|
-
return {
|
|
26073
|
-
data,
|
|
26074
|
-
loading,
|
|
26075
|
-
error,
|
|
26076
|
-
nodes,
|
|
26077
|
-
connections,
|
|
26078
|
-
composites,
|
|
26079
|
-
compositesAsNodes,
|
|
26080
|
-
hasUnsavedChanges,
|
|
26081
|
-
saving,
|
|
26082
|
-
selectedNode,
|
|
26083
|
-
selectedNodeId,
|
|
26084
|
-
showPropertiesPanel,
|
|
26085
|
-
showAIAgentModal,
|
|
26086
|
-
aiAgentNodeToEdit,
|
|
26087
|
-
showSplitModal,
|
|
26088
|
-
splitNodeToEdit,
|
|
26089
|
-
showLoopModal,
|
|
26090
|
-
loopNodeToEdit,
|
|
26091
|
-
showCompositeModal,
|
|
26092
|
-
compositeToEdit,
|
|
26093
|
-
setSelectedNodeId,
|
|
26094
|
-
setShowPropertiesPanel,
|
|
26095
|
-
setShowAIAgentModal,
|
|
26096
|
-
setAIAgentNodeToEdit,
|
|
26097
|
-
setShowSplitModal,
|
|
26098
|
-
setSplitNodeToEdit,
|
|
26099
|
-
setShowLoopModal,
|
|
26100
|
-
setLoopNodeToEdit,
|
|
26101
|
-
setShowCompositeModal,
|
|
26102
|
-
setCompositeToEdit,
|
|
26103
|
-
setNodes,
|
|
26104
|
-
setConnections,
|
|
26105
|
-
setComposites,
|
|
26106
|
-
handleSave,
|
|
26107
|
-
handleNodeAdd,
|
|
26108
|
-
handleNodeDelete,
|
|
26109
|
-
handleNodeEdit,
|
|
26110
|
-
handleNodeUpdate,
|
|
26111
|
-
handleConnectionAdd,
|
|
26112
|
-
handleConnectionDelete,
|
|
26113
|
-
handleNodesChange,
|
|
26114
|
-
handleCompositeNodeSave,
|
|
26115
|
-
handleAIAgentSave
|
|
26116
|
-
};
|
|
26117
|
-
}
|
|
26118
|
-
function useFlows() {
|
|
26119
|
-
const [flows, setFlows] = useState([]);
|
|
26120
|
-
const [loading, setLoading] = useState(true);
|
|
26121
|
-
const [error, setError] = useState(null);
|
|
26122
|
-
const loadFlows = async () => {
|
|
26123
|
-
try {
|
|
26124
|
-
setLoading(true);
|
|
26125
|
-
setError(null);
|
|
26126
|
-
const [flowsData, categoriesData] = await Promise.all([
|
|
26127
|
-
flowsService.listFlows(),
|
|
26128
|
-
flowCategoriesService.listFlowCategories()
|
|
26129
|
-
]);
|
|
26130
|
-
const categoriesMap = /* @__PURE__ */ new Map();
|
|
26131
|
-
categoriesData.forEach((category) => {
|
|
26132
|
-
categoriesMap.set(category.id, {
|
|
26133
|
-
id: category.id,
|
|
26134
|
-
nome: category.nome,
|
|
26135
|
-
descricao: category.descricao,
|
|
26136
|
-
icone: category.icone,
|
|
26137
|
-
created_at: new Date(category.created_at),
|
|
26138
|
-
updated_at: new Date(category.updated_at)
|
|
26139
|
-
});
|
|
26140
|
-
});
|
|
26141
|
-
const domainFlows = flowsData.map((flow) => ({
|
|
26142
|
-
id: flow.id,
|
|
26143
|
-
nome: flow.nome,
|
|
26144
|
-
descricao: flow.descricao,
|
|
26145
|
-
category_id: flow.category_id,
|
|
26146
|
-
category: flow.category_id ? categoriesMap.get(flow.category_id) : void 0,
|
|
26147
|
-
ativo: flow.ativo,
|
|
26148
|
-
versao: flow.versao,
|
|
26149
|
-
configuracoes: flow.configuracoes,
|
|
26150
|
-
variaveis_globais: flow.variaveis_globais,
|
|
26151
|
-
created_at: new Date(flow.created_at),
|
|
26152
|
-
updated_at: new Date(flow.updated_at)
|
|
26153
|
-
}));
|
|
26154
|
-
setFlows(domainFlows);
|
|
26155
|
-
} catch (err) {
|
|
26156
|
-
console.error("Erro ao carregar flows:", err);
|
|
26157
|
-
setError(err instanceof Error ? err.message : "Erro desconhecido");
|
|
26158
|
-
} finally {
|
|
26159
|
-
setLoading(false);
|
|
26160
|
-
}
|
|
26161
|
-
};
|
|
26162
|
-
useEffect(() => {
|
|
26163
|
-
loadFlows();
|
|
26164
|
-
}, []);
|
|
26165
|
-
return {
|
|
26166
|
-
flows,
|
|
26167
|
-
loading,
|
|
26168
|
-
error,
|
|
26169
|
-
refetch: loadFlows
|
|
26170
|
-
};
|
|
26171
|
-
}
|
|
26172
|
-
var repository5 = new HttpMotoristaRepository();
|
|
26173
|
-
function useMotorista(cd_motorista, options) {
|
|
26174
|
-
return useQuery({
|
|
26175
|
-
queryKey: ["motorista", cd_motorista],
|
|
26176
|
-
queryFn: () => repository5.getById(cd_motorista),
|
|
26177
|
-
enabled: options?.enabled !== false && !!cd_motorista && cd_motorista > 0
|
|
26178
|
-
});
|
|
26179
|
-
}
|
|
26180
|
-
function useMotoristaByCpf(cpf) {
|
|
26181
|
-
return useQuery({
|
|
26182
|
-
queryKey: ["motorista", "cpf", cpf],
|
|
26183
|
-
queryFn: () => repository5.searchByCpf(cpf),
|
|
26184
|
-
enabled: !!cpf && cpf.length >= 11
|
|
26185
|
-
});
|
|
26186
|
-
}
|
|
26187
|
-
var repository6 = new HttpMotoristaRepository();
|
|
26188
|
-
function useMotoristas(params) {
|
|
26189
|
-
return useQuery({
|
|
26190
|
-
queryKey: ["motoristas", params],
|
|
26191
|
-
queryFn: () => repository6.getAll(params),
|
|
26192
|
-
keepPreviousData: true
|
|
26193
|
-
});
|
|
26194
|
-
}
|
|
26195
|
-
function useMotoristasbyEmpresa(cd_empresa, params) {
|
|
26196
|
-
return useQuery({
|
|
26197
|
-
queryKey: ["motoristas", "empresa", cd_empresa, params],
|
|
26198
|
-
queryFn: () => repository6.getByEmpresa(cd_empresa, params),
|
|
26199
|
-
enabled: !!cd_empresa,
|
|
26200
|
-
keepPreviousData: true
|
|
26201
|
-
});
|
|
26202
|
-
}
|
|
26203
|
-
function useSearchMotoristas(params) {
|
|
26204
|
-
return useQuery({
|
|
26205
|
-
queryKey: ["motoristas", "search", params],
|
|
26206
|
-
queryFn: () => repository6.search(params),
|
|
26207
|
-
enabled: !!params.query || !!params.filters,
|
|
26208
|
-
keepPreviousData: true
|
|
26209
|
-
});
|
|
26210
|
-
}
|
|
26211
|
-
function usePaginatedUsers({
|
|
26212
|
-
initialPageSize = 20,
|
|
26213
|
-
enablePagination = true
|
|
26214
|
-
} = {}) {
|
|
26215
|
-
const { isAuthenticated, user } = useAuthContext();
|
|
26216
|
-
const { currentTenant } = useTenant();
|
|
26217
|
-
const [currentPage, setCurrentPage] = useState(1);
|
|
26218
|
-
const [pageSize, setPageSize] = useState(initialPageSize);
|
|
26219
|
-
const isReady = Boolean(isAuthenticated && user && currentTenant);
|
|
26220
|
-
const { data: allUsers = [], isLoading, error, refetch } = useQuery({
|
|
26221
|
-
queryKey: ["users-all"],
|
|
26222
|
-
queryFn: async () => {
|
|
26223
|
-
return await getAllUsersUseCase.execute({ limit: 1e3 });
|
|
26224
|
-
},
|
|
26225
|
-
enabled: isReady
|
|
26226
|
-
});
|
|
26227
|
-
const totalItems = allUsers.length;
|
|
26228
|
-
const totalPages = enablePagination ? Math.ceil(totalItems / pageSize) : 1;
|
|
26229
|
-
const paginatedUsers = enablePagination ? allUsers.slice((currentPage - 1) * pageSize, currentPage * pageSize) : allUsers;
|
|
26230
|
-
const hasNextPage = enablePagination && currentPage < totalPages;
|
|
26231
|
-
const hasPreviousPage = enablePagination && currentPage > 1;
|
|
26232
|
-
const goToPage = useCallback((page) => {
|
|
26233
|
-
if (page >= 1 && page <= totalPages) {
|
|
26234
|
-
setCurrentPage(page);
|
|
26235
|
-
}
|
|
26236
|
-
}, [totalPages]);
|
|
26237
|
-
const nextPage = useCallback(() => {
|
|
26238
|
-
if (hasNextPage) {
|
|
26239
|
-
setCurrentPage((prev) => prev + 1);
|
|
26240
|
-
}
|
|
26241
|
-
}, [hasNextPage]);
|
|
26242
|
-
const previousPage = useCallback(() => {
|
|
26243
|
-
if (hasPreviousPage) {
|
|
26244
|
-
setCurrentPage((prev) => prev - 1);
|
|
26245
|
-
}
|
|
26246
|
-
}, [hasPreviousPage]);
|
|
26247
|
-
const setPageSizeCallback = useCallback((size) => {
|
|
26248
|
-
setPageSize(size);
|
|
26249
|
-
setCurrentPage(1);
|
|
26250
|
-
}, []);
|
|
26251
|
-
const refresh = useCallback(() => {
|
|
26252
|
-
refetch();
|
|
26253
|
-
}, [refetch]);
|
|
26254
|
-
return {
|
|
26255
|
-
users: paginatedUsers,
|
|
26256
|
-
loading: isLoading,
|
|
26257
|
-
error,
|
|
26258
|
-
// Pagination state
|
|
26259
|
-
currentPage,
|
|
26260
|
-
pageSize,
|
|
26261
|
-
totalItems,
|
|
26262
|
-
totalPages,
|
|
26263
|
-
hasNextPage,
|
|
26264
|
-
hasPreviousPage,
|
|
26265
|
-
// Pagination actions
|
|
26266
|
-
goToPage,
|
|
26267
|
-
nextPage,
|
|
26268
|
-
previousPage,
|
|
26269
|
-
setPageSize: setPageSizeCallback,
|
|
26270
|
-
// Data actions
|
|
26271
|
-
refresh
|
|
26272
|
-
};
|
|
26273
|
-
}
|
|
26274
|
-
function usePerfilUsuario() {
|
|
26275
|
-
const [perfis, setPerfis] = useState([]);
|
|
26276
|
-
const [loading, setLoading] = useState(false);
|
|
26277
|
-
const [error, setError] = useState(null);
|
|
26278
|
-
const refreshPerfis = useCallback(async (filters) => {
|
|
26279
|
-
try {
|
|
26280
|
-
setLoading(true);
|
|
26281
|
-
setError(null);
|
|
26282
|
-
const data = await perfisUsuarioService.listPerfis(filters);
|
|
26283
|
-
setPerfis(data);
|
|
26284
|
-
} catch (err) {
|
|
26285
|
-
const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
|
|
26286
|
-
setError(errorMessage);
|
|
26287
|
-
toast$1.error(`Erro ao carregar perfis: ${errorMessage}`);
|
|
26288
|
-
} finally {
|
|
26289
|
-
setLoading(false);
|
|
26290
|
-
}
|
|
26291
|
-
}, []);
|
|
26292
|
-
const criarPerfil = useCallback(async (data) => {
|
|
26293
|
-
try {
|
|
26294
|
-
const novoPerfil = await perfisUsuarioService.createPerfil(data);
|
|
26295
|
-
setPerfis((prev) => [...prev, novoPerfil]);
|
|
26296
|
-
toast$1.success("Perfil criado com sucesso!");
|
|
26297
|
-
return novoPerfil;
|
|
26298
|
-
} catch (err) {
|
|
26299
|
-
const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
|
|
26300
|
-
toast$1.error(`Erro ao criar perfil: ${errorMessage}`);
|
|
26301
|
-
return null;
|
|
26302
|
-
}
|
|
26303
|
-
}, []);
|
|
26304
|
-
const atualizarPerfil = useCallback(async (id, data) => {
|
|
26305
|
-
try {
|
|
26306
|
-
const perfilAtualizado = await perfisUsuarioService.updatePerfil(id, data);
|
|
26307
|
-
setPerfis((prev) => prev.map(
|
|
26308
|
-
(perfil) => perfil.id === id ? perfilAtualizado : perfil
|
|
26309
|
-
));
|
|
26310
|
-
toast$1.success("Perfil atualizado com sucesso!");
|
|
26311
|
-
return perfilAtualizado;
|
|
26312
|
-
} catch (err) {
|
|
26313
|
-
const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
|
|
26314
|
-
toast$1.error(`Erro ao atualizar perfil: ${errorMessage}`);
|
|
26315
|
-
return null;
|
|
26316
|
-
}
|
|
26317
|
-
}, []);
|
|
26318
|
-
const removerPerfil = useCallback(async (id) => {
|
|
26319
|
-
try {
|
|
26320
|
-
await perfisUsuarioService.deletePerfil(id);
|
|
26321
|
-
setPerfis((prev) => prev.filter((perfil) => perfil.id !== id));
|
|
26322
|
-
toast$1.success("Perfil removido com sucesso!");
|
|
26323
|
-
return true;
|
|
26324
|
-
} catch (err) {
|
|
26325
|
-
const errorMessage = err instanceof Error ? err.message : "Erro desconhecido";
|
|
26326
|
-
toast$1.error(`Erro ao remover perfil: ${errorMessage}`);
|
|
26327
|
-
return false;
|
|
26328
|
-
}
|
|
26329
|
-
}, []);
|
|
26330
|
-
useEffect(() => {
|
|
26331
|
-
}, []);
|
|
26332
|
-
return {
|
|
26333
|
-
perfis,
|
|
26334
|
-
loading,
|
|
26335
|
-
error,
|
|
26336
|
-
refreshPerfis,
|
|
26337
|
-
criarPerfil,
|
|
26338
|
-
atualizarPerfil,
|
|
26339
|
-
removerPerfil
|
|
26340
|
-
};
|
|
26341
|
-
}
|
|
26342
|
-
function usePersistedFilters({ key, defaultFilters = {} }) {
|
|
26343
|
-
const [filters, setFilters] = useState(defaultFilters);
|
|
26344
|
-
const [isLoaded, setIsLoaded] = useState(false);
|
|
26345
|
-
useEffect(() => {
|
|
26346
|
-
try {
|
|
26347
|
-
const savedFilters = localStorage.getItem(`filters_${key}`);
|
|
26348
|
-
if (savedFilters) {
|
|
26349
|
-
const parsedFilters = JSON.parse(savedFilters);
|
|
26350
|
-
const mergedFilters = { ...defaultFilters, ...parsedFilters };
|
|
26351
|
-
setFilters(mergedFilters);
|
|
26352
|
-
} else {
|
|
26353
|
-
setFilters(defaultFilters);
|
|
26354
|
-
}
|
|
26355
|
-
} catch (error) {
|
|
26356
|
-
console.warn(`Erro ao carregar filtros salvos para ${key}:`, error);
|
|
26357
|
-
setFilters(defaultFilters);
|
|
26358
|
-
} finally {
|
|
26359
|
-
setIsLoaded(true);
|
|
26360
|
-
}
|
|
26361
|
-
}, [key, defaultFilters]);
|
|
26362
|
-
const updateFilters = useCallback((newFilters) => {
|
|
26363
|
-
setFilters(newFilters);
|
|
26364
|
-
try {
|
|
26365
|
-
localStorage.setItem(`filters_${key}`, JSON.stringify(newFilters));
|
|
26366
|
-
} catch (error) {
|
|
26367
|
-
console.warn(`Erro ao salvar filtros para ${key}:`, error);
|
|
26368
|
-
}
|
|
26369
|
-
}, [key]);
|
|
26370
|
-
const clearFilters = useCallback(() => {
|
|
26371
|
-
setFilters(defaultFilters);
|
|
26372
|
-
try {
|
|
26373
|
-
localStorage.removeItem(`filters_${key}`);
|
|
26374
|
-
} catch (error) {
|
|
26375
|
-
console.warn(`Erro ao limpar filtros salvos para ${key}:`, error);
|
|
26376
|
-
}
|
|
26377
|
-
}, [key, defaultFilters]);
|
|
26378
|
-
const updateFilter = useCallback((filterKey, value) => {
|
|
26379
|
-
const newFilters = { ...filters, [filterKey]: value };
|
|
26380
|
-
updateFilters(newFilters);
|
|
26381
|
-
}, [filters, updateFilters]);
|
|
26382
|
-
const removeFilter = useCallback((filterKey) => {
|
|
26383
|
-
const newFilters = { ...filters };
|
|
26384
|
-
delete newFilters[filterKey];
|
|
26385
|
-
updateFilters(newFilters);
|
|
26386
|
-
}, [filters, updateFilters]);
|
|
26387
|
-
return {
|
|
26388
|
-
filters,
|
|
26389
|
-
isLoaded,
|
|
26390
|
-
updateFilters,
|
|
26391
|
-
updateFilter,
|
|
26392
|
-
removeFilter,
|
|
26393
|
-
clearFilters
|
|
26394
|
-
};
|
|
26395
|
-
}
|
|
26396
|
-
|
|
26397
|
-
// src/hooks/usePerfilUsuarioFilters.ts
|
|
26398
|
-
var DEFAULT_FILTERS = {
|
|
26399
|
-
nome: ""
|
|
26400
|
-
};
|
|
26401
|
-
function usePerfilUsuarioFilters() {
|
|
26402
|
-
const {
|
|
26403
|
-
filters,
|
|
26404
|
-
updateFilter,
|
|
26405
|
-
clearFilters,
|
|
26406
|
-
isLoaded
|
|
26407
|
-
} = usePersistedFilters({
|
|
26408
|
-
key: "perfil-usuario-filters",
|
|
26409
|
-
defaultFilters: DEFAULT_FILTERS
|
|
26410
|
-
});
|
|
26411
|
-
const toApiFilters = useCallback((uiFilters) => {
|
|
26412
|
-
const apiFilters = {};
|
|
26413
|
-
if (uiFilters.nome.trim()) {
|
|
26414
|
-
apiFilters.nome = uiFilters.nome.trim();
|
|
26415
|
-
}
|
|
26416
|
-
return apiFilters;
|
|
26417
|
-
}, []);
|
|
26418
|
-
const activeFiltersCount = Object.values(filters).filter((value) => {
|
|
26419
|
-
if (typeof value === "string") {
|
|
26420
|
-
return value.trim() !== "";
|
|
26421
|
-
}
|
|
26422
|
-
return false;
|
|
26423
|
-
}).length;
|
|
26424
|
-
const hasActiveFilters = activeFiltersCount > 0;
|
|
26425
|
-
const typedFilters = {
|
|
26426
|
-
nome: String(filters.nome || "")
|
|
26427
|
-
};
|
|
26428
|
-
return {
|
|
26429
|
-
filters: typedFilters,
|
|
26430
|
-
isLoaded,
|
|
26431
|
-
updateFilter,
|
|
26432
|
-
clearFilters,
|
|
26433
|
-
hasActiveFilters,
|
|
26434
|
-
activeFiltersCount,
|
|
26435
|
-
toApiFilters,
|
|
26436
|
-
defaultFilters: DEFAULT_FILTERS
|
|
26437
|
-
};
|
|
26438
|
-
}
|
|
26439
|
-
function usePermissions() {
|
|
26440
|
-
const [loading, setLoading] = useState(false);
|
|
26441
|
-
const [error, setError] = useState(null);
|
|
26442
|
-
const clearError = () => setError(null);
|
|
26443
|
-
const grantPermission = useCallback(async (permissionData) => {
|
|
26444
|
-
try {
|
|
26445
|
-
setLoading(true);
|
|
26446
|
-
clearError();
|
|
26447
|
-
const result = await grantUserUnidadePermissionUseCase.execute(permissionData);
|
|
26448
|
-
return result;
|
|
26449
|
-
} catch (err) {
|
|
26450
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao conceder permiss\xE3o";
|
|
26451
|
-
setError(errorMessage);
|
|
26452
|
-
console.error("Error granting permission:", err);
|
|
26453
|
-
return null;
|
|
26454
|
-
} finally {
|
|
26455
|
-
setLoading(false);
|
|
26456
|
-
}
|
|
26457
|
-
}, []);
|
|
26458
|
-
const grantBulkPermissions = useCallback(async (permissionsData) => {
|
|
26459
|
-
try {
|
|
26460
|
-
setLoading(true);
|
|
26461
|
-
clearError();
|
|
26462
|
-
const result = await grantBulkUserUnidadePermissionsUseCase.execute(permissionsData);
|
|
26463
|
-
return result;
|
|
26464
|
-
} catch (err) {
|
|
26465
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao conceder permiss\xF5es em lote";
|
|
26466
|
-
setError(errorMessage);
|
|
26467
|
-
console.error("Error granting bulk permissions:", err);
|
|
26468
|
-
return null;
|
|
26469
|
-
} finally {
|
|
26470
|
-
setLoading(false);
|
|
26471
|
-
}
|
|
26472
|
-
}, []);
|
|
26473
|
-
const removeUserUnidadePermission = useCallback(async (userId, unidadeCodigo) => {
|
|
26474
|
-
try {
|
|
26475
|
-
setLoading(true);
|
|
26476
|
-
clearError();
|
|
26477
|
-
await removeUserUnidadePermissionUseCase.execute(userId, unidadeCodigo);
|
|
26478
|
-
return true;
|
|
26479
|
-
} catch (err) {
|
|
26480
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao remover permiss\xE3o usu\xE1rio-unidade";
|
|
26481
|
-
setError(errorMessage);
|
|
26482
|
-
console.error("Error removing user-unidade permission:", err);
|
|
26483
|
-
return false;
|
|
26484
|
-
} finally {
|
|
26485
|
-
setLoading(false);
|
|
26486
|
-
}
|
|
26487
|
-
}, []);
|
|
26488
|
-
const getUserUnidades = useCallback(async (userId) => {
|
|
26489
|
-
try {
|
|
26490
|
-
setLoading(true);
|
|
26491
|
-
clearError();
|
|
26492
|
-
const userPermissions = await getUserUnidadesUseCase.execute(userId);
|
|
26493
|
-
return userPermissions;
|
|
26494
|
-
} catch (err) {
|
|
26495
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao carregar unidades do usu\xE1rio";
|
|
26496
|
-
setError(errorMessage);
|
|
26497
|
-
console.error("Error loading user unidades:", err);
|
|
26498
|
-
return null;
|
|
26499
|
-
} finally {
|
|
26500
|
-
setLoading(false);
|
|
26501
|
-
}
|
|
26502
|
-
}, []);
|
|
26503
|
-
const getUnidadeUsers = useCallback(async (unidadeCodigo) => {
|
|
26504
|
-
try {
|
|
26505
|
-
setLoading(true);
|
|
26506
|
-
clearError();
|
|
26507
|
-
const unidadeUsers = await getUnidadeUsersUseCase.execute(unidadeCodigo);
|
|
26508
|
-
return unidadeUsers;
|
|
26509
|
-
} catch (err) {
|
|
26510
|
-
const errorMessage = err instanceof Error ? err.message : "Erro ao carregar usu\xE1rios da unidade";
|
|
26511
|
-
setError(errorMessage);
|
|
26512
|
-
console.error("Error loading unidade users:", err);
|
|
26513
|
-
return null;
|
|
26514
|
-
} finally {
|
|
26515
|
-
setLoading(false);
|
|
26516
|
-
}
|
|
26517
|
-
}, []);
|
|
26518
|
-
return {
|
|
26519
|
-
loading,
|
|
26520
|
-
error,
|
|
26521
|
-
grantPermission,
|
|
26522
|
-
grantBulkPermissions,
|
|
26523
|
-
removeUserUnidadePermission,
|
|
26524
|
-
getUserUnidades,
|
|
26525
|
-
getUnidadeUsers,
|
|
26526
|
-
clearError
|
|
26527
|
-
};
|
|
26528
|
-
}
|
|
26529
|
-
function useUnidadesNegocio(filters) {
|
|
26530
|
-
const queryClient = useQueryClient();
|
|
26531
|
-
const { isAuthenticated, user } = useAuthContext();
|
|
26532
|
-
const { currentTenant } = useTenant();
|
|
26533
|
-
const isReady = Boolean(isAuthenticated && user && currentTenant);
|
|
26534
|
-
const {
|
|
26535
|
-
data: response,
|
|
26536
|
-
isLoading: loading,
|
|
26537
|
-
isFetching,
|
|
26538
|
-
error,
|
|
26539
|
-
refetch: refreshUnidades
|
|
26540
|
-
} = useQuery({
|
|
26541
|
-
queryKey: ["unidades-negocio", filters],
|
|
26542
|
-
queryFn: () => unidadesNegocioService.listUnidadesNegocio({
|
|
26543
|
-
limit: 100,
|
|
26544
|
-
...filters
|
|
26545
|
-
}),
|
|
26546
|
-
enabled: isReady,
|
|
26547
|
-
staleTime: 0,
|
|
26548
|
-
// Sempre recarregar após login
|
|
26549
|
-
gcTime: 10 * 60 * 1e3,
|
|
26550
|
-
// 10 minutos
|
|
26551
|
-
refetchOnMount: "always"
|
|
26552
|
-
});
|
|
26553
|
-
const criarUnidadeMutation = useMutation({
|
|
26554
|
-
mutationFn: (data) => unidadesNegocioService.createUnidadeNegocio(data),
|
|
26555
|
-
onSuccess: () => {
|
|
26556
|
-
queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
|
|
26557
|
-
}
|
|
26558
|
-
});
|
|
26559
|
-
const atualizarUnidadeMutation = useMutation({
|
|
26560
|
-
mutationFn: ({ codigo, data }) => unidadesNegocioService.updateUnidadeNegocio(codigo, data),
|
|
26561
|
-
onSuccess: () => {
|
|
26562
|
-
queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
|
|
26563
|
-
}
|
|
26564
|
-
});
|
|
26565
|
-
const removerUnidadeMutation = useMutation({
|
|
26566
|
-
mutationFn: (codigo) => unidadesNegocioService.deleteUnidadeNegocio(codigo),
|
|
26567
|
-
onSuccess: () => {
|
|
26568
|
-
queryClient.invalidateQueries({ queryKey: ["unidades-negocio"] });
|
|
26569
|
-
}
|
|
26570
|
-
});
|
|
26571
|
-
const criarUnidade = useCallback(
|
|
26572
|
-
async (data) => {
|
|
26573
|
-
await criarUnidadeMutation.mutateAsync(data);
|
|
26574
|
-
},
|
|
26575
|
-
[criarUnidadeMutation]
|
|
26576
|
-
);
|
|
26577
|
-
const atualizarUnidade = useCallback(
|
|
26578
|
-
async (codigo, data) => {
|
|
26579
|
-
await atualizarUnidadeMutation.mutateAsync({ codigo, data });
|
|
26580
|
-
},
|
|
26581
|
-
[atualizarUnidadeMutation]
|
|
26582
|
-
);
|
|
26583
|
-
const removerUnidade = useCallback(
|
|
26584
|
-
async (codigo) => {
|
|
26585
|
-
await removerUnidadeMutation.mutateAsync(codigo);
|
|
26586
|
-
},
|
|
26587
|
-
[removerUnidadeMutation]
|
|
26588
|
-
);
|
|
26589
|
-
const isLoadingOrFetching = loading || isFetching && !response;
|
|
26590
|
-
return {
|
|
26591
|
-
unidades: response?.items || [],
|
|
26592
|
-
loading: isLoadingOrFetching,
|
|
26593
|
-
error: error ? error instanceof Error ? error.message : "Erro ao carregar unidades de neg\xF3cio" : null,
|
|
26594
|
-
total: response?.total || 0,
|
|
26595
|
-
refreshUnidades,
|
|
26596
|
-
criarUnidade,
|
|
26597
|
-
atualizarUnidade,
|
|
26598
|
-
removerUnidade
|
|
26599
|
-
};
|
|
26600
|
-
}
|
|
26601
|
-
var DEFAULT_FILTERS2 = {
|
|
26602
|
-
nome: "",
|
|
26603
|
-
email: "",
|
|
26604
|
-
login: "",
|
|
26605
|
-
ativo: "todos",
|
|
26606
|
-
perfil_ids: "",
|
|
26607
|
-
tipo_usuario_ids: ""
|
|
26608
|
-
};
|
|
26609
|
-
function useUserFilters() {
|
|
26610
|
-
const {
|
|
26611
|
-
filters,
|
|
26612
|
-
updateFilter,
|
|
26613
|
-
updateFilters,
|
|
26614
|
-
clearFilters,
|
|
26615
|
-
isLoaded
|
|
26616
|
-
} = usePersistedFilters({
|
|
26617
|
-
key: "user-management-filters",
|
|
26618
|
-
defaultFilters: DEFAULT_FILTERS2
|
|
26619
|
-
});
|
|
26620
|
-
const toApiFilters = useCallback((uiFilters) => {
|
|
26621
|
-
const apiFilters = {};
|
|
26622
|
-
if (uiFilters.nome.trim()) {
|
|
26623
|
-
apiFilters.nome = uiFilters.nome.trim();
|
|
26624
|
-
}
|
|
26625
|
-
if (uiFilters.email.trim()) {
|
|
26626
|
-
apiFilters.email = uiFilters.email.trim();
|
|
26627
|
-
}
|
|
26628
|
-
if (uiFilters.login.trim()) {
|
|
26629
|
-
apiFilters.login = uiFilters.login.trim();
|
|
26630
|
-
}
|
|
26631
|
-
if (uiFilters.ativo !== "todos") {
|
|
26632
|
-
apiFilters.ativo = uiFilters.ativo === "true";
|
|
26633
|
-
}
|
|
26634
|
-
if (uiFilters.perfil_ids.trim()) {
|
|
26635
|
-
const perfilIds = uiFilters.perfil_ids.split(",").map((id) => parseInt(id.trim())).filter((id) => !isNaN(id));
|
|
26636
|
-
if (perfilIds.length > 0) {
|
|
26637
|
-
apiFilters.perfil_ids = perfilIds;
|
|
26638
|
-
}
|
|
26639
|
-
}
|
|
26640
|
-
if (uiFilters.tipo_usuario_ids.trim()) {
|
|
26641
|
-
const tipoUsuarioIds = uiFilters.tipo_usuario_ids.split(",").map((id) => parseInt(id.trim())).filter((id) => !isNaN(id));
|
|
26642
|
-
if (tipoUsuarioIds.length > 0) {
|
|
26643
|
-
apiFilters.tipo_usuario_ids = tipoUsuarioIds;
|
|
26644
|
-
}
|
|
26645
|
-
}
|
|
26646
|
-
return apiFilters;
|
|
26647
|
-
}, []);
|
|
26648
|
-
const activeFiltersCount = Object.values(filters).filter((value) => {
|
|
26649
|
-
if (typeof value === "string") {
|
|
26650
|
-
return value.trim() !== "" && value !== "todos";
|
|
26651
|
-
}
|
|
26652
|
-
return false;
|
|
26653
|
-
}).length;
|
|
26654
|
-
const hasActiveFilters = activeFiltersCount > 0;
|
|
26655
|
-
const typedFilters = {
|
|
26656
|
-
nome: String(filters.nome || ""),
|
|
26657
|
-
email: String(filters.email || ""),
|
|
26658
|
-
login: String(filters.login || ""),
|
|
26659
|
-
ativo: String(filters.ativo || "todos"),
|
|
26660
|
-
perfil_ids: String(filters.perfil_ids || ""),
|
|
26661
|
-
tipo_usuario_ids: String(filters.tipo_usuario_ids || "")
|
|
26662
|
-
};
|
|
26663
|
-
return {
|
|
26664
|
-
filters: typedFilters,
|
|
26665
|
-
updateFilter,
|
|
26666
|
-
updateFilters,
|
|
26667
|
-
clearFilters,
|
|
26668
|
-
toApiFilters,
|
|
26669
|
-
activeFiltersCount,
|
|
26670
|
-
hasActiveFilters,
|
|
26671
|
-
isLoaded
|
|
26672
|
-
};
|
|
26673
|
-
}
|
|
26674
|
-
function useUserUnidades() {
|
|
26675
|
-
const { user, isAuthenticated } = useAuthContext();
|
|
26676
|
-
const { currentTenant } = useTenant();
|
|
26677
|
-
const getUserId = () => {
|
|
26678
|
-
if (user?.id && user.id > 0) return user.id;
|
|
26679
|
-
if (user?.legacy_user_id && user.legacy_user_id > 0) return user.legacy_user_id;
|
|
26680
|
-
try {
|
|
26681
|
-
const token = localStorage.getItem("access_token") || localStorage.getItem("token");
|
|
26682
|
-
if (token) {
|
|
26683
|
-
const payload = JSON.parse(atob(token.split(".")[1]));
|
|
26684
|
-
const tokenUserId = payload.sub || payload.legacy_user_id || payload.user_id;
|
|
26685
|
-
if (tokenUserId && tokenUserId > 0) {
|
|
26686
|
-
return tokenUserId;
|
|
26687
|
-
}
|
|
26688
|
-
}
|
|
26689
|
-
} catch (error2) {
|
|
26690
|
-
console.error("Error extracting user ID from token:", error2);
|
|
26691
|
-
}
|
|
26692
|
-
return 0;
|
|
26693
|
-
};
|
|
26694
|
-
const userId = getUserId();
|
|
26695
|
-
const isReady = Boolean(isAuthenticated && user && userId && userId > 0 && currentTenant);
|
|
26696
|
-
const { unidades: allUnidades, loading: loadingAllUnidades } = useUnidadesNegocio();
|
|
26697
|
-
const {
|
|
26698
|
-
data: userPermissions,
|
|
26699
|
-
isLoading: loadingPermissions,
|
|
26700
|
-
isFetching: fetchingPermissions,
|
|
26701
|
-
error: permissionsError,
|
|
26702
|
-
refetch: refreshPermissions
|
|
26703
|
-
} = useQuery({
|
|
26704
|
-
queryKey: ["user-unidades", userId],
|
|
26705
|
-
queryFn: () => getUserUnidadesUseCase.execute(userId),
|
|
26706
|
-
enabled: isReady && userId > 0,
|
|
26707
|
-
staleTime: 0,
|
|
26708
|
-
// Sempre recarregar após login
|
|
26709
|
-
gcTime: 10 * 60 * 1e3,
|
|
26710
|
-
// 10 minutos
|
|
26711
|
-
retry: 2,
|
|
26712
|
-
refetchOnMount: "always"
|
|
26713
|
-
});
|
|
26714
|
-
const userUnidades = useMemo(() => {
|
|
26715
|
-
if (!userPermissions || !allUnidades.length) {
|
|
26716
|
-
return [];
|
|
26717
|
-
}
|
|
26718
|
-
if (userPermissions.has_full_access) {
|
|
26719
|
-
return allUnidades;
|
|
26720
|
-
}
|
|
26721
|
-
const allowedUnidadesCodigos = userPermissions.unidades.map((u) => u.codigo);
|
|
26722
|
-
const filteredUnidades = allUnidades.filter(
|
|
26723
|
-
(unidade) => allowedUnidadesCodigos.includes(unidade.codigo)
|
|
26724
|
-
);
|
|
26725
|
-
const mappedUnidades = filteredUnidades.map((unidade) => ({
|
|
26726
|
-
codigo: unidade.codigo,
|
|
26727
|
-
cnpj: unidade.cnpj,
|
|
26728
|
-
descricao: unidade.descricao,
|
|
26729
|
-
ativo: unidade.ativo
|
|
26730
|
-
}));
|
|
26731
|
-
return mappedUnidades;
|
|
26732
|
-
}, [userPermissions, allUnidades]);
|
|
26733
|
-
const isInitialState = isReady && !userPermissions && !allUnidades.length && !permissionsError;
|
|
26734
|
-
const loading = loadingAllUnidades || loadingPermissions || fetchingPermissions || isInitialState;
|
|
26735
|
-
const error = permissionsError ? permissionsError instanceof Error ? permissionsError.message : "Erro ao carregar permiss\xF5es" : null;
|
|
26736
|
-
return {
|
|
26737
|
-
unidades: userUnidades,
|
|
26738
|
-
loading,
|
|
26739
|
-
error,
|
|
26740
|
-
refreshUserUnidades: refreshPermissions
|
|
26741
|
-
};
|
|
26742
|
-
}
|
|
26743
|
-
var useUsers = () => {
|
|
26744
|
-
const queryClient = useQueryClient();
|
|
26745
|
-
const { isAuthenticated, user } = useAuthContext();
|
|
26746
|
-
const { currentTenant } = useTenant();
|
|
26747
|
-
const isReady = Boolean(isAuthenticated && user && currentTenant);
|
|
26748
|
-
const getAllUsers = useQuery({
|
|
26749
|
-
queryKey: ["users"],
|
|
26750
|
-
queryFn: async () => {
|
|
26751
|
-
return await getAllUsersUseCase.execute({ limit: 1e3 });
|
|
26752
|
-
},
|
|
26753
|
-
enabled: isReady
|
|
26754
|
-
});
|
|
26755
|
-
const createUser = useMutation({
|
|
26756
|
-
mutationFn: async (userData) => {
|
|
26757
|
-
return await createUserUseCase.execute(userData);
|
|
26758
|
-
},
|
|
26759
|
-
onSuccess: () => {
|
|
26760
|
-
queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
26761
|
-
}
|
|
26762
|
-
});
|
|
26763
|
-
const updateUser = useMutation({
|
|
26764
|
-
mutationFn: async ({ id, userData }) => {
|
|
26765
|
-
return await updateUserUseCase.execute(id, userData);
|
|
26766
|
-
},
|
|
26767
|
-
onSuccess: (_, { id }) => {
|
|
26768
|
-
queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
26769
|
-
queryClient.invalidateQueries({ queryKey: ["user", id] });
|
|
26770
|
-
}
|
|
26771
|
-
});
|
|
26772
|
-
const deleteUser = useMutation({
|
|
26773
|
-
mutationFn: async (id) => {
|
|
26774
|
-
return await deleteUserUseCase.execute(id);
|
|
26775
|
-
},
|
|
26776
|
-
onSuccess: () => {
|
|
26777
|
-
queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
26778
|
-
}
|
|
26779
|
-
});
|
|
26780
|
-
const activateUser = useMutation({
|
|
26781
|
-
mutationFn: async (id) => {
|
|
26782
|
-
return await activateUserUseCase.execute(id);
|
|
26783
|
-
},
|
|
26784
|
-
onSuccess: (_, id) => {
|
|
26785
|
-
queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
26786
|
-
queryClient.invalidateQueries({ queryKey: ["user", id] });
|
|
26787
|
-
}
|
|
26788
|
-
});
|
|
26789
|
-
const deactivateUser = useMutation({
|
|
26790
|
-
mutationFn: async (id) => {
|
|
26791
|
-
return await deactivateUserUseCase.execute(id);
|
|
26792
|
-
},
|
|
26793
|
-
onSuccess: (_, id) => {
|
|
26794
|
-
queryClient.invalidateQueries({ queryKey: ["users"] });
|
|
26795
|
-
queryClient.invalidateQueries({ queryKey: ["user", id] });
|
|
26796
|
-
}
|
|
26797
|
-
});
|
|
26798
|
-
return {
|
|
26799
|
-
// Queries
|
|
26800
|
-
getAllUsers,
|
|
26801
|
-
// Mutations
|
|
26802
|
-
createUser,
|
|
26803
|
-
updateUser,
|
|
26804
|
-
deleteUser,
|
|
26805
|
-
activateUser,
|
|
26806
|
-
deactivateUser,
|
|
26807
|
-
// Derived data for compatibility
|
|
26808
|
-
users: getAllUsers.data || [],
|
|
26809
|
-
loading: getAllUsers.isLoading || createUser.isPending || updateUser.isPending || deleteUser.isPending || activateUser.isPending || deactivateUser.isPending,
|
|
26810
|
-
error: getAllUsers.error || createUser.error || updateUser.error || deleteUser.error || activateUser.error || deactivateUser.error,
|
|
26811
|
-
clearError: () => {
|
|
26812
|
-
queryClient.resetQueries({ queryKey: ["users"] });
|
|
26813
|
-
}
|
|
26814
|
-
};
|
|
26815
|
-
};
|
|
26816
|
-
var useUserById = (id) => {
|
|
26817
|
-
const { isAuthenticated, user } = useAuthContext();
|
|
26818
|
-
const { currentTenant } = useTenant();
|
|
26819
|
-
const isReady = Boolean(isAuthenticated && user && currentTenant);
|
|
26820
|
-
return useQuery({
|
|
26821
|
-
queryKey: ["user", id],
|
|
26822
|
-
queryFn: async () => {
|
|
26823
|
-
return await getUserByIdUseCase.execute(id);
|
|
26824
|
-
},
|
|
26825
|
-
enabled: isReady && !!id
|
|
26826
|
-
});
|
|
26827
|
-
};
|
|
26828
|
-
function useWebhookEvents(options = {}) {
|
|
26829
|
-
const { filter: initialFilter, pollingInterval = 5e3, enabled = true } = options;
|
|
26830
|
-
const queryClient = useQueryClient();
|
|
26831
|
-
const [filter, setFilter] = useState(initialFilter || {});
|
|
26832
|
-
const [events, setEvents] = useState([]);
|
|
26833
|
-
const [isLoadingMore, setIsLoadingMore] = useState(false);
|
|
26834
|
-
const queryKey = ["webhookEvents", filter];
|
|
26835
|
-
const { data, isLoading, isError, error, refetch } = useQuery({
|
|
26836
|
-
queryKey,
|
|
26837
|
-
queryFn: () => httpWebhookRepository.getEvents(filter),
|
|
26838
|
-
enabled,
|
|
26839
|
-
refetchInterval: pollingInterval,
|
|
26840
|
-
staleTime: 2e3
|
|
26841
|
-
});
|
|
26842
|
-
useEffect(() => {
|
|
26843
|
-
if (data?.events) {
|
|
26844
|
-
if (filter.offset === 0 || !filter.offset) {
|
|
26845
|
-
setEvents(data.events);
|
|
26846
|
-
} else {
|
|
26847
|
-
setEvents((prev) => [...prev, ...data.events]);
|
|
26848
|
-
}
|
|
26849
|
-
}
|
|
26850
|
-
}, [data, filter.offset]);
|
|
26851
|
-
const retryMutation = useMutation({
|
|
26852
|
-
mutationFn: (eventId) => httpWebhookRepository.retryEvent(eventId),
|
|
26853
|
-
onSuccess: (updatedEvent) => {
|
|
26854
|
-
queryClient.invalidateQueries({ queryKey });
|
|
26855
|
-
toast$1.success("Evento reenviado com sucesso");
|
|
26856
|
-
setEvents((prev) => prev.map(
|
|
26857
|
-
(event) => event.id === updatedEvent.id ? updatedEvent : event
|
|
26858
|
-
));
|
|
26859
|
-
},
|
|
26860
|
-
onError: (error2) => {
|
|
26861
|
-
toast$1.error("Erro ao reenviar evento: " + error2.message);
|
|
26862
|
-
}
|
|
26863
|
-
});
|
|
26864
|
-
const cancelMutation = useMutation({
|
|
26865
|
-
mutationFn: (eventId) => httpWebhookRepository.cancelEvent(eventId),
|
|
26866
|
-
onSuccess: (_, eventId) => {
|
|
26867
|
-
queryClient.invalidateQueries({ queryKey });
|
|
26868
|
-
toast$1.success("Evento cancelado com sucesso");
|
|
26869
|
-
setEvents((prev) => prev.filter((event) => event.id !== eventId));
|
|
26870
|
-
},
|
|
26871
|
-
onError: (error2) => {
|
|
26872
|
-
toast$1.error("Erro ao cancelar evento: " + error2.message);
|
|
26873
|
-
}
|
|
26874
|
-
});
|
|
26875
|
-
const retryEvent = useCallback(async (eventId) => {
|
|
26876
|
-
await retryMutation.mutateAsync(eventId);
|
|
26877
|
-
}, [retryMutation]);
|
|
26878
|
-
const cancelEvent = useCallback(async (eventId) => {
|
|
26879
|
-
await cancelMutation.mutateAsync(eventId);
|
|
26880
|
-
}, [cancelMutation]);
|
|
26881
|
-
const loadMore = useCallback(() => {
|
|
26882
|
-
if (!isLoadingMore && data?.hasMore) {
|
|
26883
|
-
setIsLoadingMore(true);
|
|
26884
|
-
const newFilter = {
|
|
26885
|
-
...filter,
|
|
26886
|
-
offset: (filter.offset || 0) + (filter.limit || 20)
|
|
26887
|
-
};
|
|
26888
|
-
setFilter(newFilter);
|
|
26889
|
-
setIsLoadingMore(false);
|
|
26890
|
-
}
|
|
26891
|
-
}, [filter, data?.hasMore, isLoadingMore]);
|
|
26892
|
-
const updateFilter = useCallback((newFilter) => {
|
|
26893
|
-
setFilter(newFilter);
|
|
26894
|
-
setEvents([]);
|
|
26895
|
-
}, []);
|
|
26896
|
-
return {
|
|
26897
|
-
events,
|
|
26898
|
-
total: data?.total || 0,
|
|
26899
|
-
hasMore: data?.hasMore || false,
|
|
26900
|
-
isLoading,
|
|
26901
|
-
isError,
|
|
26902
|
-
error,
|
|
26903
|
-
refetch,
|
|
26904
|
-
retryEvent,
|
|
26905
|
-
cancelEvent,
|
|
26906
|
-
loadMore,
|
|
26907
|
-
isLoadingMore,
|
|
26908
|
-
updateFilter
|
|
26909
|
-
};
|
|
26910
|
-
}
|
|
26911
|
-
function useWebhookEventDetails(eventId) {
|
|
26912
|
-
return useQuery({
|
|
26913
|
-
queryKey: ["webhookEvent", eventId],
|
|
26914
|
-
queryFn: () => eventId ? httpWebhookRepository.getEventById(eventId) : null,
|
|
26915
|
-
enabled: !!eventId,
|
|
26916
|
-
staleTime: 1e4
|
|
26917
|
-
});
|
|
26918
|
-
}
|
|
26919
|
-
function useWebhookEventMetrics(instanceId, startDate, endDate) {
|
|
26920
|
-
return useQuery({
|
|
26921
|
-
queryKey: ["webhookMetrics", instanceId, startDate, endDate],
|
|
26922
|
-
queryFn: () => httpWebhookRepository.getMetrics(instanceId, startDate, endDate),
|
|
26923
|
-
refetchInterval: 3e4,
|
|
26924
|
-
staleTime: 1e4
|
|
26925
|
-
});
|
|
26926
|
-
}
|
|
26927
|
-
function useWebhookSubscriptions() {
|
|
26928
|
-
const queryClient = useQueryClient();
|
|
26929
|
-
const { data: subscriptions, ...query } = useQuery({
|
|
26930
|
-
queryKey: ["webhookSubscriptions"],
|
|
26931
|
-
queryFn: () => httpWebhookRepository.getSubscriptions(),
|
|
26932
|
-
staleTime: 3e4
|
|
26933
|
-
});
|
|
26934
|
-
const createMutation = useMutation({
|
|
26935
|
-
mutationFn: httpWebhookRepository.createSubscription,
|
|
26936
|
-
onSuccess: () => {
|
|
26937
|
-
queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
|
|
26938
|
-
toast$1.success("Inscri\xE7\xE3o criada com sucesso");
|
|
26939
|
-
},
|
|
26940
|
-
onError: (error) => {
|
|
26941
|
-
toast$1.error("Erro ao criar inscri\xE7\xE3o: " + error.message);
|
|
26942
|
-
}
|
|
26943
|
-
});
|
|
26944
|
-
const updateMutation = useMutation({
|
|
26945
|
-
mutationFn: ({ id, updates }) => httpWebhookRepository.updateSubscription(id, updates),
|
|
26946
|
-
onSuccess: () => {
|
|
26947
|
-
queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
|
|
26948
|
-
toast$1.success("Inscri\xE7\xE3o atualizada com sucesso");
|
|
26949
|
-
},
|
|
26950
|
-
onError: (error) => {
|
|
26951
|
-
toast$1.error("Erro ao atualizar inscri\xE7\xE3o: " + error.message);
|
|
26952
|
-
}
|
|
26953
|
-
});
|
|
26954
|
-
const deleteMutation = useMutation({
|
|
26955
|
-
mutationFn: httpWebhookRepository.deleteSubscription,
|
|
26956
|
-
onSuccess: () => {
|
|
26957
|
-
queryClient.invalidateQueries({ queryKey: ["webhookSubscriptions"] });
|
|
26958
|
-
toast$1.success("Inscri\xE7\xE3o removida com sucesso");
|
|
26959
|
-
},
|
|
26960
|
-
onError: (error) => {
|
|
26961
|
-
toast$1.error("Erro ao remover inscri\xE7\xE3o: " + error.message);
|
|
26962
|
-
}
|
|
26963
|
-
});
|
|
26964
|
-
return {
|
|
26965
|
-
subscriptions: subscriptions || [],
|
|
26966
|
-
...query,
|
|
26967
|
-
createSubscription: createMutation.mutate,
|
|
26968
|
-
updateSubscription: updateMutation.mutate,
|
|
26969
|
-
deleteSubscription: deleteMutation.mutate
|
|
26970
|
-
};
|
|
26971
|
-
}
|
|
26972
24569
|
|
|
26973
24570
|
// src/types/mcp.types.ts
|
|
26974
24571
|
var MCPCategoryToNodeType = {
|
|
@@ -27117,6 +24714,6 @@ var WebhookMetricsMapper = class {
|
|
|
27117
24714
|
}
|
|
27118
24715
|
};
|
|
27119
24716
|
|
|
27120
|
-
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,
|
|
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 };
|
|
27121
24718
|
//# sourceMappingURL=index.js.map
|
|
27122
24719
|
//# sourceMappingURL=index.js.map
|