add: añadir funcionalidad de guardar y ver historial si estás logeado
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import { AppRouter } from './routers/AppRouter';
|
import AppRouter from './routers/AppRouter';
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
|
|||||||
@@ -1,54 +1,123 @@
|
|||||||
import { Outlet, Link } from 'react-router-dom';
|
import { useState } from 'react';
|
||||||
import { useAuth } from '../../context/AuthContext';
|
import { Link, useNavigate, useLocation } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../../context/AuthContext';
|
||||||
|
|
||||||
export default function MainLayout() {
|
export default function MainLayout({ children }) {
|
||||||
const { user, isAuthenticated, logout } = useAuth();
|
const [isDropdownOpen, setIsDropdownOpen] = useState(false);
|
||||||
|
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const location = useLocation();
|
||||||
|
|
||||||
|
const { user, logout, isAuthenticated } = useAuth();
|
||||||
|
|
||||||
|
const userInitial = user?.username ? user.username[0].toUpperCase() : "U";
|
||||||
|
|
||||||
|
const handleLogout = () => {
|
||||||
|
logout();
|
||||||
|
setIsDropdownOpen(false);
|
||||||
|
navigate('/login');
|
||||||
|
};
|
||||||
|
|
||||||
|
const isActive = (path) => {
|
||||||
|
return location.pathname === path || (path === '/editor' && location.pathname === '/');
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen bg-slate-50 flex flex-col">
|
<div className="min-h-screen bg-slate-50 font-sans">
|
||||||
|
{/* HEADER */}
|
||||||
<header className="bg-white border-b border-slate-200 sticky top-0 z-50">
|
<header className="bg-white shadow-sm border-b border-slate-200 sticky top-0 z-50">
|
||||||
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
|
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between">
|
||||||
|
|
||||||
<Link to="/" className="flex items-center gap-3 group">
|
{/* Logo / Título */}
|
||||||
<div className="w-10 h-10 bg-blue-600 rounded-xl flex items-center justify-center text-white font-bold text-xl shadow-sm group-hover:bg-blue-700 transition-colors">
|
<Link to="/" className="flex items-center gap-2 hover:opacity-80 transition-opacity">
|
||||||
DoC
|
<span className="text-2xl font-black bg-clip-text text-transparent bg-gradient-to-r from-blue-600 to-indigo-600">
|
||||||
</div>
|
|
||||||
<span className="text-xl font-bold text-slate-800 tracking-tight group-hover:text-blue-600 transition-colors">
|
|
||||||
Deck of Cards
|
Deck of Cards
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<div>
|
{/* Navegación y Usuario */}
|
||||||
{isAuthenticated ? (
|
<div className="flex items-center gap-4">
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<div
|
{/* LINKS PRINCIPALES */}
|
||||||
className="w-10 h-10 bg-indigo-100 text-indigo-700 rounded-full flex items-center justify-center font-bold text-lg shadow-sm border border-indigo-200 cursor-pointer hover:bg-indigo-200 transition-colors"
|
<div className="flex items-center gap-1 mr-4">
|
||||||
title={`Cerrar sesión de ${user?.username}`}
|
<Link
|
||||||
onClick={() => {
|
to="/editor"
|
||||||
if(window.confirm('¿Deseas cerrar sesión?')) {
|
className={`text-sm font-bold px-4 py-2 rounded-lg transition-all ${
|
||||||
logout();
|
isActive('/editor')
|
||||||
}
|
? 'text-blue-600'
|
||||||
}}
|
: 'text-slate-600 hover:text-blue-500'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
Editor
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
{/* Enlace al Historial */}
|
||||||
|
{isAuthenticated && (
|
||||||
|
<Link
|
||||||
|
to="/history"
|
||||||
|
className={`text-sm font-bold px-4 py-2 rounded-lg transition-all ${
|
||||||
|
isActive('/history')
|
||||||
|
? 'text-blue-600'
|
||||||
|
: 'text-slate-600 hover:text-blue-500'
|
||||||
|
}`}
|
||||||
>
|
>
|
||||||
{user?.username?.charAt(0).toUpperCase() || 'U'}
|
Historial
|
||||||
</div>
|
</Link>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* SECCIÓN DE USUARIO / LOGIN */}
|
||||||
|
{isAuthenticated ? (
|
||||||
|
<div className="relative">
|
||||||
|
<button
|
||||||
|
onClick={() => setIsDropdownOpen(!isDropdownOpen)}
|
||||||
|
className="w-10 h-10 rounded-full bg-blue-100 text-blue-700 font-bold flex items-center justify-center border-2 border-blue-200 hover:bg-blue-200 transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2"
|
||||||
|
>
|
||||||
|
{userInitial}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{/* Dropdown Menu (Solo Usuario y Cerrar Sesión) */}
|
||||||
|
{isDropdownOpen && (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-40"
|
||||||
|
onClick={() => setIsDropdownOpen(false)}
|
||||||
|
></div>
|
||||||
|
|
||||||
|
<div className="absolute right-0 mt-2 w-48 bg-white rounded-xl shadow-lg border border-slate-100 py-2 z-50 animate-fade-in">
|
||||||
|
<div className="px-4 py-2 border-b border-slate-50">
|
||||||
|
<p className="text-xs font-bold text-slate-400 uppercase tracking-wider">Usuario</p>
|
||||||
|
<p className="text-sm font-bold text-slate-700 truncate">{user?.username}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button
|
||||||
|
onClick={handleLogout}
|
||||||
|
className="w-full text-left px-4 py-2 text-sm font-medium text-red-600 hover:bg-red-50 transition-colors"
|
||||||
|
>
|
||||||
|
🚪 Cerrar Sesión
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<Link
|
// BOTONES PARA USUARIO NO LOGUEADO
|
||||||
to="/login"
|
<div className="flex items-center gap-3">
|
||||||
className="px-5 py-2 bg-blue-50 text-blue-600 font-bold rounded-lg hover:bg-blue-100 transition-colors text-sm"
|
<Link to="/login" className="text-sm font-bold text-slate-600 hover:text-blue-600 transition-colors">
|
||||||
>
|
Iniciar sesión
|
||||||
Iniciar Sesión
|
</Link>
|
||||||
</Link>
|
<Link to="/register" className="text-sm font-bold bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors shadow-sm">
|
||||||
|
Registrarse
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<main className="flex-1 w-full max-w-7xl mx-auto p-4 sm:p-6 lg:p-8">
|
{/* CONTENIDO PRINCIPAL */}
|
||||||
<Outlet />
|
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
|
||||||
|
{children}
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from 'react';
|
|||||||
import Step1BaseScale from '../components/editor/Step1BaseScale';
|
import Step1BaseScale from '../components/editor/Step1BaseScale';
|
||||||
import Step2FuzzyModeling from '../components/editor/Step2FuzzyModeling';
|
import Step2FuzzyModeling from '../components/editor/Step2FuzzyModeling';
|
||||||
import SubscaleModal from '../components/editor/SubscaleModal';
|
import SubscaleModal from '../components/editor/SubscaleModal';
|
||||||
import { calculateValueFunction, buildFuzzyGraph } from '../services/docService';
|
import { calculateValueFunction, buildFuzzyGraph, saveToHistory } from '../services/docService';
|
||||||
import Step3FinalGraph from '../components/editor/Step3FinalGraph';
|
import Step3FinalGraph from '../components/editor/Step3FinalGraph';
|
||||||
|
|
||||||
export default function DocEditor() {
|
export default function DocEditor() {
|
||||||
@@ -193,6 +193,38 @@ export default function DocEditor() {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Petición para guardar en el historial
|
||||||
|
const handleSaveToHistory = async () => {
|
||||||
|
const token = localStorage.getItem('token');
|
||||||
|
if (!token) {
|
||||||
|
alert("Para guardar tu modelo debes iniciar sesión primero. Puedes seguir visualizando la gráfica sin problema.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const defaultName = criterionName ? `Modelo de ${criterionName}` : "Mi nueva gráfica DoC-IT2MF";
|
||||||
|
const historyName = prompt("Dale un nombre a este modelo para guardarlo en tu historial:", defaultName);
|
||||||
|
|
||||||
|
if (!historyName) return;
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
name: historyName,
|
||||||
|
results: finalResult.levels || finalResult.results
|
||||||
|
};
|
||||||
|
|
||||||
|
await saveToHistory(payload);
|
||||||
|
|
||||||
|
alert("¡Gráfica guardada con éxito en tu historial!");
|
||||||
|
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error al guardar en el historial:", error);
|
||||||
|
alert("Hubo un problema al guardar el modelo: " + error);
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full flex flex-col items-center">
|
<div className="w-full flex flex-col items-center">
|
||||||
|
|
||||||
@@ -223,10 +255,13 @@ export default function DocEditor() {
|
|||||||
<Step3FinalGraph data={finalResult} criterionName={criterionName} />
|
<Step3FinalGraph data={finalResult} criterionName={criterionName} />
|
||||||
|
|
||||||
<button
|
<button
|
||||||
onClick={() => console.log("Lógica para guardar")}
|
onClick={handleSaveToHistory}
|
||||||
className="mt-4 px-8 py-3 bg-blue-600 text-white font-bold rounded-xl shadow-md hover:bg-blue-700 w-fit self-end transition-all"
|
disabled={isLoading}
|
||||||
|
className={`mt-4 px-8 py-3 font-bold rounded-xl shadow-md w-fit self-end transition-all ${
|
||||||
|
isLoading ? 'bg-slate-400 text-slate-100 cursor-not-allowed' : 'bg-blue-600 text-white hover:bg-blue-700'
|
||||||
|
}`}
|
||||||
>
|
>
|
||||||
Finalizar y Guardar
|
{isLoading ? 'Guardando...' : 'Finalizar y Guardar'}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
import React, { useState, useEffect } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { getUserHistory, deleteHistoryItem } from '../services/docService';
|
||||||
|
import Step3FinalGraph from '../components/editor/Step3FinalGraph';
|
||||||
|
|
||||||
|
export default function History() {
|
||||||
|
const [historyItems, setHistoryItems] = useState([]);
|
||||||
|
const [isLoading, setIsLoading] = useState(true);
|
||||||
|
const [expandedId, setExpandedId] = useState(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetchHistory();
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const fetchHistory = async () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
try {
|
||||||
|
const data = await getUserHistory();
|
||||||
|
const items = Array.isArray(data) ? data : data.history || data.items || [];
|
||||||
|
|
||||||
|
setHistoryItems(items.reverse());
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching history:", error);
|
||||||
|
alert("Hubo un problema al cargar el historial.");
|
||||||
|
} finally {
|
||||||
|
setIsLoading(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleDelete = async (id) => {
|
||||||
|
if (!window.confirm('¿Seguro que quieres borrar este modelo definitivamente?')) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await deleteHistoryItem(id);
|
||||||
|
setHistoryItems(prev => prev.filter(item => item._id !== id && item.id !== id));
|
||||||
|
if (expandedId === id) setExpandedId(null);
|
||||||
|
} catch (error) {
|
||||||
|
alert("Error al borrar: " + error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleExpand = (id) => {
|
||||||
|
setExpandedId(expandedId === id ? null : id);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="w-full max-w-5xl mx-auto flex flex-col gap-8 animate-fade-in pb-12">
|
||||||
|
|
||||||
|
{/* Cabecera */}
|
||||||
|
<div className="flex justify-between items-center bg-white p-8 rounded-3xl shadow-sm border border-slate-200">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-3xl font-black text-slate-800">Mi Historial</h1>
|
||||||
|
<p className="text-slate-500 font-medium mt-1">
|
||||||
|
Aquí están todas las gráficas y modelos que has guardado.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
to="/editor"
|
||||||
|
className="px-6 py-3 bg-blue-50 text-blue-600 font-bold rounded-xl hover:bg-blue-100 transition-colors shadow-sm"
|
||||||
|
>
|
||||||
|
+ Nuevo Modelo
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Lista de Historial */}
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="bg-white p-12 rounded-3xl shadow-sm border border-slate-200 flex flex-col items-center justify-center text-slate-400 border-dashed">
|
||||||
|
<div className="animate-spin text-4xl mb-4">⏳</div>
|
||||||
|
<p className="font-medium">Cargando tus gráficas...</p>
|
||||||
|
</div>
|
||||||
|
) : historyItems.length === 0 ? (
|
||||||
|
<div className="bg-white p-12 rounded-3xl shadow-sm border border-slate-200 flex flex-col items-center justify-center text-slate-400 border-dashed">
|
||||||
|
<span className="text-6xl mb-4">📭</span>
|
||||||
|
<p className="font-medium text-lg">Aún no has guardado ningún modelo.</p>
|
||||||
|
<p className="text-sm mt-2">Ve al editor, crea una gráfica y dale a "Finalizar y Guardar".</p>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="flex flex-col gap-6">
|
||||||
|
{historyItems.map((item) => {
|
||||||
|
const itemId = item._id || item.id;
|
||||||
|
const isExpanded = expandedId === itemId;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div key={itemId} className={`bg-white rounded-2xl shadow-sm border transition-all duration-300 ${isExpanded ? 'border-blue-300 ring-4 ring-blue-50' : 'border-slate-200 hover:border-slate-300'}`}>
|
||||||
|
|
||||||
|
{/* Cabecera de la Card (Siempre visible) */}
|
||||||
|
<div className="p-6 flex flex-col sm:flex-row justify-between items-center gap-4 bg-slate-50/50 rounded-t-2xl">
|
||||||
|
<div className="flex items-center gap-4 w-full sm:w-auto">
|
||||||
|
<div className="w-12 h-12 bg-blue-100 text-blue-600 rounded-full flex items-center justify-center text-xl shadow-inner">
|
||||||
|
📊
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-xl font-bold text-slate-800">{item.name || 'Modelo sin título'}</h3>
|
||||||
|
<p className="text-sm text-slate-500 font-medium">
|
||||||
|
Guardado en el historial
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex gap-3 w-full sm:w-auto">
|
||||||
|
<button
|
||||||
|
onClick={() => toggleExpand(itemId)}
|
||||||
|
className={`flex-1 sm:flex-none px-6 py-2.5 font-bold rounded-xl transition-colors ${isExpanded ? 'bg-slate-200 text-slate-700 hover:bg-slate-300' : 'bg-blue-50 text-blue-600 hover:bg-blue-100'}`}
|
||||||
|
>
|
||||||
|
{isExpanded ? 'Ocultar Gráfica ▴' : 'Ver Gráfica ▾'}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => handleDelete(itemId)}
|
||||||
|
className="px-4 py-2.5 bg-white border border-red-200 text-red-500 font-bold rounded-xl hover:bg-red-50 transition-colors shadow-sm"
|
||||||
|
title="Borrar modelo"
|
||||||
|
>
|
||||||
|
🗑️
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Contenido Desplegable (La Gráfica) */}
|
||||||
|
{isExpanded && (
|
||||||
|
<div className="p-6 border-t border-slate-100 animate-fade-in bg-white rounded-b-2xl">
|
||||||
|
<Step3FinalGraph data={item} criterionName={item.name} />
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,20 +1,22 @@
|
|||||||
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
|
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
|
||||||
import MainLayout from '../components/layout/MainLayout';
|
import MainLayout from '../components/layout/MainLayout';
|
||||||
import DocEditor from '../pages/DocEditor';
|
import DocEditor from '../pages/DocEditor';
|
||||||
import Login from '../pages/Login';
|
import Login from '../pages/Login';
|
||||||
import Register from '../pages/Register';
|
import Register from '../pages/Register';
|
||||||
|
import History from '../pages/History';
|
||||||
|
|
||||||
export function AppRouter() {
|
export default function AppRouter() {
|
||||||
return (
|
return (
|
||||||
<BrowserRouter>
|
<Router>
|
||||||
<Routes>
|
<MainLayout>
|
||||||
<Route path="/" element={<MainLayout />}>
|
<Routes>
|
||||||
<Route index element={<DocEditor />} />
|
<Route path="/" element={<Navigate to="/editor" replace />} />
|
||||||
<Route path="login" element={<Login />} />
|
<Route path="/editor" element={<DocEditor />} />
|
||||||
<Route path="register" element={<Register />} />
|
<Route path="/login" element={<Login />} />
|
||||||
<Route path="*" element={<Navigate to="/" replace />} />
|
<Route path="/register" element={<Register />} />
|
||||||
</Route>
|
<Route path="/history" element={<History />} />
|
||||||
</Routes>
|
</Routes>
|
||||||
</BrowserRouter>
|
</MainLayout>
|
||||||
|
</Router>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -18,4 +18,34 @@ export const buildFuzzyGraph = async (payload) => {
|
|||||||
console.error('Error building fuzzy graph:', error);
|
console.error('Error building fuzzy graph:', error);
|
||||||
throw error.response?.data?.detail || error.message;
|
throw error.response?.data?.detail || error.message;
|
||||||
}
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const saveToHistory = async (payload) => {
|
||||||
|
try {
|
||||||
|
const response = await api.post('/history/add', payload);
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error saving to history:', error);
|
||||||
|
throw error.response?.data?.detail || error.message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getUserHistory = async () => {
|
||||||
|
try {
|
||||||
|
const response = await api.get('/history/user');
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching history:', error);
|
||||||
|
throw error.response?.data?.detail || error.message;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const deleteHistoryItem = async (id) => {
|
||||||
|
try {
|
||||||
|
const response = await api.delete(`/history/delete/${id}`);
|
||||||
|
return response.data;
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error deleting history item:', error);
|
||||||
|
throw error.response?.data?.detail || error.message;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
Reference in New Issue
Block a user