Skip to content

Commit

Permalink
Merge branch 'Develop-Participation' into Develop
Browse files Browse the repository at this point in the history
  • Loading branch information
uo276976 authored Mar 4, 2024
2 parents 1bb48b8 + 62488b1 commit e8c65d6
Show file tree
Hide file tree
Showing 8 changed files with 209 additions and 17 deletions.
3 changes: 2 additions & 1 deletion gameservice/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ COPY . .
EXPOSE 8005

# Define the command to run your app
CMD ["node", "game-service.js"]
CMD ["node", "game-service.js"]

37 changes: 36 additions & 1 deletion gameservice/game-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,42 @@ app.post('/addgame', async (req, res) => {
}
});

// Lógica para juegos??
// Ruta para obtener datos de participación del usuario
app.get('/getParticipation/:userId', async (req, res) => {
try {
const userId = req.params.userId;

// Consulta para obtener los datos de participación del usuario
const participationData = await Game.aggregate([
{ $match: { user: mongoose.Types.ObjectId(userId) } },
{
$group: {
_id: null,
totalGames: { $sum: 1 }, //$sum -> Returns a sum of numerical values
correctAnswers: { $sum: { $size: {
$filter: {
input: "$answers", as: "answer", cond: "$$answer.isCorrect" }
} } },
incorrectAnswers: { $sum: { $size: {
$filter: { input: "$answers", as: "answer", cond: { $eq: ["$$answer.isCorrect", false] } }
} } },
totalTime: { $sum: "$totalTime" },
},
},
]);

if (participationData.length === 0) {
// No se encontraron datos para el usuario
res.status(404).json({ error: 'No participation data found for the user.' });
return;
}

res.status(200).json(participationData[0]);
} catch (error) {
console.error('Error al obtener datos de participación:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});

const server = app.listen(port, () => {
console.log(`Games Service listening at http://localhost:${port}`);
Expand Down
2 changes: 1 addition & 1 deletion gameservice/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,4 @@
"mongodb-memory-server": "^9.1.6",
"supertest": "^6.3.4"
}
}
}
61 changes: 61 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 9 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
{
<<<<<<< HEAD
"dependencies": {
"chart.js": "^4.4.1",
"react-chartjs-2": "^5.2.0"
}
}
=======
"devDependencies": {
"serve": "^14.2.1"
}
}
}
>>>>>>> origin/Develop
21 changes: 21 additions & 0 deletions webapp/src/App.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import React, { useState } from 'react';
import './App.css';
import { Game } from './components/Game';
import { Participation } from './components/Participation';

function App() {
const [menuState, setMenuState] = useState(0);

const goTo = (parameter) => {
setMenuState(parameter);
};

return (
<>
{menuState === 0 && <Game goTo={(x) => goTo(x)} />}
{menuState === 1 && <Participation goTo={(x) => goTo(x)} />}
</>
);
}

export default App;
24 changes: 23 additions & 1 deletion webapp/src/components/Login.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const Login = ({ goTo }) => {
const [loginSuccess, setLoginSuccess] = useState(false);
const [createdAt, setCreatedAt] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);
const [timeStart, setTimeStart] = useState(0);
const [timeElapsed, setTimeElapsed] = useState(0);

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

Expand All @@ -19,16 +21,30 @@ const Login = ({ goTo }) => {

// Extract data from the response
const { createdAt: userCreatedAt } = response.data;


setTimeStart(Date.now());
setCreatedAt(userCreatedAt);
setLoginSuccess(true);

<<<<<<< HEAD


=======
>>>>>>> origin/Develop
setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
}
};

const calculateTime = async () => {
try {
setTimeElapsed((Date.now() - timeStart) / 1000);
} catch (error) {
setError(error.response.data.error);
}
};

const handleCloseSnackbar = () => {
setOpenSnackbar(false);
};
Expand All @@ -46,6 +62,12 @@ const Login = ({ goTo }) => {
<Typography component="p" variant="body1" sx={{ textAlign: 'center', marginTop: 2 }}>
Your account was created on {new Date(createdAt).toLocaleDateString()}.
</Typography>
<Typography component="p" variant="body1" sx={{ textAlign: 'center', marginTop: 2 }}>
Han pasado {timeElapsed} segundos.
</Typography>
<Button variant="contained" color="primary" onClick={calculateTime}>
Calcular tiempo
</Button>
</div>
) : (
<div>
Expand Down
68 changes: 56 additions & 12 deletions webapp/src/components/Participation.jsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,60 @@
import React from 'react';
//import Chart from "chart.js/auto";
import React, { useState, useEffect } from 'react';
import { Bar } from 'react-chartjs-2';
import axios from 'axios';

//const mongoose = require('mongoose');
export const Participation = ({ userId, goTo }) => {
const [participationData, setParticipationData] = useState(null);

// Número de juegos, preguntas acertadas/falladas, tiempos
// Esquema de preguntas -> question, correct, incorrects[]
// Esquema de Juegos -> usuario, preguntas[], respuestas[], tiempo
useEffect(() => {
// Realizar la solicitud al servidor para obtener los datos de participación
const fetchData = async () => {
try {
const response = await axios.get(`http://localhost:8005/getParticipation/${userId}`);
setParticipationData(response.data);
} catch (error) {
console.error('Error al obtener los datos de participación:', error);
}
};

export const Participation = () => {
return (
<div>
<h1>Participation</h1>
</div>
);
fetchData();
}, [userId]);

//Gráfica
const data = {
labels: ['Preguntas Acertadas', 'Preguntas Falladas'],
datasets: [
{
label: 'Número de preguntas',
data: [participationData?.correctAnswers || 0, participationData?.incorrectAnswers || 0],
backgroundColor: ['green', 'red'],
},
],
};

const options = {
scales: {
y: {
beginAtZero: true,
max: Math.max(participationData?.correctAnswers || 0, participationData?.incorrectAnswers || 0) + 1,
},
},
};

return (
<div>
<h1>Participation</h1>
{participationData ? (
<div>
<p>Número de partidas jugadas: {participationData.totalGames}</p>
<p>Preguntas acertadas: {participationData.correctAnswers}</p>
<p>Preguntas falladas: {participationData.incorrectAnswers}</p>
<p>Tiempo total jugando: {participationData.totalTime} segundos</p>
<Bar data={data} options={options} />
</div>
) : (
<p>Cargando datos de participación...</p>
)}
<button onClick={() => goTo(0)}>Menú</button>
</div>
);
};

0 comments on commit e8c65d6

Please sign in to comment.