Add alerts ssytems to the frontend
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import React, { createContext, useContext, useEffect, useRef, useState, ReactNode } from 'react';
|
||||
import { useAuthStore } from '../stores/auth.store';
|
||||
import { useUIStore } from '../stores/ui.store';
|
||||
import { useCurrentTenant } from '../stores/tenant.store';
|
||||
|
||||
interface SSEEvent {
|
||||
type: string;
|
||||
@@ -41,18 +42,28 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
||||
|
||||
const { isAuthenticated, token } = useAuthStore();
|
||||
const { showToast } = useUIStore();
|
||||
const currentTenant = useCurrentTenant();
|
||||
|
||||
const connect = () => {
|
||||
if (!isAuthenticated || !token || eventSourceRef.current) return;
|
||||
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
// Get tenant ID from store - no fallback
|
||||
const tenantId = currentTenant?.id;
|
||||
|
||||
if (!tenantId) {
|
||||
console.log('No tenant ID available, skipping SSE connection');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const eventSource = new EventSource(`http://localhost:8000/api/events?token=${token}`, {
|
||||
// Connect to notification service SSE endpoint with token
|
||||
const eventSource = new EventSource(`http://localhost:8006/api/v1/sse/alerts/stream/${tenantId}?token=${encodeURIComponent(token)}`, {
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
@@ -69,41 +80,158 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
||||
|
||||
eventSource.onmessage = (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
// Handle different SSE message types from notification service
|
||||
if (data.status === 'keepalive') {
|
||||
console.log('SSE keepalive received');
|
||||
return;
|
||||
}
|
||||
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'message',
|
||||
data: JSON.parse(event.data),
|
||||
timestamp: new Date().toISOString(),
|
||||
type: data.item_type || 'message',
|
||||
data: data,
|
||||
timestamp: data.timestamp || new Date().toISOString(),
|
||||
};
|
||||
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
|
||||
// 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,
|
||||
});
|
||||
}
|
||||
|
||||
// Trigger registered listeners
|
||||
const listeners = eventListenersRef.current.get('message');
|
||||
const listeners = eventListenersRef.current.get(sseEvent.type);
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(sseEvent.data));
|
||||
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));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing SSE message:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle connection events from backend
|
||||
eventSource.addEventListener('connection', (event) => {
|
||||
// Handle connection confirmation from notification service
|
||||
eventSource.addEventListener('connected', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
console.log('SSE connection confirmed:', data.message);
|
||||
console.log('SSE connection confirmed:', data);
|
||||
} catch (error) {
|
||||
console.error('Error parsing connection event:', error);
|
||||
console.error('Error parsing connected event:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle heartbeat events
|
||||
eventSource.addEventListener('heartbeat', (event) => {
|
||||
// Handle ping events (keepalive)
|
||||
eventSource.addEventListener('ping', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
console.log('SSE heartbeat received:', new Date(data.timestamp * 1000));
|
||||
console.log('SSE ping received:', data.timestamp);
|
||||
} catch (error) {
|
||||
console.error('Error parsing heartbeat event:', error);
|
||||
console.error('Error parsing ping event:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// 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);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle alert events
|
||||
eventSource.addEventListener('alert', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'alert',
|
||||
data,
|
||||
timestamp: data.timestamp || new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Show alert toast
|
||||
let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
|
||||
if (data.severity === 'urgent') toastType = 'error';
|
||||
else if (data.severity === 'high') toastType = 'error';
|
||||
else if (data.severity === 'medium') toastType = 'warning';
|
||||
else toastType = 'info';
|
||||
|
||||
showToast({
|
||||
type: toastType,
|
||||
title: data.title || 'Alerta',
|
||||
message: data.message,
|
||||
duration: data.severity === 'urgent' ? 0 : 5000,
|
||||
});
|
||||
|
||||
// Trigger listeners
|
||||
const listeners = eventListenersRef.current.get('alert');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing alert event:', error);
|
||||
}
|
||||
});
|
||||
|
||||
// Handle recommendation events
|
||||
eventSource.addEventListener('recommendation', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'recommendation',
|
||||
data,
|
||||
timestamp: data.timestamp || new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Show recommendation toast
|
||||
showToast({
|
||||
type: 'info',
|
||||
title: data.title || 'Recomendación',
|
||||
message: data.message,
|
||||
duration: 5000,
|
||||
});
|
||||
|
||||
// Trigger listeners
|
||||
const listeners = eventListenersRef.current.get('recommendation');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing recommendation event:', error);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -124,96 +252,6 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
||||
}
|
||||
};
|
||||
|
||||
// Handle notification events (alerts and recommendations from alert_processor)
|
||||
eventSource.addEventListener('notification', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'notification',
|
||||
data,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Determine toast type based on severity and 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';
|
||||
}
|
||||
|
||||
// Show toast notification
|
||||
showToast({
|
||||
type: toastType,
|
||||
title: data.title || 'Notificación',
|
||||
message: data.message,
|
||||
duration: data.severity === 'urgent' ? 0 : 5000, // Keep urgent alerts until dismissed
|
||||
});
|
||||
|
||||
// Trigger registered listeners
|
||||
const listeners = eventListenersRef.current.get('notification');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing notification event:', error);
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.addEventListener('inventory_alert', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'inventory_alert',
|
||||
data,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Show inventory alert (high/urgent alerts from alert_processor)
|
||||
showToast({
|
||||
type: data.severity === 'urgent' ? 'error' : 'warning',
|
||||
title: data.title || 'Alerta de Inventario',
|
||||
message: data.message,
|
||||
duration: 0, // Keep until dismissed
|
||||
});
|
||||
|
||||
// Trigger registered listeners
|
||||
const listeners = eventListenersRef.current.get('inventory_alert');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing inventory alert:', error);
|
||||
}
|
||||
});
|
||||
|
||||
eventSource.addEventListener('production_update', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'production_update',
|
||||
data,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Trigger registered listeners
|
||||
const listeners = eventListenersRef.current.get('production_update');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing production update:', error);
|
||||
}
|
||||
});
|
||||
|
||||
eventSourceRef.current = eventSource;
|
||||
} catch (error) {
|
||||
@@ -256,9 +294,9 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
||||
};
|
||||
};
|
||||
|
||||
// Connect when authenticated, disconnect when not
|
||||
// Connect when authenticated, disconnect when not or when tenant changes
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && token) {
|
||||
if (isAuthenticated && token && currentTenant) {
|
||||
connect();
|
||||
} else {
|
||||
disconnect();
|
||||
@@ -267,7 +305,7 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
|
||||
return () => {
|
||||
disconnect();
|
||||
};
|
||||
}, [isAuthenticated, token]);
|
||||
}, [isAuthenticated, token, currentTenant?.id]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
Reference in New Issue
Block a user