Compare commits

..

No commits in common. "e795fb6dd3c59f6080611a45880c029581f2eb31" and "8d44d09c545cdf075041cfaeca0a8937add102d5" have entirely different histories.

60 changed files with 1649 additions and 3881 deletions

1
.gitignore vendored
View file

@ -41,7 +41,6 @@ build/Release
# Dependency directories
node_modules/
jspm_packages/
mongo-backup/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

View file

@ -1,30 +0,0 @@
[![CI/CD Pipeline for Frontend](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/frontend-deploy.yml/badge.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/frontend-deploy.yml)
[![CI/CD Pipeline for Backend](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml/badge.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml)
[![CI/CD Pipeline for Nginx Router](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml/badge.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml)
[![en](https://img.shields.io/badge/lang-en-red.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/blob/master/README.md)
# EvalueTonSavoir
EvalueTonSavoir est une plateforme open source et auto-hébergée qui poursuit le développement du code provenant de https://github.com/ETS-PFE004-Plateforme-sondage-minitest. Cette plateforme minimaliste est conçue comme un outil d'apprentissage et d'enseignement, offrant une solution simple et efficace pour la création de quiz utilisant le format GIFT, similaire à Moodle.
## Fonctionnalités clés
* Open Source et Auto-hébergé : Possédez et contrôlez vos données en déployant la plateforme sur votre propre infrastructure.
* Compatibilité GIFT : Créez des quiz facilement en utilisant le format GIFT, permettant une intégration transparente avec d'autres systèmes d'apprentissage.
* Minimaliste et Efficace : Une approche bare bones pour garantir la simplicité et la facilité d'utilisation, mettant l'accent sur l'essentiel de l'apprentissage.
## Contribution
Actuellement, il n'y a pas de modèle établi pour les contributions. Si vous constatez quelque chose de manquant ou si vous pensez qu'une amélioration est possible, n'hésitez pas à ouvrir un issue et/ou une PR)
## Liens utiles
* [Dépôt d'origine Frontend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
* [Dépôt d'origine Backend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
## License
EvalueTonSavoir is open-sourced and licensed under the [MIT License](/LICENSE).

View file

@ -2,26 +2,24 @@
[![CI/CD Pipeline for Backend](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml/badge.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/backend-deploy.yml)
[![CI/CD Pipeline for Nginx Router](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml/badge.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/actions/workflows/deploy.yml)
[![fr-ca](https://img.shields.io/badge/lang-fr--ca-green.svg)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/blob/main/README.fr-ca.md)
# EvalueTonSavoir
EvalueTonSavoir is an open-source and self-hosted platform that continues the development of the code from https://github.com/ETS-PFE004-Plateforme-sondage-minitest. This minimalist platform is designed as a learning and teaching tool, offering a simple and effective solution for creating quizzes using the GIFT format, similar to Moodle.
EvalueTonSavoir est une plateforme open source et auto-hébergée qui poursuit le développement du code provenant de https://github.com/ETS-PFE004-Plateforme-sondage-minitest. Cette plateforme minimaliste est conçue comme un outil d'apprentissage et d'enseignement, offrant une solution simple et efficace pour la création de quiz utilisant le format GIFT, similaire à Moodle.
## Key Features
## Fonctionnalités clés
* **Open Source and Self-Hosted**: Own and control your data by deploying the platform on your own infrastructure.
* **GIFT Compatibility**: Easily create quizzes using the GIFT format, enabling seamless integration with other learning systems.
* **Minimalist and Efficient**: A bare-bones approach to ensure simplicity and ease of use, focusing on the essentials of learning.
* Open Source et Auto-hébergé : Possédez et contrôlez vos données en déployant la plateforme sur votre propre infrastructure.
* Compatibilité GIFT : Créez des quiz facilement en utilisant le format GIFT, permettant une intégration transparente avec d'autres systèmes d'apprentissage.
* Minimaliste et Efficace : Une approche bare bones pour garantir la simplicité et la facilité d'utilisation, mettant l'accent sur l'essentiel de l'apprentissage.
## Contribution
Currently, there is no established model for contributions. If you notice something missing or think an improvement is possible, feel free to open an issue and/or a PR.
Actuellement, il n'y a pas de modèle établi pour les contributions. Si vous constatez quelque chose de manquant ou si vous pensez qu'une amélioration est possible, n'hésitez pas à ouvrir un issue et/ou une PR)
## Useful Links
## Liens utiles
* [Original Frontend Repository](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
* [Original Backend Repository](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
* [Dépôt d'origine Frontend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Frontend)
* [Dépôt d'origine Backend](https://github.com/ETS-PFE004-Plateforme-sondage-minitest/ETS-PFE004-EvalueTonSavoir-Backend)
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
## License

1248
client/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -8,7 +8,7 @@
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview",
"test": "jest --colors --silent",
"test": "jest --colors",
"test:watch": "jest --watch"
},
"dependencies": {
@ -18,21 +18,19 @@
"@fortawesome/fontawesome-svg-core": "^6.7.2",
"@fortawesome/free-solid-svg-icons": "^6.7.2",
"@fortawesome/react-fontawesome": "^0.2.0",
"@mui/icons-material": "6.4.7",
"@mui/icons-material": "^6.4.6",
"@mui/lab": "^5.0.0-alpha.153",
"@mui/material": "6.4.7",
"@mui/system": "6.4.7",
"@mui/material": "^6.4.7",
"@types/uuid": "^9.0.7",
"axios": "^1.8.1",
"dompurify": "^3.2.5",
"esbuild": "^0.25.2",
"dompurify": "^3.2.3",
"esbuild": "^0.25.0",
"gift-pegjs": "^2.0.0-beta.1",
"jest-environment-jsdom": "^29.7.0",
"jwt-decode": "^4.0.0",
"katex": "^0.16.11",
"marked": "^15.0.8",
"nanoid": "^5.1.5",
"qrcode.react": "^4.2.0",
"marked": "^14.1.2",
"nanoid": "^5.1.2",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-modal": "^3.16.3",
@ -40,40 +38,39 @@
"remark-math": "^6.0.0",
"socket.io-client": "^4.7.2",
"ts-node": "^10.9.1",
"uuid": "^11.1.0",
"vite-plugin-checker": "^0.9.1"
"uuid": "^9.0.1",
"vite-plugin-checker": "^0.9.0"
},
"devDependencies": {
"@babel/preset-env": "^7.26.9",
"@babel/preset-react": "^7.26.3",
"@babel/preset-typescript": "^7.27.0",
"@eslint/js": "^9.24.0",
"@babel/preset-typescript": "^7.23.3",
"@eslint/js": "^9.21.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@testing-library/user-event": "^14.6.1",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.13",
"@types/node": "^22.14.0",
"@types/node": "^22.13.5",
"@types/react": "^18.2.15",
"@types/react-dom": "^18.2.7",
"@types/react-latex": "^2.0.3",
"@typescript-eslint/eslint-plugin": "^8.29.1",
"@typescript-eslint/parser": "^8.29.1",
"@vitejs/plugin-react-swc": "^3.8.1",
"@typescript-eslint/eslint-plugin": "^8.25.0",
"@typescript-eslint/parser": "^8.25.0",
"@vitejs/plugin-react-swc": "^3.8.0",
"cross-env": "^7.0.3",
"eslint": "^9.24.0",
"eslint": "^9.21.0",
"eslint-plugin-eslint-comments": "^3.2.0",
"eslint-plugin-jest": "^28.11.0",
"eslint-plugin-react": "^7.37.5",
"eslint-plugin-react": "^7.37.3",
"eslint-plugin-react-hooks": "^5.1.0-rc-206df66e-20240912",
"eslint-plugin-react-refresh": "^0.4.19",
"eslint-plugin-unused-imports": "^4.1.4",
"globals": "^15.14.0",
"identity-obj-proxy": "^3.0.0",
"jest": "^29.7.0",
"ts-jest": "^29.3.1",
"typescript": "^5.8.3",
"typescript-eslint": "^8.29.1",
"ts-jest": "^29.2.6",
"typescript": "^5.7.3",
"typescript-eslint": "^8.25.0",
"vite": "^6.2.0",
"vite-plugin-environment": "^1.1.3"
}

View file

@ -1,17 +0,0 @@
export interface Images {
id: string;
file_content: string;
file_name: string;
mime_type: string;
}
export interface ImagesResponse {
images: Images[];
total: number;
}
export interface ImagesParams {
page: number;
limit: number;
uid?: string;
}

View file

@ -19,8 +19,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
});
const mockStudents: StudentType[] = [
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
];
const mockShowSelectedQuestion = jest.fn();

View file

@ -20,8 +20,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
const mockStudents: StudentType[] = [
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
];
const mockShowSelectedQuestion = jest.fn();

View file

@ -20,8 +20,8 @@ const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) =>
});
const mockStudents: StudentType[] = [
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
];
const mockGetStudentGrade = jest.fn((student: StudentType) => {

View file

@ -6,8 +6,8 @@ import LiveResultsTableFooter from 'src/components/LiveResults/LiveResultsTable/
const mockStudents: StudentType[] = [
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: ['Answer 1'], isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: ['Answer 2'], isCorrect: false }] },
{ id: "1", name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Answer 1', isCorrect: true }] },
{ id: "2", name: 'Student 2', answers: [{ idQuestion: 2, answer: 'Answer 2', isCorrect: false }] },
];
const mockGetStudentGrade = jest.fn((student: StudentType) => {

View file

@ -29,7 +29,7 @@ const katekMock: TemplateOptions & MultipleChoiceQuestion = {
formattedStem: { format: 'plain' , text: '$$\\frac{zzz}{yyy}$$'},
choices: [
{ formattedText: { format: 'plain' , text: 'Choice 1'}, isCorrect: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 },
{ formattedText: { format: 'plain', text: 'Choice 2' }, isCorrect: false, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 0 }
{ formattedText: { format: 'plain', text: 'Choice 2' }, isCorrect: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 }
],
formattedGlobalFeedback: { format: 'plain', text: 'Sample Global Feedback' }
};

View file

@ -733,7 +733,7 @@ exports[`MultipleChoice snapshot test with katex 1`] = `
<div class='multiple-choice-answers-container'>
<input class="gift-input" type="radio" id="idmocked-id" name="idmocked-id">
<span class="answer-weight-container answer-positive-weight">1%</span>
<label style="
display: inline-block;
padding: 0.2em 0 0.2em 0;
@ -742,15 +742,15 @@ exports[`MultipleChoice snapshot test with katex 1`] = `
" for="idmocked-id">
Choice 2
</label>
<svg data-testid="incorrect-icon" style="
<svg data-testid="correct-icon" style="
vertical-align: text-bottom;
display: inline-block;
margin-left: 0.1rem;
margin-right: 0.2rem;
width: 0.75em;
color: hsl(2, 64%, 58%);
" role="img" aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 352 512"><path fill="currentColor" d="M242.72 256l100.07-100.07c12.28-12.28 12.28-32.19 0-44.48l-22.24-22.24c-12.28-12.28-32.19-12.28-44.48 0L176 189.28 75.93 89.21c-12.28-12.28-32.19-12.28-44.48 0L9.21 111.45c-12.28 12.28-12.28 32.19 0 44.48L109.28 256 9.21 356.07c-12.28 12.28-12.28 32.19 0 44.48l22.24 22.24c12.28 12.28 32.2 12.28 44.48 0L176 322.72l100.07 100.07c12.28 12.28 32.2 12.28 44.48 0l22.24-22.24c12.28-12.28 12.28-32.19 0-44.48L242.72 256z"></path></svg>
width: 1em;
color: hsl(120, 39%, 54%);
" role="img" aria-hidden="true" focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="currentColor" d="M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"></path></svg>
<span class="feedback-container">Correct!</span>
</input>
</div>

View file

@ -1,147 +0,0 @@
import React, { act } from "react";
import "@testing-library/jest-dom";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import ImageGallery from "../../../components/ImageGallery/ImageGallery";
import ApiService from "../../../services/ApiService";
import { Images } from "../../../Types/Images";
import userEvent from "@testing-library/user-event";
jest.mock("../../../services/ApiService");
const mockImages: Images[] = [
{ id: "1", file_name: "image1.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content1" },
{ id: "2", file_name: "image2.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content2" },
{ id: "3", file_name: "image3.jpg", mime_type: "image/jpeg", file_content: "mockBase64Content3" },
];
beforeAll(() => {
global.URL.createObjectURL = jest.fn(() => 'mockedObjectUrl');
Object.assign(navigator, {
clipboard: {
writeText: jest.fn(),
},
});
});
describe("ImageGallery", () => {
let mockHandleDelete: jest.Mock;
beforeEach(async () => {
(ApiService.getImages as jest.Mock).mockResolvedValue({ images: mockImages, total: 3 });
(ApiService.deleteImage as jest.Mock).mockResolvedValue(true);
(ApiService.uploadImage as jest.Mock).mockResolvedValue('mockImageUrl');
await act(async () => {
render(<ImageGallery />);
});
mockHandleDelete = jest.fn();
});
it("should render images correctly", async () => {
await act(async () => {
await screen.findByText("Galerie");
});
expect(screen.getByAltText("Image image1.jpg")).toBeInTheDocument();
expect(screen.getByAltText("Image image2.jpg")).toBeInTheDocument();
});
it("should handle copy action", async () => {
const handleCopyMock = jest.fn();
await act(async () => {
render(<ImageGallery handleCopy={handleCopyMock} />);
});
const copyButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-copy-/));
await act(async () => {
fireEvent.click(copyButtons[0]);
});
expect(navigator.clipboard.writeText).toHaveBeenCalled();
});
it("should delete an image and update the gallery", async () => {
const fetchImagesMock = jest.fn().mockResolvedValue({ images: mockImages.filter((image) => image.id !== "1"), total: 2 });
(ApiService.getImages as jest.Mock).mockImplementation(fetchImagesMock);
await act(async () => {
render(<ImageGallery handleDelete={mockHandleDelete} />);
});
await act(async () => {
await screen.findByAltText("Image image1.jpg");
});
const deleteButtons = await waitFor(() => screen.findAllByTestId(/gallery-tab-delete-/));
fireEvent.click(deleteButtons[0]);
await waitFor(() => {
expect(screen.getByText("Voulez-vous supprimer cette image?")).toBeInTheDocument();
});
const confirmDeleteButton = screen.getByText("Delete");
await act(async () => {
fireEvent.click(confirmDeleteButton);
});
await waitFor(() => {
expect(ApiService.deleteImage).toHaveBeenCalledWith("1");
});
await waitFor(() => {
expect(screen.queryByAltText("Image image1.jpg")).toBeNull();
expect(screen.getByText("Image supprimée avec succès!")).toBeInTheDocument();
});
});
it("should upload an image and display success message", async () => {
const importTab = screen.getByRole("tab", { name: /import/i });
fireEvent.click(importTab);
const fileInputs = await screen.findAllByTestId("file-input");
const fileInput = fileInputs[1];
expect(fileInput).toBeInTheDocument();
const file = new File(["image"], "image.jpg", { type: "image/jpeg" });
await userEvent.upload(fileInput, file);
await waitFor(() => screen.getByAltText("Preview"));
const previewImage = screen.getByAltText("Preview");
expect(previewImage).toBeInTheDocument();
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
fireEvent.click(uploadButton);
const successMessage = await screen.findByText(/téléversée avec succès/i);
expect(successMessage).toBeInTheDocument();
});
it("should close the image preview dialog when close button is clicked", async () => {
const imageCard = screen.getByAltText("Image image1.jpg");
fireEvent.click(imageCard);
const dialogImage = await screen.findByAltText("Enlarged view");
expect(dialogImage).toBeInTheDocument();
const closeButton = screen.getByTestId("close-button");
fireEvent.click(closeButton);
await waitFor(() => {
expect(screen.queryByAltText("Enlarged view")).not.toBeInTheDocument();
});
});
it("should show an error message when no file is selected", async () => {
const importTab = screen.getByRole("tab", { name: /import/i });
fireEvent.click(importTab);
const uploadButton = screen.getByRole('button', { name: /téléverser/i });
fireEvent.click(uploadButton);
await waitFor(() => {
expect(screen.getByText("Veuillez choisir une image à téléverser.")).toBeInTheDocument();
});
});
});

View file

@ -1,44 +0,0 @@
import React from "react";
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import ImageGalleryModal from "../../../components/ImageGallery/ImageGalleryModal/ImageGalleryModal";
import "@testing-library/jest-dom";
jest.mock("../../../components/ImageGallery/ImageGallery", () => ({
__esModule: true,
default: jest.fn(() => <div data-testid="image-gallery" />),
}));
describe("ImageGalleryModal", () => {
it("renders button correctly", () => {
render(<ImageGalleryModal />);
const button = screen.getByLabelText(/images-open/i);
expect(button).toBeInTheDocument();
});
it("opens the modal when button is clicked", () => {
render(<ImageGalleryModal />);
const button = screen.getByRole("button", { name: /images/i });
fireEvent.click(button);
const dialog = screen.getByRole("dialog");
expect(dialog).toBeInTheDocument();
});
it("closes the modal when close button is clicked", async () => {
render(<ImageGalleryModal />);
fireEvent.click(screen.getByRole("button", { name: /images/i }));
const closeButton = screen.getByRole("button", { name: /close/i });
fireEvent.click(closeButton);
await waitFor(() => {
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
});
});
});

View file

@ -5,7 +5,7 @@ import LiveResults from 'src/components/LiveResults/LiveResults';
import { QuestionType } from 'src/Types/QuestionType';
import { StudentType } from 'src/Types/StudentType';
import { Socket } from 'socket.io-client';
import { BaseQuestion, parse } from 'gift-pegjs';
import { BaseQuestion,parse } from 'gift-pegjs';
const mockSocket: Socket = {
on: jest.fn(),
@ -19,28 +19,19 @@ const mockGiftQuestions = parse(
`::Sample Question 1:: Question stem
{
=Choice 1
=Choice 2
~Choice 3
~Choice 4
}
::Sample Question 2:: Question stem {TRUE}
`);
~Choice 2
}`);
const mockQuestions: QuestionType[] = mockGiftQuestions.map((question, index) => {
if (question.type !== "Category")
question.id = (index + 1).toString();
const newMockQuestion = question;
return { question: newMockQuestion as BaseQuestion };
return {question : newMockQuestion as BaseQuestion};
});
console.log(`mockQuestions: ${JSON.stringify(mockQuestions)}`);
// each student should have a different score for the tests to pass
const mockStudents: StudentType[] = [
{ id: '1', name: 'Student 1', answers: [] },
{ id: '2', name: 'Student 2', answers: [{ idQuestion: 1, answer: ['Choice 3'], isCorrect: false }, { idQuestion: 2, answer: [true], isCorrect: true}] },
{ id: '3', name: 'Student 3', answers: [{ idQuestion: 1, answer: ['Choice 1', 'Choice 2'], isCorrect: true }, { idQuestion: 2, answer: [true], isCorrect: true}] },
{ id: '1', name: 'Student 1', answers: [{ idQuestion: 1, answer: 'Choice 1', isCorrect: true }] },
{ id: '2', name: 'Student 2', answers: [{ idQuestion: 1, answer: 'Choice 2', isCorrect: false }] },
];
describe('LiveResults', () => {
@ -91,7 +82,8 @@ describe('LiveResults', () => {
});
});
test('calculates and displays the correct student grades', () => {
});
test('calculates and displays the correct student grades', () => {
render(
<LiveResults
socket={mockSocket}
@ -110,18 +102,13 @@ describe('LiveResults', () => {
fireEvent.click(toggleUsernamesSwitch);
// Check if the student grades are calculated and displayed correctly
const getByTextInTableCellBody = (text: string) => {
const elements = screen.getAllByText(text); // Get all elements with the specified text
return elements.find((element) => element.closest('.MuiTableCell-body')); // don't get the footer element(s)
};
mockStudents.forEach((student) => {
const grade = student.answers.filter(answer => answer.isCorrect).length / mockQuestions.length * 100;
const element = getByTextInTableCellBody(`${grade.toFixed()} %`);
expect(element).toBeInTheDocument();
});
expect(screen.getByText(`${grade.toFixed()} %`)).toBeInTheDocument();
});
});
test('calculates and displays the class average', () => {
test('calculates and displays the class average', () => {
render(
<LiveResults
socket={mockSocket}
@ -150,9 +137,9 @@ describe('LiveResults', () => {
return element.closest('td')?.classList.contains('MuiTableCell-footer');
});
expect(classAverageElement).toBeInTheDocument();
});
});
test('displays the correct answers per question', () => {
test('displays the correct answers per question', () => {
render(
<LiveResults
socket={mockSocket}
@ -173,6 +160,4 @@ describe('LiveResults', () => {
});
expect(correctAnswersElement).toBeInTheDocument();
});
});
});

View file

@ -12,23 +12,14 @@ const questions = parse(
{
=Choice 1
~Choice 2
}
}`) as MultipleChoiceQuestion[];
::Sample Question 2:: Question stem
{
=Choice 1
=Choice 2
~Choice 3
}
`) as MultipleChoiceQuestion[];
const questionWithOneCorrectChoice = questions[0];
const questionWithMultipleCorrectChoices = questions[1];
const question = questions[0];
describe('MultipleChoiceQuestionDisplay', () => {
const mockHandleOnSubmitAnswer = jest.fn();
const TestWrapper = ({ showAnswer, question }: { showAnswer: boolean; question: MultipleChoiceQuestion }) => {
const TestWrapper = ({ showAnswer }: { showAnswer: boolean }) => {
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
const handleOnSubmitAnswer = (answer: AnswerType) => {
@ -47,51 +38,28 @@ describe('MultipleChoiceQuestionDisplay', () => {
);
};
const twoChoices = questionWithOneCorrectChoice.choices;
const threeChoices = questionWithMultipleCorrectChoices.choices;
const choices = question.choices;
test('renders a question (that has only one correct choice) and its choices', () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
beforeEach(() => {
render(<TestWrapper showAnswer={false} />);
});
expect(screen.getByText(questionWithOneCorrectChoice.formattedStem.text)).toBeInTheDocument();
twoChoices.forEach((choice) => {
test('renders the question and choices', () => {
expect(screen.getByText(question.formattedStem.text)).toBeInTheDocument();
choices.forEach((choice) => {
expect(screen.getByText(choice.formattedText.text)).toBeInTheDocument();
});
});
test('only allows one choice to be selected when question only has one correct answer', () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
const choiceButton1 = screen.getByText('Choice 1').closest('button');
const choiceButton2 = screen.getByText('Choice 2').closest('button');
if (!choiceButton1 || !choiceButton2) throw new Error('Choice buttons not found');
// Simulate selecting multiple answers
act(() => {
fireEvent.click(choiceButton1);
});
act(() => {
fireEvent.click(choiceButton2);
});
// Verify that only the last answer is selected
expect(choiceButton1.querySelector('.answer-text.selected')).not.toBeInTheDocument();
expect(choiceButton2.querySelector('.answer-text.selected')).toBeInTheDocument();
});
test('does not submit when no answer is selected', () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
const submitButton = screen.getByText('Répondre');
act(() => {
fireEvent.click(submitButton);
});
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
mockHandleOnSubmitAnswer.mockClear();
});
test('submits the selected answer', () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
act(() => {
@ -102,68 +70,10 @@ describe('MultipleChoiceQuestionDisplay', () => {
fireEvent.click(submitButton);
});
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(['Choice 1']);
mockHandleOnSubmitAnswer.mockClear();
});
test('renders a question (that has multiple correct choices) and its choices', () => {
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
expect(screen.getByText(questionWithMultipleCorrectChoices.formattedStem.text)).toBeInTheDocument();
threeChoices.forEach((choice) => {
expect(screen.getByText(choice.formattedText.text)).toBeInTheDocument();
});
});
test('allows multiple choices to be selected when question has multiple correct answers', () => {
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
const choiceButton1 = screen.getByText('Choice 1').closest('button');
const choiceButton2 = screen.getByText('Choice 2').closest('button');
const choiceButton3 = screen.getByText('Choice 3').closest('button');
if (!choiceButton1 || !choiceButton2 || !choiceButton3) throw new Error('Choice buttons not found');
act(() => {
fireEvent.click(choiceButton1);
});
act(() => {
fireEvent.click(choiceButton2);
});
expect(choiceButton1.querySelector('.answer-text.selected')).toBeInTheDocument();
expect(choiceButton2.querySelector('.answer-text.selected')).toBeInTheDocument();
expect(choiceButton3.querySelector('.answer-text.selected')).not.toBeInTheDocument(); // didn't click
});
test('submits multiple selected answers', () => {
render(<TestWrapper showAnswer={false} question={questionWithMultipleCorrectChoices} />);
const choiceButton1 = screen.getByText('Choice 1').closest('button');
const choiceButton2 = screen.getByText('Choice 2').closest('button');
if (!choiceButton1 || !choiceButton2) throw new Error('Choice buttons not found');
// Simulate selecting multiple answers
act(() => {
fireEvent.click(choiceButton1);
});
act(() => {
fireEvent.click(choiceButton2);
});
// Simulate submitting the answers
const submitButton = screen.getByText('Répondre');
act(() => {
fireEvent.click(submitButton);
});
// Verify that the mockHandleOnSubmitAnswer function is called with both answers
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(['Choice 1', 'Choice 2']);
mockHandleOnSubmitAnswer.mockClear();
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith('Choice 1');
});
it('should show ✅ next to the correct answer and ❌ next to the wrong answers when showAnswer is true', async () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
@ -188,8 +98,7 @@ describe('MultipleChoiceQuestionDisplay', () => {
expect(wrongAnswer1?.textContent).toContain('❌');
});
it('should not show ✅ or ❌ when Répondre button is not clicked', async () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
@ -209,5 +118,5 @@ describe('MultipleChoiceQuestionDisplay', () => {
expect(wrongAnswer1?.textContent).not.toContain('❌');
});
});
});

View file

@ -67,7 +67,6 @@ describe('NumericalQuestion Component', () => {
fireEvent.click(submitButton);
expect(mockHandleOnSubmitAnswer).not.toHaveBeenCalled();
mockHandleOnSubmitAnswer.mockClear();
});
it('submits answer correctly', () => {
@ -78,7 +77,6 @@ describe('NumericalQuestion Component', () => {
fireEvent.click(submitButton);
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith([7]);
mockHandleOnSubmitAnswer.mockClear();
expect(mockHandleOnSubmitAnswer).toHaveBeenCalledWith(7);
});
});

View file

@ -29,24 +29,23 @@ describe('Questions Component', () => {
render(<QuestionDisplay question={question} {...sampleProps} />);
};
// describe('question type parsing', () => {
// it('parses true/false question type correctly', () => {
// expect(sampleTrueFalseQuestion.type).toBe('TF');
// });
describe('question type parsing', () => {
it('parses true/false question type correctly', () => {
expect(sampleTrueFalseQuestion.type).toBe('TF');
});
// it('parses multiple choice question type correctly', () => {
// expect(sampleMultipleChoiceQuestion.type).toBe('MC');
// });
it('parses multiple choice question type correctly', () => {
expect(sampleMultipleChoiceQuestion.type).toBe('MC');
});
// it('parses numerical question type correctly', () => {
// expect(sampleNumericalQuestion.type).toBe('Numerical');
// });
// it('parses short answer question type correctly', () => {
// expect(sampleShortAnswerQuestion.type).toBe('Short');
// });
// });
it('parses numerical question type correctly', () => {
expect(sampleNumericalQuestion.type).toBe('Numerical');
});
it('parses short answer question type correctly', () => {
expect(sampleShortAnswerQuestion.type).toBe('Short');
});
});
it('renders correctly for True/False question', () => {
renderComponent(sampleTrueFalseQuestion);
@ -74,8 +73,7 @@ describe('Questions Component', () => {
const submitButton = screen.getByText('Répondre');
fireEvent.click(submitButton);
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['Choice 1']);
mockHandleSubmitAnswer.mockClear();
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('Choice 1');
});
it('renders correctly for Numerical question', () => {
@ -95,8 +93,7 @@ describe('Questions Component', () => {
const submitButton = screen.getByText('Répondre');
fireEvent.click(submitButton);
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([7]);
mockHandleSubmitAnswer.mockClear();
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(7);
});
it('renders correctly for Short Answer question', () => {
@ -120,7 +117,7 @@ describe('Questions Component', () => {
const submitButton = screen.getByText('Répondre');
fireEvent.click(submitButton);
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['User Input']);
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('User Input');
});
});

View file

@ -47,7 +47,6 @@ describe('ShortAnswerQuestion Component', () => {
fireEvent.click(submitButton);
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
mockHandleSubmitAnswer.mockClear();
});
it('submits answer correctly', () => {
@ -61,7 +60,6 @@ describe('ShortAnswerQuestion Component', () => {
fireEvent.click(submitButton);
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(['User Input']);
mockHandleSubmitAnswer.mockClear();
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith('User Input');
});
});

View file

@ -56,7 +56,6 @@ describe('TrueFalseQuestion Component', () => {
});
expect(mockHandleSubmitAnswer).not.toHaveBeenCalled();
mockHandleSubmitAnswer.mockClear();
});
it('submits answer correctly for True', () => {
@ -71,8 +70,7 @@ describe('TrueFalseQuestion Component', () => {
fireEvent.click(submitButton);
});
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([true]);
mockHandleSubmitAnswer.mockClear();
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(true);
});
it('submits answer correctly for False', () => {
@ -85,8 +83,7 @@ describe('TrueFalseQuestion Component', () => {
fireEvent.click(submitButton);
});
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith([false]);
mockHandleSubmitAnswer.mockClear();
expect(mockHandleSubmitAnswer).toHaveBeenCalledWith(false);
});
@ -115,7 +112,7 @@ describe('TrueFalseQuestion Component', () => {
expect(wrongAnswer1?.textContent).toContain('❌');
});
it('should not show ✅ or ❌ when pondre button is not clicked', async () => {
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
const choiceButton = screen.getByText('Vrai').closest('button');
if (!choiceButton) throw new Error('Choice button not found');

View file

@ -1,81 +0,0 @@
import React from 'react';
import { render, screen, fireEvent, act } from '@testing-library/react';
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal.tsx';
import { QuizType } from '../../../Types/QuizType';
import '@testing-library/jest-dom';
describe('ShareQuizModal', () => {
const mockQuiz: QuizType = {
_id: '123',
folderId: 'folder-123',
folderName: 'Test Folder',
userId: 'user-123',
title: 'Test Quiz',
content: ['Question 1', 'Question 2'],
created_at: new Date(),
updated_at: new Date(),
};
beforeAll(() => {
// Properly mock the clipboard API
Object.defineProperty(navigator, 'clipboard', {
value: {
writeText: jest.fn().mockImplementation(() => Promise.resolve()),
},
writable: true,
});
});
afterEach(() => {
jest.clearAllMocks();
});
it('renders the share button', () => {
render(<ShareQuizModal quiz={mockQuiz} />);
expect(screen.getByLabelText('partager quiz')).toBeInTheDocument();
expect(screen.getByTestId('ShareIcon')).toBeInTheDocument();
});
it('copies the quiz URL to clipboard when share button is clicked', async () => {
render(<ShareQuizModal quiz={mockQuiz} />);
const shareButton = screen.getByLabelText('partager quiz');
await act(async () => {
fireEvent.click(shareButton);
});
expect(navigator.clipboard.writeText).toHaveBeenCalledWith(
`${window.location.origin}/teacher/share/${mockQuiz._id}`
);
// Check for feedback dialog content
expect(screen.getByText(/L'URL de partage pour le quiz/i)).toBeInTheDocument();
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
expect(screen.getByText(/a été copiée\./i)).toBeInTheDocument();
});
it('shows error message when clipboard write fails', async () => {
// Override the mock to reject
(navigator.clipboard.writeText as jest.Mock).mockRejectedValueOnce(new Error('Clipboard write failed'));
render(<ShareQuizModal quiz={mockQuiz} />);
const shareButton = screen.getByLabelText('partager quiz');
await act(async () => {
fireEvent.click(shareButton);
});
expect(screen.getByText(/Une erreur est survenue lors de la copie de l'URL\./i)).toBeInTheDocument();
});
it('displays the quiz title in the success message', async () => {
render(<ShareQuizModal quiz={mockQuiz} />);
const shareButton = screen.getByLabelText('partager quiz');
await act(async () => {
fireEvent.click(shareButton);
});
expect(screen.getByText(mockQuiz.title)).toBeInTheDocument();
});
});

View file

@ -1,359 +0,0 @@
import { checkIfIsCorrect } from 'src/pages/Teacher/ManageRoom/useRooms';
import { HighLowNumericalAnswer, MultipleChoiceQuestion, MultipleNumericalAnswer, NumericalQuestion, RangeNumericalAnswer, ShortAnswerQuestion, SimpleNumericalAnswer, TrueFalseQuestion } from 'gift-pegjs';
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
import { QuestionType } from 'src/Types/QuestionType';
describe('checkIfIsCorrect', () => {
const mockQuestions: QuestionType[] = [
{
question: {
id: '1',
type: 'MC',
choices: [
{ isCorrect: true, formattedText: { text: 'Answer1' } },
{ isCorrect: true, formattedText: { text: 'Answer2' } },
{ isCorrect: false, formattedText: { text: 'Answer3' } },
],
} as MultipleChoiceQuestion,
},
];
test('returns true when all selected answers are correct', () => {
const answer: AnswerType = ['Answer1', 'Answer2'];
const result = checkIfIsCorrect(answer, 1, mockQuestions);
expect(result).toBe(true);
});
test('returns false when some selected answers are incorrect', () => {
const answer: AnswerType = ['Answer1', 'Answer3'];
const result = checkIfIsCorrect(answer, 1, mockQuestions);
expect(result).toBe(false);
});
test('returns false when all correct answers are selected, but one incorrect is also selected', () => {
const answer: AnswerType = ['Answer1', 'Answer2', 'Answer3'];
const result = checkIfIsCorrect(answer, 1, mockQuestions);
expect(result).toBe(false);
});
test('returns false when no answers are selected', () => {
const answer: AnswerType = [];
const result = checkIfIsCorrect(answer, 1, mockQuestions);
expect(result).toBe(false);
});
test('returns false when no correct answers are provided in the question', () => {
const mockQuestionsWithNoCorrectAnswers: QuestionType[] = [
{
question: {
id: '1',
type: 'MC',
choices: [
{ isCorrect: false, formattedText: { text: 'Answer1' } },
{ isCorrect: false, formattedText: { text: 'Answer2' } },
],
} as MultipleChoiceQuestion,
},
];
const answer: AnswerType = ['Answer1'];
const result = checkIfIsCorrect(answer, 1, mockQuestionsWithNoCorrectAnswers);
expect(result).toBe(false);
});
test('returns true for a correct true/false answer', () => {
const mockQuestionsTF: QuestionType[] = [
{
question: {
id: '2',
type: 'TF',
isTrue: true,
} as TrueFalseQuestion,
},
];
const answer: AnswerType = [true];
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
expect(result).toBe(true);
});
test('returns false for an incorrect true/false answer', () => {
const mockQuestionsTF: QuestionType[] = [
{
question: {
id: '2',
type: 'TF',
isTrue: true,
} as TrueFalseQuestion,
},
];
const answer: AnswerType = [false];
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
expect(result).toBe(false);
});
test('returns false for a true/false question with no answer', () => {
const mockQuestionsTF: QuestionType[] = [
{
question: {
id: '2',
type: 'TF',
isTrue: true,
} as TrueFalseQuestion,
},
];
const answer: AnswerType = [];
const result = checkIfIsCorrect(answer, 2, mockQuestionsTF);
expect(result).toBe(false);
});
test('returns true for a correct true/false answer when isTrue is false', () => {
const mockQuestionsTF: QuestionType[] = [
{
question: {
id: '3',
type: 'TF',
isTrue: false, // Correct answer is false
} as TrueFalseQuestion,
},
];
const answer: AnswerType = [false];
const result = checkIfIsCorrect(answer, 3, mockQuestionsTF);
expect(result).toBe(true);
});
test('returns false for an incorrect true/false answer when isTrue is false', () => {
const mockQuestionsTF: QuestionType[] = [
{
question: {
id: '3',
type: 'TF',
isTrue: false, // Correct answer is false
} as TrueFalseQuestion,
},
];
const answer: AnswerType = [true];
const result = checkIfIsCorrect(answer, 3, mockQuestionsTF);
expect(result).toBe(false);
});
test('returns true for a correct short answer', () => {
const mockQuestionsShort: QuestionType[] = [
{
question: {
id: '4',
type: 'Short',
choices: [
{ text: 'CorrectAnswer1' },
{ text: 'CorrectAnswer2' },
],
} as ShortAnswerQuestion,
},
];
const answer: AnswerType = ['CorrectAnswer1'];
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
expect(result).toBe(true);
});
test('returns false for an incorrect short answer', () => {
const mockQuestionsShort: QuestionType[] = [
{
question: {
id: '4',
type: 'Short',
choices: [
{ text: 'CorrectAnswer1' },
{ text: 'CorrectAnswer2' },
],
} as ShortAnswerQuestion,
},
];
const answer: AnswerType = ['WrongAnswer'];
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
expect(result).toBe(false);
});
test('returns true for a correct short answer with case insensitivity', () => {
const mockQuestionsShort: QuestionType[] = [
{
question: {
id: '4',
type: 'Short',
choices: [
{ text: 'CorrectAnswer1' },
{ text: 'CorrectAnswer2' },
],
} as ShortAnswerQuestion,
},
];
const answer: AnswerType = ['correctanswer1']; // Lowercase version of the correct answer
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
expect(result).toBe(true);
});
test('returns false for a short answer question with no answer', () => {
const mockQuestionsShort: QuestionType[] = [
{
question: {
id: '4',
type: 'Short',
choices: [
{ text: 'CorrectAnswer1' },
{ text: 'CorrectAnswer2' },
],
} as ShortAnswerQuestion,
},
];
const answer: AnswerType = [];
const result = checkIfIsCorrect(answer, 4, mockQuestionsShort);
expect(result).toBe(false);
});
test('returns true for a correct simple numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '5',
type: 'Numerical',
choices: [
{ type: 'simple', number: 42 } as SimpleNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [42]; // User's answer
const result = checkIfIsCorrect(answer, 5, mockQuestionsNumerical);
expect(result).toBe(true);
});
test('returns false for an incorrect simple numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '5',
type: 'Numerical',
choices: [
{ type: 'simple', number: 42 } as SimpleNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [43]; // User's answer
const result = checkIfIsCorrect(answer, 5, mockQuestionsNumerical);
expect(result).toBe(false);
});
test('returns true for a correct range numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '6',
type: 'Numerical',
choices: [
{ type: 'range', number: 50, range: 5 } as RangeNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [52]; // User's answer within the range (50 ± 5)
const result = checkIfIsCorrect(answer, 6, mockQuestionsNumerical);
expect(result).toBe(true);
});
test('returns false for an out-of-range numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '6',
type: 'Numerical',
choices: [
{ type: 'range', number: 50, range: 5 } as RangeNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [56]; // User's answer outside the range (50 ± 5)
const result = checkIfIsCorrect(answer, 6, mockQuestionsNumerical);
expect(result).toBe(false);
});
test('returns true for a correct high-low numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '7',
type: 'Numerical',
choices: [
{ type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [95]; // User's answer within the range (90 to 100)
const result = checkIfIsCorrect(answer, 7, mockQuestionsNumerical);
expect(result).toBe(true);
});
test('returns false for an out-of-range high-low numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '7',
type: 'Numerical',
choices: [
{ type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [105]; // User's answer outside the range (90 to 100)
const result = checkIfIsCorrect(answer, 7, mockQuestionsNumerical);
expect(result).toBe(false);
});
test('returns true for a correct multiple numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '8',
type: 'Numerical',
choices: [
{
isCorrect: true,
answer: { type: 'simple', number: 42 } as SimpleNumericalAnswer,
} as MultipleNumericalAnswer,
{
isCorrect: false,
answer: { type: 'high-low', numberHigh: 100, numberLow: 90 } as HighLowNumericalAnswer,
formattedFeedback: { text: 'You guessed way too high' },
}
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [42]; // User's answer matches the correct multiple numerical answer
const result = checkIfIsCorrect(answer, 8, mockQuestionsNumerical);
expect(result).toBe(true);
});
test('returns false for an incorrect multiple numerical answer', () => {
const mockQuestionsNumerical: QuestionType[] = [
{
question: {
id: '8',
type: 'Numerical',
choices: [
{
type: 'multiple',
isCorrect: true,
answer: { type: 'simple', number: 42 } as SimpleNumericalAnswer,
} as MultipleNumericalAnswer,
],
} as NumericalQuestion,
},
];
const answer: AnswerType = [43]; // User's answer does not match the correct multiple numerical answer
const result = checkIfIsCorrect(answer, 8, mockQuestionsNumerical);
expect(result).toBe(false);
});
});

View file

@ -19,11 +19,6 @@ jest.mock('react-router-dom', () => ({
}));
jest.mock('src/pages/Teacher/ManageRoom/RoomContext');
jest.mock('qrcode.react', () => ({
__esModule: true,
QRCodeCanvas: ({ value }: { value: string }) => <div data-testid="qr-code">{value}</div>,
}));
const mockSocket = {
on: jest.fn(),
off: jest.fn(),
@ -49,7 +44,7 @@ const mockStudents: StudentType[] = [
];
const mockAnswerData: AnswerReceptionFromBackendType = {
answer: ['Answer1'],
answer: 'Answer1',
idQuestion: 1,
idUser: '1',
username: 'Student 1',
@ -238,7 +233,7 @@ describe('ManageRoom', () => {
await act(async () => {
const createSuccessCallback = (mockSocket.on as jest.Mock).mock.calls.find(call => call[0] === 'create-success')[1];
createSuccessCallback('Test Room');
createSuccessCallback('test-room-name');
});
const launchButton = screen.getByText('Lancer');
@ -261,7 +256,6 @@ describe('ManageRoom', () => {
});
await waitFor(() => {
// console.info(consoleSpy.mock.calls);
expect(consoleSpy).toHaveBeenCalledWith(
'Received answer from Student 1 for question 1: Answer1'
);
@ -299,84 +293,4 @@ describe('ManageRoom', () => {
expect(screen.queryByText('Student 1')).not.toBeInTheDocument();
});
});
test('terminates the quiz and navigates to teacher dashboard when the "Terminer le quiz" button is clicked', async () => {
await act(async () => {
render(
<MemoryRouter>
<ManageRoom />
</MemoryRouter>
);
});
await act(async () => {
const createSuccessCallback = (mockSocket.on as jest.Mock).mock.calls.find(call => call[0] === 'create-success')[1];
createSuccessCallback('Test Room');
});
fireEvent.click(screen.getByText('Lancer'));
fireEvent.click(screen.getByText('Rythme du professeur'));
fireEvent.click(screen.getAllByText('Lancer')[1]);
await waitFor(() => {
expect(screen.getByText('Test Quiz')).toBeInTheDocument();
});
const finishQuizButton = screen.getByText('Terminer le quiz');
fireEvent.click(finishQuizButton);
await waitFor(() => {
expect(navigate).toHaveBeenCalledWith('/teacher/dashboard');
});
});
test("Affiche la modale QR Code lorsquon clique sur le bouton", async () => {
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
const button = screen.getByRole('button', { name: /lien de participation/i });
fireEvent.click(button);
await waitFor(() => {
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
expect(screen.getByRole('heading', { name: /Rejoindre la salle/i })).toBeInTheDocument();
expect(screen.getByText(/Scannez ce QR code ou partagez le lien ci-dessous/i)).toBeInTheDocument();
expect(screen.getByTestId('qr-code')).toBeInTheDocument();
});
test("Ferme la modale QR Code lorsquon clique sur le bouton Fermer", async () => {
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
await waitFor(() => {
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
fireEvent.click(screen.getByRole('button', { name: /fermer/i }));
await waitFor(() => {
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
});
test('Affiche le bon lien de participation', () => {
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
const roomUrl = `${window.location.origin}/student/join-room?roomName=Test Room`;
expect(screen.getByTestId('qr-code')).toHaveTextContent(roomUrl);
});
test('Vérifie que le QR code contient la bonne URL', () => {
render(<MemoryRouter><ManageRoom /></MemoryRouter>);
fireEvent.click(screen.getByRole('button', { name: /lien de participation/i }));
const roomUrl = `${window.location.origin}/student/join-room?roomName=Test Room`;
expect(screen.getByTestId('qr-code')).toHaveTextContent(roomUrl);
});
});

View file

@ -8,7 +8,7 @@ import { QuestionType } from 'src/Types/QuestionType';
import { AnswerSubmissionToBackendType } from 'src/services/WebsocketService';
const mockGiftQuestions = parse(
`::Sample Question 1:: Sample Question 1 {=Option A =Option B ~Option C}
`::Sample Question 1:: Sample Question 1 {=Option A ~Option B}
::Sample Question 2:: Sample Question 2 {T}`);
@ -23,6 +23,9 @@ const mockSubmitAnswer = jest.fn();
const mockDisconnectWebSocket = jest.fn();
beforeEach(() => {
// Clear local storage before each test
// localStorage.clear();
render(
<MemoryRouter>
<StudentModeQuiz
@ -51,7 +54,7 @@ describe('StudentModeQuiz', () => {
fireEvent.click(screen.getByText('Répondre'));
});
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
});
test('handles shows feedback for an already answered question', async () => {
@ -62,13 +65,13 @@ describe('StudentModeQuiz', () => {
act(() => {
fireEvent.click(screen.getByText('Répondre'));
});
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
const firstButtonA = screen.getByRole("button", {name: '✅ A Option A'});
expect(firstButtonA).toBeInTheDocument();
expect(firstButtonA.querySelector('.selected')).toBeInTheDocument();
expect(screen.getByRole("button", {name: ' B Option B'})).toBeInTheDocument();
expect(screen.getByRole("button", {name: ' B Option B'})).toBeInTheDocument();
expect(screen.queryByText('Répondre')).not.toBeInTheDocument();
// Navigate to the next question
@ -84,12 +87,12 @@ describe('StudentModeQuiz', () => {
});
expect(await screen.findByText('Sample Question 1')).toBeInTheDocument();
// Since answers are mocked, it doesn't recognize the question as already answered
// Since answers are mocked, the it doesn't recognize the question as already answered
// TODO these tests are partially faked, need to be fixed if we can mock the answers
// const buttonA = screen.getByRole("button", {name: '✅ A Option A'});
const buttonA = screen.getByRole("button", {name: 'A Option A'});
expect(buttonA).toBeInTheDocument();
// const buttonB = screen.getByRole("button", {name: ' B Option B'});
// const buttonB = screen.getByRole("button", {name: ' B Option B'});
const buttonB = screen.getByRole("button", {name: 'B Option B'});
expect(buttonB).toBeInTheDocument();
// // "Option A" div inside the name of button should have selected class
@ -119,30 +122,4 @@ describe('StudentModeQuiz', () => {
expect(screen.getByText('Sample Question 2')).toBeInTheDocument();
expect(screen.getByText('Répondre')).toBeInTheDocument();
});
// le test suivant est fait dans MultipleChoiceQuestionDisplay.test.tsx
// test('allows multiple answers to be selected for a question', async () => {
// // Simulate selecting multiple answers
// act(() => {
// fireEvent.click(screen.getByText('Option A'));
// });
// act(() => {
// fireEvent.click(screen.getByText('Option B'));
// });
// // Simulate submitting the answers
// act(() => {
// fireEvent.click(screen.getByText('Répondre'));
// });
// // Verify that the mockSubmitAnswer function is called with both answers
// expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A', 'Option B'], 1);
// // Verify that the selected answers are displayed as selected
// const buttonA = screen.getByRole('button', { name: '✅ A Option A' });
// const buttonB = screen.getByRole('button', { name: '✅ B Option B' });
// expect(buttonA).toBeInTheDocument();
// expect(buttonB).toBeInTheDocument();
// });
});

View file

@ -63,8 +63,7 @@ describe('TeacherModeQuiz', () => {
act(() => {
fireEvent.click(screen.getByText('Répondre'));
});
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
mockSubmitAnswer.mockClear();
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
});
test('handles shows feedback for an already answered question', () => {
@ -75,8 +74,7 @@ describe('TeacherModeQuiz', () => {
act(() => {
fireEvent.click(screen.getByText('Répondre'));
});
expect(mockSubmitAnswer).toHaveBeenCalledWith(['Option A'], 1);
mockSubmitAnswer.mockClear();
expect(mockSubmitAnswer).toHaveBeenCalledWith('Option A', 1);
mockQuestion = mockQuestions[1].question as MultipleChoiceQuestion;
// Navigate to the next question by re-rendering with new props
act(() => {

View file

@ -1,95 +0,0 @@
import React from 'react';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MemoryRouter, Route, Routes, useParams } from 'react-router-dom';
import Share from '../../../../pages/Teacher/Share/Share.tsx';
import ApiService from '../../../../services/ApiService';
import '@testing-library/jest-dom';
// Mock the ApiService and react-router-dom
jest.mock('../../../../services/ApiService');
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: jest.fn(),
useNavigate: jest.fn(),
}));
describe('Share Component', () => {
const mockNavigate = jest.fn();
const mockUseParams = useParams as jest.Mock;
const mockApiService = ApiService as jest.Mocked<typeof ApiService>;
beforeEach(() => {
jest.clearAllMocks();
mockUseParams.mockReturnValue({ id: 'quiz123' });
require('react-router-dom').useNavigate.mockReturnValue(mockNavigate);
});
const renderComponent = (initialEntries = ['/share/quiz123']) => {
return render(
<MemoryRouter initialEntries={initialEntries}>
<Routes>
<Route path="/share/:id" element={<Share />} />
<Route path="/teacher/dashboard" element={<div>Dashboard</div>} />
<Route path="/login" element={<div>Login</div>} />
</Routes>
</MemoryRouter>
);
};
it('should show loading state initially', () => {
mockApiService.getAllQuizIds.mockResolvedValue([]);
mockApiService.getUserFolders.mockResolvedValue([]);
mockApiService.getSharedQuiz.mockResolvedValue('Test Quiz');
renderComponent();
expect(screen.getByText('Chargement...')).toBeInTheDocument();
});
it('should redirect to login if not authenticated', async () => {
mockApiService.isLoggedIn.mockReturnValue(false);
renderComponent();
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/login');
});
});
it('should show "quiz already exists" message when quiz exists', async () => {
mockApiService.isLoggedIn.mockReturnValue(true);
mockApiService.getAllQuizIds.mockResolvedValue(['quiz123']);
renderComponent();
await waitFor(() => {
expect(screen.getByText('Quiz déjà existant')).toBeInTheDocument();
expect(screen.getByText(/Le quiz que vous essayez d'importer existe déjà sur votre compte/i)).toBeInTheDocument();
expect(screen.getByText('Retour au tableau de bord')).toBeInTheDocument();
});
});
it('should navigate to dashboard when clicking return button in "quiz exists" view', async () => {
mockApiService.isLoggedIn.mockReturnValue(true);
mockApiService.getAllQuizIds.mockResolvedValue(['quiz123']);
renderComponent();
await waitFor(() => {
fireEvent.click(screen.getByText('Retour au tableau de bord'));
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
});
});
it('should show error when no folders exist', async () => {
mockApiService.isLoggedIn.mockReturnValue(true);
mockApiService.getAllQuizIds.mockResolvedValue([]);
mockApiService.getUserFolders.mockResolvedValue([]);
renderComponent();
await waitFor(() => {
expect(mockNavigate).toHaveBeenCalledWith('/teacher/dashboard');
});
});
});

View file

@ -1,42 +0,0 @@
import axios from 'axios';
import ApiService from '../../services/ApiService';
import { ENV_VARIABLES } from '../../constants';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('getSharedQuiz', () => {
it('should call the API to get a shared quiz and return the quiz data on success', async () => {
const quizId = '123';
const quizData = 'Quiz data';
const response = { status: 200, data: { data: quizData } };
mockedAxios.get.mockResolvedValue(response);
const result = await ApiService.getSharedQuiz(quizId);
expect(mockedAxios.get).toHaveBeenCalledWith(
`${ENV_VARIABLES.VITE_BACKEND_URL}/api/quiz/getShare/${quizId}`,
{ headers: expect.any(Object) }
);
expect(result).toBe(quizData);
});
it('should return an error message if the API call fails', async () => {
const quizId = '123';
const errorMessage = 'An unexpected error occurred.';
mockedAxios.get.mockRejectedValue({ response: { data: { error: errorMessage } } });
const result = await ApiService.getSharedQuiz(quizId);
expect(result).toBe(errorMessage);
});
it('should return a generic error message if an unexpected error occurs', async () => {
const quizId = '123';
mockedAxios.get.mockRejectedValue(new Error('Unexpected error'));
const result = await ApiService.getSharedQuiz(quizId);
expect(result).toBe('An unexpected error occurred.');
});
});

View file

@ -1,42 +0,0 @@
import axios from 'axios';
import ApiService from '../../services/ApiService';
import { FolderType } from '../../Types/FolderType';
import { QuizType } from '../../Types/QuizType';
jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;
describe('ApiService', () => {
describe('getAllQuizIds', () => {
it('should return all quiz IDs from all folders', async () => {
const folders: FolderType[] = [
{ _id: 'folder1', title: 'Folder 1', userId: 'user1', created_at: new Date().toISOString() },
{ _id: 'folder2', title: 'Folder 2', userId: 'user2', created_at: new Date().toISOString() }
];
const quizzesFolder1: QuizType[] = [
{ _id: 'quiz1', title: 'Quiz 1', content: [], folderId: 'folder1', folderName: 'Folder 1', userId: 'user1', created_at: new Date(), updated_at: new Date() },
{ _id: 'quiz2', title: 'Quiz 2', content: [], folderId: 'folder1', folderName: 'Folder 1', userId: 'user1', created_at: new Date(), updated_at: new Date() }
];
const quizzesFolder2: QuizType[] = [
{ _id: 'quiz3', title: 'Quiz 3', content: [], folderId: 'folder2', folderName: 'Folder 2', userId: 'user2', created_at: new Date(), updated_at: new Date() }
];
mockedAxios.get
.mockResolvedValueOnce({ status: 200, data: { data: folders } })
.mockResolvedValueOnce({ status: 200, data: { data: quizzesFolder1 } })
.mockResolvedValueOnce({ status: 200, data: { data: quizzesFolder2 } });
const result = await ApiService.getAllQuizIds();
expect(result).toEqual(['quiz1', 'quiz2', 'quiz3']);
});
it('should return an empty array if no folders are found', async () => {
mockedAxios.get.mockResolvedValueOnce({ status: 200, data: { data: [] } });
const result = await ApiService.getAllQuizIds();
expect(result).toEqual([]);
});
});
});

View file

@ -13,14 +13,14 @@ type AnswerFeedbackOptions = TemplateOptions & Pick<TextChoice, 'formattedFeedba
interface AnswerWeightOptions extends TemplateOptions {
weight: TextChoice['weight'];
}
// careful -- this template is re-used by True/False questions!
export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoiceAnswerOptions) {
const id = `id${nanoid(8)}`;
const hasManyCorrectChoices = choices.filter(({ isCorrect }) => isCorrect === true).length > 1;
const isMultipleAnswer = choices.filter(({ isCorrect }) => isCorrect === true).length === 0;
const prompt = `<span style="${ParagraphStyle(state.theme)}">Choisir une réponse${
hasManyCorrectChoices ? ` ou plusieurs` : ``
isMultipleAnswer ? ` ou plusieurs` : ``
}:</span>`;
const result = choices
.map(({ weight, isCorrect, formattedText, formattedFeedback }) => {
@ -32,12 +32,12 @@ export default function MultipleChoiceAnswersTemplate({ choices }: MultipleChoic
const inputId = `id${nanoid(6)}`;
const isPositiveWeight = (weight != undefined) && (weight > 0);
const isCorrectOption = hasManyCorrectChoices ? isPositiveWeight || isCorrect : isCorrect;
const isCorrectOption = isMultipleAnswer ? isPositiveWeight : isCorrect;
return `
<div class='multiple-choice-answers-container'>
<input class="gift-input" type="${
hasManyCorrectChoices ? 'checkbox' : 'radio'
isMultipleAnswer ? 'checkbox' : 'radio'
}" id="${inputId}" name="${id}">
${AnswerWeight({ weight: weight })}
<label style="${CustomLabel} ${ParagraphStyle(state.theme)}" for="${inputId}">

View file

@ -3,7 +3,6 @@ import * as React from 'react';
import './header.css';
import { Button } from '@mui/material';
import AdminDrawer from '../AdminDrawer/AdminDrawer';
import ExitToAppIcon from '@mui/icons-material/ExitToApp';
interface HeaderProps {
isLoggedIn: boolean;
@ -27,6 +26,7 @@ const Header: React.FC<HeaderProps> = ({ isLoggedIn, isAdmin, handleLogout }) =>
<div className="button-group">
{ isAdmin && <AdminDrawer /> }
<Button
variant="outlined"
color="primary"
@ -34,9 +34,8 @@ const Header: React.FC<HeaderProps> = ({ isLoggedIn, isAdmin, handleLogout }) =>
handleLogout();
navigate('/');
}}
startIcon={<ExitToAppIcon />}
>
Déconnexion
Logout
</Button>
</div>
)}

View file

@ -22,8 +22,8 @@ import CloseIcon from "@mui/icons-material/Close";
import { ImageType } from "../../Types/ImageType";
import ApiService from "../../services/ApiService";
import { Upload } from "@mui/icons-material";
import { ENV_VARIABLES } from '../../constants';
import { escapeForGIFT } from "src/utils/giftUtils";
import { ENV_VARIABLES } from "src/constants";
interface ImagesProps {
handleCopy?: (id: string) => void;
@ -83,9 +83,9 @@ const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
const defaultHandleCopy = (id: string) => {
if (navigator.clipboard) {
const link = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
const imgTag = `[markdown] ![texte alternatif d'écrivant l'image pour les personnes qui ne peuvent pas voir l'image](${escapeForGIFT(link)} "texte de l'infobulle (ne fonctionne pas sur écran tactile généralement)") `;
setSnackbarMessage("Le lien Markdown de l'image a été copié dans le presse-papiers");
const link = `${ENV_VARIABLES.IMG_URL}/api/image/get/${id}`;
const imgTag = `[markdown]![alt_text](${escapeForGIFT(link)} "texte de l'infobulle")`;
setSnackbarMessage("Le lien Markdown de limage a été copié dans le presse-papiers");
setSnackbarSeverity("success");
setSnackbarOpen(true);
navigator.clipboard.writeText(imgTag);
@ -147,7 +147,7 @@ const ImageGallery: React.FC<ImagesProps> = ({ handleCopy, handleDelete }) => {
return (
<Box p={3}>
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
<Tab label="Galerie" />
<Tab label="Gallery" />
<Tab label="Import" />
</Tabs>
{tabValue === 0 && (

View file

@ -51,7 +51,7 @@ const LiveResultsTableFooter: React.FC<LiveResultsFooterProps> = ({
borderWidth: 1,
borderColor: 'rgba(224, 224, 224, 1)',
fontWeight: 'bold',
color: 'rgba(0, 0, 0)',
color: 'rgba(0, 0, 0)'
}}
>
{students.length > 0
@ -67,7 +67,7 @@ const LiveResultsTableFooter: React.FC<LiveResultsFooterProps> = ({
borderColor: 'rgba(224, 224, 224, 1)',
fontWeight: 'bold',
fontSize: '1rem',
color: 'rgba(0, 0, 0)',
color: 'rgba(0, 0, 0)'
}}
>
{students.length > 0 ? `${classAverage.toFixed()} %` : '-'}

View file

@ -15,115 +15,76 @@ interface Props {
const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
const [answer, setAnswer] = useState<AnswerType>(() => {
if (passedAnswer && passedAnswer.length > 0) {
return passedAnswer;
}
return [];
});
let disableButton = false;
if (handleOnSubmitAnswer === undefined) {
if(handleOnSubmitAnswer === undefined){
disableButton = true;
}
useEffect(() => {
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
if (passedAnswer !== undefined) {
setAnswer(passedAnswer);
} else {
setAnswer([]);
}
}, [passedAnswer, question.id]);
}, [passedAnswer]);
const handleOnClickAnswer = (choice: string) => {
setAnswer((prevAnswer) => {
console.log(`handleOnClickAnswer -- setAnswer(): prevAnswer: ${prevAnswer}, choice: ${choice}`);
const correctAnswersCount = question.choices.filter((c) => c.isCorrect).length;
if (correctAnswersCount === 1) {
// If only one correct answer, replace the current selection
return prevAnswer.includes(choice) ? [] : [choice];
} else {
// Allow multiple selections if there are multiple correct answers
if (prevAnswer.includes(choice)) {
// Remove the choice if it's already selected
return prevAnswer.filter((selected) => selected !== choice);
} else {
// Add the choice if it's not already selected
return [...prevAnswer, choice];
}
}
});
setAnswer(choice);
};
const alpha = Array.from(Array(26)).map((_e, i) => i + 65);
const alphabet = alpha.map((x) => String.fromCharCode(x));
return (
<div className="question-container">
<div className="question content">
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedStem) }} />
</div>
<div className="choices-wrapper mb-1">
{question.choices.map((choice, i) => {
console.log(`answer: ${answer}, choice: ${choice.formattedText.text}`);
const selected = answer.includes(choice.formattedText.text) ? 'selected' : '';
const selected = answer === choice.formattedText.text ? 'selected' : '';
return (
<div key={choice.formattedText.text + i} className="choice-container">
<Button
variant="text"
className="button-wrapper"
disabled={disableButton}
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}
>
{showAnswer ? (
<div>{choice.isCorrect ? '✅' : '❌'}</div>
) : (
''
)}
onClick={() => !showAnswer && handleOnClickAnswer(choice.formattedText.text)}>
{showAnswer? (<div> {(choice.isCorrect ? '✅' : '❌')}</div>)
:``}
<div className={`circle ${selected}`}>{alphabet[i]}</div>
<div className={`answer-text ${selected}`}>
<div
dangerouslySetInnerHTML={{
__html: FormattedTextTemplate(choice.formattedText),
}}
/>
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedText) }} />
</div>
{choice.formattedFeedback && showAnswer && (
<div className="feedback-container mb-1 mt-1/2">
<div
dangerouslySetInnerHTML={{
__html: FormattedTextTemplate(choice.formattedFeedback),
}}
/>
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(choice.formattedFeedback) }} />
</div>
)}
</Button>
</div>
);
})}
</div>
{question.formattedGlobalFeedback && showAnswer && (
<div className="global-feedback mb-2">
<div
dangerouslySetInnerHTML={{
__html: FormattedTextTemplate(question.formattedGlobalFeedback),
}}
/>
<div dangerouslySetInnerHTML={{ __html: FormattedTextTemplate(question.formattedGlobalFeedback) }} />
</div>
)}
{!showAnswer && handleOnSubmitAnswer && (
<Button
variant="contained"
onClick={() =>
answer.length > 0 && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
answer !== "" && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
}
disabled={answer.length === 0}
disabled={answer === '' || answer === null}
>
Répondre
</Button>
)}
</div>

View file

@ -17,7 +17,7 @@ interface Props {
const NumericalQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } =
props;
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || []);
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
const correctAnswers = question.choices;
let correctAnswer = '';
@ -69,7 +69,7 @@ const NumericalQuestionDisplay: React.FC<Props> = (props) => {
id={question.formattedStem.text}
name={question.formattedStem.text}
onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
setAnswer([e.target.valueAsNumber]);
setAnswer(e.target.valueAsNumber);
}}
inputProps={{ 'data-testid': 'number-input' }}
/>
@ -87,7 +87,7 @@ const NumericalQuestionDisplay: React.FC<Props> = (props) => {
handleOnSubmitAnswer &&
handleOnSubmitAnswer(answer)
}
disabled={answer === undefined || answer === null || isNaN(answer[0] as number)}
disabled={answer === "" || isNaN(answer as number)}
>
Répondre
</Button>

View file

@ -16,7 +16,7 @@ interface Props {
const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || []);
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || '');
useEffect(() => {
if (passedAnswer !== undefined) {
@ -58,7 +58,7 @@ const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
id={question.formattedStem.text}
name={question.formattedStem.text}
onChange={(e) => {
setAnswer([e.target.value]);
setAnswer(e.target.value);
}}
disabled={showAnswer}
aria-label="short-answer-input"
@ -72,7 +72,7 @@ const ShortAnswerQuestionDisplay: React.FC<Props> = (props) => {
handleOnSubmitAnswer &&
handleOnSubmitAnswer(answer)
}
disabled={answer === null || answer === undefined || answer.length === 0}
disabled={answer === null || answer === ''}
>
Répondre
</Button>

View file

@ -1,5 +1,5 @@
// TrueFalseQuestion.tsx
import React, { useState, useEffect } from 'react';
import React, { useState,useEffect } from 'react';
import '../questionStyle.css';
import { Button } from '@mui/material';
import { TrueFalseQuestion } from 'gift-pegjs';
@ -14,32 +14,32 @@ interface Props {
}
const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } =
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer} =
props;
const [answer, setAnswer] = useState<boolean | undefined>(() => {
if (passedAnswer && (passedAnswer[0] === true || passedAnswer[0] === false)) {
return passedAnswer[0];
}
return undefined;
});
let disableButton = false;
if (handleOnSubmitAnswer === undefined) {
if(handleOnSubmitAnswer === undefined){
disableButton = true;
}
useEffect(() => {
console.log("passedAnswer", passedAnswer);
if (passedAnswer && (passedAnswer[0] === true || passedAnswer[0] === false)) {
setAnswer(passedAnswer[0]);
console.log("passedAnswer", answer);
if (passedAnswer === true || passedAnswer === false) {
setAnswer(passedAnswer);
} else {
setAnswer(undefined);
}
}, [passedAnswer, question.id]);
const [answer, setAnswer] = useState<boolean | undefined>(() => {
if (passedAnswer === true || passedAnswer === false) {
return passedAnswer;
}
return undefined;
});
const handleOnClickAnswer = (choice: boolean) => {
setAnswer(choice);
};
@ -58,7 +58,8 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
fullWidth
disabled={disableButton}
>
{showAnswer ? (<div> {(question.isTrue ? '✅' : '❌')}</div>) : ``}
{showAnswer? (<div> {(question.isTrue ? '✅' : '❌')}</div>):``}
<div className={`circle ${selectedTrue}`}>V</div>
<div className={`answer-text ${selectedTrue}`}>Vrai</div>
{showAnswer && answer && question.trueFormattedFeedback && (
@ -74,7 +75,8 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
disabled={disableButton}
>
{showAnswer ? (<div> {(!question.isTrue ? '✅' : '❌')}</div>) : ``}
{showAnswer? (<div> {(!question.isTrue ? '✅' : '❌')}</div>):``}
<div className={`circle ${selectedFalse}`}>F</div>
<div className={`answer-text ${selectedFalse}`}>Faux</div>
{showAnswer && !answer && question.falseFormattedFeedback && (
@ -93,7 +95,8 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
<Button
variant="contained"
onClick={() =>
answer !== undefined && handleOnSubmitAnswer && handleOnSubmitAnswer([answer])
answer !== undefined && handleOnSubmitAnswer && handleOnSubmitAnswer(answer)
}
disabled={answer === undefined}
>

View file

@ -1,94 +0,0 @@
import React, { useState } from 'react';
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton, Typography, Box } from '@mui/material';
import { Share } from '@mui/icons-material';
import { QuizType } from '../../Types/QuizType';
interface ShareQuizModalProps {
quiz: QuizType;
}
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
const [_open, setOpen] = useState(false);
const [feedback, setFeedback] = useState({
open: false,
title: '',
isError: false
});
const handleCloseModal = () => setOpen(false);
const handleShareByUrl = () => {
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
navigator.clipboard.writeText(quizUrl)
.then(() => {
setFeedback({
open: true,
title: 'L\'URL de partage pour le quiz',
isError: false
});
})
.catch(() => {
setFeedback({
open: true,
title: 'Une erreur est survenue lors de la copie de l\'URL.',
isError: true
});
});
handleCloseModal();
};
const closeFeedback = () => {
setFeedback(prev => ({ ...prev, open: false }));
};
return (
<>
<Tooltip title="Partager" placement="top">
<IconButton color="primary" onClick={handleShareByUrl} aria-label="partager quiz">
<Share />
</IconButton>
</Tooltip>
{/* Feedback Dialog */}
<Dialog
open={feedback.open}
onClose={closeFeedback}
fullWidth
maxWidth="xs"
>
<DialogTitle sx={{ textAlign: "center" }}>
<Box>
{feedback.isError ? (
<Typography color="error.main">
{feedback.title}
</Typography>
) : (
<>
<Typography component="span">
L'URL de partage pour le quiz{' '}
</Typography>
<Typography component="span" fontWeight="bold">
{quiz.title}
</Typography>
<Typography component="span">
{' '}a é copiée.
</Typography>
</>
)}
</Box>
</DialogTitle>
<DialogActions sx={{ display: "flex", justifyContent: "center" }}>
<Button
onClick={closeFeedback}
variant="contained"
>
OK
</Button>
</DialogActions>
</Dialog>
</>
);
};
export default ShareQuizModal;

View file

@ -26,7 +26,8 @@ const StudentWaitPage: React.FC<Props> = ({ students, launchQuiz, setQuizMode })
variant="contained"
onClick={handleLaunchClick}
startIcon={<PlayArrow />}
sx={{ fontWeight: 600, fontSize: 20, width: 'auto' }}
fullWidth
sx={{ fontWeight: 600, fontSize: 20 }}
>
Lancer
</Button>

View file

@ -116,7 +116,7 @@ const TeacherModeQuiz: React.FC<TeacherModeQuizProps> = ({
</DialogContent>
<DialogActions>
<Button onClick={handleFeedbackDialogClose} color="primary">
Fermer
OK
</Button>
</DialogActions>
</Dialog>

View file

@ -2,8 +2,9 @@
const ENV_VARIABLES = {
MODE: process.env.MODE || "production",
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}` : ''}` : process.env.VITE_BACKEND_URL || '',
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}` : ''}` : ''
IMG_URL: process.env.MODE == "development" ? process.env.VITE_BACKEND_URL : process.env.VITE_IMG_URL,
BACKEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.BACKEND_PORT}`:''}` : process.env.VITE_BACKEND_URL || '',
FRONTEND_URL: process.env.SITE_URL != undefined ? `${process.env.SITE_URL}${process.env.USE_PORTS ? `:${process.env.PORT}`:''}` : ''
};
console.log(`ENV_VARIABLES.VITE_BACKEND_URL=${ENV_VARIABLES.VITE_BACKEND_URL}`);

View file

@ -44,6 +44,7 @@ const SimpleLogin: React.FC = () => {
variant="outlined"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder="Nom d'utilisateur"
sx={{ marginBottom: '1rem' }}
fullWidth
/>
@ -54,6 +55,7 @@ const SimpleLogin: React.FC = () => {
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Nom de la salle"
sx={{ marginBottom: '1rem' }}
fullWidth
/>

View file

@ -5,7 +5,7 @@ import { ENV_VARIABLES } from 'src/constants';
import StudentModeQuiz from 'src/components/StudentModeQuiz/StudentModeQuiz';
import TeacherModeQuiz from 'src/components/TeacherModeQuiz/TeacherModeQuiz';
import webSocketService, {AnswerSubmissionToBackendType} from '../../../services/WebsocketService';
import webSocketService, { AnswerSubmissionToBackendType } from '../../../services/WebsocketService';
import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
import './joinRoom.css';
@ -13,12 +13,11 @@ import { QuestionType } from '../../../Types/QuestionType';
import { TextField } from '@mui/material';
import LoadingButton from '@mui/lab/LoadingButton';
import LoginContainer from 'src/components/LoginContainer/LoginContainer';
import LoginContainer from 'src/components/LoginContainer/LoginContainer'
import ApiService from '../../../services/ApiService';
import { useSearchParams } from 'react-router-dom';
import ApiService from '../../../services/ApiService'
export type AnswerType = Array<string | number | boolean>;
export type AnswerType = string | number | boolean;
const JoinRoom: React.FC = () => {
const [roomName, setRoomName] = useState('');
@ -31,17 +30,6 @@ const JoinRoom: React.FC = () => {
const [answers, setAnswers] = useState<AnswerSubmissionToBackendType[]>([]);
const [connectionError, setConnectionError] = useState<string>('');
const [isConnecting, setIsConnecting] = useState<boolean>(false);
const [isQRCodeJoin, setIsQRCodeJoin] = useState(false);
const [searchParams] = useSearchParams();
useEffect(() => {
const roomFromUrl = searchParams.get('roomName');
if (roomFromUrl) {
setRoomName(roomFromUrl);
setIsQRCodeJoin(true);
console.log('Mode QR Code détecté, salle:', roomFromUrl);
}
}, [searchParams]);
useEffect(() => {
handleCreateSocket();
@ -113,7 +101,7 @@ const JoinRoom: React.FC = () => {
};
const disconnect = () => {
// localStorage.clear();
// localStorage.clear();
webSocketService.disconnect();
setSocket(null);
setQuestion(undefined);
@ -210,11 +198,9 @@ const JoinRoom: React.FC = () => {
default:
return (
<LoginContainer
title={isQRCodeJoin ? `Rejoindre la salle ${roomName}` : 'Rejoindre une salle'}
error={connectionError}
>
{/* Afficher champ salle SEULEMENT si pas de QR code */}
{!isQRCodeJoin && (
title='Rejoindre une salle'
error={connectionError}>
<TextField
type="text"
label="Nom de la salle"
@ -226,9 +212,7 @@ const JoinRoom: React.FC = () => {
fullWidth={true}
onKeyDown={handleReturnKey}
/>
)}
{/* Champ username toujours visible */}
<TextField
label="Nom d'utilisateur"
variant="outlined"
@ -245,10 +229,9 @@ const JoinRoom: React.FC = () => {
onClick={handleSocket}
variant="contained"
sx={{ marginBottom: `${connectionError && '2rem'}` }}
disabled={!username || (isQRCodeJoin && !roomName)}
>
{isQRCodeJoin ? 'Rejoindre avec QR Code' : 'Rejoindre'}
</LoadingButton>
disabled={!username || !roomName}
>Rejoindre</LoadingButton>
</LoginContainer>
);
}

View file

@ -38,9 +38,10 @@ import {
Upload,
FolderCopy,
ContentCopy,
Edit
Edit,
Share
// DriveFileMove
} from '@mui/icons-material';
import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal';
// Create a custom-styled Card component
const CustomCard = styled(Card)({
@ -65,7 +66,6 @@ const Dashboard: React.FC = () => {
const [selectedRoom, selectRoom] = useState<RoomType>(); // menu
const [errorMessage, setErrorMessage] = useState('');
const [showErrorDialog, setShowErrorDialog] = useState(false);
const [isSearchVisible, setIsSearchVisible] = useState(false);
// Filter quizzes based on search term
// const filteredQuizzes = quizzes.filter(quiz =>
@ -121,10 +121,6 @@ const Dashboard: React.FC = () => {
}
};
const toggleSearchVisibility = () => {
setIsSearchVisible(!isSearchVisible);
};
// Créer une salle
const createRoom = async (title: string) => {
// Créer la salle et récupérer l'objet complet
@ -138,9 +134,10 @@ const Dashboard: React.FC = () => {
selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné
};
// Sélectionner une salle
const selectRoomByName = (roomId: string) => {
const room = rooms.find((r) => r._id === roomId);
const room = rooms.find(r => r._id === roomId);
selectRoom(room);
localStorage.setItem('selectedRoomId', roomId);
};
@ -154,7 +151,7 @@ const Dashboard: React.FC = () => {
setOpenAddRoomDialog(false);
setNewRoomTitle('');
} catch (error) {
setErrorMessage(error instanceof Error ? error.message : 'Erreur inconnue');
setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue");
setShowErrorDialog(true);
}
}
@ -404,65 +401,54 @@ const Dashboard: React.FC = () => {
}
};
const handleShareQuiz = async (quiz: QuizType) => {
try {
const email = prompt(
`Veuillez saisir l'email de la personne avec qui vous souhaitez partager ce quiz`,
''
);
if (email) {
const result = await ApiService.ShareQuiz(quiz._id, email);
if (!result) {
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`);
return;
}
window.alert(`Quiz partagé avec succès!`);
}
} catch (error) {
console.error('Erreur lors du partage du quiz:', error);
}
};
return (
<div className="dashboard">
{/* Conteneur pour le titre et le sélecteur de salle */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '20px'
}}
>
{/* Titre tableau de bord */}
<div className="title" style={{ fontSize: '30px', fontWeight: 'bold' }}>
Tableau de bord
</div>
<div className="title">Tableau de bord</div>
{/* Sélecteur de salle */}
<div
className="roomSelection"
style={{ display: 'flex', justifyContent: 'flex-end', gap: '15px' }}
>
<select
value={selectedRoom?._id || ''}
onChange={(e) => handleSelectRoom(e)}
id="room-select"
style={{
padding: '8px 12px',
fontSize: '14px',
borderRadius: '8px',
border: '1px solid #ccc',
backgroundColor: '#fff',
maxWidth: '200px',
cursor: 'pointer',
fontWeight: '500'
}}
>
<div className="roomSelection">
<label htmlFor="select-room">Sélectionner une salle: </label>
<select value={selectedRoom?._id || ''} onChange={(e) => handleSelectRoom(e)}>
<option value="" disabled>
Sélectionner une salle
-- Sélectionner une salle --
</option>
{rooms.map((room) => (
<option key={room._id} value={room._id}>
{room.title}
</option>
))}
<option
value="add-room"
style={{
color: 'black',
backgroundColor: '#f0f0f0',
fontWeight: 'bold'
}}
>
Ajouter une salle
</option>
<option value="add-room">Ajouter salle</option>
</select>
</div>
</div>
{/* Dialog pour créer une salle */}
{selectedRoom && (
<div className="roomTitle">
<h2>Salle sélectionnée: {selectedRoom.title}</h2>
</div>
)}
<Dialog open={openAddRoomDialog} onClose={() => setOpenAddRoomDialog(false)}>
<DialogTitle>Créer une nouvelle salle</DialogTitle>
<DialogContent>
@ -487,17 +473,24 @@ const Dashboard: React.FC = () => {
</DialogActions>
</Dialog>
<div
style={{
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'center',
width: '100%',
gap: '20px'
<div className="search-bar">
<TextField
onChange={handleSearch}
value={searchTerm}
placeholder="Rechercher un quiz par son titre"
fullWidth
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton>
<Search />
</IconButton>
</InputAdornment>
)
}}
></div>
/>
</div>
{/* Conteneur principal avec les actions et la liste des quiz */}
<div className="folder">
<div className="select">
<NativeSelect
@ -505,18 +498,13 @@ const Dashboard: React.FC = () => {
color="primary"
value={selectedFolderId}
onChange={handleSelectFolder}
sx={{
padding: '6px 12px',
maxWidth: '180px',
borderRadius: '8px',
borderColor: '#e0e0e0',
'&:hover': { borderColor: '#5271FF' }
}}
>
<option value="">Tous les dossiers...</option>
{folders.map((folder) => (
<option value=""> Tous les dossiers... </option>
{folders.map((folder: FolderType) => (
<option value={folder._id} key={folder._id}>
{folder.title}
{' '}
{folder.title}{' '}
</option>
))}
</NativeSelect>
@ -572,77 +560,14 @@ const Dashboard: React.FC = () => {
</div>
</div>
<div
className="search-bar"
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
gap: '20px',
width: '100%'
}}
>
<div style={{ flex: 1 }}>
{!isSearchVisible ? (
<IconButton
onClick={toggleSearchVisibility}
sx={{
borderRadius: '8px',
border: '1px solid #ccc',
padding: '8px 12px',
backgroundColor: '#fff',
color: '#5271FF'
}}
>
<Search />
</IconButton>
) : (
<TextField
onChange={handleSearch}
value={searchTerm}
placeholder="Rechercher un quiz"
fullWidth
autoFocus
sx={{
borderRadius: '8px',
border: '1px solid #ccc',
padding: '8px 12px',
backgroundColor: '#fff',
fontWeight: 500,
width: '100%',
maxWidth: '1000px'
}}
InputProps={{
endAdornment: (
<InputAdornment position="end">
<IconButton
onClick={toggleSearchVisibility}
sx={{
borderRadius: '8px',
border: '1px solid #ccc',
backgroundColor: '#fff',
color: '#5271FF'
}}
>
<Search />
</IconButton>
</InputAdornment>
)
}}
/>
)}
</div>
{/* À droite : les boutons */}
<div style={{ display: 'flex', gap: '12px' }}>
<div className="ajouter">
<Button
variant="outlined"
color="primary"
startIcon={<Add />}
onClick={handleCreateQuiz}
sx={{ borderRadius: '8px', minWidth: 'auto', padding: '4px 12px' }}
>
Nouveau quiz
Ajouter un nouveau quiz
</Button>
<Button
@ -651,11 +576,9 @@ const Dashboard: React.FC = () => {
startIcon={<Upload />}
onClick={handleOnImport}
>
Importer
Import
</Button>
</div>
</div>
<div className="list">
{Object.keys(quizzesByFolder).map((folderName) => (
<CustomCard key={folderName} className="folder-card">
@ -664,16 +587,14 @@ const Dashboard: React.FC = () => {
{quizzesByFolder[folderName].map((quiz: QuizType) => (
<div className="quiz" key={quiz._id}>
<div className="title">
<Tooltip title="Démarrer" placement="top">
<Tooltip title="Lancer quiz" placement="top">
<div>
<Button
variant="outlined"
onClick={() => handleLancerQuiz(quiz)}
disabled={!validateQuiz(quiz.content)}
>
{`${quiz.title} (${
quiz.content.length
} question${
{`${quiz.title} (${quiz.content.length} question${
quiz.content.length > 1 ? 's' : ''
})`}
</Button>
@ -682,7 +603,7 @@ const Dashboard: React.FC = () => {
</div>
<div className="actions">
<Tooltip title="Télécharger" placement="top">
<Tooltip title="Télécharger quiz" placement="top">
<IconButton
color="primary"
onClick={() => downloadTxtFile(quiz)}
@ -692,7 +613,7 @@ const Dashboard: React.FC = () => {
</IconButton>
</Tooltip>
<Tooltip title="Modifier" placement="top">
<Tooltip title="Modifier quiz" placement="top">
<IconButton
color="primary"
onClick={() => handleEditQuiz(quiz)}
@ -702,7 +623,7 @@ const Dashboard: React.FC = () => {
</IconButton>
</Tooltip>
<Tooltip title="Dupliquer" placement="top">
<Tooltip title="Dupliquer quiz" placement="top">
<IconButton
color="primary"
onClick={() => handleDuplicateQuiz(quiz)}
@ -711,20 +632,27 @@ const Dashboard: React.FC = () => {
<ContentCopy />{' '}
</IconButton>
</Tooltip>
<div className="quiz-share">
<ShareQuizModal quiz={quiz} />
</div>
<Tooltip title="Supprimer" placement="top">
<Tooltip title="Supprimer quiz" placement="top">
<IconButton
aria-label="delete"
color="error"
color="primary"
onClick={() => handleRemoveQuiz(quiz)}
>
{' '}
<DeleteOutline />{' '}
</IconButton>
</Tooltip>
<Tooltip title="Partager quiz" placement="top">
<IconButton
color="primary"
onClick={() => handleShareQuiz(quiz)}
>
{' '}
<Share />{' '}
</IconButton>
</Tooltip>
</div>
</div>
))}

View file

@ -1,5 +1,5 @@
// EditorQuiz.tsx
import React, { useState, useEffect, CSSProperties } from 'react';
import React, { useState, useEffect, useRef, CSSProperties } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { FolderType } from '../../../Types/FolderType';
@ -9,15 +9,14 @@ import GiftCheatSheet from 'src/components/GIFTCheatSheet/GiftCheatSheet';
import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview';
import { QuizType } from '../../../Types/QuizType';
import SaveIcon from '@mui/icons-material/Save';
import './editorQuiz.css';
import { Button, TextField, NativeSelect, Divider } from '@mui/material';
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent } from '@mui/material';
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
import ImageGalleryModal from 'src/components/ImageGallery/ImageGalleryModal/ImageGalleryModal';
import ApiService from '../../../services/ApiService';
import { escapeForGIFT } from '../../../utils/giftUtils';
import { ENV_VARIABLES } from 'src/constants';
import { Upload } from '@mui/icons-material';
interface EditQuizParams {
id: string;
@ -39,6 +38,8 @@ const QuizForm: React.FC = () => {
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSelectedFolder(event.target.value);
};
const fileInputRef = useRef<HTMLInputElement>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [showScrollButton, setShowScrollButton] = useState(false);
const scrollToTop = () => {
@ -165,75 +166,86 @@ const QuizForm: React.FC = () => {
return <div>Chargement...</div>;
}
const handleSaveImage = async () => {
try {
const inputElement = document.getElementById('file-input') as HTMLInputElement;
if (!inputElement?.files || inputElement.files.length === 0) {
setDialogOpen(true);
return;
}
if (!inputElement.files || inputElement.files.length === 0) {
window.alert("Veuillez d'abord choisir une image à téléverser.")
return;
}
const imageUrl = await ApiService.uploadImage(inputElement.files[0]);
// Check for errors
if(imageUrl.indexOf("ERROR") >= 0) {
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
return;
}
setImageLinks(prevLinks => [...prevLinks, imageUrl]);
// Reset the file input element
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
} catch (error) {
window.alert(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`)
}
};
const handleCopyToClipboard = async (link: string) => {
navigator.clipboard.writeText(link);
}
const handleCopyImage = (id: string) => {
const escLink = `${ENV_VARIABLES.BACKEND_URL}/api/image/get/${id}`;
setImageLinks(prevLinks => [...prevLinks, escLink]);
}
return (
<div className="quizEditor">
<div
className="editHeader"
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '32px'
}}
>
<div className='quizEditor'>
<div className='editHeader'>
<ReturnButton
askConfirm
message={`Êtes-vous sûr de vouloir quitter l'éditeur sans sauvegarder le questionnaire?`}
/>
<Button
variant="contained"
onClick={handleQuizSave}
sx={{ display: 'flex', alignItems: 'center' }}
>
<SaveIcon sx={{ fontSize: 20 }} />
Enregistrer
</Button>
</div>
<div className='title'>Éditeur de quiz</div>
<div style={{ textAlign: 'center', marginTop: '30px' }}>
<div className="title">Éditeur de quiz</div>
<div className='dumb'></div>
</div>
{/* <h2 className="subtitle">Éditeur</h2> */}
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<TextField
onChange={handleQuizTitleChange}
value={quizTitle}
color="primary"
placeholder="Titre du quiz"
label="Titre du quiz"
sx={{ width: '200px', marginTop: '50px' }}
fullWidth
/>
<label>Choisir un dossier:
<NativeSelect
id="select-folder"
color="primary"
value={selectedFolder}
onChange={handleSelectFolder}
disabled={!isNewQuiz}
style={{ marginBottom: '16px', width: '200px', marginTop: '10px' }}
style={{ marginBottom: '16px' }} // Ajout de marge en bas
>
<option disabled value="">
Choisir un dossier...
</option>
{folders.map((folder: FolderType) => (
<option value={folder._id} key={folder._id}>
{folder.title}
</option>
))}
</NativeSelect>
</div>
<option disabled value=""> Choisir un dossier... </option>
{folders.map((folder: FolderType) => (
<option value={folder._id} key={folder._id}> {folder.title} </option>
))}
</NativeSelect></label>
<Button variant="contained" onClick={handleQuizSave}>
Enregistrer
</Button>
<Divider style={{ margin: '16px 0' }} />
@ -246,11 +258,37 @@ const QuizForm: React.FC = () => {
onEditorChange={handleUpdatePreview} />
<div className='images'>
<div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<h4>Mes images :</h4>
<ImageGalleryModal handleCopy={handleCopyImage} />
<div className='upload'>
<label className="dropArea">
<input type="file" id="file-input" className="file-input"
accept="image/jpeg, image/png"
multiple
ref={fileInputRef} />
<Button
variant="outlined"
aria-label='Téléverser'
onClick={handleSaveImage}>
Téléverser <Upload />
</Button>
</label>
<Dialog
open={dialogOpen}
onClose={() => setDialogOpen(false)} >
<DialogTitle>Erreur</DialogTitle>
<DialogContent>
Veuillez d&apos;abord choisir une image à téléverser.
</DialogContent>
<DialogActions>
<Button onClick={() => setDialogOpen(false)} color="primary">
OK
</Button>
</DialogActions>
</Dialog>
</div>
<h4>Mes images :</h4>
<div>
<div>
<div style={{ display: "inline" }}>(Voir section </div>
@ -264,7 +302,7 @@ const QuizForm: React.FC = () => {
</div>
<ul>
{imageLinks.map((link, index) => {
const imgTag = `[markdown]![alt_text](${escapeForGIFT(link)} "texte de l'infobulle") {T}`;
const imgTag = `![alt_text](${escapeForGIFT(link)} "texte de l'infobulle")`;
return (
<li key={index}>
<code

View file

@ -1,7 +1,12 @@
import React, { useEffect, useState } from 'react';
import { useNavigate, useParams } from 'react-router-dom';
import { Socket } from 'socket.io-client';
import { BaseQuestion, parse, Question } from 'gift-pegjs';
import { ParsedGIFTQuestion, BaseQuestion, parse, Question } from 'gift-pegjs';
import {
isSimpleNumericalAnswer,
isRangeNumericalAnswer,
isHighLowNumericalAnswer
} from 'gift-pegjs/typeGuards';
import LiveResultsComponent from 'src/components/LiveResults/LiveResults';
import webSocketService, {
AnswerReceptionFromBackendType
@ -9,7 +14,6 @@ import webSocketService, {
import { QuizType } from '../../../Types/QuizType';
import GroupIcon from '@mui/icons-material/Group';
import './manageRoom.css';
import QRCodeIcon from '@mui/icons-material/QrCode';
import { ENV_VARIABLES } from 'src/constants';
import { StudentType, Answer } from '../../../Types/StudentType';
import LoadingCircle from 'src/components/LoadingCircle/LoadingCircle';
@ -19,41 +23,22 @@ import DisconnectButton from 'src/components/DisconnectButton/DisconnectButton';
import QuestionDisplay from 'src/components/QuestionsDisplay/QuestionDisplay';
import ApiService from '../../../services/ApiService';
import { QuestionType } from 'src/Types/QuestionType';
import {
Button,
Dialog,
DialogTitle,
DialogContent,
DialogContentText,
DialogActions
} from '@mui/material';
import { checkIfIsCorrect } from './useRooms';
import { QRCodeCanvas } from 'qrcode.react';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';
import { Button } from '@mui/material';
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
const ManageRoom: React.FC = () => {
const navigate = useNavigate();
const [socket, setSocket] = useState<Socket | null>(null);
const [students, setStudents] = useState<StudentType[]>([]);
const { quizId = '', roomName = '' } = useParams<{ quizId: string; roomName: string }>();
const { quizId = '', roomName = '' } = useParams<{ quizId: string, roomName: string }>();
const [quizQuestions, setQuizQuestions] = useState<QuestionType[] | undefined>();
const [quiz, setQuiz] = useState<QuizType | null>(null);
const [quizMode, setQuizMode] = useState<'teacher' | 'student'>('teacher');
const [connectingError, setConnectingError] = useState<string>('');
const [currentQuestion, setCurrentQuestion] = useState<QuestionType | undefined>(undefined);
const [quizStarted, setQuizStarted] = useState<boolean>(false);
const [formattedRoomName, setFormattedRoomName] = useState('');
const [formattedRoomName, setFormattedRoomName] = useState("");
const [newlyConnectedUser, setNewlyConnectedUser] = useState<StudentType | null>(null);
const roomUrl = `${window.location.origin}/student/join-room?roomName=${roomName}`;
const [showQrModal, setShowQrModal] = useState(false);
const [copied, setCopied] = useState(false);
const handleCopy = () => {
navigator.clipboard.writeText(roomUrl).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 2000);
});
};
// Handle the newly connected user in useEffect, because it needs state info
// not available in the socket.on() callback
@ -97,15 +82,6 @@ const ManageRoom: React.FC = () => {
verifyLogin();
}, []);
useEffect(() => {
if (!roomName) {
console.error('Room name is missing!');
return;
}
console.log(`Joining room: ${roomName}`);
}, [roomName]);
useEffect(() => {
if (!roomName || !quizId) {
window.alert(
@ -208,6 +184,7 @@ const ManageRoom: React.FC = () => {
};
useEffect(() => {
if (socket) {
console.log(`Listening for submit-answer-room in room ${formattedRoomName}`);
socket.on('submit-answer-room', (answerData: AnswerReceptionFromBackendType) => {
@ -281,12 +258,10 @@ const ManageRoom: React.FC = () => {
if (nextQuestionIndex === undefined || nextQuestionIndex > quizQuestions.length - 1) return;
setCurrentQuestion(quizQuestions[nextQuestionIndex]);
webSocketService.nextQuestion({
roomName: formattedRoomName,
webSocketService.nextQuestion({roomName: formattedRoomName,
questions: quizQuestions,
questionIndex: nextQuestionIndex,
isLaunch: false
});
isLaunch: false});
};
const previousQuestion = () => {
@ -296,12 +271,7 @@ const ManageRoom: React.FC = () => {
if (prevQuestionIndex === undefined || prevQuestionIndex < 0) return;
setCurrentQuestion(quizQuestions[prevQuestionIndex]);
webSocketService.nextQuestion({
roomName: formattedRoomName,
questions: quizQuestions,
questionIndex: prevQuestionIndex,
isLaunch: false
});
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: prevQuestionIndex, isLaunch: false});
};
const initializeQuizQuestion = () => {
@ -329,12 +299,7 @@ const ManageRoom: React.FC = () => {
}
setCurrentQuestion(quizQuestions[0]);
webSocketService.nextQuestion({
roomName: formattedRoomName,
questions: quizQuestions,
questionIndex: 0,
isLaunch: true
});
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex: 0, isLaunch: true});
};
const launchStudentMode = () => {
@ -371,26 +336,73 @@ const ManageRoom: React.FC = () => {
if (quiz?.content && quizQuestions) {
setCurrentQuestion(quizQuestions[questionIndex]);
if (quizMode === 'teacher') {
webSocketService.nextQuestion({
roomName: formattedRoomName,
questions: quizQuestions,
questionIndex,
isLaunch: false
});
webSocketService.nextQuestion({roomName: formattedRoomName, questions: quizQuestions, questionIndex, isLaunch: false});
}
}
};
const finishQuiz = () => {
disconnectWebSocket();
navigate('/teacher/dashboard');
};
const handleReturn = () => {
disconnectWebSocket();
navigate('/teacher/dashboard');
};
function checkIfIsCorrect(
answer: AnswerType,
idQuestion: number,
questions: QuestionType[]
): boolean {
const questionInfo = questions.find((q) =>
q.question.id ? q.question.id === idQuestion.toString() : false
) as QuestionType | undefined;
const answerText = answer.toString();
if (questionInfo) {
const question = questionInfo.question as ParsedGIFTQuestion;
if (question.type === 'TF') {
return (
(question.isTrue && answerText == 'true') ||
(!question.isTrue && answerText == 'false')
);
} else if (question.type === 'MC') {
return question.choices.some(
(choice) => choice.isCorrect && choice.formattedText.text === answerText
);
} else if (question.type === 'Numerical') {
if (isHighLowNumericalAnswer(question.choices[0])) {
const choice = question.choices[0];
const answerNumber = parseFloat(answerText);
if (!isNaN(answerNumber)) {
return (
answerNumber <= choice.numberHigh && answerNumber >= choice.numberLow
);
}
}
if (isRangeNumericalAnswer(question.choices[0])) {
const answerNumber = parseFloat(answerText);
const range = question.choices[0].range;
const correctAnswer = question.choices[0].number;
if (!isNaN(answerNumber)) {
return (
answerNumber <= correctAnswer + range &&
answerNumber >= correctAnswer - range
);
}
}
if (isSimpleNumericalAnswer(question.choices[0])) {
const answerNumber = parseFloat(answerText);
if (!isNaN(answerNumber)) {
return answerNumber === question.choices[0].number;
}
}
} else if (question.type === 'Short') {
return question.choices.some(
(choice) => choice.text.toUpperCase() === answerText.toUpperCase()
);
}
}
return false;
}
if (!formattedRoomName) {
return (
<div className="center">
@ -415,95 +427,32 @@ const ManageRoom: React.FC = () => {
return (
<div className="room">
{/* En-tête avec bouton Disconnect à gauche et QR code à droite */}
<div
style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '20px'
}}
>
<h1>Salle : {formattedRoomName}</h1>
<div className="roomHeader">
<DisconnectButton
onReturn={handleReturn}
askConfirm
message={`Êtes-vous sûr de vouloir quitter?`}
/>
<Button
variant="contained"
color="primary"
onClick={() => setShowQrModal(true)}
startIcon={<QRCodeIcon />}
>
Lien de participation
</Button>
</div>
<Dialog
open={showQrModal}
onClose={() => setShowQrModal(false)}
aria-labelledby="qr-modal-title"
>
<DialogTitle id="qr-modal-title">
Rejoindre la salle: {formattedRoomName}
</DialogTitle>
<DialogContent>
<DialogContentText>
Scannez ce QR code ou partagez le lien ci-dessous pour rejoindre la salle :
</DialogContentText>
<div style={{ textAlign: 'center', margin: '20px 0' }}>
<QRCodeCanvas value={roomUrl} size={256} />
</div>
<div style={{ wordBreak: 'break-all', textAlign: 'center' }}>
<h3>URL de participation :</h3>
<p>{roomUrl}</p>
<Button
variant="contained"
startIcon={<ContentCopyIcon />}
onClick={handleCopy}
style={{ marginTop: '10px' }}
>
{copied ? 'Copié !' : 'Copier le lien'}
</Button>
</div>
</DialogContent>
<DialogActions>
<Button onClick={() => setShowQrModal(false)} color="primary">
Fermer
</Button>
</DialogActions>
</Dialog>
<div className="roomHeader">
<div
className="headerContent"
style={{
display: 'flex',
justifyContent: 'center',
justifyContent: 'space-between',
alignItems: 'center',
width: '100%',
marginBottom: '10px'
width: '100%'
}}
>
<h1 style={{ margin: 0, display: 'flex', alignItems: 'center' }}>
Salle : {formattedRoomName}
{(
<div
className="userCount subtitle"
style={{
display: 'inline-flex',
alignItems: 'center',
fontSize: '1.5rem',
fontWeight: 'bold',
marginLeft: '20px',
marginBottom: '0px'
}}
className="userCount subtitle smallText"
style={{ display: "flex", justifyContent: "flex-end" }}
>
<GroupIcon style={{ marginRight: '5px', verticalAlign: 'middle' }} />{' '}
<GroupIcon style={{ marginRight: '5px' }} />
{students.length}/60
</div>
</h1>
)}
</div>
<div className="dumb"></div>
@ -538,6 +487,7 @@ const ManageRoom: React.FC = () => {
<QuestionDisplay
showAnswer={false}
question={currentQuestion?.question as Question}
/>
)}
@ -579,11 +529,6 @@ const ManageRoom: React.FC = () => {
</div>
</div>
)}
<div className="finishQuizButton">
<Button onClick={finishQuiz} variant="contained">
Terminer le quiz
</Button>
</div>
</div>
) : (
<StudentWaitPage

View file

@ -2,31 +2,25 @@
.room .roomHeader {
width: 100%;
display: flex;
flex-direction: column;
align-items: flex-start;
position: relative;
flex-direction: row;
justify-content: space-between;
align-content: stretch
}
.room .roomHeader .returnButton {
position: absolute;
top: 10px;
left: 0;
z-index: 10;
flex-basis: 10%;
display: flex;
justify-content: center;
}
.room .roomHeader .centerTitle {
flex-basis: auto;
display: flex;
justify-content: flex-start;
align-items: flex-start;
margin-top: 40px;
}
.room .roomHeader .headerContent {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 60px;
flex-direction: column;
justify-content: flex-end;
align-items: flex-end;
}
.room .roomHeader .dumb {
@ -40,16 +34,152 @@
overflow: auto;
justify-content: center;
/* align-items: center; */
}
.room .finishQuizButton {
/* .create-room-container {
display: flex;
justify-content: flex-end;
margin-left: auto;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
}
.manage-room-container {
display: flex;
flex-direction: column;
align-items: center;
height: 100%;
width: 100%;
}
.room h1 {
text-align: center;
margin-top: 50px;
.quiz-setup-container {
display: flex;
flex-direction: column;
width: 100%;
margin-top: 2rem;
}
.quiz-mode-selection {
display: flex;
flex-grow: 0;
flex-direction: column;
justify-content: center;
align-items: center;
margin-top: 10px;
height: 15vh;
}
.users-container {
display: flex;
flex-direction: column;
align-items: center;
flex-grow: 1;
gap: 2vh;
}
.launch-quiz-btn {
width: 20vw;
height: 11vh;
margin-top: 2vh;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}
.mode-choice {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
width: 20vw;
margin-top: 2vh;
}
.user {
background-color: #e7dad1;
padding: 10px 20px;
border: 1px solid black;
border-radius: 10px;
box-shadow: 2px 2px 4px rgba(0, 0, 0, 0.2);
}
.bottom-btn {
display: flex;
width: 100%;
justify-content: flex-end;
margin-top: 2vh;
}
.room-container {
position: relative;
width: 100%;
max-width: 60vw;
}
@media only screen and (max-device-width: 768px) {
.room-container {
max-width: 100%;
}
}
.room-wrapper {
display: flex;
width: 100%;
height: 100%;
justify-content: center;
}
.room-name-wrapper {
display: flex;
flex-direction: column;
align-items: end;
}
.user-item {
width: 100%;
}
.flex-column-wrapper {
display: flex;
flex-direction: column;
height: 85vh;
overflow: auto;
}
.preview-and-result-container {
display: flex;
flex-direction: column;
gap: 2rem;
}
.nextQuestionButton {
align-self: flex-end;
margin-bottom: 5rem !important;
}
.top-container {
display: flex;
justify-content: space-between;
align-items: center;
}
@media only screen and (max-device-height: 4000px) {
.flex-column-wrapper {
height: 60vh;
}
}
@media only screen and (max-device-height: 1079px) {
.flex-column-wrapper {
height: 50vh;
}
}
@media only screen and (max-device-height: 741px) {
.flex-column-wrapper {
height: 40vh;
}
} */

View file

@ -1,15 +1,8 @@
import { useContext } from 'react';
import { RoomType } from 'src/Types/RoomType';
import { createContext } from 'react';
import { MultipleNumericalAnswer, NumericalAnswer, ParsedGIFTQuestion } from 'gift-pegjs';
import { QuestionType } from 'src/Types/QuestionType';
import { AnswerType } from 'src/pages/Student/JoinRoom/JoinRoom';
import {
isSimpleNumericalAnswer,
isRangeNumericalAnswer,
isHighLowNumericalAnswer,
isMultipleNumericalAnswer
} from 'gift-pegjs/typeGuards';
//import { RoomContext } from './RoomContext';
type RoomContextType = {
rooms: RoomType[];
@ -25,137 +18,3 @@ export const useRooms = () => {
if (!context) throw new Error('useRooms must be used within a RoomProvider');
return context;
};
/**
* Checks if the answer is correct - logic varies by type of question!
* True/False: answer must match the isTrue property
* Multiple Choice: answer must match the correct choice(s)
* Numerical: answer must be within the range or equal to the number (for each type of correct answer)
* Short Answer: answer must match the correct choice(s) (case-insensitive)
* @param answer
* @param idQuestion
* @param questions
* @returns
*/
export function checkIfIsCorrect(
answer: AnswerType,
idQuestion: number,
questions: QuestionType[]
): boolean {
const questionInfo = questions.find((q) =>
q.question.id ? q.question.id === idQuestion.toString() : false
) as QuestionType | undefined;
const simpleAnswerText = answer.toString();
if (questionInfo) {
const question = questionInfo.question as ParsedGIFTQuestion;
if (question.type === 'TF') {
return (
(question.isTrue && simpleAnswerText == 'true') ||
(!question.isTrue && simpleAnswerText == 'false')
);
} else if (question.type === 'MC') {
const correctChoices = question.choices.filter((choice) => choice.isCorrect
/* || (choice.weight && choice.weight > 0)*/ // handle weighted answers
);
const multipleAnswers = Array.isArray(answer) ? answer : [answer as string];
if (correctChoices.length === 0) {
return false;
}
// check if all (and only) correct choices are in the multipleAnswers array
return correctChoices.length === multipleAnswers.length && correctChoices.every(
(choice) => multipleAnswers.includes(choice.formattedText.text)
);
} else if (question.type === 'Numerical') {
if (isMultipleNumericalAnswer(question.choices[0])) { // Multiple numerical answers
// check to see if answer[0] is a match for any of the choices that isCorrect
const correctChoices = question.choices.filter((choice) => isMultipleNumericalAnswer(choice) && choice.isCorrect);
if (correctChoices.length === 0) { // weird case where there are multiple numerical answers but none are correct
return false;
}
return correctChoices.some((choice) => {
// narrow choice to MultipleNumericalAnswer type
const multipleNumericalChoice = choice as MultipleNumericalAnswer;
return isCorrectNumericalAnswer(multipleNumericalChoice.answer, simpleAnswerText);
});
}
if (isHighLowNumericalAnswer(question.choices[0])) {
// const choice = question.choices[0];
// const answerNumber = parseFloat(simpleAnswerText);
// if (!isNaN(answerNumber)) {
// return (
// answerNumber <= choice.numberHigh && answerNumber >= choice.numberLow
// );
// }
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
}
if (isRangeNumericalAnswer(question.choices[0])) {
// const answerNumber = parseFloat(simpleAnswerText);
// const range = question.choices[0].range;
// const correctAnswer = question.choices[0].number;
// if (!isNaN(answerNumber)) {
// return (
// answerNumber <= correctAnswer + range &&
// answerNumber >= correctAnswer - range
// );
// }
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
}
if (isSimpleNumericalAnswer(question.choices[0])) {
// const answerNumber = parseFloat(simpleAnswerText);
// if (!isNaN(answerNumber)) {
// return answerNumber === question.choices[0].number;
// }
return isCorrectNumericalAnswer(question.choices[0], simpleAnswerText);
}
} else if (question.type === 'Short') {
return question.choices.some(
(choice) => choice.text.toUpperCase() === simpleAnswerText.toUpperCase()
);
}
}
return false;
}
/**
* Determines if a numerical answer is correct based on the type of numerical answer.
* @param correctAnswer The correct answer (of type NumericalAnswer).
* @param userAnswer The user's answer (as a string or number).
* @returns True if the user's answer is correct, false otherwise.
*/
export function isCorrectNumericalAnswer(
correctAnswer: NumericalAnswer,
userAnswer: string | number
): boolean {
const answerNumber = typeof userAnswer === 'string' ? parseFloat(userAnswer) : userAnswer;
if (isNaN(answerNumber)) {
return false; // User's answer is not a valid number
}
if (isSimpleNumericalAnswer(correctAnswer)) {
// Exact match for simple numerical answers
return answerNumber === correctAnswer.number;
}
if (isRangeNumericalAnswer(correctAnswer)) {
// Check if the user's answer is within the range
const { number, range } = correctAnswer;
return answerNumber >= number - range && answerNumber <= number + range;
}
if (isHighLowNumericalAnswer(correctAnswer)) {
// Check if the user's answer is within the high-low range
const { numberLow, numberHigh } = correctAnswer;
return answerNumber >= numberLow && answerNumber <= numberHigh;
}
// if (isMultipleNumericalAnswer(correctAnswer)) {
// // Check if the user's answer matches any of the multiple numerical answers
// return correctAnswer.answer.some((choice) =>
// isCorrectNumericalAnswer(choice, answerNumber)
// );
// }
return false; // Default to false if the answer type is not recognized
}

View file

@ -1,47 +1,46 @@
// EditorQuiz.tsx
import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { FolderType } from '../../../Types/FolderType';
import './share.css';
import { Button, NativeSelect, Typography, Box } from '@mui/material';
import { Button, NativeSelect } from '@mui/material';
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
import ApiService from '../../../services/ApiService';
import SaveIcon from '@mui/icons-material/Save';
const Share: React.FC = () => {
console.log('Component rendered');
const navigate = useNavigate();
const { id } = useParams<string>();
const [quizTitle, setQuizTitle] = useState('');
const [selectedFolder, setSelectedFolder] = useState<string>('');
const [folders, setFolders] = useState<FolderType[]>([]);
const [quizExists, setQuizExists] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
console.log("QUIZID : " + id)
if (!id) {
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
console.error('Quiz not found for id:', id);
navigate('/teacher/dashboard');
return;
}
if (!ApiService.isLoggedIn()) {
window.alert(`Vous n'êtes pas connecté.\nVeuillez vous connecter et revenir à ce lien`);
navigate("/login");
return;
}
const quizIds = await ApiService.getAllQuizIds();
if (quizIds.includes(id)) {
setQuizExists(true);
setLoading(false);
return;
}
const userFolders = await ApiService.getUserFolders();
if (userFolders.length == 0) {
window.alert(`Vous n'avez aucun dossier.\nVeuillez en créer un et revenir à ce lien`)
navigate('/teacher/dashboard');
return;
}
@ -51,22 +50,17 @@ const Share: React.FC = () => {
const title = await ApiService.getSharedQuiz(id);
if (!title) {
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
console.error('Quiz not found for id:', id);
navigate('/teacher/dashboard');
return;
}
setQuizTitle(title);
setLoading(false);
} catch (error) {
console.error('Error fetching data:', error);
setLoading(false);
navigate('/teacher/dashboard');
}
};
fetchData();
}, [id, navigate]);
}, []);
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
setSelectedFolder(event.target.value);
@ -74,12 +68,14 @@ const Share: React.FC = () => {
const handleQuizSave = async () => {
try {
if (selectedFolder == '') {
alert("Veuillez choisir un dossier");
return;
}
if (!id) {
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
console.error('Quiz not found for id:', id);
navigate('/teacher/dashboard');
return;
@ -89,90 +85,47 @@ const Share: React.FC = () => {
navigate('/teacher/dashboard');
} catch (error) {
window.alert(`Une erreur est survenue.\n Veuillez réessayer plus tard`)
console.log(error)
}
};
if (loading) {
return <div className='quizImport'>Chargement...</div>;
}
if (quizExists) {
return (
<div className='quizImport'>
<div className='importHeader'>
<ReturnButton />
<div className='titleContainer'>
<div className='mainTitle'>Quiz déjà existant</div>
</div>
<div className='title'>Importer quiz: {quizTitle}</div>
<div className='dumb'></div>
</div>
<div className='editSection'>
<Box sx={{
textAlign: 'center',
padding: 3,
maxWidth: 600,
margin: '0 auto'
}}>
<Typography variant="h6" gutterBottom>
Le quiz que vous essayez d'importer existe déjà sur votre compte.
</Typography>
<Button
variant="contained"
onClick={() => navigate('/teacher/dashboard')}
sx={{ mt: 3, mb: 1 }}
fullWidth
>
Retour au tableau de bord
</Button>
<div>
<Typography variant="body2" color="text.secondary">
Si vous souhaitiez créer une copie de ce quiz,
vous pouvez utiliser la fonction "Dupliquer" disponible
dans votre tableau de bord.
</Typography>
</Box>
</div>
</div>
);
}
return (
<div className='quizImport'>
<div className='importHeader'>
<ReturnButton />
<div className='titleContainer'>
<div className='mainTitle'>Importation du Quiz: {quizTitle}</div>
<div className='subTitle'>
Vous êtes sur le point d'importer le quiz <strong>{quizTitle}</strong>, choisissez un dossier dans lequel enregistrer ce nouveau quiz.
</div>
</div>
<div className='dumb'></div>
</div>
<div className='editSection'>
<div className='formContainer'>
<NativeSelect
id="select-folder"
color="primary"
value={selectedFolder}
onChange={handleSelectFolder}
className="folderSelect"
>
<option disabled value=""> Choisir un dossier... </option>
{folders.map((folder: FolderType) => (
<option value={folder._id} key={folder._id}> {folder.title} </option>
))}
</NativeSelect>
<Button variant="contained" onClick={handleQuizSave} className="saveButton">
{<SaveIcon sx={{ fontSize: 20, marginRight: '8px' }} />}
<Button variant="contained" onClick={handleQuizSave}>
Enregistrer
</Button>
</div>
</div>
</div>
);
};

View file

@ -3,58 +3,19 @@
display: flex;
flex-direction: row;
justify-content: space-between;
align-content: stretch;
align-content: stretch
}
.quizImport .importHeader .returnButton {
flex-basis: 10%;
display: flex;
justify-content: center;
}
.quizImport .importHeader .titleContainer {
.quizImport .importHeader .title {
flex-basis: auto;
text-align: center; /* Center the title and subtitle */
}
.quizImport .importHeader .mainTitle {
font-size: 44px; /* Larger font size for the main title */
font-weight: bold; /* Remove bold */
color: #333; /* Slightly paler color */
}
.quizImport .importHeader .subTitle {
font-size: 14px; /* Smaller font size for the subtitle */
color: #666; /* Pale gray color */
margin-top: 8px; /* Add some space between the title and subtitle */
}
.quizImport .importHeader .dumb {
flex-basis: 10%;
}
.quizImport .editSection {
display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
}
.quizImport .editSection .formContainer {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px; /* Adds space between the select and button */
width: 100%;
max-width: 400px; /* Limits the width of the form container */
}
.quizImport .editSection .folderSelect {
width: 100%; /* Ensures the select element takes the full width of its container */
}
.quizImport .editSection .saveButton {
width: 100%; /* Makes the button take the full width of its container */
padding: 10px 20px; /* Increases the button's padding for a larger appearance */
font-size: 16px; /* Increases the font size for better visibility */
}

View file

@ -76,6 +76,8 @@ class ApiService {
return false;
}
console.log("ApiService: isLoggedIn: Token:", token);
// Update token expiry
this.saveToken(token);
@ -91,6 +93,7 @@ class ApiService {
}
try {
console.log("ApiService: isLoggedInTeacher: Token:", token);
const decodedToken = jwtDecode(token) as { roles: string[] };
/////// REMOVE BELOW
@ -102,6 +105,7 @@ class ApiService {
const userRoles = decodedToken.roles;
const requiredRole = 'teacher';
console.log("ApiService: isLoggedInTeacher: UserRoles:", userRoles);
if (!userRoles || !userRoles.includes(requiredRole)) {
return false;
}
@ -161,22 +165,6 @@ class ApiService {
return object.username;
}
public getUserID(): string {
const token = localStorage.getItem("jwt");
if (!token) {
return "";
}
const jsonObj = jwtDecode(token) as { userId: string };
if (!jsonObj.userId) {
return "";
}
return jsonObj.userId;
}
// Route to know if rooms need authentication to join
public async getRoomsRequireAuth(): Promise<any> {
const url: string = this.constructRequestUrl(`/auth/getRoomsRequireAuth`);
@ -213,6 +201,7 @@ class ApiService {
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
console.log(result);
if (result.status == 200) {
//window.location.href = result.request.responseURL;
window.location.href = '/login';
@ -224,6 +213,7 @@ class ApiService {
return true;
} catch (error) {
console.log("Error details: ", error);
if (axios.isAxiosError(error)) {
const err = error as AxiosError;
@ -586,6 +576,7 @@ public async login(email: string, password: string): Promise<any> {
const headers = this.constructRequestHeaders();
const body = { folderId };
console.log(headers);
const result: AxiosResponse = await axios.post(url, body, { headers: headers });
if (result.status !== 200) {
@ -875,6 +866,36 @@ public async login(email: string, password: string): Promise<any> {
}
}
async ShareQuiz(quizId: string, email: string): Promise<ApiResponse> {
try {
if (!quizId || !email) {
throw new Error(`quizId and email are required.`);
}
const url: string = this.constructRequestUrl(`/quiz/Share`);
const headers = this.constructRequestHeaders();
const body = { quizId, email };
const result: AxiosResponse = await axios.put(url, body, { headers: headers });
if (result.status !== 200) {
throw new Error(`Update and share quiz failed. Status: ${result.status}`);
}
return true;
} catch (error) {
console.log("Error details: ", error);
if (axios.isAxiosError(error)) {
const err = error as AxiosError;
const data = err.response?.data as { error: string } | undefined;
return data?.error || 'Unknown server error during request.';
}
return `An unexpected error occurred.`;
}
}
async getSharedQuiz(quizId: string): Promise<string> {
try {
if (!quizId) {
@ -1171,103 +1192,6 @@ public async login(email: string, password: string): Promise<any> {
}
}
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
return this.isAdmin() ? this.getAllImages(page, limit) : this.getUserImages(page, limit);
}
public async getUserImages(page: number, limit: number): Promise<ImagesResponse> {
try {
const url: string = this.constructRequestUrl(`/image/getUserImages`);
const headers = this.constructRequestHeaders();
let params : ImagesParams = { page: page, limit: limit };
const uid = this.getUserID();
if(uid !== ''){
params.uid = uid;
}
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
if (result.status !== 200) {
throw new Error(`L'affichage des images de l'utilisateur a échoué. Status: ${result.status}`);
}
const images = result.data;
return images;
} catch (error) {
console.log("Error details: ", error);
if (axios.isAxiosError(error)) {
const err = error as AxiosError;
const data = err.response?.data as { error: string } | undefined;
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
}
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
}
}
public async deleteImage(imgId: string): Promise<ApiResponse> {
return this.isAdmin() ? this.deleteAnyImage(imgId) : this.deleteUserImage(imgId);
}
public async deleteUserImage(imgId: string): Promise<ApiResponse> {
try {
const url: string = this.constructRequestUrl(`/image/delete`);
const headers = this.constructRequestHeaders();
const uid = this.getUserID();
let params = { uid: uid, imgId: imgId };
const result: AxiosResponse = await axios.delete(url, { params: params, headers: headers });
if (result.status !== 200) {
throw new Error(`La suppression de l'image a échoué. Status: ${result.status}`);
}
const deleted = result.data.deleted;
return deleted;
} catch (error) {
console.log("Error details: ", error);
if (axios.isAxiosError(error)) {
const err = error as AxiosError;
const data = err.response?.data as { error: string } | undefined;
const msg = data?.error || 'Erreur serveur inconnue lors de la requête.';
throw new Error(`L'enregistrement a échoué. Status: ${msg}`);
}
throw new Error(`ERROR : Une erreur inattendue s'est produite.`);
}
}
public async getAllQuizIds(): Promise<string[]> {
try {
const folders = await this.getUserFolders();
const allQuizIds: string[] = [];
if (Array.isArray(folders)) {
for (const folder of folders) {
const folderQuizzes = await this.getFolderContent(folder._id);
if (Array.isArray(folderQuizzes)) {
allQuizIds.push(...folderQuizzes.map(quiz => quiz._id));
}
}
} else {
console.error('Failed to get user folders:', folders);
}
return allQuizIds;
} catch (error) {
console.error('Failed to get all quiz ids:', error);
throw error;
}
}
public async getUsers(): Promise<AdminTableType[]> {
try {
@ -1294,7 +1218,7 @@ public async login(email: string, password: string): Promise<any> {
}
}
public async getAllImages(page: number, limit: number): Promise<ImagesResponse> {
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
try {
const url: string = this.constructRequestUrl(`/admin/getImages`);
const headers = this.constructRequestHeaders();
@ -1323,7 +1247,7 @@ public async login(email: string, password: string): Promise<any> {
}
}
public async deleteAnyImage(imgId: string): Promise<ApiResponse> {
public async deleteImage(imgId: string): Promise<ApiResponse> {
try {
const url: string = this.constructRequestUrl(`/admin/deleteImage`);
const headers = this.constructRequestHeaders();

View file

@ -55,7 +55,7 @@ services:
image: mongo
container_name: mongo
ports:
- "27019:27017"
- "27017:27017"
tty: true
volumes:
- mongodb_data:/data/db

329
package-lock.json generated
View file

@ -1,329 +0,0 @@
{
"name": "EvalueTonSavoir",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"dependencies": {
"axios-mock-adapter": "^2.1.0"
}
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"peer": true
},
"node_modules/axios": {
"version": "1.8.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.8.2.tgz",
"integrity": "sha512-ls4GYBm5aig9vWx8AWDSGLpnpDQRtWAfrjU+EuytuODrFBkqesN2RkOQCBzrA1RQNHw1SmRMSDDDSwzNAYQ6Rg==",
"peer": true,
"dependencies": {
"follow-redirects": "^1.15.6",
"form-data": "^4.0.0",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/axios-mock-adapter": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/axios-mock-adapter/-/axios-mock-adapter-2.1.0.tgz",
"integrity": "sha512-AZUe4OjECGCNNssH8SOdtneiQELsqTsat3SQQCWLPjN436/H+L9AjWfV7bF+Zg/YL9cgbhrz5671hoh+Tbn98w==",
"dependencies": {
"fast-deep-equal": "^3.1.3",
"is-buffer": "^2.0.5"
},
"peerDependencies": {
"axios": ">= 0.17.0"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"peer": true,
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"peer": true,
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"peer": true,
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"peer": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"peer": true,
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"peer": true,
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"peer": true,
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"peer": true,
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
},
"node_modules/follow-redirects": {
"version": "1.15.9",
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",
"integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"peer": true,
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.2.tgz",
"integrity": "sha512-hGfm/slu0ZabnNt4oaRZ6uREyfCj6P4fT/n6A1rGV+Z0VdGXjfOhVUpkn6qVQONHGIFwmveGXyDs75+nr6FM8w==",
"peer": true,
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/function-bind": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
"integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
"peer": true,
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"peer": true,
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"peer": true,
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"peer": true,
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"peer": true,
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"peer": true,
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",
"integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==",
"peer": true,
"dependencies": {
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/is-buffer": {
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/is-buffer/-/is-buffer-2.0.5.tgz",
"integrity": "sha512-i2R6zNFDwgEHJyQUtJEk0XFi1i0dPFn/oqjK3/vPCcDeJvW5NQ83V8QbicfF1SupOaB0h8ntgBC2YiE7dfyctQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"engines": {
"node": ">=4"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"peer": true,
"engines": {
"node": ">= 0.4"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"peer": true,
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"peer": true,
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"peer": true
}
}
}

View file

@ -1,5 +0,0 @@
{
"dependencies": {
"axios-mock-adapter": "^2.1.0"
}
}

View file

@ -7,9 +7,6 @@
// const BASE_URL = '/image'
const Images = require('../models/images');
const ObjectId = require('mongodb').ObjectId;
describe.skip("POST /upload", () => {
describe("when the jwt is not sent", () => {
@ -67,289 +64,3 @@ describe.skip("GET /get", () => {
})
})
jest.mock('mongodb', () => {
const originalModule = jest.requireActual('mongodb');
return {
...originalModule,
ObjectId: {
...originalModule.ObjectId,
createFromHexString: jest.fn().mockReturnValue('507f191e810c19729de860ea'), // Return a valid 24-character ObjectId string
},
};
});
describe('Images', () => {
let db;
let images;
let dbConn;
let mockImagesCollection;
let mockFindCursor;
beforeEach(() => {
const mockImagesCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn()
};
const mockFilesCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn()
};
mockImagesCollection = {
insertOne: jest.fn().mockResolvedValue({ insertedId: 'image123' }),
findOne: jest.fn(),
find: jest.fn().mockReturnValue(mockImagesCursor),
countDocuments: jest.fn(),
deleteOne: jest.fn()
};
mockFilesCollection = {
find: jest.fn().mockReturnValue(mockFilesCursor)
};
dbConn = {
collection: jest.fn((name) => {
if (name === 'images') {
return mockImagesCollection;
} else if (name === 'files') {
return mockFilesCollection;
}
})
};
db = {
connect: jest.fn().mockResolvedValue(),
getConnection: jest.fn().mockReturnValue(dbConn)
};
images = new Images(db);
});
describe('upload', () => {
it('should upload an image and return the inserted ID', async () => {
const testFile = { originalname: 'test.png', buffer: Buffer.from('dummydata'), mimetype: 'image/png' };
const userId = 'user123';
const result = await images.upload(testFile, userId);
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.insertOne).toHaveBeenCalledWith({
userId: userId,
file_name: 'test.png',
file_content: testFile.buffer.toString('base64'),
mime_type: 'image/png',
created_at: expect.any(Date)
});
expect(result).toBe('image123');
});
});
describe('get', () => {
it('should retrieve the image if found', async () => {
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
const testImage = {
file_name: 'test.png',
file_content: Buffer.from('dummydata').toString('base64'),
mime_type: 'image/png'
};
mockImagesCollection.findOne.mockResolvedValue(testImage);
const result = await images.get(imageId);
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.findOne).toHaveBeenCalledWith({ _id: ObjectId.createFromHexString(imageId) });
expect(result).toEqual({
file_name: 'test.png',
file_content: Buffer.from('dummydata'),
mime_type: 'image/png'
});
});
it('should return null if image is not found', async () => {
const imageId = '65d9a8f9b5e8d1a5e6a8c9f0';
mockImagesCollection.findOne.mockResolvedValue(null);
const result = await images.get(imageId);
expect(result).toBeNull();
});
});
describe('getImages', () => {
it('should retrieve a paginated list of images', async () => {
const mockImages = [
{ _id: '1', userId: 'user1', file_name: 'image1.png', file_content: Buffer.from('data1'), mime_type: 'image/png' },
{ _id: '2', userId: 'user2', file_name: 'image2.png', file_content: Buffer.from('data2'), mime_type: 'image/png' }
];
mockImagesCollection.countDocuments.mockResolvedValue(2);
// Create a mock cursor for images collection
const mockFindCursor = {
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn().mockResolvedValue(mockImages), // Return mock images when toArray is called
};
// Mock the find method to return the mock cursor
mockImagesCollection.find.mockReturnValue(mockFindCursor);
const result = await images.getImages(1, 10);
expect(db.connect).toHaveBeenCalled();
expect(db.getConnection).toHaveBeenCalled();
expect(dbConn.collection).toHaveBeenCalledWith('images');
expect(mockImagesCollection.find).toHaveBeenCalledWith({});
expect(mockFindCursor.sort).toHaveBeenCalledWith({ created_at: 1 });
expect(mockFindCursor.skip).toHaveBeenCalledWith(0);
expect(mockFindCursor.limit).toHaveBeenCalledWith(10);
expect(result).toEqual({
images: [
{ id: '1', user: 'user1', file_name: 'image1.png', file_content: 'ZGF0YTE=', mime_type: 'image/png' },
{ id: '2', user: 'user2', file_name: 'image2.png', file_content: 'ZGF0YTI=', mime_type: 'image/png' }
],
total: 2,
});
});
it('should return an empty array if no images are found', async () => {
mockImagesCollection.countDocuments.mockResolvedValue(0);
const result = await images.getImages(1, 10);
expect(result).toEqual({ images: [], total: 0 });
});
});
describe('getUserImages', () => {
it('should return empty images array when no images exist', async () => {
mockImagesCollection.countDocuments.mockResolvedValue(0);
const result = await images.getUserImages(1, 10, 'user123');
expect(result).toEqual({ images: [], total: 0 });
expect(db.connect).toHaveBeenCalled();
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
});
it('should return images when they exist', async () => {
const mockImages = [
{
_id: 'img1',
userId: 'user123',
file_name: 'image1.png',
file_content: Buffer.from('testdata'),
mime_type: 'image/png'
}
];
mockImagesCollection.countDocuments.mockResolvedValue(1);
mockImagesCollection.find.mockReturnValue({
sort: jest.fn().mockReturnThis(),
skip: jest.fn().mockReturnThis(),
limit: jest.fn().mockReturnThis(),
toArray: jest.fn().mockResolvedValue(mockImages)
});
const result = await images.getUserImages(1, 10, 'user123');
expect(result).toEqual({
images: [
{
id: 'img1',
user: 'user123',
file_name: 'image1.png',
file_content: Buffer.from('testdata').toString('base64'),
mime_type: 'image/png'
}
],
total: 1
});
expect(db.connect).toHaveBeenCalled();
expect(mockImagesCollection.countDocuments).toHaveBeenCalledWith({ userId: 'user123' });
});
});
describe('delete', () => {
it('should not delete the image when it exists in the files collection', async () => {
const uid = 'user123';
const imgId = '507f191e810c19729de860ea'; // A valid 24-character ObjectId string
// Mock the files collection cursor to simulate an image found
const mockFilesCursor = {
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
};
mockFilesCollection.find.mockReturnValue(mockFilesCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 });
const result = await images.delete(uid, imgId);
// Ensure the files collection is queried
expect(dbConn.collection).toHaveBeenCalledWith('files');
expect(mockFilesCollection.find).toHaveBeenCalledWith({
userId: uid,
content: { $regex: new RegExp(`/api/image/get/${imgId}`) },
});
// Ensure the images collection is queried for deletion
expect(dbConn.collection).toHaveBeenCalledWith('files');
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
});
expect(result).toEqual({ deleted: false });
});
it('should delete the image if not found in the files collection', async () => {
const uid = 'user123';
const imgId = '507f191e810c19729de860ea';
// Mock the files collection cursor to simulate the image not being found
const mockFindCursor = {
toArray: jest.fn().mockResolvedValue([]) // Empty array means image not found
};
mockFilesCollection.find.mockReturnValue(mockFindCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 1 });
const result = await images.delete(uid, imgId);
// Ensure the deleteOne is not called if the image is not found
expect(mockImagesCollection.deleteOne).toHaveBeenCalled();
expect(result).toEqual({ deleted: true });
});
it('should return false if the delete operation fails in the images collection', async () => {
const uid = 'user123';
const imgId = '507f191e810c19729de860ea';
// Mock the files collection cursor to simulate the image being found
const mockFindCursor = {
toArray: jest.fn().mockResolvedValue([{ _id: imgId }]) // Image found
};
mockFilesCollection.find.mockReturnValue(mockFindCursor);
mockImagesCollection.deleteOne.mockResolvedValue({ deletedCount: 0 }); // Simulate failure
const result = await images.delete(uid, imgId);
// Ensure the images collection deletion is called
expect(mockImagesCollection.deleteOne).not.toHaveBeenCalledWith({
_id: ObjectId.createFromHexString(imgId), // Ensure the ObjectId is created correctly
});
expect(result).toEqual({ deleted: false });
});
});
});

View file

@ -50,58 +50,6 @@ class ImagesController {
}
};
getImages = async (req, res, next) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const images = await this.images.getImages(page, limit);
if (!images || images.length === 0) {
throw new AppError(IMAGE_NOT_FOUND);
}
res.setHeader('Content-Type', 'application/json');
return res.status(200).json(images);
} catch (error) {
return next(error);
}
};
getUserImages = async (req, res, next) => {
try {
const page = parseInt(req.query.page) || 1;
const limit = parseInt(req.query.limit) || 5;
const uid = req.query.uid;
const images = await this.images.getUserImages(page, limit, uid);
if (!images || images.length === 0) {
throw new AppError(IMAGE_NOT_FOUND);
}
res.setHeader('Content-Type', 'application/json');
return res.status(200).json(images);
} catch (error) {
return next(error);
}
};
delete = async (req, res, next) => {
try {
const uid = req.query.uid;
const imgId = req.query.imgId;
if (!uid || !imgId) {
throw new AppError(MISSING_REQUIRED_PARAMETER);
}
const images = await this.images.delete(uid, imgId);
res.setHeader('Content-Type', 'application/json');
return res.status(200).json(images);
} catch (error) {
return next(error);
}
};
}
module.exports = ImagesController;

View file

@ -42,84 +42,6 @@ class Images {
};
}
async getImages(page, limit) {
await this.db.connect()
const conn = this.db.getConnection();
const imagesCollection = conn.collection('images');
const total = await imagesCollection.countDocuments();
if (!total || total === 0) return { images: [], total };
const result = await imagesCollection.find({})
.sort({ created_at: 1 })
.skip((page - 1) * limit)
.limit(limit)
.toArray();
const objImages = result.map(image => ({
id: image._id,
user: image.userId,
file_name: image.file_name,
file_content: image.file_content.toString('base64'),
mime_type: image.mime_type
}));
let respObj = {
images: objImages,
total: total
}
return respObj;
}
async getUserImages(page, limit, uid) {
await this.db.connect()
const conn = this.db.getConnection();
const imagesCollection = conn.collection('images');
const total = await imagesCollection.countDocuments({ userId: uid });
if (!total || total === 0) return { images: [], total };
const result = await imagesCollection.find({ userId: uid })
.sort({ created_at: -1 })
.skip((page - 1) * limit)
.limit(limit)
.toArray();
const objImages = result.map(image => ({
id: image._id,
user: image.userId,
file_name: image.file_name,
file_content: image.file_content.toString('base64'),
mime_type: image.mime_type
}));
let respObj = {
images: objImages,
total: total
}
return respObj;
}
async delete(uid, imgId) {
let resp = false;
await this.db.connect()
const conn = this.db.getConnection();
const quizColl = conn.collection('files');
const rgxImg = new RegExp(`/api/image/get/${imgId}`);
const result = await quizColl.find({ userId: uid, content: { $regex: rgxImg }}).toArray();
if(!result || result.length < 1){
const imgsColl = conn.collection('images');
const isDeleted = await imgsColl.deleteOne({ _id: ObjectId.createFromHexString(imgId) });
if(isDeleted){
resp = true;
}
}
return { deleted: resp };
}
}
module.exports = Images;

219
server/package-lock.json generated
View file

@ -24,7 +24,6 @@
"passport-oauth2": "^1.8.0",
"passport-openidconnect": "^0.1.2",
"patch-package": "^8.0.0",
"qrcode.react": "^4.2.0",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2"
},
@ -39,7 +38,7 @@
"supertest": "^6.3.4"
},
"engines": {
"node": "22.x"
"node": "20.x"
}
},
"node_modules/@ampproject/remapping": {
@ -56,20 +55,68 @@
}
},
"node_modules/@babel/code-frame": {
"version": "7.26.2",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.26.2.tgz",
"integrity": "sha512-RJlIHRueQgwWitWgF8OdFYGZX328Ax5BCemNGlqHfplnRT9ESi8JkFlvaVYbS+UubVY6dpv87Fs2u5M29iNFVQ==",
"version": "7.22.13",
"resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.13.tgz",
"integrity": "sha512-XktuhWlJ5g+3TJXc5upd9Ks1HutSArik6jf2eAjYFyIOf4ej3RN+184cZbzDvbPnuTJIUhPKKJE3cIsYTiAT3w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-validator-identifier": "^7.25.9",
"js-tokens": "^4.0.0",
"picocolors": "^1.0.0"
"@babel/highlight": "^7.22.13",
"chalk": "^2.4.2"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/code-frame/node_modules/ansi-styles": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
"dev": true,
"dependencies": {
"color-convert": "^1.9.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/code-frame/node_modules/chalk": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
"dev": true,
"dependencies": {
"ansi-styles": "^3.2.1",
"escape-string-regexp": "^1.0.5",
"supports-color": "^5.3.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/code-frame/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"dev": true,
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/@babel/code-frame/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"dev": true
},
"node_modules/@babel/code-frame/node_modules/escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
"integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
"dev": true,
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/@babel/compat-data": {
"version": "7.23.3",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.3.tgz",
@ -295,21 +342,19 @@
}
},
"node_modules/@babel/helper-string-parser": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.25.9.tgz",
"integrity": "sha512-4A/SCr/2KLd5jrtOMFzaKjVtAei3+2r/NChoBNoZ3EyP/+GlhoaEGoWOZUmFmoITP7zOJyHIMm+DYRd8o3PvHA==",
"version": "7.22.5",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.22.5.tgz",
"integrity": "sha512-mM4COjgZox8U+JcXQwPijIZLElkgEpO5rsERVDJTc2qfCDfERyob6k5WegS14SX18IIjv+XD+GrqNumY5JRCDw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/helper-validator-identifier": {
"version": "7.25.9",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.9.tgz",
"integrity": "sha512-Ed61U6XJc3CVRfkERJWDz4dJwKe7iLmmJsbOGu9wSloNSFttHV0I8g6UAgb7qnK5ly5bGLPd4oXZlxCdANBOWQ==",
"version": "7.22.20",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz",
"integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
@ -324,28 +369,88 @@
}
},
"node_modules/@babel/helpers": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.26.10.tgz",
"integrity": "sha512-UPYc3SauzZ3JGgj87GgZ89JVdC5dj0AoetR5Bw6wj4niittNyFh6+eOGonYvJ1ao6B8lEa3Q3klS7ADZ53bc5g==",
"version": "7.23.2",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.23.2.tgz",
"integrity": "sha512-lzchcp8SjTSVe/fPmLwtWVBFC7+Tbn8LGHDVfDp9JGxpAY5opSaEFgt8UQvrnECWOTdji2mOWMz1rOhkHscmGQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.26.9",
"@babel/types": "^7.26.10"
"@babel/template": "^7.22.15",
"@babel/traverse": "^7.23.2",
"@babel/types": "^7.23.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/parser": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.26.10.tgz",
"integrity": "sha512-6aQR2zGE/QFi8JpDLjUZEPYOs7+mhKXm86VaKFiLP35JQwQb6bwUE+XbvkH0EptsYhbNBSUGaUBLKqxH1xSgsA==",
"node_modules/@babel/highlight": {
"version": "7.22.20",
"resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.22.20.tgz",
"integrity": "sha512-dkdMCN3py0+ksCgYmGG8jKeGA/8Tk+gJwSYYlFGxG5lmhfKNoAy004YpLxpS1W2J8m/EK2Ew+yOs9pVRwO89mg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/types": "^7.26.10"
"@babel/helper-validator-identifier": "^7.22.20",
"chalk": "^2.4.2",
"js-tokens": "^4.0.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@babel/highlight/node_modules/ansi-styles": {
"version": "3.2.1",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz",
"integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==",
"dev": true,
"dependencies": {
"color-convert": "^1.9.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/highlight/node_modules/chalk": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
"integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==",
"dev": true,
"dependencies": {
"ansi-styles": "^3.2.1",
"escape-string-regexp": "^1.0.5",
"supports-color": "^5.3.0"
},
"engines": {
"node": ">=4"
}
},
"node_modules/@babel/highlight/node_modules/color-convert": {
"version": "1.9.3",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz",
"integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==",
"dev": true,
"dependencies": {
"color-name": "1.1.3"
}
},
"node_modules/@babel/highlight/node_modules/color-name": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==",
"dev": true
},
"node_modules/@babel/highlight/node_modules/escape-string-regexp": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz",
"integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==",
"dev": true,
"engines": {
"node": ">=0.8.0"
}
},
"node_modules/@babel/parser": {
"version": "7.23.3",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.3.tgz",
"integrity": "sha512-uVsWNvlVsIninV2prNz/3lHCb+5CJ+e+IUBfbjToAHODtfGYLfCFuY4AU7TskI+dAKk+njsPiBjq1gKTvZOBaw==",
"dev": true,
"bin": {
"parser": "bin/babel-parser.js"
},
@ -531,15 +636,14 @@
}
},
"node_modules/@babel/template": {
"version": "7.26.9",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.26.9.tgz",
"integrity": "sha512-qyRplbeIpNZhmzOysF/wFMuP9sctmh2cFzRAZOn1YapxBsE1i9bJIY586R/WBLfLcmcBlM8ROBiQURnnNy+zfA==",
"version": "7.22.15",
"resolved": "https://registry.npmjs.org/@babel/template/-/template-7.22.15.tgz",
"integrity": "sha512-QPErUVm4uyJa60rkI73qneDacvdvzxshT3kksGqlGWYdOTIUOwJ7RDUL8sGqslY1uXWSL6xMFKEXDS3ox2uF0w==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.26.2",
"@babel/parser": "^7.26.9",
"@babel/types": "^7.26.9"
"@babel/code-frame": "^7.22.13",
"@babel/parser": "^7.22.15",
"@babel/types": "^7.22.15"
},
"engines": {
"node": ">=6.9.0"
@ -600,14 +704,14 @@
"dev": true
},
"node_modules/@babel/types": {
"version": "7.26.10",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.26.10.tgz",
"integrity": "sha512-emqcG3vHrpxUKTrxcblR36dcrcoRDvKmnL/dCL6ZsHaShW80qxCAcNhzQZrpeM765VzEos+xOi4s+r4IXzTwdQ==",
"version": "7.23.3",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.3.tgz",
"integrity": "sha512-OZnvoH2l8PK5eUvEcUyCt/sXgr/h+UWpVuBbOljwcrAgUl6lpchoQ++PHGyQy1AtYnVA6CEq3y5xeEI10brpXw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.25.9",
"@babel/helper-validator-identifier": "^7.25.9"
"@babel/helper-string-parser": "^7.22.5",
"@babel/helper-validator-identifier": "^7.22.20",
"to-fast-properties": "^2.0.0"
},
"engines": {
"node": ">=6.9.0"
@ -4668,8 +4772,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
"dev": true
},
"node_modules/js-yaml": {
"version": "3.14.1",
@ -5851,15 +5954,6 @@
}
]
},
"node_modules/qrcode.react": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/qrcode.react/-/qrcode.react-4.2.0.tgz",
"integrity": "sha512-QpgqWi8rD9DsS9EP3z7BT+5lY5SFhsqGjpgW5DY/i3mK4M9DTBNz3ErMi8BWYEfI3L0d8GIbGmcdFAS1uIRGjA==",
"license": "ISC",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/qs": {
"version": "6.13.0",
"resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz",
@ -5904,16 +5998,6 @@
"node": ">= 0.8"
}
},
"node_modules/react": {
"version": "19.0.0",
"resolved": "https://registry.npmjs.org/react/-/react-19.0.0.tgz",
"integrity": "sha512-V8AVnmPIICiWpGfm6GLzCR/W5FXLchHop40W4nXBmdlEceh16rCN8O8LNWm5bh5XUX91fh7KpA+W0TgMKmgTpQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-is": {
"version": "18.2.0",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-18.2.0.tgz",
@ -6599,6 +6683,15 @@
"integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==",
"dev": true
},
"node_modules/to-fast-properties": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz",
"integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==",
"dev": true,
"engines": {
"node": ">=4"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",

View file

@ -28,7 +28,6 @@
"passport-oauth2": "^1.8.0",
"passport-openidconnect": "^0.1.2",
"patch-package": "^8.0.0",
"qrcode.react": "^4.2.0",
"socket.io": "^4.7.2",
"socket.io-client": "^4.7.2"
},
@ -43,7 +42,7 @@
"supertest": "^6.3.4"
},
"engines": {
"node": "22.x"
"node": "20.x"
},
"jest": {
"testEnvironment": "node",

View file

@ -12,8 +12,5 @@ const upload = multer({ storage: storage });
router.post("/upload", jwt.authenticate, upload.single('image'), asyncHandler(images.upload));
router.get("/get/:id", asyncHandler(images.get));
router.get("/getImages", asyncHandler(images.getImages));
router.get("/getUserImages", jwt.authenticate, asyncHandler(images.getUserImages));
router.delete("/delete", jwt.authenticate, asyncHandler(images.delete));
module.exports = router;