2025-08-28 10:41:04 +02:00
|
|
|
import React, { createContext, useContext, useEffect, useRef, useState, ReactNode } from 'react';
|
|
|
|
|
import { useAuthStore } from '../stores/auth.store';
|
|
|
|
|
import { useUIStore } from '../stores/ui.store';
|
2025-09-21 17:35:36 +02:00
|
|
|
import { useCurrentTenant } from '../stores/tenant.store';
|
2025-08-28 10:41:04 +02:00
|
|
|
|
|
|
|
|
interface SSEEvent {
|
|
|
|
|
type: string;
|
|
|
|
|
data: any;
|
|
|
|
|
timestamp: string;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
interface SSEContextType {
|
|
|
|
|
isConnected: boolean;
|
|
|
|
|
lastEvent: SSEEvent | null;
|
|
|
|
|
connect: () => void;
|
|
|
|
|
disconnect: () => void;
|
|
|
|
|
addEventListener: (eventType: string, callback: (data: any) => void) => () => void;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const SSEContext = createContext<SSEContextType | undefined>(undefined);
|
|
|
|
|
|
|
|
|
|
export const useSSE = () => {
|
|
|
|
|
const context = useContext(SSEContext);
|
|
|
|
|
if (context === undefined) {
|
|
|
|
|
throw new Error('useSSE must be used within an SSEProvider');
|
|
|
|
|
}
|
|
|
|
|
return context;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
interface SSEProviderProps {
|
|
|
|
|
children: ReactNode;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
|
|
|
|
const [isConnected, setIsConnected] = useState(false);
|
|
|
|
|
const [lastEvent, setLastEvent] = useState<SSEEvent | null>(null);
|
|
|
|
|
|
|
|
|
|
const eventSourceRef = useRef<EventSource | null>(null);
|
|
|
|
|
const eventListenersRef = useRef<Map<string, Set<(data: any) => void>>>(new Map());
|
|
|
|
|
const reconnectTimeoutRef = useRef<NodeJS.Timeout>();
|
|
|
|
|
const reconnectAttempts = useRef(0);
|
|
|
|
|
|
|
|
|
|
const { isAuthenticated, token } = useAuthStore();
|
|
|
|
|
const { showToast } = useUIStore();
|
2025-09-21 17:35:36 +02:00
|
|
|
const currentTenant = useCurrentTenant();
|
2025-08-28 10:41:04 +02:00
|
|
|
|
|
|
|
|
const connect = () => {
|
|
|
|
|
if (!isAuthenticated || !token || eventSourceRef.current) return;
|
2025-09-21 17:35:36 +02:00
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
// Skip SSE connection for demo/development mode when no backend is available
|
|
|
|
|
if (token === 'mock-jwt-token') {
|
|
|
|
|
console.log('SSE connection skipped for demo mode');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Get tenant ID from store - no fallback
|
|
|
|
|
const tenantId = currentTenant?.id;
|
|
|
|
|
|
|
|
|
|
if (!tenantId) {
|
|
|
|
|
console.log('No tenant ID available, skipping SSE connection');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
try {
|
2025-09-21 17:35:36 +02:00
|
|
|
// Connect to notification service SSE endpoint with token
|
|
|
|
|
const eventSource = new EventSource(`http://localhost:8006/api/v1/sse/alerts/stream/${tenantId}?token=${encodeURIComponent(token)}`, {
|
2025-08-28 10:41:04 +02:00
|
|
|
withCredentials: true,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
eventSource.onopen = () => {
|
|
|
|
|
console.log('SSE connection opened');
|
|
|
|
|
setIsConnected(true);
|
|
|
|
|
reconnectAttempts.current = 0;
|
|
|
|
|
|
|
|
|
|
if (reconnectTimeoutRef.current) {
|
|
|
|
|
clearTimeout(reconnectTimeoutRef.current);
|
|
|
|
|
reconnectTimeoutRef.current = undefined;
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
eventSource.onmessage = (event) => {
|
|
|
|
|
try {
|
2025-09-21 17:35:36 +02:00
|
|
|
const data = JSON.parse(event.data);
|
|
|
|
|
|
|
|
|
|
// Handle different SSE message types from notification service
|
|
|
|
|
if (data.status === 'keepalive') {
|
|
|
|
|
console.log('SSE keepalive received');
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
const sseEvent: SSEEvent = {
|
2025-09-21 17:35:36 +02:00
|
|
|
type: data.item_type || 'message',
|
|
|
|
|
data: data,
|
|
|
|
|
timestamp: data.timestamp || new Date().toISOString(),
|
2025-08-28 10:41:04 +02:00
|
|
|
};
|
2025-09-21 17:35:36 +02:00
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
setLastEvent(sseEvent);
|
2025-09-21 17:35:36 +02:00
|
|
|
|
|
|
|
|
// Show notification if it's an alert or recommendation
|
|
|
|
|
if (data.item_type && ['alert', 'recommendation'].includes(data.item_type)) {
|
|
|
|
|
let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
|
|
|
|
|
|
|
|
|
|
if (data.item_type === 'alert') {
|
|
|
|
|
if (data.severity === 'urgent') toastType = 'error';
|
|
|
|
|
else if (data.severity === 'high') toastType = 'error';
|
|
|
|
|
else if (data.severity === 'medium') toastType = 'warning';
|
|
|
|
|
else toastType = 'info';
|
|
|
|
|
} else if (data.item_type === 'recommendation') {
|
|
|
|
|
toastType = 'info';
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
showToast({
|
|
|
|
|
type: toastType,
|
|
|
|
|
title: data.title || 'Notificación',
|
|
|
|
|
message: data.message,
|
|
|
|
|
duration: data.severity === 'urgent' ? 0 : 5000,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
// Trigger registered listeners
|
2025-09-21 17:35:36 +02:00
|
|
|
const listeners = eventListenersRef.current.get(sseEvent.type);
|
2025-08-28 10:41:04 +02:00
|
|
|
if (listeners) {
|
2025-09-21 17:35:36 +02:00
|
|
|
listeners.forEach(callback => callback(data));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Also trigger 'message' listeners for backward compatibility
|
|
|
|
|
const messageListeners = eventListenersRef.current.get('message');
|
|
|
|
|
if (messageListeners) {
|
|
|
|
|
messageListeners.forEach(callback => callback(data));
|
2025-08-28 10:41:04 +02:00
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error parsing SSE message:', error);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Handle connection confirmation from notification service
|
|
|
|
|
eventSource.addEventListener('connected', (event) => {
|
2025-09-04 23:19:53 +02:00
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(event.data);
|
2025-09-21 17:35:36 +02:00
|
|
|
console.log('SSE connection confirmed:', data);
|
2025-09-04 23:19:53 +02:00
|
|
|
} catch (error) {
|
2025-09-21 17:35:36 +02:00
|
|
|
console.error('Error parsing connected event:', error);
|
2025-09-04 23:19:53 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Handle ping events (keepalive)
|
|
|
|
|
eventSource.addEventListener('ping', (event) => {
|
2025-09-04 23:19:53 +02:00
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(event.data);
|
2025-09-21 17:35:36 +02:00
|
|
|
console.log('SSE ping received:', data.timestamp);
|
2025-09-04 23:19:53 +02:00
|
|
|
} catch (error) {
|
2025-09-21 17:35:36 +02:00
|
|
|
console.error('Error parsing ping event:', error);
|
2025-09-04 23:19:53 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Handle initial items
|
|
|
|
|
eventSource.addEventListener('initial_items', (event) => {
|
|
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(event.data);
|
|
|
|
|
console.log('Initial items received:', data);
|
|
|
|
|
|
|
|
|
|
// Trigger listeners for initial data
|
|
|
|
|
const listeners = eventListenersRef.current.get('initial_items');
|
|
|
|
|
if (listeners) {
|
|
|
|
|
listeners.forEach(callback => callback(data));
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Error parsing initial_items event:', error);
|
2025-08-28 10:41:04 +02:00
|
|
|
}
|
2025-09-21 17:35:36 +02:00
|
|
|
});
|
2025-08-28 10:41:04 +02:00
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Handle alert events
|
|
|
|
|
eventSource.addEventListener('alert', (event) => {
|
2025-08-28 10:41:04 +02:00
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(event.data);
|
|
|
|
|
const sseEvent: SSEEvent = {
|
2025-09-21 17:35:36 +02:00
|
|
|
type: 'alert',
|
2025-08-28 10:41:04 +02:00
|
|
|
data,
|
2025-09-21 17:35:36 +02:00
|
|
|
timestamp: data.timestamp || new Date().toISOString(),
|
2025-08-28 10:41:04 +02:00
|
|
|
};
|
2025-09-21 17:35:36 +02:00
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
setLastEvent(sseEvent);
|
2025-09-21 17:35:36 +02:00
|
|
|
|
|
|
|
|
// Show alert toast
|
2025-09-04 23:19:53 +02:00
|
|
|
let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
|
2025-09-21 17:35:36 +02:00
|
|
|
if (data.severity === 'urgent') toastType = 'error';
|
|
|
|
|
else if (data.severity === 'high') toastType = 'error';
|
|
|
|
|
else if (data.severity === 'medium') toastType = 'warning';
|
|
|
|
|
else toastType = 'info';
|
|
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
showToast({
|
2025-09-04 23:19:53 +02:00
|
|
|
type: toastType,
|
2025-09-21 17:35:36 +02:00
|
|
|
title: data.title || 'Alerta',
|
2025-08-28 10:41:04 +02:00
|
|
|
message: data.message,
|
2025-09-21 17:35:36 +02:00
|
|
|
duration: data.severity === 'urgent' ? 0 : 5000,
|
2025-08-28 10:41:04 +02:00
|
|
|
});
|
2025-09-21 17:35:36 +02:00
|
|
|
|
|
|
|
|
// Trigger listeners
|
|
|
|
|
const listeners = eventListenersRef.current.get('alert');
|
2025-08-28 10:41:04 +02:00
|
|
|
if (listeners) {
|
|
|
|
|
listeners.forEach(callback => callback(data));
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
2025-09-21 17:35:36 +02:00
|
|
|
console.error('Error parsing alert event:', error);
|
2025-08-28 10:41:04 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Handle recommendation events
|
|
|
|
|
eventSource.addEventListener('recommendation', (event) => {
|
2025-08-28 10:41:04 +02:00
|
|
|
try {
|
|
|
|
|
const data = JSON.parse(event.data);
|
|
|
|
|
const sseEvent: SSEEvent = {
|
2025-09-21 17:35:36 +02:00
|
|
|
type: 'recommendation',
|
2025-08-28 10:41:04 +02:00
|
|
|
data,
|
2025-09-21 17:35:36 +02:00
|
|
|
timestamp: data.timestamp || new Date().toISOString(),
|
2025-08-28 10:41:04 +02:00
|
|
|
};
|
2025-09-21 17:35:36 +02:00
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
setLastEvent(sseEvent);
|
2025-09-21 17:35:36 +02:00
|
|
|
|
|
|
|
|
// Show recommendation toast
|
2025-08-28 10:41:04 +02:00
|
|
|
showToast({
|
2025-09-21 17:35:36 +02:00
|
|
|
type: 'info',
|
|
|
|
|
title: data.title || 'Recomendación',
|
2025-08-28 10:41:04 +02:00
|
|
|
message: data.message,
|
2025-09-21 17:35:36 +02:00
|
|
|
duration: 5000,
|
2025-08-28 10:41:04 +02:00
|
|
|
});
|
2025-09-21 17:35:36 +02:00
|
|
|
|
|
|
|
|
// Trigger listeners
|
|
|
|
|
const listeners = eventListenersRef.current.get('recommendation');
|
2025-08-28 10:41:04 +02:00
|
|
|
if (listeners) {
|
|
|
|
|
listeners.forEach(callback => callback(data));
|
|
|
|
|
}
|
|
|
|
|
} catch (error) {
|
2025-09-21 17:35:36 +02:00
|
|
|
console.error('Error parsing recommendation event:', error);
|
2025-08-28 10:41:04 +02:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
eventSource.onerror = (error) => {
|
|
|
|
|
console.error('SSE connection error:', error);
|
|
|
|
|
setIsConnected(false);
|
|
|
|
|
|
|
|
|
|
if (eventSource.readyState === EventSource.CLOSED) {
|
|
|
|
|
// Attempt reconnection with exponential backoff
|
|
|
|
|
const delay = Math.min(1000 * Math.pow(2, reconnectAttempts.current), 30000);
|
|
|
|
|
reconnectAttempts.current++;
|
2025-08-28 10:41:04 +02:00
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
reconnectTimeoutRef.current = setTimeout(() => {
|
|
|
|
|
if (isAuthenticated && token) {
|
|
|
|
|
connect();
|
|
|
|
|
}
|
|
|
|
|
}, delay);
|
2025-08-28 10:41:04 +02:00
|
|
|
}
|
2025-09-21 17:35:36 +02:00
|
|
|
};
|
|
|
|
|
|
2025-08-28 10:41:04 +02:00
|
|
|
|
|
|
|
|
eventSourceRef.current = eventSource;
|
|
|
|
|
} catch (error) {
|
|
|
|
|
console.error('Failed to establish SSE connection:', error);
|
|
|
|
|
setIsConnected(false);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const disconnect = () => {
|
|
|
|
|
if (eventSourceRef.current) {
|
|
|
|
|
eventSourceRef.current.close();
|
|
|
|
|
eventSourceRef.current = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (reconnectTimeoutRef.current) {
|
|
|
|
|
clearTimeout(reconnectTimeoutRef.current);
|
|
|
|
|
reconnectTimeoutRef.current = undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
setIsConnected(false);
|
|
|
|
|
reconnectAttempts.current = 0;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const addEventListener = (eventType: string, callback: (data: any) => void) => {
|
|
|
|
|
if (!eventListenersRef.current.has(eventType)) {
|
|
|
|
|
eventListenersRef.current.set(eventType, new Set());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
eventListenersRef.current.get(eventType)!.add(callback);
|
|
|
|
|
|
|
|
|
|
// Return cleanup function
|
|
|
|
|
return () => {
|
|
|
|
|
const listeners = eventListenersRef.current.get(eventType);
|
|
|
|
|
if (listeners) {
|
|
|
|
|
listeners.delete(callback);
|
|
|
|
|
if (listeners.size === 0) {
|
|
|
|
|
eventListenersRef.current.delete(eventType);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
2025-09-21 17:35:36 +02:00
|
|
|
// Connect when authenticated, disconnect when not or when tenant changes
|
2025-08-28 10:41:04 +02:00
|
|
|
useEffect(() => {
|
2025-09-21 17:35:36 +02:00
|
|
|
if (isAuthenticated && token && currentTenant) {
|
2025-08-28 10:41:04 +02:00
|
|
|
connect();
|
|
|
|
|
} else {
|
|
|
|
|
disconnect();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
|
disconnect();
|
|
|
|
|
};
|
2025-09-21 17:35:36 +02:00
|
|
|
}, [isAuthenticated, token, currentTenant?.id]);
|
2025-08-28 10:41:04 +02:00
|
|
|
|
|
|
|
|
// Cleanup on unmount
|
|
|
|
|
useEffect(() => {
|
|
|
|
|
return () => {
|
|
|
|
|
disconnect();
|
|
|
|
|
};
|
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
|
|
const contextValue: SSEContextType = {
|
|
|
|
|
isConnected,
|
|
|
|
|
lastEvent,
|
|
|
|
|
connect,
|
|
|
|
|
disconnect,
|
|
|
|
|
addEventListener,
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
return (
|
|
|
|
|
<SSEContext.Provider value={contextValue}>
|
|
|
|
|
{children}
|
|
|
|
|
</SSEContext.Provider>
|
|
|
|
|
);
|
|
|
|
|
};
|