Skip to content

Commit

Permalink
Merge pull request #207 from Arquisoft/laura
Browse files Browse the repository at this point in the history
front ranking
  • Loading branch information
uo277310 authored Mar 27, 2024
2 parents c05701a + e39aa10 commit cdee584
Show file tree
Hide file tree
Showing 2 changed files with 226 additions and 91 deletions.
215 changes: 124 additions & 91 deletions webapp/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import Game from './Game';
import UsersList from './UsersList';
import GeneratedQuestionsList from './GeneratedQuestionsList';
import RecordList from './RecordList';
import RankingList from './RankingList';
import CircularProgress from '@mui/material/CircularProgress';

//import Link from '@mui/material/Link';

Expand All @@ -22,7 +24,8 @@ const Login = ({setLogged}) => {
const [showUsersList, setShowUsersList] = useState(false);
const [showQuestionList, setShowQuestionList] = useState(false);
const [showRecordList, setShowRecordList] = useState(false);

const [showRankingList, setShowRankingList] = useState(false);
const [loading, setLoading] = useState(false);

const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

Expand All @@ -39,17 +42,23 @@ const Login = ({setLogged}) => {
const usersResponse = await axios.get(`${apiEndpoint}/getAllUsers`);
const users = usersResponse.data;


setCreatedAt(userCreatedAt);
setLoginSuccess(true);
setLogged();

setLoading(true);
// Para cada usuario, crear su ranking
for (const user of users) {
await axios.post(`${apiEndpoint}/createUserRank`, { username: user.username });
}
const { data: updatedRankingData } = await axios.get(`${apiEndpoint}/actRanking`);//obtengo datos actualizados del ranking
await axios.post(`${apiEndpoint}/updateAllRanking`, updatedRankingData); //los actualizo

setLoading(false);

setCreatedAt(userCreatedAt);
setLoginSuccess(true);
setLogged();
//setCreatedAt(userCreatedAt);
// setLoginSuccess(true);
//setLogged();
setOpenSnackbar(true);
} catch (error) {
if (error.response) {
Expand All @@ -68,127 +77,151 @@ const Login = ({setLogged}) => {
setShowUsersList(false);
setShowQuestionList(false);
setShowRecordList(false);
setShowRankingList(false);
setShowGame(true);

};

const handleShowUsersList = () => {
setShowGame(false);
setShowQuestionList(false);
setShowRecordList(false);
setShowRankingList(false);
setShowUsersList(true);
};

const handleShowQuestionList = () => {
setShowGame(false);
setShowUsersList(false);
setShowRecordList(false);
setShowRankingList(false);
setShowQuestionList(true);
};

const handleShowRecordList = () => {
setShowGame(false);
setShowUsersList(false);
setShowQuestionList(false);
setShowRankingList(false);
setShowRecordList(true);
};

const handleShowRankingList = () => {
setShowGame(false);
setShowUsersList(false);
setShowQuestionList(false);
setShowRecordList(false);
setShowRankingList(true);

};


const handleCloseSnackbar = () => {
setOpenSnackbar(false);
};


return (
<>
{loginSuccess && (
<AppBar position="static">
<Toolbar>
<Button color="inherit" onClick={handleShowGame}>
Jugar
</Button>
{username === 'admin' && (
<Button color="inherit" onClick={handleShowUsersList}>
Historial de Usuarios
{loginSuccess && (
<AppBar position="static">
<Toolbar>
<Button color="inherit" onClick={handleShowGame}>
Jugar
</Button>
{username === 'admin' && (
<Button color="inherit" onClick={handleShowUsersList}>
Historial de Usuarios
</Button>
)}
{username === 'admin' && (
<Button color="inherit" onClick={handleShowQuestionList}>
Historial de Preguntas Generadas
</Button>
)}
<Button color="inherit" onClick={handleShowRecordList}>
Historial de jugadas
</Button>
)}
{username === 'admin' && (
<Button color="inherit" onClick={handleShowQuestionList}>
Historial de Preguntas Generadas
<Button color="inherit" onClick={handleShowRankingList}>
Ranking
</Button>
)}
<Button color="inherit" onClick={handleShowRecordList}>
Historial de jugadas
</Button>
</Toolbar>
</AppBar>
)}

<Container maxWidth="lg" style={{ marginTop: '2rem' }}>
{loginSuccess ? (
<>

{showGame ? (
<Game username={username} />
) : showUsersList ? (
<UsersList />
) :

showQuestionList ? (
<GeneratedQuestionsList />
) :
showRecordList ? (
<RecordList username={username} />
)

:
(

<div>
<Typography component="h1" variant="h5" sx={{ textAlign: 'center' }}>
Hola {username}!
</Typography>
<Typography component="p" variant="body1" sx={{ textAlign: 'center', marginTop: 2 }}>
Tu cuenta fue creada el {new Date(createdAt).toLocaleDateString()}.
</Typography>
<Button variant="contained" color="secondary" onClick={handleShowGame}>
Comenzar a jugar
</Button>

</div>
</Toolbar>
</AppBar>
)}

<Container maxWidth="lg" style={{ marginTop: '2rem' }}>
{loading ? ( // Mostrar CircularProgress si loading es true
<div style={{ textAlign: 'center', marginTop: '2rem' }}>
<CircularProgress />
<Typography variant="body1" sx={{ marginTop: 2 }}>
Espere, estamos cargando sus datos...
</Typography>
</div>
) : (
loginSuccess ? (
<>
{showGame ? (
<Game username={username} />
) : showUsersList ? (
<UsersList />
) :
showQuestionList ? (
<GeneratedQuestionsList />
) :
showRecordList ? (
<RecordList username={username} />
) :
showRankingList ? (
<RankingList />
) :
(
<div>
<Typography component="h1" variant="h5" sx={{ textAlign: 'center' }}>
Hola {username}!
</Typography>
<Typography component="p" variant="body1" sx={{ textAlign: 'center', marginTop: 2 }}>
Tu cuenta fue creada el {new Date(createdAt).toLocaleDateString()}.
</Typography>
<Button variant="contained" color="secondary" onClick={handleShowGame}>
Comenzar a jugar
</Button>
</div>
)}
</>
) : (
<div>
<Typography component="h1" variant="h5">
Iniciar sesión
</Typography>
<TextField
margin="normal"
fullWidth
label="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<TextField
margin="normal"
fullWidth
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button variant="contained" color="primary" onClick={loginUser}>
Iniciar sesión
</Button>
<Snackbar open={openSnackbar} autoHideDuration={6000} onClose={handleCloseSnackbar} message="Login successful" />
{error && (
<Snackbar open={!!error} autoHideDuration={6000} onClose={() => setError('')} message={`Error: ${error}`} />
)}
</div>
)
)}
</Container>
</>
) : (
<div>
<Typography component="h1" variant="h5">
Iniciar sesión
</Typography>
<TextField
margin="normal"
fullWidth
label="Username"
value={username}
onChange={(e) => setUsername(e.target.value)}
/>
<TextField
margin="normal"
fullWidth
label="Password"
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<Button variant="contained" color="primary" onClick={loginUser}>
Iniciar sesión
</Button>
<Snackbar open={openSnackbar} autoHideDuration={6000} onClose={handleCloseSnackbar} message="Login successful" />
{error && (
<Snackbar open={!!error} autoHideDuration={6000} onClose={() => setError('')} message={`Error: ${error}`} />
)}
</div>
)}

</Container>
</>
);
};
};


export default Login;
102 changes: 102 additions & 0 deletions webapp/src/components/RankingList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';

const RankingList = () => {
const [listUsers, setListUsers] = useState([]);
const [sortColumn, setSortColumn] = useState(null);
const [sortOrder, setSortOrder] = useState('asc');
const [topThreeUsers, setTopThreeUsers] = useState([]);

const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

useEffect(() => {
const fetchUsers = async () => {
try {
const response = await axios.get(`${apiEndpoint}/obtainRank`);

if (response.status === 200) {
const uList = response.data.map(record => ({
...record,
createdAt: new Date(record.createdAt).toLocaleString(),
}));
setListUsers(uList);
const sortedUsers = [...uList].sort((a, b) => b.porcentajeAciertos - a.porcentajeAciertos);
setTopThreeUsers(sortedUsers.slice(0, 3));
} else {
console.error('Error obteniendo la lista de usuarios');
}
} catch (error) {
console.error('Error obteniendo la lista de usuarios:', error);
}
};

fetchUsers();
}, []);

const sortedUsers = [...listUsers].sort((a, b) => {
if (sortColumn === 'username') {
return sortOrder === 'asc' ? a.username.localeCompare(b.username) : b.username.localeCompare(a.username);
} else if (sortColumn === 'porcentajeAciertos') {
return sortOrder === 'asc' ? a.porcentajeAciertos - b.porcentajeAciertos : b.porcentajeAciertos - a.porcentajeAciertos;
} else if (sortColumn === 'preguntasCorrectas') {
return sortOrder === 'asc' ? a.preguntasCorrectas - b.preguntasCorrectas : b.preguntasCorrectas - a.preguntasCorrectas;
} else if (sortColumn === 'preguntasFalladas') {
return sortOrder === 'asc' ? a.preguntasFalladas - b.preguntasFalladas : b.preguntasFalladas - a.preguntasFalladas;
} else if (sortColumn === 'numPartidas') {
return sortOrder === 'asc' ? a.numPartidas - b.numPartidas : b.numPartidas - a.numPartidas;
} else {
// Ordenar por defecto por _id si no se especifica ninguna columna de ordenamiento específica
return sortOrder === 'asc' ? a._id - b._id : b._id - a._id;
}
});

const handleSort = (column) => {
if (sortColumn === column) {
setSortOrder((order) => (order === 'asc' ? 'desc' : 'asc'));
} else {
setSortColumn(column);
setSortOrder('asc');
}
};

return (
<div>
<h2>Top 3 usurios con mejor porcentaje de aciertos</h2>
<div style={{ display: 'flex', justifyContent: 'space-around', marginBottom: '20px' }}>
{topThreeUsers.map((user, index) => (
<div key={index} style={{ width: '30%', padding: '20px', backgroundColor: index === 0 ? '#ffd700' : index === 1 ? '#c0c0c0' : '#cd7f32', color: 'white', textAlign: 'center', borderRadius: '10px', boxShadow: '0 4px 8px 0 rgba(0,0,0,0.2)', transition: '0.3s', border: '1px solid #ddd' }}>
<h3 style={{ margin: '0' }}>{index + 1}</h3>
<p style={{ fontWeight: 'bold', fontSize: '20px' }}>{user.username}</p>
<p style={{ marginBottom: '5px' }}>{user.porcentajeAciertos}% Aciertos</p>
</div>
))}
</div>

<h2>Ranking</h2>
<table style={{ borderCollapse: 'collapse', width: '100%' }}>
<thead>
<tr style={{ border: '1px solid #ddd', padding: '8px', backgroundColor: '#f2f2f2' }}>
<th onClick={() => handleSort('username')}>Nombre de Usuario {sortColumn === 'username' && sortOrder === 'asc' ? '▲' : '▼'}</th>
<th onClick={() => handleSort('porcentajeAciertos')}>Porcentaje de Aciertos {sortColumn === 'porcentajeAciertos' && sortOrder === 'asc' ? '▲' : '▼'}</th>
<th onClick={() => handleSort('preguntasCorrectas')}>Preguntas Correctas {sortColumn === 'preguntasCorrectas' && sortOrder === 'asc' ? '▲' : '▼'}</th>
<th onClick={() => handleSort('preguntasFalladas')}>Preguntas Falladas {sortColumn === 'preguntasFalladas' && sortOrder === 'asc' ? '▲' : '▼'}</th>
<th onClick={() => handleSort('numPartidas')}>Número de Partidas {sortColumn === 'numPartidas' && sortOrder === 'asc' ? '▲' : '▼'}</th>
</tr>
</thead>
<tbody>
{sortedUsers.map((user, index) => (
<tr key={index} style={{ border: '1px solid #ddd', padding: '8px' }}>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>{user.username}</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>{user.porcentajeAciertos}</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>{user.preguntasCorrectas}</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>{user.preguntasFalladas}</td>
<td style={{ border: '1px solid #ddd', padding: '8px' }}>{user.numPartidas}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};

export default RankingList;

0 comments on commit cdee584

Please sign in to comment.