From 80e814609ae15b6620032b3efa395d0638532f8c Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 12:52:45 +0200 Subject: [PATCH 01/21] ahora el modo de juego de pregunta diaria deberia de devolver la pregunta en el idioma correcto --- questionservice/question-service.js | 3 +-- .../src/components/game/gameModes/DailyGameMode.js | 12 +++++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/questionservice/question-service.js b/questionservice/question-service.js index 10a21d7d..8d5bfe1a 100644 --- a/questionservice/question-service.js +++ b/questionservice/question-service.js @@ -46,6 +46,7 @@ app.get('/getQuestionDiaria', async(req,res)=> { try{ const idioma = req.query.idioma; const fecha = req.query.fecha; + console.log("idioma: "+idioma+" fecha: "+fecha); //coger pregunta bd const questions = await question.obtenerPreguntaDiaria(idioma, fecha); //para devolver la pregunta @@ -58,11 +59,9 @@ app.get('/getQuestionDiaria', async(req,res)=> { }); app.get('/getQuestionModoBasico', async(req,res)=> { - console.log('entra en el getQuestionModoBasico del question Service'); try{ const idioma = req.query.idioma; - console.log("idioma",idioma); //coger pregunta bd const questions = await question.obtenerPregunta(10, idioma); //para devolver la pregunta diff --git a/webapp/src/components/game/gameModes/DailyGameMode.js b/webapp/src/components/game/gameModes/DailyGameMode.js index eca3e80c..0e6524d6 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.js @@ -6,11 +6,21 @@ class DailyGameMode extends BasicGame{ constructor() { super(); this.enviarHistorialPorQueHasAcetado=false; + console.log("entra en dailygamemode"); } async fetchQuestions() { try { - const response = await fetch(`${this.apiEndpoint}/getQuestionDiaria`); + + const fecha = new Date(); // Obtenemos la fecha actual + // como nos da tambien la hora y no queremos eso, la eliminamos + const año = fecha.getFullYear(); + const mes = fecha.getMonth() + 1; + const dia = fecha.getDate(); + // Formateamos la fecha para que sea compatible con la base de datos + const fechaSinHora = `${año}-${mes < 10 ? '0' : ''}${mes}-${dia < 10 ? '0' : ''}${dia}`; + + const response = await fetch(`${this.apiEndpoint}/getQuestionDiaria?idioma=${this.idioma}&fecha=${fechaSinHora}`); const data = await response.json(); this.questions = Object.values(data); From b5d31b2db7602e40b28edac7f4777a7ab4643e69 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 13:06:34 +0200 Subject: [PATCH 02/21] actualizado nombre de la cookie para el questiondiaria --- webapp/src/components/game/gameModes/DailyGameMode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/components/game/gameModes/DailyGameMode.js b/webapp/src/components/game/gameModes/DailyGameMode.js index 0e6524d6..fb36d706 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.js @@ -109,7 +109,7 @@ class DailyGameMode extends BasicGame{ expiryDate.setHours(24, 0, 0, 0); // Almacenar la variable en localStorage con la fecha de caducidad - localStorage.setItem('diaria', JSON.stringify({ + localStorage.setItem('lastDailyGame', JSON.stringify({ value: 'valor que quieras almacenar', expiry: expiryDate.getTime(), })); From 53fbba759b8216b41c62b0fbe7aa96d875ed9904 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 13:59:16 +0200 Subject: [PATCH 03/21] pruebas para que se guarde bien lo de la questionDiaria --- gatewayservice/gateway-service.js | 1 + users/authservice/auth-service.js | 43 +++++++++++++++- .../game/gameModes/DailyGameMode.js | 51 +++++++++++++++---- webapp/src/components/home/Home.js | 6 ++- 4 files changed, 89 insertions(+), 12 deletions(-) diff --git a/gatewayservice/gateway-service.js b/gatewayservice/gateway-service.js index 7582b512..e2613a31 100644 --- a/gatewayservice/gateway-service.js +++ b/gatewayservice/gateway-service.js @@ -36,6 +36,7 @@ const handleServiceRequest = async (req, res, serviceUrl) => { }; app.post('/login', (req, res) => handleServiceRequest(req, res, serviceUrls.auth)); +app.post('/updateUserDaily', (req, res) => handleServiceRequest(req, res, serviceUrls.auth)); app.post('/adduser', (req, res) => handleServiceRequest(req, res, serviceUrls.user)); //*********************ENDPOINTS DEL QUESTION SERVICE********************************************* */ diff --git a/users/authservice/auth-service.js b/users/authservice/auth-service.js index 8722a7a2..7debd9de 100644 --- a/users/authservice/auth-service.js +++ b/users/authservice/auth-service.js @@ -23,6 +23,17 @@ function validateRequiredFields(req, requiredFields) { } } +function getFecha() { + const fecha = new Date(); // Obtenemos la fecha actual + // como nos da tambien la hora y no queremos eso, la eliminamos + const año = fecha.getFullYear(); + const mes = fecha.getMonth() + 1; + const dia = fecha.getDate(); + // Formateamos la fecha para que sea compatible con la base de datos + const fechaSinHora = `${año}-${mes < 10 ? '0' : ''}${mes}-${dia < 10 ? '0' : ''}${dia}`; + return fechaSinHora; +} + // Route for user login app.post('/login', async (req, res) => { try { @@ -38,8 +49,22 @@ app.post('/login', async (req, res) => { if (user && await bcrypt.compare(password, user.password)) { // Generate a JWT token const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' }); + + let ultimaDiaria; + + //comprobamos lo de diaria + if(user.diaria === getFecha()){ + let expiryDate = new Date(); + expiryDate.setHours(24, 0, 0, 0); + //si no hay ese token lo creamos + ultimaDiaria = { + value: 'valor que quieras almacenar', + expiry: expiryDate.getTime() + }; + } + // Respond with the token and user information - res.json({ token: token, username: username, createdAt: user.createdAt , lastDailyGame: user.lastDailyGame}); + res.json({ token: token, username: username, createdAt: user.createdAt , lastDailyGame: ultimaDiaria}); } else { res.status(401).json({ error: 'Credenciales erroneas' }); } @@ -48,6 +73,22 @@ app.post('/login', async (req, res) => { } }); +app.post('/updateUserDaily', async (req, res) => { + try { + console.log("Entra en el auth service del update") + if((req.body.user != null && req.body.fecha != null) || (req.body.user != undefined && req.body.fecha != undefined)){ + var user = await User.findOneAndUpdate( + { username:req.body.user, $or: [{ diaria: null }, { diaria: { $exists: true } }] }, + { $set: { diaria: req.body.fecha } }, // Establecer el valor de 'diaria' a la fecha proporcionada + { new: true, upsert: true, strict: false } // Para devolver el documento actualizado y permitir campos no definidos en el esquema + ); + } + + } catch (error) { + res.status(400).json({ error: error.message }); + } +}); + // Start the server const server = app.listen(port, () => { console.log(`Auth Service listening at http://localhost:${port}`); diff --git a/webapp/src/components/game/gameModes/DailyGameMode.js b/webapp/src/components/game/gameModes/DailyGameMode.js index fb36d706..4097dc4d 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.js @@ -7,20 +7,15 @@ class DailyGameMode extends BasicGame{ super(); this.enviarHistorialPorQueHasAcetado=false; console.log("entra en dailygamemode"); + this.fechaAct = this.fechaActual(); } async fetchQuestions() { try { - const fecha = new Date(); // Obtenemos la fecha actual - // como nos da tambien la hora y no queremos eso, la eliminamos - const año = fecha.getFullYear(); - const mes = fecha.getMonth() + 1; - const dia = fecha.getDate(); - // Formateamos la fecha para que sea compatible con la base de datos - const fechaSinHora = `${año}-${mes < 10 ? '0' : ''}${mes}-${dia < 10 ? '0' : ''}${dia}`; + - const response = await fetch(`${this.apiEndpoint}/getQuestionDiaria?idioma=${this.idioma}&fecha=${fechaSinHora}`); + const response = await fetch(`${this.apiEndpoint}/getQuestionDiaria?idioma=${this.idioma}&fecha=${this.fechaAct}`); const data = await response.json(); this.questions = Object.values(data); @@ -93,6 +88,7 @@ class DailyGameMode extends BasicGame{ //this.questionIndex=10; this.volverAJugarCoockie(); } + //next question con indice 10 termina el juego incrementCorrectas(){ this.enviarHistorialPorQueHasAcetado=true; @@ -103,7 +99,31 @@ class DailyGameMode extends BasicGame{ this.volverAJugarCoockie(); } - volverAJugarCoockie(){ + async volverAJugarCoockie(){ + try { + console.log("entra en el try"); + const volverJugarData = { + user: null, + fecha : this.fechaAct + }; + //sacar del localStorage el usuario + volverJugarData.user = localStorage.getItem('username'); + + const response = await fetch(`${this.apiEndpoint}/updateUserDaily`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json' + }, + body: JSON.stringify(volverJugarData) + }); + const data = await response.json(); + console.log('Datos enviados:', data); + + } catch (error) { + console.error('Error enviando los datos de diaria del usuario:', error); + } + + console.log("sigue apra el localstorage"); // Obtener la fecha actual y establecer la hora a las 12 de la noche let expiryDate = new Date(); expiryDate.setHours(24, 0, 0, 0); @@ -113,9 +133,20 @@ class DailyGameMode extends BasicGame{ value: 'valor que quieras almacenar', expiry: expiryDate.getTime(), })); + + console.log("localStorage" + localStorage.getItem('lastDailyGame')); } - + fechaActual(){ + const fecha = new Date(); // Obtenemos la fecha actual + // como nos da tambien la hora y no queremos eso, la eliminamos + const año = fecha.getFullYear(); + const mes = fecha.getMonth() + 1; + const dia = fecha.getDate(); + // Formateamos la fecha para que sea compatible con la base de datos + const fechaSinHora = `${año}-${mes < 10 ? '0' : ''}${mes}-${dia < 10 ? '0' : ''}${dia}`; + return fechaSinHora; + } } module.exports = DailyGameMode ; \ No newline at end of file diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index cc5b7c2f..9b36e6f6 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -26,7 +26,11 @@ const Home = () => { navigate("/customWindow"); }; const handleClickDiario = () => { - let diaria = JSON.parse(localStorage.getItem('lastDailyGame')); + let diaria = null; + console.log("localll" + localStorage.getItem('lastDailyGame')); + if(localStorage.getItem('lastDailyGame') === undefined){ + diaria = JSON.parse(localStorage.getItem('lastDailyGame')); + } // Comprobar si la variable ha caducado if (diaria !== null && diaria.expiry > Date.now()) { From e592f9a0be0d057ee09a2781d9ab382469447ae3 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 16:07:27 +0200 Subject: [PATCH 04/21] question diaria deberia funcionar correctamente --- users/authservice/auth-model.js | 2 +- users/authservice/auth-service.js | 11 +++++------ webapp/src/components/authcontext.js | 5 ++++- webapp/src/components/game/gameModes/DailyGameMode.js | 3 +-- webapp/src/components/home/Home.js | 2 +- webapp/src/components/login/Login.js | 3 ++- 6 files changed, 14 insertions(+), 12 deletions(-) diff --git a/users/authservice/auth-model.js b/users/authservice/auth-model.js index 8d764035..14cb4fd5 100644 --- a/users/authservice/auth-model.js +++ b/users/authservice/auth-model.js @@ -5,7 +5,7 @@ const userSchema = new mongoose.Schema({ username: String, password: String, createdAt: Date, - lastDailyGame: Date, + diaria: String, }); const User = mongoose.model('User', userSchema); diff --git a/users/authservice/auth-service.js b/users/authservice/auth-service.js index 7debd9de..c2f49e6d 100644 --- a/users/authservice/auth-service.js +++ b/users/authservice/auth-service.js @@ -51,16 +51,15 @@ app.post('/login', async (req, res) => { const token = jwt.sign({ userId: user._id }, 'your-secret-key', { expiresIn: '1h' }); let ultimaDiaria; - - //comprobamos lo de diaria + if(user.diaria === getFecha()){ let expiryDate = new Date(); expiryDate.setHours(24, 0, 0, 0); //si no hay ese token lo creamos - ultimaDiaria = { + ultimaDiaria = JSON.stringify({ value: 'valor que quieras almacenar', - expiry: expiryDate.getTime() - }; + expiry: expiryDate.getTime(), + }); } // Respond with the token and user information @@ -83,7 +82,7 @@ app.post('/updateUserDaily', async (req, res) => { { new: true, upsert: true, strict: false } // Para devolver el documento actualizado y permitir campos no definidos en el esquema ); } - + res.json({ user: user}); } catch (error) { res.status(400).json({ error: error.message }); } diff --git a/webapp/src/components/authcontext.js b/webapp/src/components/authcontext.js index 20816bbd..eba9b5ba 100644 --- a/webapp/src/components/authcontext.js +++ b/webapp/src/components/authcontext.js @@ -5,12 +5,15 @@ export const AuthContext = createContext(); export const AuthProvider = ({ children }) => { const [token, setToken] = useState(localStorage.getItem('token')); // leer el token del localStorage const [username,setUsername]=useState(localStorage.getItem('username')); + const [lastDailyGame,setLastDailyGame]=useState(localStorage.getItem('lastDailyGame')); - const handleLogin = (jwtToken,username) => { // Modifica handleLogin para aceptar un token + const handleLogin = (jwtToken,username,lastDailyGame) => { // Modifica handleLogin para aceptar un token setToken(jwtToken); // Guarda el token en el estado setUsername(username); //almacena el username + setLastDailyGame(lastDailyGame); localStorage.setItem('token', jwtToken); // Guarda el token en el localStorage localStorage.setItem('username',username); + localStorage.setItem('lastDailyGame',lastDailyGame); }; const logout = () => { diff --git a/webapp/src/components/game/gameModes/DailyGameMode.js b/webapp/src/components/game/gameModes/DailyGameMode.js index 4097dc4d..1f73a614 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.js @@ -123,8 +123,7 @@ class DailyGameMode extends BasicGame{ console.error('Error enviando los datos de diaria del usuario:', error); } - console.log("sigue apra el localstorage"); - // Obtener la fecha actual y establecer la hora a las 12 de la noche + // Obtener la fecha actual y establecer la hora a las 12 de la noche let expiryDate = new Date(); expiryDate.setHours(24, 0, 0, 0); diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index 9b36e6f6..3d0fe0bc 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -28,7 +28,7 @@ const Home = () => { const handleClickDiario = () => { let diaria = null; console.log("localll" + localStorage.getItem('lastDailyGame')); - if(localStorage.getItem('lastDailyGame') === undefined){ + if(localStorage.getItem('lastDailyGame') !== undefined){ diaria = JSON.parse(localStorage.getItem('lastDailyGame')); } diff --git a/webapp/src/components/login/Login.js b/webapp/src/components/login/Login.js index 359d75b9..8edd3383 100644 --- a/webapp/src/components/login/Login.js +++ b/webapp/src/components/login/Login.js @@ -36,7 +36,8 @@ const Login = (darkMode) => { // Extract data from the response const { createdAt: userCreatedAt} = response.data; - handleLogin(response.data.token,response.data.username);//pasasr el token que nos da el servidor + console.log(response.data.lastDailyGame); + handleLogin(response.data.token,response.data.username, response.data.lastDailyGame);//pasasr el token que nos da el servidor //meter en localstorage el ultimo partida localStorage.setItem('lastDailyGame', response.data.lastDailyGame); From 9693cb08942bb767d1d9e6880bc64e4a38a3a7b7 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 16:12:58 +0200 Subject: [PATCH 05/21] cambiado la forma de que salga el que el usuario ya ha jugado la pregunta diaria --- webapp/src/components/home/Home.js | 9 ++++++++- webapp/src/components/rooms/Room.js | 6 ------ .../src/internacionalizacion/locales/en/translation.json | 5 ++++- .../src/internacionalizacion/locales/es/translation.json | 4 +++- 4 files changed, 15 insertions(+), 9 deletions(-) diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index 3d0fe0bc..ccc9b220 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -35,7 +35,14 @@ const Home = () => { // Comprobar si la variable ha caducado if (diaria !== null && diaria.expiry > Date.now()) { // La variable no ha caducado, mostrar una alerta - alert('Ya has jugado hoy. Por favor, vuelve mañana.'); + Swal.fire({ + title: t('diaryGameTitle'), + text: t('diaryGameText'), + confirmButtonText: i18n.t('close'), + customClass: { + popup: 'yaJugoDiaria' + } + }); } else { // La variable ha caducado o no existe, navegar a /gameDiaria navigate("/gameDiaria"); diff --git a/webapp/src/components/rooms/Room.js b/webapp/src/components/rooms/Room.js index 3c31b18a..6a6edb09 100644 --- a/webapp/src/components/rooms/Room.js +++ b/webapp/src/components/rooms/Room.js @@ -90,7 +90,6 @@ function Room({ darkMode }) { } } - //funcion que le pasas a game para gestionar el finaldel juego function endGame(results) { @@ -101,11 +100,6 @@ function Room({ darkMode }) { } //pasasrlelos datos al juego - - - - - return (

{t('room')}{roomId}

diff --git a/webapp/src/internacionalizacion/locales/en/translation.json b/webapp/src/internacionalizacion/locales/en/translation.json index a9e20cd3..bd851a31 100644 --- a/webapp/src/internacionalizacion/locales/en/translation.json +++ b/webapp/src/internacionalizacion/locales/en/translation.json @@ -95,6 +95,9 @@ "wrongAnswers": "Wrong Answers: ", "timePlayed": "Total Time Played: ", - "createRoomInfo": "By clicking 'Create Room', a new room with a unique ID will be created. You'll need to share this ID with the people you want to join your room." + "createRoomInfo": "By clicking 'Create Room', a new room with a unique ID will be created. You'll need to share this ID with the people you want to join your room.", + + "diaryGameTitle": "Daily Challenge", + "diaryGameText": "You have already played today's daily challenge, come back tomorrow to play again." } \ No newline at end of file diff --git a/webapp/src/internacionalizacion/locales/es/translation.json b/webapp/src/internacionalizacion/locales/es/translation.json index 570e4c81..f82a565d 100644 --- a/webapp/src/internacionalizacion/locales/es/translation.json +++ b/webapp/src/internacionalizacion/locales/es/translation.json @@ -96,5 +96,7 @@ "customModeNumPreguntas":"Seleccione el número de preguntas que desea en la partida: ", "customModeNumTiempo":"Seleccione el tiempo que desea de la partida: ", "cancelar": "Cancelar", - "jugar": "Jugar" + "jugar": "Jugar", + "diaryGameTitle" : "Desafio diario", + "diaryGameText" : "Ya has jugado el desafio diario de hoy, vuelve mañana para jugar de nuevo" } \ No newline at end of file From d46f3dcf4aaa9889cd4abea0efab384b3223e6d7 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 16:20:25 +0200 Subject: [PATCH 06/21] actualizados los tests e2e del daily mode --- webapp/e2e/features/dailyQuestionMode-form.feature | 2 +- webapp/e2e/steps/dailyQuestionMode-form.steps.js | 6 ++---- webapp/src/components/home/Home.js | 8 ++------ 3 files changed, 5 insertions(+), 11 deletions(-) diff --git a/webapp/e2e/features/dailyQuestionMode-form.feature b/webapp/e2e/features/dailyQuestionMode-form.feature index d93d60ec..f018c21a 100644 --- a/webapp/e2e/features/dailyQuestionMode-form.feature +++ b/webapp/e2e/features/dailyQuestionMode-form.feature @@ -11,4 +11,4 @@ Scenario: User play the daily question Scenario: User wants to play the daily question but he/she/they already played it When I try to play the daily question - Then I should see a message with a message \ No newline at end of file + Then I should see a message \ No newline at end of file diff --git a/webapp/e2e/steps/dailyQuestionMode-form.steps.js b/webapp/e2e/steps/dailyQuestionMode-form.steps.js index d4ffeca0..96394acf 100644 --- a/webapp/e2e/steps/dailyQuestionMode-form.steps.js +++ b/webapp/e2e/steps/dailyQuestionMode-form.steps.js @@ -93,12 +93,10 @@ defineFeature(feature, test => { when('I try to play the daily question', async () => { //vamos a las opciones del usuario await expect(page).toClick("#button-diario-game"); - - //pendiente de implementar }); - then('I should see a message with a message', async () => { - //pendiente de implementar + then('I should see a message', async () => { + await expect(page).toMatchElement(".yaJugoDiaria"); }); }) diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index ccc9b220..097ebeb7 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -1,4 +1,5 @@ import React from 'react'; +import Swal from 'sweetalert2'; import { Box, Image, Button,ChakraProvider } from '@chakra-ui/react'; import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; @@ -9,9 +10,6 @@ const Home = () => { const {t} = useTranslation(); const navigate = useNavigate(); - - - const handleClickClassic = () => { navigate("/game"); }; @@ -38,7 +36,7 @@ const Home = () => { Swal.fire({ title: t('diaryGameTitle'), text: t('diaryGameText'), - confirmButtonText: i18n.t('close'), + confirmButtonText: t('close'), customClass: { popup: 'yaJugoDiaria' } @@ -48,8 +46,6 @@ const Home = () => { navigate("/gameDiaria"); } }; - - return ( From 0a51b46fc2bf22d9bf6786fc986b174f7292c569 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 16:34:27 +0200 Subject: [PATCH 07/21] actualizado el modo diaria y ahora si, deberia funcionar bien --- webapp/src/components/home/Home.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index 097ebeb7..ba5e7612 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -25,8 +25,9 @@ const Home = () => { }; const handleClickDiario = () => { let diaria = null; - console.log("localll" + localStorage.getItem('lastDailyGame')); - if(localStorage.getItem('lastDailyGame') !== undefined){ + let daily = localStorage.getItem('lastDailyGame'); + console.log(typeof(daily)); + if(daily !== undefined && daily !== "undefined"){ diaria = JSON.parse(localStorage.getItem('lastDailyGame')); } From fc7bfa7df1c412109c7076f5aa96d87d6cd66ff8 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 16:52:49 +0200 Subject: [PATCH 08/21] intento de arreglar el modo categoria (pendiente probarlo porque mi ordenador no da para mas con el docker --- webapp/src/App.js | 7 +- .../src/components/categories/Categories.js | 136 ++++++++++++++++++ .../components/categories/Categories.test.js | 36 +++++ .../src/components/categories/categories.css | 13 ++ .../game/gameModes/SameCategoryMode.js | 4 +- webapp/src/components/home/Home.js | 2 +- 6 files changed, 195 insertions(+), 3 deletions(-) create mode 100644 webapp/src/components/categories/Categories.js create mode 100644 webapp/src/components/categories/Categories.test.js create mode 100644 webapp/src/components/categories/categories.css diff --git a/webapp/src/App.js b/webapp/src/App.js index 69c7adc5..7ca45794 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -65,11 +65,16 @@ const App = () => { } /> - } /> + + + + } /> diff --git a/webapp/src/components/categories/Categories.js b/webapp/src/components/categories/Categories.js new file mode 100644 index 00000000..96846e55 --- /dev/null +++ b/webapp/src/components/categories/Categories.js @@ -0,0 +1,136 @@ +import React from 'react'; +import { Box, Image, Button,ChakraProvider } from '@chakra-ui/react'; +import { useTranslation } from 'react-i18next'; +import { useNavigate } from 'react-router-dom'; + + +const Home = () => { + + const {t} = useTranslation(); + const navigate = useNavigate(); + + const handleClickGeography = () => { + navigate("/gameSameCat?category=geografia"); + }; + const handleClickArt = () => { + navigate("/gameSameCat?category=arte"); + }; + const handleClickEntertainment = () => { + navigate("/gameSameCat?category=entretenimiento"); + }; + const handleClickSports = () => { + navigate("/gameSameCat?category=deportes"); + }; + const handleClickHistory = () => { + navigate("/gameSameCat?category=historia"); + }; + const handleClickScience = () => { + navigate("/gameSameCat?category=ciencia"); + }; + const handleClickMusic = () => { + navigate("/gameSameCat?category=musica"); + }; + + return ( + + + + + + + + + + + + Icono WIQ05 + + + + + + + + + + + + + + ); +}; + +export default CategoriesWindow; \ No newline at end of file diff --git a/webapp/src/components/categories/Categories.test.js b/webapp/src/components/categories/Categories.test.js new file mode 100644 index 00000000..6d73713c --- /dev/null +++ b/webapp/src/components/categories/Categories.test.js @@ -0,0 +1,36 @@ +import React from 'react'; +import { render, fireEvent } from '@testing-library/react'; +import { BrowserRouter as Router } from 'react-router-dom'; +import { useNavigate } from 'react-router-dom'; +import Home from './Home'; + +jest.mock('react-router-dom', () => ({ + ...jest.requireActual('react-router-dom'), + useNavigate: jest.fn(), +})); + +test('navigates when buttons are clicked', () => { + const navigate = jest.fn(); + useNavigate.mockReturnValue(navigate); + + const { getByText } = render( + + + + ); + + fireEvent.click(getByText('modoClasico')); + expect(navigate).toHaveBeenCalledWith('/game'); + + fireEvent.click(getByText('modoMismaCategoria')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat'); + + fireEvent.click(getByText('modoInfinito')); + expect(navigate).toHaveBeenCalledWith('/gameInfinity'); + + fireEvent.click(getByText('modoCustom')); + expect(navigate).toHaveBeenCalledWith('/customWindow'); + + fireEvent.click(getByText('modoDiario')); + expect(navigate).toHaveBeenCalledWith('/game'); +}); \ No newline at end of file diff --git a/webapp/src/components/categories/categories.css b/webapp/src/components/categories/categories.css new file mode 100644 index 00000000..4b9ba6dc --- /dev/null +++ b/webapp/src/components/categories/categories.css @@ -0,0 +1,13 @@ +body { + margin: 0; + font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + } + + code { + font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New', + monospace; + } \ No newline at end of file diff --git a/webapp/src/components/game/gameModes/SameCategoryMode.js b/webapp/src/components/game/gameModes/SameCategoryMode.js index 3225646b..16c60333 100644 --- a/webapp/src/components/game/gameModes/SameCategoryMode.js +++ b/webapp/src/components/game/gameModes/SameCategoryMode.js @@ -1,11 +1,13 @@ const { default: BasicGame } = require("../BasicGame"); +import { useParams } from 'react-router-dom'; class SameCategoryMode extends BasicGame{ async fetchQuestions() { + let { category } = useParams(); try { //getQuestionModoMismaCategoria?idioma=${idioma}?=categoria=${categoria} - const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria`); + const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria?idioma=${this.language}?categoria=${category}`); const data = await response.json(); this.questions = Object.values(data); diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index ba5e7612..c67ec589 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -14,7 +14,7 @@ const Home = () => { navigate("/game"); }; const handleClickSameCat = () => { - navigate("/gameSameCat"); + navigate("/sameCategoryWindow"); }; const handleClickInfinity = () => { From d11136e35b6f3aaa6d664c6e89a360d33d04db7d Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 17:07:15 +0200 Subject: [PATCH 09/21] empezar los tests e2e del categoria y arreglar algunas cosas --- .../features/customCategoryMode-form.feature | 10 ++ .../steps/customCategoryMode-form.steps.js | 94 +++++++++++++++++++ .../e2e/steps/dailyQuestionMode-form.steps.js | 2 - webapp/src/App.js | 7 +- .../src/components/categories/Categories.js | 2 +- .../game/gameModes/SameCategoryMode.js | 10 +- 6 files changed, 117 insertions(+), 8 deletions(-) create mode 100644 webapp/e2e/features/customCategoryMode-form.feature create mode 100644 webapp/e2e/steps/customCategoryMode-form.steps.js diff --git a/webapp/e2e/features/customCategoryMode-form.feature b/webapp/e2e/features/customCategoryMode-form.feature new file mode 100644 index 00000000..76d79b6f --- /dev/null +++ b/webapp/e2e/features/customCategoryMode-form.feature @@ -0,0 +1,10 @@ +Feature: Custom Category Mode + +Scenario: The user is not registered in the site + Given An unregistered user + When I fill the data in the form and press submit + Then The user is logged + +Scenario: User play the custom category game + When I play the game + Then I should see a message with my game results diff --git a/webapp/e2e/steps/customCategoryMode-form.steps.js b/webapp/e2e/steps/customCategoryMode-form.steps.js new file mode 100644 index 00000000..2fb2d264 --- /dev/null +++ b/webapp/e2e/steps/customCategoryMode-form.steps.js @@ -0,0 +1,94 @@ +const puppeteer = require('puppeteer'); +const { defineFeature, loadFeature }=require('jest-cucumber'); +const setDefaultOptions = require('expect-puppeteer').setDefaultOptions +const feature = loadFeature('./features/customCategoryMode-form.feature'); + +let page; +let browser; + +defineFeature(feature, test => { + + beforeAll(async () => { + browser = process.env.GITHUB_ACTIONS + ? await puppeteer.launch() + : await puppeteer.launch({ headless: false, slowMo: 20 }); + page = await browser.newPage(); + //Way of setting up the timeout + setDefaultOptions({ timeout: 10000 }) + + await page + .goto("http://localhost:3000/addUser", { + waitUntil: "networkidle0", + }) + .catch(() => {}); + + }); + + afterEach(async () => { + await page.waitForTimeout(1000); + + await page.goto("http://localhost:3000/home", { + waitUntil: "networkidle0", + }); + }); + + //test para crear el usuario + test('The user is not registered in the site', ({given,when,then}) => { + + let email; + let username; + let password; + let passwordConfirmation; + + given('An unregistered user', async () => { + email = "userTestDailyQuestionGame@email.com" + username = "userTestDailyQuestionGame" + password = "Contraseña_1?" + passwordConfirmation = "Contraseña_1?" + }); + + when('I fill the data in the form and press submit', async () => { + + await expect(page).toFill('input[name="email"]', email); + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toFill('input[name="passwordConfirm"]', passwordConfirmation); + + await expect(page).toClick('#addRegister'); + + await page.goto("http://localhost:3000/login", { + waitUntil: "networkidle0", + }); + + //nos logeamos con ese usuario + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + + await expect(page).toClick('#login'); + }); + + then('The user is logged', async () => { + await expect(page).toMatchElement("#iconoUsuario"); + }); + }) + + test('User play the custom category game', ({when,then}) => { + + when('I play the game', async () => { + //como en la bd tenemos preguntas de arte vamos a elegir esa categoria + await expect(page).toClick("#button-samecat-game"); + await expect(page).toClick("#button-category-art"); + + //empieza el juego y responde 10 preguntas + for(let i = 0; i < 10; i++){ + await expect(page).toClick("#buttonAnswer0"); + } + }); + + then('I should see a message with my game results', async () => { + //comprobamos que se ha acabado el juego + await expect(page).toMatchElement(".finDelJuego"); + }); + }) + +}); \ No newline at end of file diff --git a/webapp/e2e/steps/dailyQuestionMode-form.steps.js b/webapp/e2e/steps/dailyQuestionMode-form.steps.js index 96394acf..9edd2852 100644 --- a/webapp/e2e/steps/dailyQuestionMode-form.steps.js +++ b/webapp/e2e/steps/dailyQuestionMode-form.steps.js @@ -75,7 +75,6 @@ defineFeature(feature, test => { test('User play the daily question', ({when,then}) => { when('I play the daily question', async () => { - //vamos a las opciones del usuario await expect(page).toClick("#button-diario-game"); //empieza el juego y respoonde la pregunta @@ -91,7 +90,6 @@ defineFeature(feature, test => { test('User wants to play the daily question but he/she/they already played it', ({when,then}) => { when('I try to play the daily question', async () => { - //vamos a las opciones del usuario await expect(page).toClick("#button-diario-game"); }); diff --git a/webapp/src/App.js b/webapp/src/App.js index 7ca45794..4c6f763f 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -3,7 +3,7 @@ import Navbar from './components/navbar/NavBar'; import AddUser from './components/adduser/AddUser'; import Login from './components/login/Login'; import { AuthProvider } from './components/authcontext'; -import { BrowserRouter as Router, Routes, Route } from 'react-router-dom'; +import { BrowserRouter as Router, Routes, Route, useParams } from 'react-router-dom'; import Game from './components/game/Game'; import SameCategoryMode from './components/game/gameModes/SameCategoryMode'; import InfinityGameMode from './components/game/gameModes/InfinityGameMode'; @@ -24,6 +24,7 @@ import { Ranking } from './components/ranking/Ranking'; import RankingRoom from './components/rooms/RankingRoom'; // Asegúrate de que la ruta de importación es correcta import BasicGame from './components/game/BasicGame'; import DailyGameMode from './components/game/gameModes/DailyGameMode'; +import CategoriesWindow from './components/categories/Categories'; const App = () => { @@ -32,6 +33,8 @@ const App = () => { const [timeToAnswer, setTime] = useState(20); const [nQuestions, setNQuestions] = useState(20); + const { category } = useParams(); + useEffect(() => { if (darkMode) { document.body.classList.add('dark-mode'); @@ -42,7 +45,7 @@ const App = () => { } }, [darkMode]); - const sameCatMode = new SameCategoryMode(); + const sameCatMode = new SameCategoryMode({category}); const infinityMode = new InfinityGameMode(); const dailyGameMode = new DailyGameMode(); return ( diff --git a/webapp/src/components/categories/Categories.js b/webapp/src/components/categories/Categories.js index 96846e55..22890a92 100644 --- a/webapp/src/components/categories/Categories.js +++ b/webapp/src/components/categories/Categories.js @@ -4,7 +4,7 @@ import { useTranslation } from 'react-i18next'; import { useNavigate } from 'react-router-dom'; -const Home = () => { +const CategoriesWindow = () => { const {t} = useTranslation(); const navigate = useNavigate(); diff --git a/webapp/src/components/game/gameModes/SameCategoryMode.js b/webapp/src/components/game/gameModes/SameCategoryMode.js index 16c60333..af3c31f0 100644 --- a/webapp/src/components/game/gameModes/SameCategoryMode.js +++ b/webapp/src/components/game/gameModes/SameCategoryMode.js @@ -1,13 +1,17 @@ + const { default: BasicGame } = require("../BasicGame"); -import { useParams } from 'react-router-dom'; class SameCategoryMode extends BasicGame{ + constructor(category){ + super(); + this.category = category; + } + async fetchQuestions() { - let { category } = useParams(); try { //getQuestionModoMismaCategoria?idioma=${idioma}?=categoria=${categoria} - const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria?idioma=${this.language}?categoria=${category}`); + const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria?idioma=${this.language}?categoria=${this.category}`); const data = await response.json(); this.questions = Object.values(data); From 8be0fac71cbadb0c296b914700ec47a87485c319 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 17:18:44 +0200 Subject: [PATCH 10/21] ya se pasa bien la url a los servicios falta mirar la categoria --- webapp/src/components/categories/Categories.js | 14 +++++++------- .../components/game/gameModes/SameCategoryMode.js | 3 +-- 2 files changed, 8 insertions(+), 9 deletions(-) diff --git a/webapp/src/components/categories/Categories.js b/webapp/src/components/categories/Categories.js index 22890a92..1331bb3c 100644 --- a/webapp/src/components/categories/Categories.js +++ b/webapp/src/components/categories/Categories.js @@ -10,25 +10,25 @@ const CategoriesWindow = () => { const navigate = useNavigate(); const handleClickGeography = () => { - navigate("/gameSameCat?category=geografia"); + navigate("/gameSameCat/geografia"); }; const handleClickArt = () => { - navigate("/gameSameCat?category=arte"); + navigate("/gameSameCat/arte"); }; const handleClickEntertainment = () => { - navigate("/gameSameCat?category=entretenimiento"); + navigate("/gameSameCat/entretenimiento"); }; const handleClickSports = () => { - navigate("/gameSameCat?category=deportes"); + navigate("/gameSameCat/deportes"); }; const handleClickHistory = () => { - navigate("/gameSameCat?category=historia"); + navigate("/gameSameCat/historia"); }; const handleClickScience = () => { - navigate("/gameSameCat?category=ciencia"); + navigate("/gameSameCat/ciencia"); }; const handleClickMusic = () => { - navigate("/gameSameCat?category=musica"); + navigate("/gameSameCat/musica"); }; return ( diff --git a/webapp/src/components/game/gameModes/SameCategoryMode.js b/webapp/src/components/game/gameModes/SameCategoryMode.js index af3c31f0..0fd847c6 100644 --- a/webapp/src/components/game/gameModes/SameCategoryMode.js +++ b/webapp/src/components/game/gameModes/SameCategoryMode.js @@ -10,8 +10,7 @@ class SameCategoryMode extends BasicGame{ async fetchQuestions() { try { - //getQuestionModoMismaCategoria?idioma=${idioma}?=categoria=${categoria} - const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria?idioma=${this.language}?categoria=${this.category}`); + const response = await fetch(`${this.apiEndpoint}/getQuestionModoMismaCategoria?idioma=${this.idioma}&categoria=${this.category}`); const data = await response.json(); this.questions = Object.values(data); From c83451cfebf2e4cbe813cfa836eb9982f39f0a49 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 17:57:34 +0200 Subject: [PATCH 11/21] arreglos para el modo de elegir categoria --- webapp/e2e/steps/basicButtons-form.steps.js | 4 ++++ .../steps/customCategoryMode-form.steps.js | 4 ++++ .../e2e/steps/dailyQuestionMode-form.steps.js | 4 ++++ webapp/e2e/steps/gameBasicMode-form.steps.js | 5 +++- webapp/e2e/steps/register-form.steps.js | 1 - webapp/src/App.js | 22 ++++++++++++----- .../game/gameModes/SameCategoryMode.js | 24 ++++++++++++++++--- webapp/src/components/home/Home.js | 2 +- 8 files changed, 54 insertions(+), 12 deletions(-) diff --git a/webapp/e2e/steps/basicButtons-form.steps.js b/webapp/e2e/steps/basicButtons-form.steps.js index 45904773..dbe57fd3 100644 --- a/webapp/e2e/steps/basicButtons-form.steps.js +++ b/webapp/e2e/steps/basicButtons-form.steps.js @@ -186,5 +186,9 @@ defineFeature(feature, test => { await expect(page).toMatchElement("#loginButton"); }); }) + + afterAll(async ()=>{ + browser.close() + }) }); \ No newline at end of file diff --git a/webapp/e2e/steps/customCategoryMode-form.steps.js b/webapp/e2e/steps/customCategoryMode-form.steps.js index 2fb2d264..d1b8b413 100644 --- a/webapp/e2e/steps/customCategoryMode-form.steps.js +++ b/webapp/e2e/steps/customCategoryMode-form.steps.js @@ -91,4 +91,8 @@ defineFeature(feature, test => { }); }) + afterAll(async ()=>{ + browser.close() + }) + }); \ No newline at end of file diff --git a/webapp/e2e/steps/dailyQuestionMode-form.steps.js b/webapp/e2e/steps/dailyQuestionMode-form.steps.js index 9edd2852..292fa27d 100644 --- a/webapp/e2e/steps/dailyQuestionMode-form.steps.js +++ b/webapp/e2e/steps/dailyQuestionMode-form.steps.js @@ -98,4 +98,8 @@ defineFeature(feature, test => { }); }) + afterAll(async ()=>{ + browser.close() + }) + }); \ No newline at end of file diff --git a/webapp/e2e/steps/gameBasicMode-form.steps.js b/webapp/e2e/steps/gameBasicMode-form.steps.js index f077b68a..947dd9b1 100644 --- a/webapp/e2e/steps/gameBasicMode-form.steps.js +++ b/webapp/e2e/steps/gameBasicMode-form.steps.js @@ -88,7 +88,10 @@ defineFeature(feature, test => { await expect(page).toMatchElement(".finDelJuego"); }); }) - + + afterAll(async ()=>{ + browser.close() + }) }); \ No newline at end of file diff --git a/webapp/e2e/steps/register-form.steps.js b/webapp/e2e/steps/register-form.steps.js index 822d142f..16b00b9e 100644 --- a/webapp/e2e/steps/register-form.steps.js +++ b/webapp/e2e/steps/register-form.steps.js @@ -207,7 +207,6 @@ defineFeature(feature, test => { }); }) - afterAll(async ()=>{ browser.close() }) diff --git a/webapp/src/App.js b/webapp/src/App.js index 4c6f763f..545c76e5 100644 --- a/webapp/src/App.js +++ b/webapp/src/App.js @@ -33,8 +33,6 @@ const App = () => { const [timeToAnswer, setTime] = useState(20); const [nQuestions, setNQuestions] = useState(20); - const { category } = useParams(); - useEffect(() => { if (darkMode) { document.body.classList.add('dark-mode'); @@ -45,9 +43,21 @@ const App = () => { } }, [darkMode]); - const sameCatMode = new SameCategoryMode({category}); const infinityMode = new InfinityGameMode(); const dailyGameMode = new DailyGameMode(); + + const SameCategoryGame = () => { + const { category } = useParams(); + const sameCatMode = new SameCategoryMode(category); + + return + + + + + ; + }; + return ( @@ -69,9 +79,7 @@ const App = () => { } /> - - + } /> @@ -119,6 +127,8 @@ const App = () => { ); + + }; export default App; \ No newline at end of file diff --git a/webapp/src/components/game/gameModes/SameCategoryMode.js b/webapp/src/components/game/gameModes/SameCategoryMode.js index 0fd847c6..096f296c 100644 --- a/webapp/src/components/game/gameModes/SameCategoryMode.js +++ b/webapp/src/components/game/gameModes/SameCategoryMode.js @@ -1,5 +1,7 @@ -const { default: BasicGame } = require("../BasicGame"); +import BasicGame from '../BasicGame'; +import Swal from 'sweetalert2'; +import i18n from 'i18next'; // Importa i18n class SameCategoryMode extends BasicGame{ @@ -23,7 +25,23 @@ class SameCategoryMode extends BasicGame{ } async sendHistory(historyData) { - //No se guarda la partida si no es clásica + //No se guarda la partida si no es + Swal.fire({ + title: i18n.t('basicGameEnd'), + html: ` +

: ${i18n.t('correctAnswers')} ${this.correctas}

+

${i18n.t('wrongAnswers')} ${this.incorrectas}

+

${i18n.t('timePlayed')} ${this.tiempoTotal}

+ `, + confirmButtonText: i18n.t('close'), + customClass: { + popup: 'finDelJuego' + } + }).then(()=>{ + + this.navigate('/home'); + + }); } } -module.exports = SameCategoryMode ; \ No newline at end of file +export default SameCategoryMode; \ No newline at end of file diff --git a/webapp/src/components/home/Home.js b/webapp/src/components/home/Home.js index c67ec589..f404c8a7 100644 --- a/webapp/src/components/home/Home.js +++ b/webapp/src/components/home/Home.js @@ -26,7 +26,7 @@ const Home = () => { const handleClickDiario = () => { let diaria = null; let daily = localStorage.getItem('lastDailyGame'); - console.log(typeof(daily)); + if(daily !== undefined && daily !== "undefined"){ diaria = JSON.parse(localStorage.getItem('lastDailyGame')); } From 84deb3735a3a7687f76ec685a6ba8e70d38a1c92 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 19:49:03 +0200 Subject: [PATCH 12/21] empezar el test e2e del infinity --- webapp/e2e/features/infinityMode-form.feature | 10 ++ webapp/e2e/steps/infinityMode-form.steps.js | 99 +++++++++++++++++++ 2 files changed, 109 insertions(+) create mode 100644 webapp/e2e/features/infinityMode-form.feature create mode 100644 webapp/e2e/steps/infinityMode-form.steps.js diff --git a/webapp/e2e/features/infinityMode-form.feature b/webapp/e2e/features/infinityMode-form.feature new file mode 100644 index 00000000..4b11a583 --- /dev/null +++ b/webapp/e2e/features/infinityMode-form.feature @@ -0,0 +1,10 @@ +Feature: Infinity Mode + +Scenario: The user is not registered in the site + Given An unregistered user + When I fill the data in the form and press submit + Then The user is logged + +Scenario: User play the infinity mode + When I play the infinity mode + Then I should see a message with my game results \ No newline at end of file diff --git a/webapp/e2e/steps/infinityMode-form.steps.js b/webapp/e2e/steps/infinityMode-form.steps.js new file mode 100644 index 00000000..b5f03aa2 --- /dev/null +++ b/webapp/e2e/steps/infinityMode-form.steps.js @@ -0,0 +1,99 @@ +const puppeteer = require('puppeteer'); +const { defineFeature, loadFeature }=require('jest-cucumber'); +const setDefaultOptions = require('expect-puppeteer').setDefaultOptions +const feature = loadFeature('./features/infinityMode-form.feature'); + +let page; +let browser; + +defineFeature(feature, test => { + + beforeAll(async () => { + browser = process.env.GITHUB_ACTIONS + ? await puppeteer.launch() + : await puppeteer.launch({ headless: false, slowMo: 20 }); + page = await browser.newPage(); + //Way of setting up the timeout + setDefaultOptions({ timeout: 10000 }) + + await page + .goto("http://localhost:3000/addUser", { + waitUntil: "networkidle0", + }) + .catch(() => {}); + + }); + + afterEach(async () => { + await page.waitForTimeout(1000); + + await page.goto("http://localhost:3000/home", { + waitUntil: "networkidle0", + }); + }); + + //test para crear el usuario + test('The user is not registered in the site', ({given,when,then}) => { + + let email; + let username; + let password; + let passwordConfirmation; + + given('An unregistered user', async () => { + email = "userTestBasicGame@email.com" + username = "userTestBasicGame" + password = "Contraseña_1?" + passwordConfirmation = "Contraseña_1?" + }); + + when('I fill the data in the form and press submit', async () => { + + await expect(page).toFill('input[name="email"]', email); + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + await expect(page).toFill('input[name="passwordConfirm"]', passwordConfirmation); + + await expect(page).toClick('#addRegister'); + + await page.goto("http://localhost:3000/login", { + waitUntil: "networkidle0", + }); + + //nos logeamos con ese usuario + await expect(page).toFill('input[name="username"]', username); + await expect(page).toFill('input[name="password"]', password); + + await expect(page).toClick('#login'); + }); + + then('The user is logged', async () => { + await expect(page).toMatchElement("#iconoUsuario"); + }); + }) + + test('User play the infinity mode', ({when,then}) => { + + when('I play the infinity mode', async () => { + await expect(page).toClick("#button-infinite-game"); + + while (!(await page.$('.finDelJuego'))) { + // Responde a las preguntas + for (let i = 0; i < 10; i++) { + await expect(page).toClick("#buttonAnswer0"); + } + } + }); + + then('I should see a message with my game results', async () => { + //comprobamos que se ha acabado el juego + await expect(page).toMatchElement(".finDelJuego"); + }); + }) + + + afterAll(async ()=>{ + browser.close() + }) + +}); \ No newline at end of file From 60c401c197d7b7c1e1cfefba4b4e91836f264054 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:00:42 +0200 Subject: [PATCH 13/21] test e2e del infinity game pasan correctamente --- webapp/e2e/steps/infinityMode-form.steps.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/e2e/steps/infinityMode-form.steps.js b/webapp/e2e/steps/infinityMode-form.steps.js index b5f03aa2..38489709 100644 --- a/webapp/e2e/steps/infinityMode-form.steps.js +++ b/webapp/e2e/steps/infinityMode-form.steps.js @@ -41,8 +41,8 @@ defineFeature(feature, test => { let passwordConfirmation; given('An unregistered user', async () => { - email = "userTestBasicGame@email.com" - username = "userTestBasicGame" + email = "userTestInfinityGame@email.com" + username = "userTestInfinityGame" password = "Contraseña_1?" passwordConfirmation = "Contraseña_1?" }); From fd2f97aaedb6b12c161e6179a714cc6ba6a7136b Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:03:49 +0200 Subject: [PATCH 14/21] =?UTF-8?q?a=C3=B1adida=20internacionalizacion=20a?= =?UTF-8?q?=20los=20botones=20de=20las=20categorias?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../internacionalizacion/locales/en/translation.json | 10 +++++++++- .../internacionalizacion/locales/es/translation.json | 10 +++++++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/webapp/src/internacionalizacion/locales/en/translation.json b/webapp/src/internacionalizacion/locales/en/translation.json index bd851a31..e4dbb190 100644 --- a/webapp/src/internacionalizacion/locales/en/translation.json +++ b/webapp/src/internacionalizacion/locales/en/translation.json @@ -98,6 +98,14 @@ "createRoomInfo": "By clicking 'Create Room', a new room with a unique ID will be created. You'll need to share this ID with the people you want to join your room.", "diaryGameTitle": "Daily Challenge", - "diaryGameText": "You have already played today's daily challenge, come back tomorrow to play again." + "diaryGameText": "You have already played today's daily challenge, come back tomorrow to play again.", + + "categoryGeography": "Geography", + "categoryHistory": "History", + "categoryScience": "Science", + "categoryArt": "Art", + "categorySports": "Sports", + "categoryEntertainment": "Entertainment", + "categoryMusic": "Music" } \ No newline at end of file diff --git a/webapp/src/internacionalizacion/locales/es/translation.json b/webapp/src/internacionalizacion/locales/es/translation.json index f82a565d..b0bad32a 100644 --- a/webapp/src/internacionalizacion/locales/es/translation.json +++ b/webapp/src/internacionalizacion/locales/es/translation.json @@ -98,5 +98,13 @@ "cancelar": "Cancelar", "jugar": "Jugar", "diaryGameTitle" : "Desafio diario", - "diaryGameText" : "Ya has jugado el desafio diario de hoy, vuelve mañana para jugar de nuevo" + "diaryGameText" : "Ya has jugado el desafio diario de hoy, vuelve mañana para jugar de nuevo", + + "categoryGeography": "Geography", + "categoryHistory": "History", + "categoryScience": "Science", + "categoryArt": "Art", + "categorySports": "Sports", + "categoryEntertainment": "Entertainment", + "categoryMusic": "Music" } \ No newline at end of file From 4cf1198b8d35c7ed6129250775b2836392060eef Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:04:21 +0200 Subject: [PATCH 15/21] =?UTF-8?q?a=C3=B1adida=20internacionalizacion=20a?= =?UTF-8?q?=20los=20botones=20de=20las=20categorias=20(se=20me=20olvido=20?= =?UTF-8?q?guardar=20el=20archivo?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../locales/es/translation.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/webapp/src/internacionalizacion/locales/es/translation.json b/webapp/src/internacionalizacion/locales/es/translation.json index b0bad32a..177eb25f 100644 --- a/webapp/src/internacionalizacion/locales/es/translation.json +++ b/webapp/src/internacionalizacion/locales/es/translation.json @@ -100,11 +100,11 @@ "diaryGameTitle" : "Desafio diario", "diaryGameText" : "Ya has jugado el desafio diario de hoy, vuelve mañana para jugar de nuevo", - "categoryGeography": "Geography", - "categoryHistory": "History", - "categoryScience": "Science", - "categoryArt": "Art", - "categorySports": "Sports", - "categoryEntertainment": "Entertainment", - "categoryMusic": "Music" + "categoryGeography": "Geografía", + "categoryHistory": "Historia", + "categoryScience": "Ciencia", + "categoryArt": "Arte", + "categorySports": "Deportes", + "categoryEntertainment": "Entretenimiento", + "categoryMusic": "Música" } \ No newline at end of file From b3101f14d29891dadaa82bf3698aa48bea75781a Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:09:36 +0200 Subject: [PATCH 16/21] cambiado eso en la internacionalizacion para que salga bien --- webapp/src/internacionalizacion/locales/en/translation.json | 2 +- webapp/src/internacionalizacion/locales/es/translation.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/webapp/src/internacionalizacion/locales/en/translation.json b/webapp/src/internacionalizacion/locales/en/translation.json index e4dbb190..e374ae6a 100644 --- a/webapp/src/internacionalizacion/locales/en/translation.json +++ b/webapp/src/internacionalizacion/locales/en/translation.json @@ -22,7 +22,7 @@ "userName": "Username", "password": "Password", "passwordHelper": "Password must be at least 12 characters long, include one uppercase letter, one lowercase letter, one number, and one special character", - "passwordRepeat": "Repeat Password", + "passRepeat": "Repeat Password", "passwordRepeatHelper": "Passwords must match", "historyMessage": "History of ", diff --git a/webapp/src/internacionalizacion/locales/es/translation.json b/webapp/src/internacionalizacion/locales/es/translation.json index 177eb25f..b35c5720 100644 --- a/webapp/src/internacionalizacion/locales/es/translation.json +++ b/webapp/src/internacionalizacion/locales/es/translation.json @@ -22,7 +22,7 @@ "userName": "Nombre de Usuario", "password": "Contraseña", "passwordHelper": "La contraseña tiene que tener al menos 12 caracteres, una letra mayúscula, una letra minúscula, un número y un carácter especial", - "passwordRepeat": "Repetir Contraseña", + "passRepeat": "Repetir Contraseña", "passwordRepeatHelper": "Las contraseñas tienen que coincidir", "historyMessage": "Historial de ", From d92864358e6c17570217f3bae8b4e3a1937687ae Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:21:57 +0200 Subject: [PATCH 17/21] intento de reducir duplicidad en el userservice-test --- users/userservice/user-service.test.js | 39 ++++++++++---------------- 1 file changed, 15 insertions(+), 24 deletions(-) diff --git a/users/userservice/user-service.test.js b/users/userservice/user-service.test.js index f0c38cb0..df30c1c7 100644 --- a/users/userservice/user-service.test.js +++ b/users/userservice/user-service.test.js @@ -17,6 +17,13 @@ afterAll(async () => { }); describe('User Service', () => { + + const addUserTest = async (userData, expectedStatus, expectedError) => { + const response = await request(app).post('/adduser').send(userData); + expect(response.status).toBe(expectedStatus); + expect(response.body.error).toBe(expectedError); + }; + it('should add a new user on POST /adduser', async () => { const newUser = { email: 'test@email.com', @@ -25,9 +32,7 @@ describe('User Service', () => { passwordConfirm: 'Testpassword_1', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(200); - expect(response.body).toHaveProperty('email', 'username', 'testuser'); + await addUserTest(newUser, 200, undefined); }); it('should not add a new user on POST /adduser', async () => { @@ -38,9 +43,7 @@ describe('User Service', () => { passwordConfirm: 'Testpassword_1', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe("Missing required field: username"); + await addUserTest(newUser, 400, 'Missing required field: username'); }); //pruebas para el formato de las contraseñas @@ -60,9 +63,7 @@ describe('User Service', () => { "La contraseña tiene que tener al menos un carácter especial" ; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe(errors); + await addUserTest(newUser, 400, errors); }); it('should send an error because the password is incorrect on POST /adduser', async () => { @@ -80,9 +81,7 @@ describe('User Service', () => { "La contraseña tiene que tener al menos un carácter especial" ; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe(errors); + await addUserTest(newUser, 400, errors); }); //pruebas para comprobar el formato del email @@ -95,9 +94,7 @@ describe('User Service', () => { passwordConfirm: 'Testpassword_1', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe('El email es invalido'); + await addUserTest(newUser, 400, 'El email es invalido'); }); //pruebas para comprobar si el email o el username ya existe en la bd @@ -110,9 +107,7 @@ describe('User Service', () => { passwordConfirm: 'Testpassword_1', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe('El email ya existe en la base de datos'); + await addUserTest(newUser, 400, 'El email ya existe en la base de datos'); }); it('should send an error because the username already exist in the database on POST /adduser', async () => { @@ -123,9 +118,7 @@ describe('User Service', () => { passwordConfirm: 'Testpassword_1', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe('El username ya existe en la base de datos'); + await addUserTest(newUser, 400, 'El username ya existe en la base de datos'); }); @@ -139,9 +132,7 @@ it('should send an error because the passwords are not equals on POST /adduser', passwordConfirm: 'Testpassword_2', }; - const response = await request(app).post('/adduser').send(newUser); - expect(response.status).toBe(400); - expect(response.body.error).toBe('Las contraseñas no coinciden'); + await addUserTest(newUser, 400, 'Las contraseñas no coinciden'); }); }); \ No newline at end of file From 0324c2a2ca7205737cb48c666bfa87c566c6db1f Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:29:38 +0200 Subject: [PATCH 18/21] arreglado el test del home para la nueva url --- webapp/src/components/home/Home.test.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webapp/src/components/home/Home.test.js b/webapp/src/components/home/Home.test.js index 6d73713c..a830518e 100644 --- a/webapp/src/components/home/Home.test.js +++ b/webapp/src/components/home/Home.test.js @@ -23,7 +23,7 @@ test('navigates when buttons are clicked', () => { expect(navigate).toHaveBeenCalledWith('/game'); fireEvent.click(getByText('modoMismaCategoria')); - expect(navigate).toHaveBeenCalledWith('/gameSameCat'); + expect(navigate).toHaveBeenCalledWith('/sameCategoryWindow'); fireEvent.click(getByText('modoInfinito')); expect(navigate).toHaveBeenCalledWith('/gameInfinity'); From d8029ab431e49699382b564c80cbbcdc1e6a2bc3 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:39:49 +0200 Subject: [PATCH 19/21] =?UTF-8?q?a=C3=B1adido=20test=20del=20category?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../components/categories/Categories.test.js | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/webapp/src/components/categories/Categories.test.js b/webapp/src/components/categories/Categories.test.js index 6d73713c..25784627 100644 --- a/webapp/src/components/categories/Categories.test.js +++ b/webapp/src/components/categories/Categories.test.js @@ -2,7 +2,7 @@ import React from 'react'; import { render, fireEvent } from '@testing-library/react'; import { BrowserRouter as Router } from 'react-router-dom'; import { useNavigate } from 'react-router-dom'; -import Home from './Home'; +import Categories from './Categories'; jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), @@ -15,22 +15,28 @@ test('navigates when buttons are clicked', () => { const { getByText } = render( - + ); - fireEvent.click(getByText('modoClasico')); - expect(navigate).toHaveBeenCalledWith('/game'); + fireEvent.click(getByText('categoryGeography')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/geografia'); - fireEvent.click(getByText('modoMismaCategoria')); - expect(navigate).toHaveBeenCalledWith('/gameSameCat'); + fireEvent.click(getByText('categoryArt')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/arte'); + + fireEvent.click(getByText('categoryEntertainment')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/entretenimiento'); - fireEvent.click(getByText('modoInfinito')); - expect(navigate).toHaveBeenCalledWith('/gameInfinity'); + fireEvent.click(getByText('categorySports')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/deportes'); - fireEvent.click(getByText('modoCustom')); - expect(navigate).toHaveBeenCalledWith('/customWindow'); + fireEvent.click(getByText('categoryHistory')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/historia'); - fireEvent.click(getByText('modoDiario')); - expect(navigate).toHaveBeenCalledWith('/game'); + fireEvent.click(getByText('categoryScience')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/ciencia'); + + fireEvent.click(getByText('categoryMusic')); + expect(navigate).toHaveBeenCalledWith('/gameSameCat/musica'); }); \ No newline at end of file From fc9984782424427c5e3d4955e03a0775be0f6367 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 20:53:49 +0200 Subject: [PATCH 20/21] deberian de pasar ya los tests del dailygame --- .../game/gameModes/DailyGameMode.js | 27 ++++++++++--------- .../game/gameModes/DailyGameMode.test.js | 10 +++---- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/webapp/src/components/game/gameModes/DailyGameMode.js b/webapp/src/components/game/gameModes/DailyGameMode.js index 1f73a614..832ca4a4 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.js @@ -99,7 +99,20 @@ class DailyGameMode extends BasicGame{ this.volverAJugarCoockie(); } - async volverAJugarCoockie(){ + async volverAJugarCoockie(){ + + // Obtener la fecha actual y establecer la hora a las 12 de la noche + let expiryDate = new Date(); + expiryDate.setHours(24, 0, 0, 0); + + // Almacenar la variable en localStorage con la fecha de caducidad + localStorage.setItem('lastDailyGame', JSON.stringify({ + value: 'valor que quieras almacenar', + expiry: expiryDate.getTime(), + })); + + console.log("localStorage" + localStorage.getItem('lastDailyGame')); + try { console.log("entra en el try"); const volverJugarData = { @@ -122,18 +135,6 @@ class DailyGameMode extends BasicGame{ } catch (error) { console.error('Error enviando los datos de diaria del usuario:', error); } - - // Obtener la fecha actual y establecer la hora a las 12 de la noche - let expiryDate = new Date(); - expiryDate.setHours(24, 0, 0, 0); - - // Almacenar la variable en localStorage con la fecha de caducidad - localStorage.setItem('lastDailyGame', JSON.stringify({ - value: 'valor que quieras almacenar', - expiry: expiryDate.getTime(), - })); - - console.log("localStorage" + localStorage.getItem('lastDailyGame')); } fechaActual(){ diff --git a/webapp/src/components/game/gameModes/DailyGameMode.test.js b/webapp/src/components/game/gameModes/DailyGameMode.test.js index 5e1fa10f..ffad1324 100644 --- a/webapp/src/components/game/gameModes/DailyGameMode.test.js +++ b/webapp/src/components/game/gameModes/DailyGameMode.test.js @@ -45,7 +45,7 @@ describe('DailyGameMode', () => { const questions = await dailyGameMode.fetchQuestions(); - expect(global.fetch).toHaveBeenCalledWith(`${dailyGameMode.apiEndpoint}/getQuestionDiaria`); + expect(global.fetch).toHaveBeenCalledWith(`${dailyGameMode.apiEndpoint}/getQuestionDiaria?idioma=${dailyGameMode.idioma}&fecha=${dailyGameMode.fechaAct}`); expect(questions).toEqual(Object.values(mockData)); expect(dailyGameMode.isLoading).toBe(false); }); @@ -58,7 +58,7 @@ describe('DailyGameMode', () => { const questions = await dailyGameMode.fetchQuestions(); - expect(global.fetch).toHaveBeenCalledWith(`${dailyGameMode.apiEndpoint}/getQuestionDiaria`); + expect(global.fetch).toHaveBeenCalledWith(`${dailyGameMode.apiEndpoint}/getQuestionDiaria?idioma=${dailyGameMode.idioma}&fecha=${dailyGameMode.fechaAct}`); expect(questions).toEqual([]); expect(console.error).toHaveBeenCalledWith('Error fetching question data:', mockError); }); @@ -106,7 +106,7 @@ describe('DailyGameMode', () => { dailyGameMode.incrementIncorrectas(); expect(dailyGameMode.incorrectas).toBe(1); - expect(localStorage.getItem('diaria')).toBeTruthy(); + expect(localStorage.getItem('lastDailyGame')).toBeTruthy(); }); it('should increment correctas correctly', () => { @@ -114,13 +114,13 @@ describe('DailyGameMode', () => { expect(dailyGameMode.correctas).toBe(1); expect(dailyGameMode.enviarHistorialPorQueHasAcetado).toBe(true); - expect(localStorage.getItem('diaria')).toBeTruthy(); + expect(localStorage.getItem('lastDailyGame')).toBeTruthy(); }); it('should set volverAJugarCoockie correctly', () => { dailyGameMode.volverAJugarCoockie(); - const diaria = JSON.parse(localStorage.getItem('diaria')); + const diaria = JSON.parse(localStorage.getItem('lastDailyGame')); expect(diaria.value).toBe('valor que quieras almacenar'); expect(diaria.expiry).toBeGreaterThan(Date.now()); From 11a3e0bd3b92f03f801469f7a7486fe6d7615417 Mon Sep 17 00:00:00 2001 From: lucia-sonia Date: Thu, 25 Apr 2024 21:02:55 +0200 Subject: [PATCH 21/21] ahora el test del sameCategory deberia funcionar --- .../src/components/game/gameModes/SameCategoryMode.test.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/webapp/src/components/game/gameModes/SameCategoryMode.test.js b/webapp/src/components/game/gameModes/SameCategoryMode.test.js index 20a20417..e5626f3a 100644 --- a/webapp/src/components/game/gameModes/SameCategoryMode.test.js +++ b/webapp/src/components/game/gameModes/SameCategoryMode.test.js @@ -1,4 +1,4 @@ -const SameCategoryMode = require('./SameCategoryMode'); +import SameCategoryMode from './SameCategoryMode'; describe('SameCategoryMode', () => { @@ -33,7 +33,7 @@ describe('SameCategoryMode', () => { }); test('fetchQuestions should handle errors', async () => { - const sameCategoryMode = new SameCategoryMode(); + const sameCategoryMode = new SameCategoryMode("arte"); sameCategoryMode.apiEndpoint = 'https://example.com'; sameCategoryMode.questions = []; sameCategoryMode.isLoading = true; @@ -47,7 +47,7 @@ describe('SameCategoryMode', () => { }); test('sendHistory should not save game history', async () => { - const sameCategoryMode = new SameCategoryMode(); + const sameCategoryMode = new SameCategoryMode("arte"); sameCategoryMode.sendHistory(); });