Skip to content
This repository has been archived by the owner on May 10, 2024. It is now read-only.

Commit

Permalink
Merge branch 'develop' into separate-history
Browse files Browse the repository at this point in the history
# Conflicts:
#	game_service/game.js
#	game_service/game/endpoints.js
  • Loading branch information
22Noel committed Apr 25, 2024
2 parents 4605ae7 + 33bc69f commit 8281e3d
Show file tree
Hide file tree
Showing 20 changed files with 722 additions and 38 deletions.
3 changes: 2 additions & 1 deletion game_service/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ const YAML = require('yaml')

// My own libs
const authMiddleware = require('./auth/authMiddleware');
const { newGame, next, awnser, update, getGameSettingsByUser, getHistory, setGameSettingsByUser, getNumberOfQuestions,
const { newGame, next, awnser, update, getGameSettingsByUser, getHistory, getHistoryByUser, setGameSettingsByUser, getNumberOfQuestions,
getQuestion, getGamemodes
} = require("./game/endpoints");
const { saveQuestionsInDB, deleteOlderQuestions, loadInitialQuestions } = require('./services/questionsService');
Expand All @@ -41,6 +41,7 @@ app.post('/api/game/update', update);
app.post('/api/game/settings', getGameSettingsByUser);
app.post('/api/game/updatesettings', setGameSettingsByUser);
app.post('/api/game/getHistory', getHistory);
app.post('/api/game/getHistoryByUser', getHistoryByUser);
app.post('/api/game/numberofquestions', getNumberOfQuestions);
app.post('/api/game/currentquestion', getQuestion);
app.post('/api/game/gamemodes', getGamemodes);
Expand Down
28 changes: 27 additions & 1 deletion game_service/game.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ describe('Game Service', () => {

expect(response.statusCode).toBe(200);
expect(response.text).toBe("Santiago");
})
});

it("Should return 200 with a valid token when accessing game settings", async () =>
{
Expand All @@ -121,6 +121,24 @@ describe('Game Service', () => {
expect(response.statusCode).toBe(200);
});

it("Should return 200 with a valid user id when accessing game history by user", async () =>
{
const response = await request(app)
.post('/api/game/getHistoryByUser')
.send({ token: validToken, userId: '1234' });

expect(response.statusCode).toBe(200);
});

it("Should return 400 with a not valid user id when accessing game history by user", async () =>
{
const response = await request(app)
.post('/api/game/getHistoryByUser')
.send({ token: validToken, userId: undefined });

expect(response.statusCode).toBe(400);
});

it("Should return 200 with a valid token when accessing game settings", async () => {
const response = await request(app)
.post('/api/game/settings')
Expand Down Expand Up @@ -173,4 +191,12 @@ describe('Game Service', () => {

expect(response.statusCode).toBe(400);
});

it("Should return 200 with a valid token when get question", async () => {
let response = await request(app)
.post('/api/game/currentquestion')
.send({ token: validToken });

expect(response.statusCode).toBe(200);
});
})
29 changes: 28 additions & 1 deletion game_service/game/endpoints.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,31 @@ const getHistory = async (req,res) => {
return res.status(200).json(games.map(game => game.toJSON()))
}

const getHistoryByUser = async (req, res) =>
{
const userId = req.body.userId;

if (!userId)
{
res.status(400).json({ error: 'user id not valid' });
return;
}

const games = await Game.findAll({
where: {
user_id: userId
},
include: [{
model: Question,
as: 'Questions' // alias defined in the association
}]
});

return res.status(200).json(
games.map(game => game.toJSON())
);
}

const getGameSettingsByUser = async (req, res) =>{
const userId = await jwt.verify(req.body.token, privateKey).user_id;

Expand Down Expand Up @@ -242,4 +267,6 @@ const getGamemodes = async (req, res) => {
res.status(200).send(games.map(game => game.DISTINCT));
};

module.exports = {newGame, next, awnser, update, getHistory, getGameSettingsByUser, setGameSettingsByUser, getNumberOfQuestions, getQuestion, getGamemodes}

module.exports = {newGame, next, awnser, update, getHistory, getHistoryByUser, getGameSettingsByUser, setGameSettingsByUser, getNumberOfQuestions, getQuestion, getGamemodes}

27 changes: 26 additions & 1 deletion userdetails_service/service/gameService.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,29 @@ const getHistory = async (req,res) => {
res.status(200).send((await response.json()));
}

module.exports = getHistory;
const getHistoryByUser = async (req, res) =>
{
if (!req.body.userId)
{
res.status(400).json({ error: 'user id is not valid' });
return;
}

let response = await fetch("http://game:8003/api/game/getHistoryByUser", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
token: req.body.token,
userId: req.body.userId
})
});

res.status(200).send(
await response.json()
);
}

module.exports = { getHistory, getHistoryByUser };
3 changes: 2 additions & 1 deletion userdetails_service/userdetails.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const YAML = require('yaml')
const authMiddleware = require('./auth/authMiddleware');

const getUsername = require("./service/loginService");
const getHistory = require("./service/gameService");
const { getHistory, getHistoryByUser } = require("./service/gameService");

const port = 8004;
const app = express();
Expand All @@ -30,6 +30,7 @@ app.use('/api/*',authMiddleware); // Auth middleware for the questions API
// Api endpoints
app.post('/api/userdetails/name', getUsername);
app.post('/api/userdetails/history', getHistory);
app.post('/api/userdetails/history-by-user', getHistoryByUser);

// Read the OpenAPI YAML file synchronously
openapiPath='./openapi.yaml'
Expand Down
39 changes: 39 additions & 0 deletions userdetails_service/userdetails.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,43 @@ describe('User Details Endpoints', () => {
expect(response.statusCode).toBe(200);
expect(response.body).toEqual(mockHistory);
});

it("Should return history if token is valid in getHistoryByUser endpoint", async () => {
// Generate token for the mock user
const token = jwt.sign({ user_id: 1 }, privateKey);

// Mock response from the external service
const mockHistory = [{ game_id: 1, score: 100 }, { game_id: 2, score: 150 }];

// Mocking fetch call
global.fetch = jest.fn().mockResolvedValue({
json: async () => (mockHistory)
});

const response = await request(app)
.post('/api/userdetails/history-by-user')
.send({ token: token, userId: 1 });

expect(response.statusCode).toBe(200);
expect(response.body).toEqual(mockHistory);
});

it("Should return 400 if user id is not valid in getHistoryByUser endpoint", async () => {
// Generate token for the mock user
const token = jwt.sign({ user_id: 1 }, privateKey);

// Mock response from the external service
const mockHistory = [{ game_id: 1, score: 100 }, { game_id: 2, score: 150 }];

// Mocking fetch call
global.fetch = jest.fn().mockResolvedValue({
json: async () => (mockHistory)
});

const response = await request(app)
.post('/api/userdetails/history-by-user')
.send({ token: token, userId: undefined });

expect(response.statusCode).toBe(400);
});
});
5 changes: 4 additions & 1 deletion webapp/src/components/footer/Footer.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import React from 'react';
import { MDBFooter } from 'mdb-react-ui-kit';
import { useTranslation } from "react-i18next";
//import './Footer.css';

export const Footer= () => {
const { t } = useTranslation();

return (

<MDBFooter className='footer text-black dark:text-white bg-teal-50 dark:bg-zinc-800' style={{position: 'relative', bottom: 0, width: '100%', padding: '10px', textAlign: 'center', display: 'flex', flexDirection: 'column' }}>
Expand All @@ -11,7 +14,7 @@ export const Footer= () => {
<a href='https://github.com/Arquisoft/wiq_es1c'>
Wiq_es1c.
</a>
<p>All rights reserved. </p>
<p>{ t('Footer.copyright') }</p>
</div>
</MDBFooter>
);
Expand Down
4 changes: 2 additions & 2 deletions webapp/src/components/footer/Footer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { render, screen, act, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { MemoryRouter, BrowserRouter as Router } from 'react-router-dom';
import { Footer } from './Footer';

import '../../i18n';

describe("Footer component", () => {
beforeEach(() => localStorage.setItem("token", "manolineldelpino"));
Expand All @@ -13,7 +13,7 @@ describe("Footer component", () => {

await act(async () => {});

expect(screen.getByText(/All rights reserved./i)).toBeInTheDocument();
expect(screen.getByText(/Todos los derechos reservados./i)).toBeInTheDocument();


});
Expand Down
18 changes: 11 additions & 7 deletions webapp/src/components/game/Game.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {Footer} from '../footer/Footer';
import {useLocation} from "react-router-dom";
import Swal from 'sweetalert2';
import i18n from "../../i18n";
import { useTranslation } from "react-i18next";


const token = localStorage.getItem("token");
Expand All @@ -29,6 +30,7 @@ let isFinished = async () => {
}

export const Game = ({finishFunction, name, tags}) => {
const { t } = useTranslation();

const navigate = useNavigate();

Expand All @@ -41,6 +43,7 @@ export const Game = ({finishFunction, name, tags}) => {
const [loading, setLoading] = useState(true);
const [time , setTime] = useState(undefined);
const [remTime, setRemTime] = useState(0);
const [percentage, setPercentage] = useState(0);
const location = useLocation();

const againstClockFinish = async () => {
Expand Down Expand Up @@ -106,14 +109,14 @@ export const Game = ({finishFunction, name, tags}) => {
confirmButton: "text-black dark:text-white ",
cancelButton: "text-black dark:text-white " ,
},
title: "El juego ha finalizado!",
text: "Gracias por jugar",
title: t('Home.finishGameTitle'),
text: t('Home.finishGameText'),
imageUrl: bannerDark,
showCancelButton: true,
confirmButtonColor: "#f384f6",
cancelButtonColor: "#e8b260",
confirmButtonText: "Volver al menu principal",
cancelButtonText: "Continuar jugando"
confirmButtonText: t('Home.finishGameConfirm'),
cancelButtonText: t('Home.finishGameCancel')
}).then((result) => {
if (result.isConfirmed) {
navigate("/home")
Expand Down Expand Up @@ -171,7 +174,8 @@ export const Game = ({finishFunction, name, tags}) => {

percentage = (trans/total) * 100;
invertedPercentage = 100 - Number(percentage);


setPercentage(invertedPercentage)
setRemTime((invertedPercentage/100)*gameTime);
}else{
gameTime = basicGameSetting.durationQuestion ;
Expand All @@ -181,9 +185,9 @@ export const Game = ({finishFunction, name, tags}) => {
percentage = (trans/total) * 100;
invertedPercentage = 100 - Number(percentage);

setPercentage(invertedPercentage)
setRemTime((invertedPercentage/100)*gameTime);
}

if(percentage > 100){
comprobarPregunta("");
time = undefined;
Expand Down Expand Up @@ -328,7 +332,7 @@ export const Game = ({finishFunction, name, tags}) => {
}}
className="text-black dark:text-white "
>
<LinearProgress color='inherit' variant={loading? "indeterminate" : "determinate"} value={remTime} />
<LinearProgress color='inherit' variant={loading? "indeterminate" : "determinate"} value={percentage} />
</Box>
</Container>
</Container>
Expand Down
18 changes: 9 additions & 9 deletions webapp/src/components/history/History.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,17 +42,17 @@ jest.mock('../../services/game.service', () => ({
describe('Game Component', () => {
beforeEach(() => localStorage.setItem("token", "manolineldelpino"));

test("renders component and the games",async () => {
await act(async () => render(<MemoryRouter><History/></MemoryRouter>));
test("renders component and the games",async () => {
await act(async () => render(<MemoryRouter><History/></MemoryRouter>));

expect(screen.getByText(/4\/4\/2024/i)).toBeInTheDocument();
expect(screen.getByText(/5\/5\/2024/i)).toBeInTheDocument();
expect(screen.getByText(/4\/4\/2024/i)).toBeInTheDocument();
expect(screen.getByText(/5\/5\/2024/i)).toBeInTheDocument();

expect(screen.getByText(/Fecha/i)).toBeInTheDocument();
expect(screen.getByText(/Acertadas/i)).toBeInTheDocument();
expect(screen.getByText(/Falladas/i)).toBeInTheDocument();
expect(screen.getByText(/% de aciertos/i)).toBeInTheDocument();
});
expect(screen.getByText(/Fecha/i)).toBeInTheDocument();
expect(screen.getByText(/Acertadas/i)).toBeInTheDocument();
expect(screen.getByText(/Falladas/i)).toBeInTheDocument();
expect(screen.getByText(/% de aciertos/i)).toBeInTheDocument();
});

test("when you click a game, it shows its questions",async () => {
await act(async () => render(<MemoryRouter><History/></MemoryRouter>));
Expand Down
3 changes: 2 additions & 1 deletion webapp/src/components/home/Home.js
Original file line number Diff line number Diff line change
Expand Up @@ -184,7 +184,7 @@ export const Home = () =>
from-cyan-50 via-cyan-300 to blue-500
dark:from-orange-500 dark:via-purple-500 dark:to-pink-500
buttonGradient">
<span className="text-black dark:text-white text">JUGAR Contrareloj</span>
<span className="text-black dark:text-white text">{ t('Home.playAgainstClock') }</span>
</button>
</div>
<div className="flex align-middle justify-center flex-grow m-3">
Expand Down Expand Up @@ -246,6 +246,7 @@ export const Home = () =>

</Container>
)}
<br />
<Footer/>
</>
)
Expand Down
Loading

0 comments on commit 8281e3d

Please sign in to comment.