mirror of
https://github.com/ets-cfuhrman-pfe/EvalueTonSavoir.git
synced 2025-08-11 21:23:54 -04:00
Compare commits
No commits in common. "95f914ce3e9d89202a7b49a726f5ff20c186eb41" and "0d7b6ee5ebed36f5a8c3a6881addfdd7a449c0bc" have entirely different histories.
95f914ce3e
...
0d7b6ee5eb
6 changed files with 248 additions and 261 deletions
|
|
@ -1,81 +1,74 @@
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
import { render, screen, fireEvent, act } from '@testing-library/react';
|
import { render, fireEvent, screen, waitFor } from '@testing-library/react';
|
||||||
import ShareQuizModal from '../../../components/ShareQuizModal/ShareQuizModal.tsx';
|
|
||||||
import { QuizType } from '../../../Types/QuizType';
|
|
||||||
import '@testing-library/jest-dom';
|
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', () => {
|
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(() => {
|
beforeEach(() => {
|
||||||
jest.clearAllMocks();
|
jest.clearAllMocks();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('renders the share button', () => {
|
it('should call ApiService.ShareQuiz when sharing by email', async () => {
|
||||||
render(<ShareQuizModal quiz={mockQuiz} />);
|
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 () => {
|
const shareButton = screen.getByRole('button', { name: /partager quiz/i });
|
||||||
render(<ShareQuizModal quiz={mockQuiz} />);
|
fireEvent.click(shareButton);
|
||||||
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 () => {
|
const emailButton = screen.getByRole('button', { name: /partager par email/i });
|
||||||
// Override the mock to reject
|
fireEvent.click(emailButton);
|
||||||
(navigator.clipboard.writeText as jest.Mock).mockRejectedValueOnce(new Error('Clipboard write failed'));
|
|
||||||
|
const email = 'test@example.com';
|
||||||
render(<ShareQuizModal quiz={mockQuiz} />);
|
window.prompt = jest.fn().mockReturnValue(email);
|
||||||
const shareButton = screen.getByLabelText('partager quiz');
|
|
||||||
|
await fireEvent.click(emailButton);
|
||||||
await act(async () => {
|
|
||||||
fireEvent.click(shareButton);
|
expect(ApiService.ShareQuiz).toHaveBeenCalledWith(mockQuiz._id, email);
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(screen.getByText(/Une erreur est survenue lors de la copie de l'URL\./i)).toBeInTheDocument();
|
it('copies the correct URL to the clipboard when sharing by URL', async () => {
|
||||||
});
|
render(<ShareQuizModal quiz={mockQuiz} />);
|
||||||
|
|
||||||
|
// 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.');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
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();
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
@ -5,6 +5,46 @@ import { ENV_VARIABLES } from '../../constants';
|
||||||
jest.mock('axios');
|
jest.mock('axios');
|
||||||
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
const mockedAxios = axios as jest.Mocked<typeof axios>;
|
||||||
|
|
||||||
|
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', () => {
|
describe('getSharedQuiz', () => {
|
||||||
it('should call the API to get a shared quiz and return the quiz data on success', async () => {
|
it('should call the API to get a shared quiz and return the quiz data on success', async () => {
|
||||||
const quizId = '123';
|
const quizId = '123';
|
||||||
|
|
|
||||||
|
|
@ -1,90 +1,67 @@
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton, Typography, Box } from '@mui/material';
|
import { Dialog, DialogTitle, DialogActions, Button, Tooltip, IconButton } from '@mui/material';
|
||||||
import { Share } from '@mui/icons-material';
|
import { Share } from '@mui/icons-material';
|
||||||
import { QuizType } from '../../Types/QuizType';
|
import { QuizType } from '../../Types/QuizType';
|
||||||
|
import ApiService from '../../services/ApiService';
|
||||||
|
|
||||||
interface ShareQuizModalProps {
|
interface ShareQuizModalProps {
|
||||||
quiz: QuizType;
|
quiz: QuizType;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
|
const ShareQuizModal: React.FC<ShareQuizModalProps> = ({ quiz }) => {
|
||||||
const [_open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
const [feedback, setFeedback] = useState({
|
|
||||||
open: false,
|
const handleOpenModal = () => setOpen(true);
|
||||||
title: '',
|
|
||||||
isError: false
|
|
||||||
});
|
|
||||||
|
|
||||||
const handleCloseModal = () => setOpen(false);
|
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 handleShareByUrl = () => {
|
||||||
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
|
const quizUrl = `${window.location.origin}/teacher/share/${quiz._id}`;
|
||||||
navigator.clipboard.writeText(quizUrl)
|
navigator.clipboard.writeText(quizUrl)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setFeedback({
|
window.alert('URL a été copiée avec succès.');
|
||||||
open: true,
|
|
||||||
title: 'L\'URL de partage pour le quiz',
|
|
||||||
isError: false
|
|
||||||
});
|
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
setFeedback({
|
window.alert('Une erreur est survenue lors de la copie de l\'URL.');
|
||||||
open: true,
|
|
||||||
title: 'Une erreur est survenue lors de la copie de l\'URL.',
|
|
||||||
isError: true
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
handleCloseModal();
|
handleCloseModal();
|
||||||
};
|
};
|
||||||
|
|
||||||
const closeFeedback = () => {
|
|
||||||
setFeedback(prev => ({ ...prev, open: false }));
|
|
||||||
};
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Tooltip title="Partager" placement="top">
|
<Tooltip title="Partager quiz" placement="top">
|
||||||
<IconButton color="primary" onClick={handleShareByUrl} aria-label="partager quiz">
|
<IconButton color="primary" onClick={handleOpenModal} aria-label="partager quiz">
|
||||||
<Share />
|
<Share />
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
{/* Feedback Dialog */}
|
<Dialog open={open} onClose={handleCloseModal} fullWidth maxWidth="xs">
|
||||||
<Dialog
|
<DialogTitle sx={{ textAlign: "center" }}>Choisissez une méthode de partage</DialogTitle>
|
||||||
open={feedback.open}
|
<DialogActions sx={{ display: "flex", justifyContent: "center", gap: 2 }}>
|
||||||
onClose={closeFeedback}
|
<Button onClick={handleShareByEmail}>Partager par email</Button>
|
||||||
fullWidth
|
<Button onClick={handleShareByUrl}>Partager par URL</Button>
|
||||||
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 été copiée.
|
|
||||||
</Typography>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</DialogTitle>
|
|
||||||
<DialogActions sx={{ display: "flex", justifyContent: "center" }}>
|
|
||||||
<Button
|
|
||||||
onClick={closeFeedback}
|
|
||||||
variant="contained"
|
|
||||||
>
|
|
||||||
OK
|
|
||||||
</Button>
|
|
||||||
</DialogActions>
|
</DialogActions>
|
||||||
</Dialog>
|
</Dialog>
|
||||||
</>
|
</>
|
||||||
|
|
|
||||||
|
|
@ -564,7 +564,7 @@ const Dashboard: React.FC = () => {
|
||||||
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
{quizzesByFolder[folderName].map((quiz: QuizType) => (
|
||||||
<div className="quiz" key={quiz._id}>
|
<div className="quiz" key={quiz._id}>
|
||||||
<div className="title">
|
<div className="title">
|
||||||
<Tooltip title="Démarrer" placement="top">
|
<Tooltip title="Lancer quiz" placement="top">
|
||||||
<div>
|
<div>
|
||||||
<Button
|
<Button
|
||||||
variant="outlined"
|
variant="outlined"
|
||||||
|
|
@ -580,7 +580,7 @@ const Dashboard: React.FC = () => {
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="actions">
|
<div className="actions">
|
||||||
<Tooltip title="Télécharger" placement="top">
|
<Tooltip title="Télécharger quiz" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => downloadTxtFile(quiz)}
|
onClick={() => downloadTxtFile(quiz)}
|
||||||
|
|
@ -590,7 +590,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Modifier" placement="top">
|
<Tooltip title="Modifier quiz" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleEditQuiz(quiz)}
|
onClick={() => handleEditQuiz(quiz)}
|
||||||
|
|
@ -600,7 +600,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Dupliquer" placement="top">
|
<Tooltip title="Dupliquer quiz" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
color="primary"
|
color="primary"
|
||||||
onClick={() => handleDuplicateQuiz(quiz)}
|
onClick={() => handleDuplicateQuiz(quiz)}
|
||||||
|
|
@ -610,7 +610,7 @@ const Dashboard: React.FC = () => {
|
||||||
</IconButton>
|
</IconButton>
|
||||||
</Tooltip>
|
</Tooltip>
|
||||||
|
|
||||||
<Tooltip title="Supprimer" placement="top">
|
<Tooltip title="Supprimer quiz" placement="top">
|
||||||
<IconButton
|
<IconButton
|
||||||
aria-label="delete"
|
aria-label="delete"
|
||||||
color="primary"
|
color="primary"
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,7 @@ import React, { useState, useEffect } from 'react';
|
||||||
import { useParams, useNavigate } from 'react-router-dom';
|
import { useParams, useNavigate } from 'react-router-dom';
|
||||||
import { FolderType } from '../../../Types/FolderType';
|
import { FolderType } from '../../../Types/FolderType';
|
||||||
import './share.css';
|
import './share.css';
|
||||||
import { Button, NativeSelect, Typography, Box, Divider } from '@mui/material';
|
import { Button, NativeSelect } from '@mui/material';
|
||||||
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
import ReturnButton from 'src/components/ReturnButton/ReturnButton';
|
||||||
import ApiService from '../../../services/ApiService';
|
import ApiService from '../../../services/ApiService';
|
||||||
|
|
||||||
|
|
@ -12,64 +12,56 @@ const Share: React.FC = () => {
|
||||||
|
|
||||||
const [quizTitle, setQuizTitle] = useState('');
|
const [quizTitle, setQuizTitle] = useState('');
|
||||||
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
const [selectedFolder, setSelectedFolder] = useState<string>('');
|
||||||
|
|
||||||
const [folders, setFolders] = useState<FolderType[]>([]);
|
const [folders, setFolders] = useState<FolderType[]>([]);
|
||||||
const [quizExists, setQuizExists] = useState(false);
|
|
||||||
const [loading, setLoading] = useState(true);
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const fetchData = async () => {
|
const fetchData = async () => {
|
||||||
try {
|
if (!id) {
|
||||||
if (!id) {
|
window.alert(`Une erreur est survenue.\n Le quiz n'a pas été trouvé\nVeuillez réessayer plus tard`)
|
||||||
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);
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
setFolders(userFolders as FolderType[]);
|
|
||||||
|
|
||||||
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');
|
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)) {
|
||||||
|
window.alert(`Le quiz que vous essayez d'importer existe déjà sur votre compte.`)
|
||||||
|
navigate('/teacher/dashboard');
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
setFolders(userFolders as FolderType[]);
|
||||||
|
|
||||||
|
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);
|
||||||
};
|
};
|
||||||
|
|
||||||
fetchData();
|
fetchData();
|
||||||
}, [id, navigate]);
|
}, []);
|
||||||
|
|
||||||
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
const handleSelectFolder = (event: React.ChangeEvent<HTMLSelectElement>) => {
|
||||||
setSelectedFolder(event.target.value);
|
setSelectedFolder(event.target.value);
|
||||||
|
|
@ -77,6 +69,7 @@ const Share: React.FC = () => {
|
||||||
|
|
||||||
const handleQuizSave = async () => {
|
const handleQuizSave = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
if (selectedFolder == '') {
|
if (selectedFolder == '') {
|
||||||
alert("Veuillez choisir un dossier");
|
alert("Veuillez choisir un dossier");
|
||||||
return;
|
return;
|
||||||
|
|
@ -98,87 +91,41 @@ const Share: React.FC = () => {
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
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='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>
|
|
||||||
|
|
||||||
<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 (
|
return (
|
||||||
<div className='quizImport'>
|
<div className='quizImport'>
|
||||||
<div className='importHeader'>
|
<div className='importHeader'>
|
||||||
<ReturnButton />
|
<ReturnButton />
|
||||||
<div className='titleContainer'>
|
<div className='titleContainer'>
|
||||||
<div className='mainTitle'>Importation du Quiz: {quizTitle}</div>
|
<div className='mainTitle'>Importation du Quiz: {quizTitle}</div>
|
||||||
<div className='subTitle'>
|
<div className='subTitle'>
|
||||||
Vous êtes sur le point d'importer le quiz <strong>{quizTitle}</strong>, choisissez un dossier dans lequel enregistrer ce nouveau quiz.
|
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">
|
|
||||||
Enregistrer
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</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">
|
||||||
|
Enregistrer
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default Share;
|
export default Share;
|
||||||
|
|
|
||||||
|
|
@ -836,6 +836,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> {
|
async getSharedQuiz(quizId: string): Promise<string> {
|
||||||
try {
|
try {
|
||||||
if (!quizId) {
|
if (!quizId) {
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue