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 Apr 3, 2024
2 parents b997078 + 815e83a commit 8e30c84
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 26 deletions.
39 changes: 28 additions & 11 deletions gameservice/game-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,24 +45,40 @@ app.post('/addgame', async (req, res) => {
});

// Ruta para obtener datos de participación del usuario
app.get('/getParticipation/:userId', async (req, res) => {
app.get('/getParticipation/:username', async (req, res) => {
try {
const userId = req.params.userId;
const { username } = req.params;
const user = await User.findOne({ username });

// Consulta para obtener los datos de participación del usuario
const participationData = await Game.aggregate([
{ $match: { user: mongoose.Types.ObjectId(userId) } },
{ $match: { user } },
{
$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] } }
} } },
totalGames: { $sum: 1 },
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" },
},
},
Expand All @@ -81,6 +97,7 @@ app.get('/getParticipation/:userId', async (req, res) => {
}
});


const server = app.listen(port, () => {
console.log(`Games Service listening at http://localhost:${port}`);
});
Expand Down
39 changes: 39 additions & 0 deletions webapp/package-lock.json

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

1 change: 1 addition & 0 deletions webapp/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"react": "^18.2.0",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3",
"react-scripts": "5.0.1",
"web-vitals": "^3.5.1"
},
Expand Down
17 changes: 10 additions & 7 deletions webapp/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Start } from './components/Start'
import { Game } from './components/Game'
import { Participation } from './components/Participation'
import User from './components/User'
import { UserProvider } from './components/UserContext';

function App() {
const [menuState, setMenuState] = useState(0)
Expand All @@ -14,13 +15,15 @@ function App() {
}

return (
<>
{menuState === 0 && <User goTo={(x) => goTo(x)}/>}
{menuState > 0 && <Nav goTo={(x) => goTo(x)}/>}
{menuState === 1 && <Start goTo={(x) => goTo(x)}/>}
{menuState === 2 && <Game />}
{menuState === 3 && <Participation goTo={(x) => goTo(x)}/>}
</>
<UserProvider>
<>
{menuState === 0 && <User goTo={(x) => goTo(x)}/>}
{menuState > 0 && <Nav goTo={(x) => goTo(x)}/>}
{menuState === 1 && <Start goTo={(x) => goTo(x)}/>}
{menuState === 2 && <Game />}
{menuState === 3 && <Participation goTo={(x) => goTo(x)}/>}
</>
</UserProvider>
)
}

Expand Down
25 changes: 22 additions & 3 deletions webapp/src/components/AddUser.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
// src/components/AddUser.js
import React, { useState } from 'react';
import axios from 'axios';
import { Container, Typography, TextField, Button, Snackbar, IconButton } from '@mui/material';

import profileImg1 from '../assets/defaultImgProfile.jpg';
import profileImg2 from '../assets/perfil2.jpg';
import profileImg3 from '../assets/perfil3.jpg';
import profileImg4 from '../assets/perfil4.jpg';
import profileImg5 from '../assets/perfil5.jpg';


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

const AddUser = () => {
Expand All @@ -19,6 +18,7 @@ const AddUser = () => {

const [error, setError] = useState('');
const [openSnackbar, setOpenSnackbar] = useState(false);
const { updateUser } = useUser(); // Obtén la función updateUser del contexto de usuario

const addUser = async () => {
try {
Expand All @@ -29,6 +29,25 @@ const AddUser = () => {

await axios.post(`${apiEndpoint}/adduser`, { username, password, profileImage });
setOpenSnackbar(true);

// Después de agregar el usuario, realiza el login automáticamente
loginUser();
} catch (error) {
setError(error.response.data.error);
}
};

const loginUser = async () => {
try {
const response = await axios.post(`${apiEndpoint}/login`, { username, password });

// Extrae los datos de la respuesta
const { createdAt: userCreatedAt } = response.data;

// Actualiza el contexto de usuario con el nombre de usuario
updateUser({ username });

setOpenSnackbar(true);
} catch (error) {
setError(error.response.data.error);
}
Expand Down Expand Up @@ -109,4 +128,4 @@ const AddUser = () => {
);
};

export default AddUser;
export default AddUser;
11 changes: 7 additions & 4 deletions webapp/src/components/Participation.jsx
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import React, { useState, useEffect } from 'react';
import { Bar } from 'react-chartjs-2';
import axios from 'axios';
import { useUser } from './UserContext';

export const Participation = ({ userId, goTo }) => {
export const Participation = ({ goTo }) => {
const { userData } = useUser(); // Obtener el contexto de usuario
const [participationData, setParticipationData] = useState(null);

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}`);
const response = await axios.get(`http://localhost:8005/getParticipation/${userData.username}`); // Utilizar el nombre de usuario del contexto
setParticipationData(response.data);
} catch (error) {
console.error('Error al obtener los datos de participación:', error);
}
};

fetchData();
}, [userId]);
}, [userData.username]);

//Gráfica
const data = {
Expand All @@ -43,7 +45,7 @@ export const Participation = ({ userId, goTo }) => {
return (
<main>
<div>
<h1>Participation</h1>
<h1>Bienvenido a tus estadísticas de participación {userData.username}!</h1>
{participationData ? (
<div>
<p>Número de partidas jugadas: {participationData.totalGames}</p>
Expand All @@ -55,6 +57,7 @@ export const Participation = ({ userId, goTo }) => {
) : (
<p>Cargando datos de participación...</p>
)}
<button onClick={() => goTo(1)}>Menú</button>
</div>
</main>
);
Expand Down
5 changes: 4 additions & 1 deletion webapp/src/components/PostGame.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react';

import { Card, Typography } from "@mui/material";
import Table from '@mui/material/Table';
import TableBody from '@mui/material/TableBody';
import TableCell from '@mui/material/TableCell';
import TableContainer from '@mui/material/TableContainer';
import TableRow from '@mui/material/TableRow';
import Paper from '@mui/material/Paper';
import { useUser } from './UserContext';
import axios from 'axios';

export const PostGame = () => {

Expand Down Expand Up @@ -46,6 +49,6 @@ export const PostGame = () => {
</div>
</main>
)
}
};

export default PostGame;
34 changes: 34 additions & 0 deletions webapp/src/components/UserContext.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { createContext, useContext, useState } from 'react';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';

const UserContext = createContext();

export const UserProvider = ({ children }) => {
const [userData, setUserData] = useState({
username: '',
});
const history = useNavigate();

const updateUser = (newData) => {
setUserData((prevData) => ({ ...prevData, ...newData }));
};

const loginUser = async (username, password) => {
try {
const response = await axios.post('http://localhost:8000/login', { username, password });
const { createdAt: userCreatedAt } = response.data;

setUserData({ username });
history.push('/');
} catch (error) {
console.error('Error al iniciar sesión:', error);
}
};

return <UserContext.Provider value={{ userData, updateUser, loginUser }}>{children}</UserContext.Provider>;
};

export const useUser = () => {
return useContext(UserContext);
};

0 comments on commit 8e30c84

Please sign in to comment.