Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIXED:#2 Added a Quiz Lock Feature #38

Merged
merged 1 commit into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 39 additions & 19 deletions app/admin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import { collection, doc, getDocs, updateDoc } from 'firebase/firestore';
import { useRouter } from 'next/navigation';
import * as XLSX from 'xlsx';
import QuizDetails from '../components/QuizDetails';
import {formatDate} from '../Date';
import { formatDate } from '../Date';
import toast from 'react-hot-toast';

const AdminPage = () => {
const [user, setUser] = useState(auth.currentUser);
const router = useRouter();
const [userData, setUserData] = useState<any[]>([]);
const [quizData, setQuizData] = useState<any>([]);
const [lockStatus, setLockStatus] = useState<Record<string, boolean>>({});

useEffect(() => {
fetchQuizData();
Expand Down Expand Up @@ -44,7 +45,6 @@ const AdminPage = () => {
userDataArray.push(data);
}
});
// Sort userDataArray by USN
userDataArray.sort((a: any, b: any) => a.USN.localeCompare(b.USN));
setUserData(userDataArray);
} catch (error) {
Expand All @@ -68,19 +68,38 @@ const AdminPage = () => {
try {
const querySnapshot = await getDocs(collection(db, 'quizzes'));
const quizDoc = querySnapshot.docs.find(doc => doc.data().data.quizName === quizName);

if (quizDoc) {
await updateDoc(doc(db, 'quizzes', quizDoc.id), {
'data.isDeleted': true,
});
fetchQuizData();
toast.success(`Quiz ${quizName} marked as deleted.`);
toast.success(`Quiz "${quizName}" marked as deleted.`);
} else {
console.error('Quiz not found:', quizName);
toast.error(`Quiz ${quizName} not found.`);
toast.error(`Quiz "${quizName}" not found.`);
}
} catch (error) {
console.error('Error deleting quiz:', error);
toast.error(`Error marking quiz ${quizName} as deleted.`);
toast.error(`Error marking quiz "${quizName}" as deleted.`);
}
};

async function handleLockUnlockQuiz(quizName: any) {
const querySnapshot = await getDocs(collection(db, 'quizzes'));
const quizDoc = querySnapshot.docs.find(doc => doc.data().data.quizName === quizName);

if (quizDoc) {
const currentLockStatus = quizDoc.data().data.isLocked;
await updateDoc(doc(db, 'quizzes', quizDoc.id), {
'data.isLocked': !currentLockStatus,
});
setLockStatus(prevStatus => ({ ...prevStatus, [quizName]: !currentLockStatus }));
fetchQuizData();
toast.success(`Quiz "${quizName}" ${currentLockStatus ? 'unlocked' : 'locked'} successfully.`);
} else {
console.error('Quiz not found:', quizName);
toast.error(`Quiz "${quizName}" not found.`);
}
};

Expand All @@ -99,19 +118,16 @@ const AdminPage = () => {
const handleDownloadExcel = () => {
var d = new Date();
var n = formatDate(d);

// Create a sorted copy of userData based on USN

const sortedUserData = [...userData].sort((a: any, b: any) => a.USN.localeCompare(b.USN));

// Flatten the sortedUserData array and include details for each quiz
const flatData = sortedUserData.map(user => {
const userFlat = {
'USN': user.USN,
'Email': user.email,
'Student Name': user.displayName,
'Total Score': calculateTotalScore(user.quizData),
// Flatten quizData array
...user.quizData.reduce((acc : any, quiz : any, index : any) => ({
...user.quizData.reduce((acc: any, quiz: any, index: any) => ({
...acc,
[` ${quiz.quizName} `]: `${quiz.score} / ${quiz.totalQuestions}`,
[`${quiz.quizName} Time`]: quiz.time,
Expand All @@ -122,18 +138,17 @@ const AdminPage = () => {
};
return userFlat;
});

// Create Excel sheet
const ws = XLSX.utils.json_to_sheet(flatData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, `Student Data Sheet ${n}` );
XLSX.utils.book_append_sheet(wb, ws, `Student Data Sheet ${n}`);
const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
saveAsExcelFile(excelBuffer, `Student Data Sheet ${n} .xlsx`);
};

// Function to handle downloading individual quiz data
const handleDownloadQuiz = (quizName : any) => {
// Filter userData to get data for the specific quizName
const handleDownloadQuiz = (quizName: any) => {
const quizData = userData.map(user => {
const userQuiz = user.quizData.find((quiz: any) => quiz.quizName === quizName);
return {
Expand All @@ -147,7 +162,6 @@ const AdminPage = () => {
};
}).filter(user => user['Quiz Name'] !== '');

// Create Excel sheet for the specific quiz
const ws = XLSX.utils.json_to_sheet(quizData);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, `${quizName} Data`);
Expand Down Expand Up @@ -178,27 +192,33 @@ const AdminPage = () => {
<div className="flex flex-wrap">
{console.log(quizData)}
{quizData
.map((quiz:any, index: any) => (
.map((quiz: any, index: any) => (
<div key={index} className="mr-4 mb-4">
<button
onClick={() => handleDownloadQuiz(quiz)}
className={`bg-green-500 hover:bg-green-700 text-white font-bold py-2 px-4 rounded mb-4`}
>
Download {quiz} Data
Download "{quiz}" Data
</button>
<button
onClick={() => handleDeleteQuiz(quiz)}
className={`bg-red-500 hover:bg-red-700 text-white font-bold py-2 px-4 rounded mb-4`}
>
Delete
</button>
<button
onClick={() => handleLockUnlockQuiz(quiz)}
className={`bg-yellow-500 hover:bg-yellow-700 text-white font-bold py-2 px-4 rounded mb-4`}
>
{lockStatus[quiz] ? 'Unlock' : 'Lock'}
</button>
</div>
))}
</div>
)}
<a
href='/createquiz'
className={`bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 mx-4 rounded mb-4`}
href='/createquiz'
className={`bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 mx-4 rounded mb-4`}
>
Create Quiz
</a>
Expand Down
7 changes: 5 additions & 2 deletions app/components/Fileinput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import React, { useState } from "react";
import * as XLSX from "xlsx";
import { useDropzone } from "react-dropzone";
import { v4 as uuidv4 } from 'uuid';
import {useRouter} from "next/navigation";
import { useRouter } from "next/navigation";

interface FileInputProps {
onFileUpload: (data: any) => void;
}
Expand All @@ -13,6 +14,7 @@ interface QuizInfo {
courseCode: string;
id: string;
isDeleted: boolean;
isLcoked: boolean;
}

interface QuizData {
Expand All @@ -31,6 +33,7 @@ function FileInput({ onFileUpload }: FileInputProps) {
courseCode: "",
id: uuidv4(),
isDeleted: false,
isLcoked: false,
} as QuizInfo);
const [quizGenerated, setQuizGenerated] = useState(false);
const [viewQuizData, setViewQuizData] = useState(false);
Expand All @@ -47,7 +50,7 @@ function FileInput({ onFileUpload }: FileInputProps) {
const excelData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
const quizData = condenseExcelData(excelData);
const fileName = file.name;

setExcelData(quizData as any);
setFileName(fileName);
};
Expand Down
132 changes: 61 additions & 71 deletions app/student/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,52 +7,51 @@ import { db } from '../firebase';
import { onAuthStateChanged } from 'firebase/auth';
import { useRouter } from 'next/navigation';

// Define a function to fetch quiz data
async function fetchQuizData() {
const quizCollection = collection(db, 'quizzes');
const querySnapshot = await getDocs(quizCollection);
const quizData:any = [];
const querySnapshot = await getDocs(collection(db, 'quizzes'));
const quizData: any = [];
querySnapshot.forEach((doc) => {
quizData.push(doc.data());
if (!doc.data().data.isDeleted && !doc.data().data.isLocked) {
quizData.push(doc.data());
}
});
// console.log(quizData);
return quizData;
}

async function fetchUserData() {
const userCollection = collection(db, 'users');
const querySnapshot = await getDocs(userCollection);
const userData:any = [];
const userData: any = [];
querySnapshot.forEach((doc) => {
userData.push(doc.data());
});
const currentUserData = userData.filter((entry:any) => {
const currentUserData = userData.filter((entry: any) => {
return (
entry.uid == auth.currentUser?.uid
);
});
console.log(currentUserData);
return userData;
}

// StudentPage component
const StudentPage = () => {
const router = useRouter();
const router = useRouter();

const [user, setUser] = useState(auth.currentUser);
const [userData, setUserData] = useState([]);
const [user, setUser] = useState(auth.currentUser);
const [userData, setUserData] = useState([]);

useEffect(() => {
// Check the user's authentication state
onAuthStateChanged(auth, (user) => {
if (user) {

setUser(user as any);
} else {
// Redirect unauthenticated users to the login page
router.push('/login');
}
});
}, []);
useEffect(() => {
// Check the user's authentication state
onAuthStateChanged(auth, (user) => {
if (user) {
setUser(user as any);
} else {
// Redirect unauthenticated users to the login page
router.push('/login');
}
});
}, []);

const [quizzes, setQuizzes] = useState([]);

Expand All @@ -66,60 +65,51 @@ const StudentPage = () => {
}
fetchData();
}, []);
// console.log("quizzes are " + quizzes)

return (
<div className="flex flex-col items-center justify-center min-h-screen">
{/* Quiz Cards Section */}
<div className="mt-8 text-gray-300 text-center">
<h1 className="text-3xl font-semibold mb-6">Join the quiz challenge and unlock your potential!</h1>
<div className="flex flex-wrap justify-center mt-4">
{quizzes.map((quiz: any) => {
const userAttempts: any = userData.find(
(data: any) => data.uid === auth.currentUser?.uid
);

const isQuizAttempted =
userAttempts &&
userAttempts.quizData.some((attempt: any) => attempt.quizId === quiz.data.id);

return (
<div
key={quiz.data.id}
className={`bg-gradient-to-r from-customBlue to-customViolet font-black px-6 py-4 rounded-md m-4 cursor-pointer transform hover:scale-105 transition duration-300 ${
isQuizAttempted ? 'opacity-50' : ''
}`}
>
{isQuizAttempted ? (
<div>
<p className="text-lg">Quiz Name: {quiz.data.quizName}</p>
<p>Course: {quiz.data.course}</p>
<p>Course Code: {quiz.data.courseCode}</p>
<p>This quiz has been attempted.</p>
<h1 className="text-3xl font-semibold mb-6">Join the quiz challenge and unlock your potential!</h1>
<div className="flex flex-wrap justify-center mt-4">
{quizzes.map((quiz: any) => {
const userAttempts: any = userData.find(
(data: any) => data.uid === auth.currentUser?.uid
);

const isQuizAttempted =
userAttempts &&
userAttempts.quizData.some((attempt: any) => attempt.quizId === quiz.data.id);

return (
<div
key={quiz.data.id}
className={`bg-gradient-to-r from-customBlue to-customViolet font-black px-6 py-4 rounded-md m-4 cursor-pointer transform hover:scale-105 transition duration-300 ${isQuizAttempted ? 'opacity-50' : ''
}`}
>
{isQuizAttempted ? (
<div>
<p className="text-lg">Quiz Name: {quiz.data.quizName}</p>
<p>Course: {quiz.data.course}</p>
<p>Course Code: {quiz.data.courseCode}</p>
<p>This quiz has been attempted.</p>
</div>
) : (
<Link
href={`/quiz?id=${quiz.data.id}&name=${quiz.data.quizName}&course=${quiz.data.course}&coursecode=${quiz.data.courseCode}`}
>
<div>
<p className="text-lg">Quiz Name: {quiz.data.quizName}</p>
<p>Course: {quiz.data.course}</p>
<p>Course Code: {quiz.data.courseCode}</p>
</div>
</Link>
)}
</div>
);
})}
</div>
) : (
<Link
href={`/quiz?id=${quiz.data.id}&name=${quiz.data.quizName}&course=${quiz.data.course}&coursecode=${quiz.data.courseCode}`}
>
<div>
<p className="text-lg">Quiz Name: {quiz.data.quizName}</p>
<p>Course: {quiz.data.course}</p>
<p>Course Code: {quiz.data.courseCode}</p>
</div>
</Link>
)}
</div>
);
})}






</div>
</div>

</div>
</div>
);
};
Expand Down
Loading