From 51ae004c5b725255d1b62831a461470faebfd800 Mon Sep 17 00:00:00 2001 From: Philippe <83185129+phil3838@users.noreply.github.com> Date: Mon, 24 Mar 2025 15:25:13 -0400 Subject: [PATCH] share by email function removed --- .../ShareQuizModal/ShareQuizModal.test.tsx | 74 --------- .../services/ShareQuizService.test.tsx | 83 ---------- .../ShareQuizModal/ShareQuizModal.tsx | 71 --------- .../src/pages/Teacher/Dashboard/Dashboard.tsx | 145 ++++++++++-------- client/src/services/ApiService.tsx | 30 ---- 5 files changed, 81 insertions(+), 322 deletions(-) delete mode 100644 client/src/__tests__/components/ShareQuizModal/ShareQuizModal.test.tsx delete mode 100644 client/src/__tests__/services/ShareQuizService.test.tsx delete mode 100644 client/src/components/ShareQuizModal/ShareQuizModal.tsx diff --git a/client/src/__tests__/components/ShareQuizModal/ShareQuizModal.test.tsx b/client/src/__tests__/components/ShareQuizModal/ShareQuizModal.test.tsx deleted file mode 100644 index 2a878a5..0000000 --- a/client/src/__tests__/components/ShareQuizModal/ShareQuizModal.test.tsx +++ /dev/null @@ -1,74 +0,0 @@ -import React from 'react'; -import { render, fireEvent, screen, waitFor } from '@testing-library/react'; -import '@testing-library/jest-dom'; -import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal'; -import { QuizType } from '../../../Types/QuizType'; -import ApiService from '../../../services/ApiService'; - -jest.mock('../../../services/ApiService'); - -Object.assign(navigator, { - clipboard: { - writeText: jest.fn().mockResolvedValue(undefined), - }, -}); - -window.alert = jest.fn(); - -const mockQuiz: QuizType = { - _id: '1', - title: 'Sample Quiz', - content: ['::Question 1:: What is 2+2? {=4 ~3 ~5}'], - folderId: 'folder1', - folderName: 'Sample Folder', - userId: 'user1', - created_at: new Date(), - updated_at: new Date(), -}; - -describe('ShareQuizModal', () => { - - - beforeEach(() => { - jest.clearAllMocks(); - }); - - it('should call ApiService.ShareQuiz when sharing by email', async () => { - render(); - - const shareButton = screen.getByRole('button', { name: /partager quiz/i }); - fireEvent.click(shareButton); - - const emailButton = screen.getByRole('button', { name: /partager par email/i }); - fireEvent.click(emailButton); - - const email = 'test@example.com'; - window.prompt = jest.fn().mockReturnValue(email); - - await fireEvent.click(emailButton); - - expect(ApiService.ShareQuiz).toHaveBeenCalledWith(mockQuiz._id, email); - }); - - it('copies the correct URL to the clipboard when sharing by URL', async () => { - render(); - - // Open the modal - const shareButton = screen.getByRole('button', { name: /partager quiz/i }); - fireEvent.click(shareButton); - - // Click the "Share by URL" button - const shareByUrlButton = screen.getByRole('button', { name: /partager par url/i }); - fireEvent.click(shareByUrlButton); - - // Check if the correct URL was copied - const expectedUrl = `${window.location.origin}/teacher/share/${mockQuiz._id}`; - expect(navigator.clipboard.writeText).toHaveBeenCalledWith(expectedUrl); - - // Check if the alert is shown - await waitFor(() => { - expect(window.alert).toHaveBeenCalledWith('URL a été copiée avec succès.'); - }); - }); - -}); \ No newline at end of file diff --git a/client/src/__tests__/services/ShareQuizService.test.tsx b/client/src/__tests__/services/ShareQuizService.test.tsx deleted file mode 100644 index c1e473e..0000000 --- a/client/src/__tests__/services/ShareQuizService.test.tsx +++ /dev/null @@ -1,83 +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; - -describe('ApiService', () => { - describe('shareQuiz', () => { - it('should call the API to share a quiz and return true on success', async () => { - const quizId = '123'; - const email = 'test@example.com'; - const response = { status: 200 }; - mockedAxios.put.mockResolvedValue(response); - - const result = await ApiService.ShareQuiz(quizId, email); - - expect(mockedAxios.put).toHaveBeenCalledWith( - `${ENV_VARIABLES.VITE_BACKEND_URL}/api/quiz/Share`, - { quizId, email }, - { headers: expect.any(Object) } - ); - expect(result).toBe(true); - }); - - it('should return an error message if the API call fails', async () => { - const quizId = '123'; - const email = 'test@example.com'; - const errorMessage = 'An unexpected error occurred.'; - mockedAxios.put.mockRejectedValue({ response: { data: { error: errorMessage } } }); - - const result = await ApiService.ShareQuiz(quizId, email); - - expect(result).toBe(errorMessage); - }); - - it('should return a generic error message if an unexpected error occurs', async () => { - const quizId = '123'; - const email = 'test@example.com'; - mockedAxios.put.mockRejectedValue(new Error('Unexpected error')); - - const result = await ApiService.ShareQuiz(quizId, email); - - expect(result).toBe('An unexpected error occurred.'); - }); - }); - - 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.'); - }); - }); -}); \ No newline at end of file diff --git a/client/src/components/ShareQuizModal/ShareQuizModal.tsx b/client/src/components/ShareQuizModal/ShareQuizModal.tsx deleted file mode 100644 index 336aadb..0000000 --- a/client/src/components/ShareQuizModal/ShareQuizModal.tsx +++ /dev/null @@ -1,71 +0,0 @@ -import React, { useState } from 'react'; -import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton } from '@mui/material'; -import { Share } from '@mui/icons-material'; -import { QuizType } from '../../Types/QuizType'; -import ApiService from '../../services/ApiService'; - -interface ShareQuizModalProps { - quiz: QuizType; -} - -const ShareQuizModal: React.FC = ({ quiz }) => { - const [open, setOpen] = useState(false); - - const handleOpenModal = () => setOpen(true); - - const handleCloseModal = () => setOpen(false); - - const handleShareByEmail = async () => { - const email = prompt(`Veuillez saisir l'email de la personne avec qui vous souhaitez partager ce quiz`, ""); - - if (email) { - try { - 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); - } - } - - handleCloseModal(); - }; - - const handleShareByUrl = () => { - const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`; - navigator.clipboard.writeText(quizUrl) - .then(() => { - window.alert('URL a été copiée avec succès.'); - }) - .catch(() => { - window.alert('Une erreur est survenue lors de la copie de l\'URL.'); - }); - - handleCloseModal(); - }; - - return ( - <> - - - - - - - - Choisissez une méthode de partage - - - - - - - ); -}; - -export default ShareQuizModal; \ No newline at end of file diff --git a/client/src/pages/Teacher/Dashboard/Dashboard.tsx b/client/src/pages/Teacher/Dashboard/Dashboard.tsx index d319515..6e3bd94 100644 --- a/client/src/pages/Teacher/Dashboard/Dashboard.tsx +++ b/client/src/pages/Teacher/Dashboard/Dashboard.tsx @@ -28,7 +28,7 @@ import { NativeSelect, CardContent, styled, - DialogContentText + DialogContentText, } from '@mui/material'; import { Search, @@ -39,8 +39,8 @@ import { FolderCopy, ContentCopy, Edit, + Share, } from '@mui/icons-material'; -import ShareQuizModal from 'src/components/ShareQuizModal/ShareQuizModal'; // Create a custom-styled Card component const CustomCard = styled(Card)({ @@ -104,7 +104,7 @@ const Dashboard: React.FC = () => { fetchData(); }, []); - + useEffect(() => { if (rooms.length > 0 && !selectedRoom) { selectRoom(rooms[rooms.length - 1]); @@ -120,41 +120,41 @@ const Dashboard: React.FC = () => { } }; - // Créer une salle - const createRoom = async (title: string) => { - // Créer la salle et récupérer l'objet complet - const newRoom = await ApiService.createRoom(title); - - // Mettre à jour la liste des salles - const updatedRooms = await ApiService.getUserRooms(); - setRooms(updatedRooms as RoomType[]); - - // Sélectionner la nouvelle salle avec son ID - selectRoomByName(newRoom); // Utiliser l'ID de l'objet retourné - }; + // Créer une salle + const createRoom = async (title: string) => { + // Créer la salle et récupérer l'objet complet + const newRoom = await ApiService.createRoom(title); + + // Mettre à jour la liste des salles + const updatedRooms = await ApiService.getUserRooms(); + setRooms(updatedRooms as RoomType[]); + + // Sélectionner la nouvelle salle avec son ID + 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); - selectRoom(room); - localStorage.setItem('selectedRoomId', roomId); - }; + // Sélectionner une salle + const selectRoomByName = (roomId: string) => { + const room = rooms.find(r => r._id === roomId); + selectRoom(room); + localStorage.setItem('selectedRoomId', roomId); + }; - const handleCreateRoom = async () => { - if (newRoomTitle.trim()) { - try { + const handleCreateRoom = async () => { + if (newRoomTitle.trim()) { + try { await createRoom(newRoomTitle); const userRooms = await ApiService.getUserRooms(); setRooms(userRooms as RoomType[]); - setOpenAddRoomDialog(false); - setNewRoomTitle(''); - } catch (error) { - setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue"); - setShowErrorDialog(true); - } - } - }; + setOpenAddRoomDialog(false); + setNewRoomTitle(''); + } catch (error) { + setErrorMessage(error instanceof Error ? error.message : "Erreur inconnue"); + setShowErrorDialog(true); + } + } + }; const handleSelectFolder = (event: React.ChangeEvent) => { setSelectedFolderId(event.target.value); @@ -397,9 +397,21 @@ const Dashboard: React.FC = () => { } else { const randomSixDigit = Math.floor(100000 + Math.random() * 900000); navigate(`/teacher/manage-room/${quiz._id}/${randomSixDigit}`); - } + } }; + const handleShareByUrl = (quiz: QuizType) => { + const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`; + navigator.clipboard.writeText(quizUrl) + .then(() => { + window.alert('URL a été copiée avec succès.'); + }) + .catch(() => { + window.alert('Une erreur est survenue lors de la copie de l\'URL.'); + }); + }; + + return (
Tableau de bord
@@ -497,41 +509,41 @@ const Dashboard: React.FC = () => {
- - {' '} - {' '} - + + {' '} + {' '} +
- - {' '} - {' '} - + + {' '} + {' '} +
- - {' '} - {' '} - + + {' '} + {' '} +
@@ -571,9 +583,8 @@ const Dashboard: React.FC = () => { onClick={() => handleLancerQuiz(quiz)} disabled={!validateQuiz(quiz.content)} > - {`${quiz.title} (${quiz.content.length} question${ - quiz.content.length > 1 ? 's' : '' - })`} + {`${quiz.title} (${quiz.content.length} question${quiz.content.length > 1 ? 's' : '' + })`} @@ -621,9 +632,15 @@ const Dashboard: React.FC = () => { -
- -
+ + handleShareByUrl(quiz)} + > + + + ))} diff --git a/client/src/services/ApiService.tsx b/client/src/services/ApiService.tsx index fa2b4e7..8f9cc67 100644 --- a/client/src/services/ApiService.tsx +++ b/client/src/services/ApiService.tsx @@ -836,36 +836,6 @@ public async login(email: string, password: string): Promise { } } - async ShareQuiz(quizId: string, email: string): Promise { - 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 { try { if (!quizId) {