demo seed change

This commit is contained in:
Urtzi Alfaro
2025-12-13 23:57:54 +01:00
parent f3688dfb04
commit ff830a3415
299 changed files with 20328 additions and 19485 deletions

View File

@@ -2,6 +2,7 @@ import React, { createContext, useContext, useEffect, useRef, useState, ReactNod
import { useAuthStore } from '../stores/auth.store';
import { useCurrentTenant } from '../stores/tenant.store';
import { showToast } from '../utils/toast';
import i18n from '../i18n';
interface SSEEvent {
type: string;
@@ -151,14 +152,41 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
toastType = 'info';
}
// Show toast with enriched data
const title = data.title || 'Alerta';
// Translate title and message using i18n keys
let title = 'Alerta';
let message = 'Nueva alerta';
if (data.i18n?.title_key) {
// Extract namespace from key (e.g., "alerts.critical_stock_shortage.title" -> namespace: "alerts", key: "critical_stock_shortage.title")
const titleParts = data.i18n.title_key.split('.');
const titleNamespace = titleParts[0];
const titleKey = titleParts.slice(1).join('.');
title = String(i18n.t(titleKey, {
ns: titleNamespace,
...data.i18n.title_params,
defaultValue: data.i18n.title_key
}));
}
if (data.i18n?.message_key) {
// Extract namespace from key (e.g., "alerts.critical_stock_shortage.message_generic" -> namespace: "alerts", key: "critical_stock_shortage.message_generic")
const messageParts = data.i18n.message_key.split('.');
const messageNamespace = messageParts[0];
const messageKey = messageParts.slice(1).join('.');
message = String(i18n.t(messageKey, {
ns: messageNamespace,
...data.i18n.message_params,
defaultValue: data.i18n.message_key
}));
}
const duration = data.priority_level === 'critical' ? 0 : 5000;
// Add financial impact to message if available
let message = data.message;
if (data.business_impact?.financial_impact_eur) {
message = `${data.message} • €${data.business_impact.financial_impact_eur} en riesgo`;
message = `${message} • €${data.business_impact.financial_impact_eur} en riesgo`;
}
showToast[toastType](message, { title, duration });
@@ -176,6 +204,209 @@ export const SSEProvider: React.FC<SSEProviderProps> = ({ children }) => {
}
});
// Handle notification events (from various services)
eventSource.addEventListener('notification', (event) => {
try {
const data = JSON.parse(event.data);
const sseEvent: SSEEvent = {
type: 'notification',
data,
timestamp: data.timestamp || new Date().toISOString(),
};
setLastEvent(sseEvent);
// Determine toast type based on notification priority or type
let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
// Use type_class if available from the new event architecture
if (data.type_class) {
if (data.type_class === 'success' || data.type_class === 'completed') {
toastType = 'success';
} else if (data.type_class === 'error') {
toastType = 'error';
} else if (data.type_class === 'warning') {
toastType = 'warning';
} else if (data.type_class === 'info') {
toastType = 'info';
}
} else {
// Fallback to priority_level for legacy compatibility
if (data.priority_level === 'critical') {
toastType = 'error';
} else if (data.priority_level === 'important') {
toastType = 'warning';
} else if (data.priority_level === 'standard') {
toastType = 'info';
}
}
// Translate title and message using i18n keys
let title = 'Notificación';
let message = 'Nueva notificación recibida';
if (data.i18n?.title_key) {
// Extract namespace from key
const titleParts = data.i18n.title_key.split('.');
const titleNamespace = titleParts[0];
const titleKey = titleParts.slice(1).join('.');
title = String(i18n.t(titleKey, {
ns: titleNamespace,
...data.i18n.title_params,
defaultValue: data.i18n.title_key
}));
} else if (data.title || data.subject) {
// Fallback to legacy fields if i18n not available
title = data.title || data.subject;
}
if (data.i18n?.message_key) {
// Extract namespace from key
const messageParts = data.i18n.message_key.split('.');
const messageNamespace = messageParts[0];
const messageKey = messageParts.slice(1).join('.');
message = String(i18n.t(messageKey, {
ns: messageNamespace,
...data.i18n.message_params,
defaultValue: data.i18n.message_key
}));
} else if (data.message || data.content || data.description) {
// Fallback to legacy fields if i18n not available
message = data.message || data.content || data.description;
}
// Add entity context to message if available
if (data.entity_links && Object.keys(data.entity_links).length > 0) {
const entityInfo = Object.entries(data.entity_links)
.map(([type, id]) => `${type}: ${id}`)
.join(', ');
message = `${message} (${entityInfo})`;
}
// Add state change information if available
if (data.old_state && data.new_state) {
message = `${message} - ${data.old_state}${data.new_state}`;
}
const duration = data.priority_level === 'critical' ? 0 : 5000;
showToast[toastType](message, { title, duration });
// Trigger listeners with notification data
// Wrap in queueMicrotask to prevent setState during render warnings
const listeners = eventListenersRef.current.get('notification');
if (listeners) {
listeners.forEach(callback => {
queueMicrotask(() => callback(data));
});
}
} catch (error) {
console.error('Error parsing notification event:', error);
}
});
// Handle recommendation events (AI-driven insights)
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);
// Recommendations are typically positive insights
let toastType: 'info' | 'success' | 'warning' | 'error' = 'info';
// Use type_class if available from the new event architecture
if (data.type_class) {
if (data.type_class === 'opportunity' || data.type_class === 'insight') {
toastType = 'success';
} else if (data.type_class === 'error') {
toastType = 'error';
} else if (data.type_class === 'warning') {
toastType = 'warning';
} else if (data.type_class === 'info') {
toastType = 'info';
}
} else {
// Fallback to priority_level for legacy compatibility
if (data.priority_level === 'critical') {
toastType = 'error';
} else if (data.priority_level === 'important') {
toastType = 'warning';
} else {
toastType = 'info';
}
}
// Translate title and message using i18n keys
let title = 'Recomendación';
let message = 'Nueva recomendación del sistema AI';
if (data.i18n?.title_key) {
// Extract namespace from key
const titleParts = data.i18n.title_key.split('.');
const titleNamespace = titleParts[0];
const titleKey = titleParts.slice(1).join('.');
title = String(i18n.t(titleKey, {
ns: titleNamespace,
...data.i18n.title_params,
defaultValue: data.i18n.title_key
}));
} else if (data.title) {
// Fallback to legacy field if i18n not available
title = data.title;
}
if (data.i18n?.message_key) {
// Extract namespace from key
const messageParts = data.i18n.message_key.split('.');
const messageNamespace = messageParts[0];
const messageKey = messageParts.slice(1).join('.');
message = String(i18n.t(messageKey, {
ns: messageNamespace,
...data.i18n.message_params,
defaultValue: data.i18n.message_key
}));
} else if (data.message) {
// Fallback to legacy field if i18n not available
message = data.message;
}
// Add estimated impact if available
if (data.estimated_impact) {
const impact = data.estimated_impact;
if (impact.savings_eur) {
message = `${message} • €${impact.savings_eur} de ahorro estimado`;
} else if (impact.risk_reduction_percent) {
message = `${message}${impact.risk_reduction_percent}% reducción de riesgo`;
}
}
const duration = 5000; // Recommendations are typically informational
showToast[toastType](message, { title, duration });
// Trigger listeners with recommendation data
// Wrap in queueMicrotask to prevent setState during render warnings
const listeners = eventListenersRef.current.get('recommendation');
if (listeners) {
listeners.forEach(callback => {
queueMicrotask(() => callback(data));
});
}
} catch (error) {
console.error('Error parsing recommendation event:', error);
}
});
eventSource.onerror = (error) => {
console.error('SSE connection error:', error);
setIsConnected(false);