Skip to content

Commit

Permalink
Merge pull request #132 from Arquisoft/ray
Browse files Browse the repository at this point in the history
Ray
  • Loading branch information
UO290054 authored Apr 15, 2024
2 parents 25d7b0e + 04962bd commit 6fafdf8
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 19 deletions.
8 changes: 8 additions & 0 deletions gatewayservice/gateway-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,14 @@ app.get('/getgamehistory/:username', async (req, res) => {
res.status(error.response.status).json({ error: error.response.data.error });
}
});
app.get('/getScoreBoard', async (req, res) => {
try {
const userResponse = await axios.get(`${retrieveServiceUrl}/getScoreBoard`);
res.json(userResponse.data);
} catch (error) {
res.status(error.response.status).json({ error: error.response.data.error });
}
});



Expand Down
39 changes: 39 additions & 0 deletions questions/retrieveservice/retrieve-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,45 @@ app.get('/getgamehistory/:username', async (req, res) => {
});
}
});
app.get('/getScoreBoard', async (req, res) => {
try {
// Obtener todas las partidas
const games = await Game.find({});

// Objeto para almacenar el scoreboard
const scoreboard = {};

// Calcular el scoreboard para cada usuario
games.forEach(game => {
if (!scoreboard[game.username]) {
scoreboard[game.username] = {
username: game.username,
totalCorrect: 0,
totalIncorrect: 0,
points: 0
};
}

// Sumar el número total de preguntas acertadas y falladas
scoreboard[game.username].totalCorrect += game.correctAnswers;
scoreboard[game.username].totalIncorrect += game.incorrectAnswers;

// Calcular los puntos totales
scoreboard[game.username].points += (game.correctAnswers * 15) - (game.incorrectAnswers * 5);
});

// Convertir el objeto de scoreboard en un array de objetos
const scoreboardArray = Object.values(scoreboard);

// Enviar la respuesta con el scoreboard
res.json(scoreboardArray);
} catch (error) {
res.status(400).json({
error: error.message
});
}
});


const server = app.listen(port, () => {
console.log(`Creation Service listening at http://localhost:${port}`);
Expand Down
43 changes: 26 additions & 17 deletions webapp/src/components/HistoricalUserData.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const HistoricalUserData = () => {
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';

const [gameHistory, setGameHistory] = useState([]);
const [expandedRows, setExpandedRows] = useState([]);


useEffect(() => {
Expand All @@ -19,25 +20,33 @@ const HistoricalUserData = () => {
const handleLoadHistory = async () => {
try {
const username = localStorage.getItem('username');
const response = await axios.get(`${apiEndpoint}/getgamehistory/${username}`);
const response = await axios.get(`${apiEndpoint}/getgamehistory/${username}`);

// Ordenar la lista de historial de partidas por fecha (de más reciente a más antigua)
const sortedHistory = response.data.sort((a, b) => new Date(b.date) - new Date(a.date));

setGameHistory(sortedHistory);

console.log("el historial actual es "+gameHistory);
// Ordenar la lista de historial de partidas por fecha (de más reciente a más antigua)
const sortedHistory = response.data.sort((a, b) => new Date(b.date) - new Date(a.date));

setGameHistory(sortedHistory);
} catch (error) {
console.error('Error:', error);
}
};

const handlePreviousPage = async () => {
let path= '/MainPage';
navigate(path);
}
const handlePreviousPage = async () => {
let path = '/MainPage';
navigate(path);
};

const toggleRow = (index) => {
const newExpandedRows = [...expandedRows];
if (newExpandedRows.includes(index)) {
// Si la fila ya está expandida, la contraemos
newExpandedRows.splice(newExpandedRows.indexOf(index), 1);
} else {
// Si la fila no está expandida, la expandimos
newExpandedRows.push(index);
}
setExpandedRows(newExpandedRows);
};

return (
<Container component="main" maxWidth="md" sx={{ marginTop: 4 }}>
Expand All @@ -59,20 +68,20 @@ const HistoricalUserData = () => {
</tr>
</thead>
<tbody>
{gameHistory.map((game) => (
{gameHistory.map((game, index) => (
<React.Fragment key={game.id}>
<tr>
<tr onClick={() => toggleRow(index)}>
<td>{game.date}</td>
<td>{game.duration}</td>
<td>{game.percentage}%</td>
<td>{game.totalQuestions}</td>
<td>{game.correctAnswers}</td>
<td>{game.incorrectAnswers}</td>
</tr>
{game.questions && game.questions.map((question, index) => (
<tr key={index}>
{expandedRows.includes(index) && game.questions && game.questions.map((question, qIndex) => (
<tr key={qIndex}>
<td colSpan="6">
<p>Pregunta {index + 1}: {question.question}</p>
<p>Pregunta {qIndex + 1}: {question.question}</p>
<p>Respuesta Correcta: {question.correctAnswer}</p>
<p>Respuesta del Usuario: {question.userAnswer}</p>
<p>La respuesta fue: {question.correctAnswer === question.userAnswer ? 'Correcta' : 'Incorrecta'}</p>
Expand All @@ -86,7 +95,7 @@ const HistoricalUserData = () => {
</div>
</Container>
);

};

export default HistoricalUserData;
17 changes: 15 additions & 2 deletions webapp/src/components/Navbar.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,20 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { Link ,useNavigate} from 'react-router-dom';
import './Navbar.css';

const Navbar = () => {
const [historialDropdownOpen, setHistorialDropdownOpen] = useState(false);

const navigate = useNavigate();
const toggleHistorialDropdown = () => {
setHistorialDropdownOpen(!historialDropdownOpen);
};

const handleLogout = () => {
localStorage.removeItem('username');
navigate("/"); // Redirige a la página de inicio de sesión
};


return (
<nav className="navbar navbar-expand-lg">
<div className="container">
Expand Down Expand Up @@ -36,6 +42,13 @@ const Navbar = () => {
<li className="nav-item">
<Link className="nav-link" to="/RegisteredUsers">Usuarios registrados</Link>
</li>
<li className="nav-item">
<Link className="nav-link" to="/ScoreBoard">ScoreBoard</Link>
</li>
<li className="nav-item">
<button className="nav-link btn btn-link" onClick={handleLogout}>Logout</button>
</li>

</ul>
</div>
</div>
Expand Down
59 changes: 59 additions & 0 deletions webapp/src/components/ScoreBoard.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { Container, Button } from '@mui/material';

const ScoreBoard = () => {
const apiEndpoint = process.env.REACT_APP_API_ENDPOINT || 'http://localhost:8000';
const navigate = useNavigate();
const [scoreboard, setScoreboard] = useState([]);

useEffect(() => {
loadScoreboard();
}, []);

const loadScoreboard = async () => {
try {
const response = await axios.get(`${apiEndpoint}/getScoreBoard`);
setScoreboard(response.data);
} catch (error) {
console.error('Error:', error);
}
};
const handlePreviousPage = async () => {
let path = '/MainPage';
navigate(path);
};
return (
<Container component="main" maxWidth="md" sx={{ marginTop: 4 }}>
<Button variant="contained" color="primary" onClick={handlePreviousPage}>
Página anterior
</Button>
<div>
<h2>Tabla de Puntuaciones</h2>
<table>
<thead>
<tr>
<th>Usuario</th>
<th>Preguntas Totales Acertadas</th>
<th>Preguntas Totales Falladas</th>
<th>Puntos</th>
</tr>
</thead>
<tbody>
{scoreboard.map((user, index) => (
<tr key={index}>
<td>{user.username}</td>
<td>{user.totalCorrect}</td>
<td>{user.totalIncorrect}</td>
<td>{user.points}</td>
</tr>
))}
</tbody>
</table>
</div>
</Container>
);
};

export default ScoreBoard;
2 changes: 2 additions & 0 deletions webapp/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import HistoricalData from './components/HistoricalData';
import MainPage from './components/MainPage';
import HistoricalUserData from './components/HistoricalUserData';
import RegisteredUsers from './components/RegisteredUsers';
import ScoreBoard from './components/ScoreBoard';

import './index.css';
import 'animate.css';
Expand All @@ -26,6 +27,7 @@ root.render(
<Route path="/historicaldata" element={<HistoricalData />}> </Route>
<Route path="/historicalUserdata" element={<HistoricalUserData />}> </Route>
<Route path="/RegisteredUsers" element={<RegisteredUsers />}> </Route>
<Route path="/ScoreBoard" element={<ScoreBoard />}> </Route>
</Routes>
</Router>
</React.StrictMode>
Expand Down

0 comments on commit 6fafdf8

Please sign in to comment.