Compare commits

...

33 commits

Author SHA1 Message Date
Edwin S Lopez
b02da32083
Merge 81bedf0672 into ee7a7a0544 2025-03-21 14:03:32 -04:00
Christopher (Cris) Fuhrman
ee7a7a0544
Update README.md
Some checks failed
CI/CD Pipeline for Backend / build_and_push_backend (push) Failing after 20s
CI/CD Pipeline for Nginx Router / build_and_push_nginx (push) Failing after 18s
CI/CD Pipeline for Frontend / build_and_push_frontend (push) Failing after 19s
Tests / lint-and-tests (client) (push) Failing after 1m10s
Tests / lint-and-tests (server) (push) Failing after 57s
fix link
2025-03-21 13:15:20 -04:00
Christopher (Cris) Fuhrman
8c57a8759f
Merge pull request #302 from ets-cfuhrman-pfe/Multilingual-readme
Update readme (bilingual)
2025-03-21 13:11:55 -04:00
C. Fuhrman
22a2754e31 Update readme (bilingual) 2025-03-21 11:58:44 -04:00
C. Fuhrman
3d9015febd Fix bug with multiple choice (radio vs checkbox)
Some checks failed
CI/CD Pipeline for Backend / build_and_push_backend (push) Failing after 18s
CI/CD Pipeline for Nginx Router / build_and_push_nginx (push) Failing after 17s
CI/CD Pipeline for Frontend / build_and_push_frontend (push) Failing after 18s
Tests / lint-and-tests (client) (push) Failing after 57s
Tests / lint-and-tests (server) (push) Failing after 1m2s
Snapshot update
2025-03-21 11:25:06 -04:00
C. Fuhrman
fc15d2c3bd refactor
Some checks failed
CI/CD Pipeline for Backend / build_and_push_backend (push) Failing after 18s
CI/CD Pipeline for Nginx Router / build_and_push_nginx (push) Failing after 17s
CI/CD Pipeline for Frontend / build_and_push_frontend (push) Failing after 18s
Tests / lint-and-tests (client) (push) Failing after 1m3s
Tests / lint-and-tests (server) (push) Failing after 1m1s
2025-03-21 11:08:21 -04:00
C. Fuhrman
13136b9e91 fix bugs that showed in dev 2025-03-21 11:05:16 -04:00
Eddi3_As
81bedf0672 Fix - tests 2025-03-20 23:19:54 -04:00
Eddi3_As
c50cd3e6e7 FIX
- Changement de table en gallery
- Ajout option de résolution
- Ajout warning
- Intégration de upload
- Ajout de snackbar
2025-03-20 21:11:46 -04:00
Eddi3_As
4e0d5d778d fixed server tests 2025-03-14 01:56:53 -04:00
Eddi3_As
d9480e2d14 fichier manquant 2025-03-14 00:54:14 -04:00
Eddi3_As
ab9636c8db test issues 2025-03-14 00:53:58 -04:00
Eddi3_As
e2376dd8c3 FIX undefined IMG_URL 2025-03-14 00:45:59 -04:00
Eddi3_As
92699f9a83 FIX objectID et mauvaise collection 2025-03-13 22:44:43 -04:00
Eddi3_As
1c16e06319 FIX - erreur infinite loading 2025-03-13 21:48:15 -04:00
Eddi3_As
b7a7962435 FIX admin param error 2025-03-13 18:06:24 -04:00
Eddi3_As
b7ec35c0c9 FIX - ajustement delete image et tests 2025-03-13 18:02:26 -04:00
Eddi3_As
f4bcfd27b9 ajout test getuserimages 2025-03-11 23:15:59 -04:00
Eddi3_As
9ff2882761 updated path 2025-03-11 19:53:34 -04:00
Eddi3_As
de5f8fad6c FIX
- url DEV et PROD
- images par prof
2025-03-11 19:50:28 -04:00
Eddi3_As
1512f320c8 tests fix 2025-03-10 19:03:58 -04:00
Eddi3_As
78f6993547 remove user-id 2025-03-10 18:49:29 -04:00
Eddi3_As
f6afb1f7ed Merge remote-tracking branch 'merge/main' into feature/gestion-images 2025-03-10 18:41:01 -04:00
Eddi3_As
1b321c74f9 update gitignore 2025-03-10 17:54:50 -04:00
Eddi3_As
add7d9954b update package,json 2025-03-10 17:52:51 -04:00
Eddi3_As
f055a47305 ajout test imagegallery 2025-03-06 20:33:57 -05:00
Eddi3_As
f8357883e6 FIX image render 2025-03-04 19:59:05 -05:00
Eddi3_As
0f87bab5ff FIX dialog front et perf pagination 2025-03-04 19:49:18 -05:00
Eddi3_As
c9d65c0082 ajout front images gallery 2025-03-02 20:52:08 -05:00
Eddi3_As
16d594c61d FIX erreur encoding 2025-02-25 17:38:23 -05:00
Eddi3_As
e7c3c84b80 UC38 - gestion images backend fin 2025-02-24 20:26:30 -05:00
Eddi3_As
ee5e096984 added comments 2025-02-22 18:08:38 -05:00
Eddi3_As
c6c830ef74 init gestion img 2025-02-22 17:56:53 -05:00
28 changed files with 1202 additions and 155 deletions

1
.gitignore vendored
View file

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

30
README.fr-ca.md Normal file
View file

@ -0,0 +1,30 @@
[![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,24 +2,26 @@
[![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)
# EvalueTonSavoir
[![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 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.
# EvalueTonSavoir
## Fonctionnalités clés
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.
* 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.
## Key Features
* **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.
## 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)
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.
## Liens utiles
## Useful Links
* [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)
* [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)
* [Documentation (Wiki)](https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir/wiki)
## License

View file

@ -43,6 +43,7 @@
"@babel/preset-typescript": "^7.23.3",
"@eslint/js": "^9.21.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/user-event": "^14.6.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.13",
@ -4436,6 +4437,20 @@
}
}
},
"node_modules/@testing-library/user-event": {
"version": "14.6.1",
"resolved": "https://registry.npmjs.org/@testing-library/user-event/-/user-event-14.6.1.tgz",
"integrity": "sha512-vq7fv0rnt+QTXgPxr5Hjc210p6YKq2kmdziLgnsZGgLJ9e6VAShx1pACLuRjd/AS/sr7phAR58OIIpf0LlmQNw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12",
"npm": ">=6"
},
"peerDependencies": {
"@testing-library/dom": ">=7.21.4"
}
},
"node_modules/@tootallnate/once": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/@tootallnate/once/-/once-2.0.0.tgz",

View file

@ -47,6 +47,7 @@
"@babel/preset-typescript": "^7.23.3",
"@eslint/js": "^9.21.0",
"@testing-library/dom": "^10.4.0",
"@testing-library/user-event": "^14.6.1",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.2.0",
"@types/jest": "^29.5.13",

View file

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

View file

@ -0,0 +1,17 @@
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

@ -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: true, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 1 }
{ formattedText: { format: 'plain', text: 'Choice 2' }, isCorrect: false, formattedFeedback: { format: 'plain' , text: 'Correct!'}, weight: 0 }
],
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="correct-icon" style="
<svg data-testid="incorrect-icon" style="
vertical-align: text-bottom;
display: inline-block;
margin-left: 0.1rem;
margin-right: 0.2rem;
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>
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>
<span class="feedback-container">Correct!</span>
</input>
</div>

View file

@ -0,0 +1,55 @@
import React, { act } from "react";
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 "@testing-library/jest-dom";
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(() => {
Object.assign(navigator, {
clipboard: {
writeText: jest.fn(),
},
});
});
describe("ImageGallery", () => {
beforeEach(() => {
(ApiService.getUserImages as jest.Mock).mockResolvedValue({ images: mockImages, total: 3 });
(ApiService.deleteImage as jest.Mock).mockResolvedValue(true);
(ApiService.uploadImage as jest.Mock).mockResolvedValue('mockImageUrl');
render(<ImageGallery />);
});
it("should render images correctly", async () => {
await act(async () => {
await screen.findByText("Gallery");
});
expect(screen.getByAltText("Image image1.jpg")).toBeInTheDocument();
expect(screen.getByAltText("Image image2.jpg")).toBeInTheDocument();
});
it("should handle copy action", async () => {
const handleCopyMock = jest.fn();
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();
});
});

View file

@ -12,14 +12,23 @@ const questions = parse(
{
=Choice 1
~Choice 2
}`) as MultipleChoiceQuestion[];
}
::Sample Question 2:: Question stem
{
=Choice 1
=Choice 2
~Choice 3
}
`) as MultipleChoiceQuestion[];
const question = questions[0];
const questionWithOneCorrectChoice = questions[0];
const questionWithMultipleCorrectChoices = questions[1];
describe('MultipleChoiceQuestionDisplay', () => {
const mockHandleOnSubmitAnswer = jest.fn();
const TestWrapper = ({ showAnswer }: { showAnswer: boolean }) => {
const TestWrapper = ({ showAnswer, question }: { showAnswer: boolean; question: MultipleChoiceQuestion }) => {
const [showAnswerState, setShowAnswerState] = useState(showAnswer);
const handleOnSubmitAnswer = (answer: AnswerType) => {
@ -38,20 +47,41 @@ describe('MultipleChoiceQuestionDisplay', () => {
);
};
const choices = question.choices;
const twoChoices = questionWithOneCorrectChoice.choices;
const threeChoices = questionWithMultipleCorrectChoices.choices;
beforeEach(() => {
render(<TestWrapper showAnswer={false} />);
});
test('renders a question (that has only one correct choice) and its choices', () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
test('renders the question and choices', () => {
expect(screen.getByText(question.formattedStem.text)).toBeInTheDocument();
choices.forEach((choice) => {
expect(screen.getByText(questionWithOneCorrectChoice.formattedStem.text)).toBeInTheDocument();
twoChoices.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);
@ -61,6 +91,7 @@ describe('MultipleChoiceQuestionDisplay', () => {
});
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(() => {
@ -75,12 +106,43 @@ describe('MultipleChoiceQuestionDisplay', () => {
mockHandleOnSubmitAnswer.mockClear();
});
test('submits multiple selected answers', () => {
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);
@ -88,19 +150,20 @@ describe('MultipleChoiceQuestionDisplay', () => {
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();
});
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');
@ -116,16 +179,17 @@ describe('MultipleChoiceQuestionDisplay', () => {
});
// Wait for the DOM to update
const correctAnswer = screen.getByText("Choice 1").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).toContain('✅');
const correctAnswer = screen.getByText("Choice 1").closest('button');
expect(correctAnswer).toBeInTheDocument();
expect(correctAnswer?.textContent).toContain('✅');
const wrongAnswer1 = screen.getByText("Choice 2").closest('button');
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).toContain('❌');
const wrongAnswer1 = screen.getByText("Choice 2").closest('button');
expect(wrongAnswer1).toBeInTheDocument();
expect(wrongAnswer1?.textContent).toContain('❌');
});
it('should not show ✅ or ❌ when repondre button is not clicked', async () => {
it('should not show ✅ or ❌ when Répondre button is not clicked', async () => {
render(<TestWrapper showAnswer={false} question={questionWithOneCorrectChoice} />);
const choiceButton = screen.getByText('Choice 1').closest('button');
if (!choiceButton) throw new Error('Choice button not found');
@ -145,5 +209,5 @@ describe('MultipleChoiceQuestionDisplay', () => {
expect(wrongAnswer1?.textContent).not.toContain('❌');
});
});
});

View file

@ -30,6 +30,12 @@ describe('checkIfIsCorrect', () => {
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);

View file

@ -120,27 +120,29 @@ describe('StudentModeQuiz', () => {
expect(screen.getByText('Répondre')).toBeInTheDocument();
});
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'));
});
// 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'));
});
// // 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 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();
// });
// 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

@ -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 isMultipleAnswer = choices.filter(({ isCorrect }) => isCorrect === true).length === 0;
const hasManyCorrectChoices = choices.filter(({ isCorrect }) => isCorrect === true).length > 1;
const prompt = `<span style="${ParagraphStyle(state.theme)}">Choisir une réponse${
isMultipleAnswer ? ` ou plusieurs` : ``
hasManyCorrectChoices ? ` 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 = isMultipleAnswer ? isPositiveWeight : isCorrect;
const isCorrectOption = hasManyCorrectChoices ? isPositiveWeight || isCorrect : isCorrect;
return `
<div class='multiple-choice-answers-container'>
<input class="gift-input" type="${
isMultipleAnswer ? 'checkbox' : 'radio'
hasManyCorrectChoices ? 'checkbox' : 'radio'
}" id="${inputId}" name="${id}">
${AnswerWeight({ weight: weight })}
<label style="${CustomLabel} ${ParagraphStyle(state.theme)}" for="${inputId}">

View file

@ -0,0 +1,282 @@
import React, { useState, useEffect } from "react";
import {
Box,
CircularProgress,
Button,
IconButton,
Card,
CardContent,
Dialog,
DialogContent,
DialogActions,
DialogTitle,
DialogContentText,
Tabs,
Tab,
TextField, Snackbar,
Alert
} from "@mui/material";
import DeleteIcon from "@mui/icons-material/Delete";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import CloseIcon from "@mui/icons-material/Close";
import { ImageType } from "../../Types/ImageType";
import ApiService from "../../services/ApiService";
import { Upload } from "@mui/icons-material";
interface ImagesProps {
handleCopy?: (id: string) => void;
}
const ImageGallery: React.FC<ImagesProps> = ({ handleCopy }) => {
const [images, setImages] = useState<ImageType[]>([]);
const [totalImg, setTotalImg] = useState(0);
const [imgPage, setImgPage] = useState(1);
const [imgLimit] = useState(6);
const [loading, setLoading] = useState(false);
const [selectedImage, setSelectedImage] = useState<ImageType | null>(null);
const [openDeleteDialog, setOpenDeleteDialog] = useState(false);
const [imageToDelete, setImageToDelete] = useState<ImageType | null>(null);
const [tabValue, setTabValue] = useState(0);
const [importedImage, setImportedImage] = useState<File | null>(null);
const [preview, setPreview] = useState<string | null>(null);
const [snackbarOpen, setSnackbarOpen] = useState(false);
const [snackbarMessage, setSnackbarMessage] = useState("");
const [snackbarSeverity, setSnackbarSeverity] = useState<"success" | "error">("success");
const fetchImages = async () => {
setLoading(true);
const data = await ApiService.getUserImages(imgPage, imgLimit);
setImages(data.images);
setTotalImg(data.total);
setLoading(false);
};
useEffect(() => {
fetchImages();
}, [imgPage]);
const handleDelete = async () => {
if (imageToDelete) {
setLoading(true);
const isDeleted = await ApiService.deleteImage(imageToDelete.id);
setLoading(false);
if (isDeleted) {
setImages(images.filter((image) => image.id !== imageToDelete.id));
setSnackbarMessage("Image supprimée avec succès !");
setSnackbarSeverity("success");
} else {
setSnackbarMessage("Erreur lors de la suppression de l'image. Veuillez réessayer.");
setSnackbarSeverity("error");
}
setSnackbarOpen(true);
setSelectedImage(null);
setImageToDelete(null);
setOpenDeleteDialog(false);
}
};
const defaultHandleCopy = (id: string) => {
if (navigator.clipboard) {
navigator.clipboard.writeText(id);
}
};
const handleCopyFunction = handleCopy || defaultHandleCopy;
const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
const file = event.target.files ? event.target.files[0] : null;
setImportedImage(file);
if (file) {
const objectUrl = URL.createObjectURL(file);
setPreview(objectUrl);
}
};
const handleSaveImage = async () => {
try {
if (!importedImage) {
setSnackbarMessage("Veuillez d'abord choisir une image à téléverser.");
setSnackbarSeverity("error");
setSnackbarOpen(true);
return;
}
const imageUrl = await ApiService.uploadImage(importedImage);
if (imageUrl.includes("ERROR")) {
setSnackbarMessage("Une erreur est survenue. Veuillez réessayer plus tard.");
setSnackbarSeverity("error");
setSnackbarOpen(true);
return;
}
fetchImages();
setSnackbarMessage("Téléversée avec succès !");
setSnackbarSeverity("success");
setSnackbarOpen(true);
// Reset the input field and preview after successful upload
setImportedImage(null);
setPreview(null);
} catch (error) {
setSnackbarMessage(`Une erreur est survenue.\n${error}\nVeuillez réessayer plus tard.`);
setSnackbarSeverity("error");
setSnackbarOpen(true);
}
};
return (
<Box p={3}>
<Tabs value={tabValue} onChange={(_, newValue) => setTabValue(newValue)}>
<Tab label="Gallery" />
<Tab label="Import" />
</Tabs>
{tabValue === 0 && (
<>
{loading ? (
<Box display="flex" justifyContent="center" alignItems="center" height={200}>
<CircularProgress />
</Box>
) : (
<>
<Box display="grid" gridTemplateColumns="repeat(3, 1fr)" gridTemplateRows="repeat(2, 1fr)" gap={2} maxWidth="900px" margin="auto">
{images.map((obj) => (
<Card key={obj.id} sx={{ cursor: "pointer", display: "flex", flexDirection: "column", alignItems: "center" }} onClick={() => setSelectedImage(obj)}>
<CardContent sx={{ p: 0 }}>
<img
src={`data:${obj.mime_type};base64,${obj.file_content}`}
alt={`Image ${obj.file_name}`}
style={{ width: "100%", height: 250, objectFit: "cover", borderRadius: 8 }}
/>
</CardContent>
<Box display="flex" justifyContent="center" mt={1}>
<IconButton onClick={(e) => {
e.stopPropagation();
handleCopyFunction(obj.id);
}}
color="primary"
data-testid={`gallery-tab-copy-${obj.id}`} >
<ContentCopyIcon sx={{ fontSize: 18 }} />
</IconButton>
<IconButton
onClick={(e) => {
e.stopPropagation();
setImageToDelete(obj);
setOpenDeleteDialog(true);
}}
color="error"
data-testid={`gallery-tab-delete-${obj.id}`} >
<DeleteIcon sx={{ fontSize: 18 }} />
</IconButton>
</Box>
</Card>
))}
</Box>
<Box display="flex" justifyContent="center" mt={2}>
<Button onClick={() => setImgPage((prev) => Math.max(prev - 1, 1))} disabled={imgPage === 1} color="primary">
Précédent
</Button>
<Button onClick={() => setImgPage((prev) => (prev * imgLimit < totalImg ? prev + 1 : prev))} disabled={imgPage * imgLimit >= totalImg} color="primary">
Suivant
</Button>
</Box>
</>
)}
</>
)}
{tabValue === 1 && (
<Box display="flex" flexDirection="column" alignItems="center" width="100%" mt={3}>
{/* Image Preview at the top */}
{preview && (
<Box
mt={2}
mb={2}
sx={{
width: "100%",
maxWidth: 600,
textAlign: "center",
display: "flex",
justifyContent: "center",
alignItems: "center",
}}
>
<img
src={preview}
alt="Preview"
style={{
width: "100%",
height: "auto",
borderRadius: 8,
maxHeight: "600px",
}}
/>
</Box>
)}
<Box display="flex" flexDirection="row" alignItems="center" width="100%" maxWidth={400}>
<TextField
type="file"
onChange={handleImageUpload}
slotProps={{
htmlInput: {
accept: "image/*",
},
}}
sx={{ flexGrow: 1 }}
/>
<Button
variant="outlined"
aria-label="Téléverser"
onClick={() => { handleSaveImage() }}
sx={{ ml: 2, height: "100%" }}
>
Téléverser <Upload sx={{ ml: 1 }} />
</Button>
</Box>
</Box>
)}
<Dialog open={!!selectedImage} onClose={() => setSelectedImage(null)} maxWidth="md">
<IconButton color="primary" onClick={() => setSelectedImage(null)} sx={{ position: "absolute", right: 8, top: 8, zIndex: 1 }}>
<CloseIcon />
</IconButton>
<DialogContent>
{selectedImage && (
<img
src={`data:${selectedImage.mime_type};base64,${selectedImage.file_content}`}
alt="Enlarged view"
style={{ width: "100%", height: "auto", borderRadius: 8, maxHeight: "500px" }}
/>
)}
</DialogContent>
</Dialog>
{/* Delete Confirmation Dialog */}
<Dialog open={openDeleteDialog} onClose={() => setOpenDeleteDialog(false)}>
<DialogTitle>Supprimer</DialogTitle>
<DialogContent>
<DialogContentText>Voulez-vous supprimer cette image?</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => setOpenDeleteDialog(false)} color="primary">
Annuler
</Button>
<Button onClick={handleDelete} color="error">
Delete
</Button>
</DialogActions>
</Dialog>
<Snackbar open={snackbarOpen} autoHideDuration={4000} onClose={() => setSnackbarOpen(false)}>
<Alert onClose={() => setSnackbarOpen(false)} severity={snackbarSeverity} sx={{ width: "100%" }}>
{snackbarMessage}
</Alert>
</Snackbar>
</Box>
);
};
export default ImageGallery;

View file

@ -0,0 +1,54 @@
import React, { useState } from "react";
import {
Button,
IconButton,
Dialog,
DialogContent,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import ImageGallery from "../ImageGallery";
import { ImageSearch } from "@mui/icons-material";
interface ImageGalleryModalProps {
handleCopy?: (id: string) => void;
}
const ImageGalleryModal: React.FC<ImageGalleryModalProps> = ({ handleCopy }) => {
const [open, setOpen] = useState<boolean>(false);
const handleOpen = () => setOpen(true);
const handleClose = () => setOpen(false);
return (
<>
<Button
variant="outlined"
aria-label='Téléverser'
onClick={() => handleOpen()}>
Images <ImageSearch />
</Button>
<Dialog open={open} onClose={handleClose} maxWidth="md" fullWidth>
<DialogContent sx={{ display: "flex", flexDirection: "column", alignItems: "center", py: 3 }}>
<IconButton
onClick={handleClose}
color="primary"
sx={{
position: "absolute",
right: 8,
top: 8,
zIndex: 1,
}}
>
<CloseIcon />
</IconButton>
<ImageGallery handleCopy={handleCopy}/>
</DialogContent>
</Dialog>
</>
);
};
export default ImageGalleryModal;

View file

@ -15,7 +15,14 @@ interface Props {
const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
const { question, showAnswer, handleOnSubmitAnswer, passedAnswer } = props;
const [answer, setAnswer] = useState<AnswerType>(passedAnswer || []);
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
const [answer, setAnswer] = useState<AnswerType>(() => {
if (passedAnswer && passedAnswer.length > 0) {
return passedAnswer;
}
return [];
});
let disableButton = false;
if (handleOnSubmitAnswer === undefined) {
@ -23,19 +30,31 @@ const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
}
useEffect(() => {
console.log('MultipleChoiceQuestionDisplay: passedAnswer', JSON.stringify(passedAnswer));
if (passedAnswer !== undefined) {
setAnswer(passedAnswer);
} else {
setAnswer([]);
}
}, [passedAnswer]);
}, [passedAnswer, question.id]);
const handleOnClickAnswer = (choice: string) => {
setAnswer((prevAnswer) => {
if (prevAnswer.includes(choice)) {
// Remove the choice if it's already selected
return prevAnswer.filter((selected) => selected !== choice);
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 {
// Add the choice if it's not already selected
return [...prevAnswer, choice];
// 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];
}
}
});
};
@ -50,6 +69,7 @@ const MultipleChoiceQuestionDisplay: React.FC<Props> = (props) => {
</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' : '';
return (
<div key={choice.formattedText.text + i} className="choice-container">

View file

@ -17,6 +17,15 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
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) {
disableButton = true;
@ -31,15 +40,6 @@ const TrueFalseQuestionDisplay: React.FC<Props> = (props) => {
}
}, [passedAnswer, question.id]);
const [answer, setAnswer] = useState<boolean | undefined>(() => {
if (passedAnswer && (passedAnswer[0] === true || passedAnswer[0] === false)) {
return passedAnswer[0];
}
return undefined;
});
const handleOnClickAnswer = (choice: boolean) => {
setAnswer(choice);
};

View file

@ -2,6 +2,7 @@
const ENV_VARIABLES = {
MODE: process.env.MODE || "production",
VITE_BACKEND_URL: process.env.VITE_BACKEND_URL || "",
IMG_URL: process.env.MODE == "development" ? process.env.VITE_BACKEND_URL : process.env.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}`:''}` : ''
};

View file

@ -1,5 +1,5 @@
// EditorQuiz.tsx
import React, { useState, useEffect, useRef, CSSProperties } from 'react';
import React, { useState, useEffect, CSSProperties } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { FolderType } from '../../../Types/FolderType';
@ -11,12 +11,13 @@ import GIFTTemplatePreview from 'src/components/GiftTemplate/GIFTTemplatePreview
import { QuizType } from '../../../Types/QuizType';
import './editorQuiz.css';
import { Button, TextField, NativeSelect, Divider, Dialog, DialogTitle, DialogActions, DialogContent } from '@mui/material';
import { Button, TextField, NativeSelect, Divider } 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 { Upload } from '@mui/icons-material';
import { ENV_VARIABLES } from '../../../constants';
interface EditQuizParams {
id: string;
@ -38,8 +39,6 @@ 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 = () => {
@ -166,44 +165,16 @@ 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.IMG_URL}/api/image/get/${id}`;
navigator.clipboard.writeText(id);
setImageLinks(prevLinks => [...prevLinks, escLink]);
}
return (
<div className='quizEditor'>
@ -258,37 +229,11 @@ const QuizForm: React.FC = () => {
onEditorChange={handleUpdatePreview} />
<div className='images'>
<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 style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<h4>Mes images :</h4>
<ImageGalleryModal handleCopy={handleCopyImage} />
</div>
<h4>Mes images :</h4>
<div>
<div>
<div style={{ display: "inline" }}>(Voir section </div>
@ -302,7 +247,7 @@ const QuizForm: React.FC = () => {
</div>
<ul>
{imageLinks.map((link, index) => {
const imgTag = `![alt_text](${escapeForGIFT(link)} "texte de l'infobulle")`;
const imgTag = `[markdown]![alt_text](${escapeForGIFT(link)} "texte de l'infobulle") {T}`;
return (
<li key={index}>
<code

View file

@ -55,14 +55,15 @@ export function checkIfIsCorrect(
(!question.isTrue && simpleAnswerText == 'false')
);
} else if (question.type === 'MC') {
const correctAnswers = question.choices.filter((choice) => choice.isCorrect
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 (correctAnswers.length === 0) {
if (correctChoices.length === 0) {
return false;
}
return correctAnswers.every(
// 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') {

View file

@ -3,6 +3,7 @@ import { jwtDecode } from 'jwt-decode';
import { ENV_VARIABLES } from '../constants';
import { FolderType } from 'src/Types/FolderType';
import { ImagesResponse, ImagesParams } from '../Types/Images';
import { QuizType } from 'src/Types/QuizType';
import { RoomType } from 'src/Types/RoomType';
@ -142,6 +143,22 @@ 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`);
@ -1167,7 +1184,99 @@ public async login(email: string, password: string): Promise<any> {
return `ERROR : Une erreur inattendue s'est produite.`
}
}
// NOTE : Get Image pas necessaire
public async getImages(page: number, limit: number): Promise<ImagesResponse> {
try {
const url: string = this.constructRequestUrl(`/image/getImages`);
const headers = this.constructRequestHeaders();
let params : ImagesParams = { page: page, limit: limit };
const result: AxiosResponse = await axios.get(url, { params: params, headers: headers });
if (result.status !== 200) {
throw new Error(`L'affichage des images 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 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> {
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.`);
}
}
}

View file

@ -7,6 +7,8 @@ services:
context: ./client
dockerfile: Dockerfile
container_name: frontend
environment:
VITE_IMG_URL: http://localhost
ports:
- "5173:5173"
restart: always
@ -54,7 +56,7 @@ services:
image: mongo
container_name: mongo
ports:
- "27017:27017"
- "27019:27017"
tty: true
volumes:
- mongodb_data:/data/db

View file

@ -10,6 +10,7 @@ services:
- VITE_BACKEND_URL=
# Define empty VITE_BACKEND_SOCKET_URL so it will default to window.location.host
- VITE_BACKEND_SOCKET_URL=
- VITE_IMG_URL=https://evalsa.etsmtl.ca
ports:
- "5173:5173"
restart: always

View file

@ -7,6 +7,9 @@
// 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", () => {
@ -64,3 +67,289 @@ 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,6 +50,58 @@ 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,6 +42,84 @@ 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;

View file

@ -12,5 +12,8 @@ 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", asyncHandler(images.getUserImages));
router.delete("/delete", asyncHandler(images.delete));
module.exports = router;