ADD new frontend
This commit is contained in:
97
frontend/src/contexts/AuthContext.tsx
Normal file
97
frontend/src/contexts/AuthContext.tsx
Normal file
@@ -0,0 +1,97 @@
|
||||
import React, { createContext, useContext, useEffect, ReactNode } from 'react';
|
||||
import { useAuthStore, User } from '../stores/auth.store';
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null;
|
||||
isAuthenticated: boolean;
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
login: (email: string, password: string) => Promise<void>;
|
||||
logout: () => void;
|
||||
refreshAuth: () => Promise<void>;
|
||||
clearError: () => void;
|
||||
hasPermission: (permission: string) => boolean;
|
||||
hasRole: (role: string) => boolean;
|
||||
canAccess: (resource: string, action: string) => boolean;
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined);
|
||||
|
||||
export const useAuth = () => {
|
||||
const context = useContext(AuthContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useAuth must be used within an AuthProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
interface AuthProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
|
||||
const authStore = useAuthStore();
|
||||
|
||||
// Initialize auth on mount
|
||||
useEffect(() => {
|
||||
const initializeAuth = async () => {
|
||||
// Check if we have stored auth data
|
||||
const storedAuth = localStorage.getItem('auth-storage');
|
||||
if (storedAuth) {
|
||||
try {
|
||||
const { state } = JSON.parse(storedAuth);
|
||||
if (state.token && state.user) {
|
||||
// Validate token by attempting to refresh
|
||||
try {
|
||||
await authStore.refreshAuth();
|
||||
} catch (error) {
|
||||
// Token is invalid, clear auth
|
||||
authStore.logout();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing stored auth:', error);
|
||||
authStore.logout();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initializeAuth();
|
||||
}, []);
|
||||
|
||||
// Set up token refresh interval
|
||||
useEffect(() => {
|
||||
if (authStore.isAuthenticated && authStore.token) {
|
||||
const refreshInterval = setInterval(() => {
|
||||
if (authStore.refreshToken) {
|
||||
authStore.refreshAuth().catch(() => {
|
||||
// Refresh failed, logout user
|
||||
authStore.logout();
|
||||
});
|
||||
}
|
||||
}, 14 * 60 * 1000); // Refresh every 14 minutes
|
||||
|
||||
return () => clearInterval(refreshInterval);
|
||||
}
|
||||
}, [authStore.isAuthenticated, authStore.token, authStore.refreshToken]);
|
||||
|
||||
const contextValue: AuthContextType = {
|
||||
user: authStore.user,
|
||||
isAuthenticated: authStore.isAuthenticated,
|
||||
isLoading: authStore.isLoading,
|
||||
error: authStore.error,
|
||||
login: authStore.login,
|
||||
logout: authStore.logout,
|
||||
refreshAuth: authStore.refreshAuth,
|
||||
clearError: authStore.clearError,
|
||||
hasPermission: authStore.hasPermission,
|
||||
hasRole: authStore.hasRole,
|
||||
canAccess: authStore.canAccess,
|
||||
};
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
261
frontend/src/contexts/SSEContext.tsx
Normal file
261
frontend/src/contexts/SSEContext.tsx
Normal file
@@ -0,0 +1,261 @@
|
||||
import React, { createContext, useContext, useEffect, useRef, useState, ReactNode } from 'react';
|
||||
import { useAuthStore } from '../stores/auth.store';
|
||||
import { useUIStore } from '../stores/ui.store';
|
||||
|
||||
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();
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
try {
|
||||
const eventSource = new EventSource(`/api/events?token=${token}`, {
|
||||
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 {
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'message',
|
||||
data: JSON.parse(event.data),
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Trigger registered listeners
|
||||
const listeners = eventListenersRef.current.get('message');
|
||||
if (listeners) {
|
||||
listeners.forEach(callback => callback(sseEvent.data));
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error parsing SSE message:', error);
|
||||
}
|
||||
};
|
||||
|
||||
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++;
|
||||
|
||||
reconnectTimeoutRef.current = setTimeout(() => {
|
||||
if (isAuthenticated && token) {
|
||||
connect();
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
};
|
||||
|
||||
// Handle custom event types
|
||||
eventSource.addEventListener('notification', (event) => {
|
||||
try {
|
||||
const data = JSON.parse(event.data);
|
||||
const sseEvent: SSEEvent = {
|
||||
type: 'notification',
|
||||
data,
|
||||
timestamp: new Date().toISOString(),
|
||||
};
|
||||
|
||||
setLastEvent(sseEvent);
|
||||
|
||||
// Show toast notification
|
||||
showToast({
|
||||
type: data.type || 'info',
|
||||
title: data.title || 'Notificación',
|
||||
message: data.message,
|
||||
duration: data.persistent ? 0 : 5000,
|
||||
});
|
||||
|
||||
// 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
|
||||
showToast({
|
||||
type: 'warning',
|
||||
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) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Connect when authenticated, disconnect when not
|
||||
useEffect(() => {
|
||||
if (isAuthenticated && token) {
|
||||
connect();
|
||||
} else {
|
||||
disconnect();
|
||||
}
|
||||
|
||||
return () => {
|
||||
disconnect();
|
||||
};
|
||||
}, [isAuthenticated, token]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const contextValue: SSEContextType = {
|
||||
isConnected,
|
||||
lastEvent,
|
||||
connect,
|
||||
disconnect,
|
||||
addEventListener,
|
||||
};
|
||||
|
||||
return (
|
||||
<SSEContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</SSEContext.Provider>
|
||||
);
|
||||
};
|
||||
46
frontend/src/contexts/ThemeContext.tsx
Normal file
46
frontend/src/contexts/ThemeContext.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import React, { createContext, useContext } from 'react';
|
||||
import { useUIStore } from '../stores/ui.store';
|
||||
|
||||
interface ThemeContextType {
|
||||
theme: 'light' | 'dark' | 'auto';
|
||||
setTheme: (theme: 'light' | 'dark' | 'auto') => void;
|
||||
resolvedTheme: 'light' | 'dark';
|
||||
}
|
||||
|
||||
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
||||
|
||||
export const useTheme = () => {
|
||||
const context = useContext(ThemeContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useTheme must be used within a ThemeProvider');
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
interface ThemeProviderProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
export const ThemeProvider: React.FC<ThemeProviderProps> = ({ children }) => {
|
||||
const { theme, setTheme } = useUIStore();
|
||||
|
||||
// Calculate resolved theme based on current theme and system preference
|
||||
const getResolvedTheme = (): 'light' | 'dark' => {
|
||||
if (theme === 'auto') {
|
||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
}
|
||||
return theme as 'light' | 'dark';
|
||||
};
|
||||
|
||||
const contextValue: ThemeContextType = {
|
||||
theme,
|
||||
setTheme,
|
||||
resolvedTheme: getResolvedTheme(),
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={contextValue}>
|
||||
{children}
|
||||
</ThemeContext.Provider>
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user