- Adapted more of the design to be more responsive;

- Revamped some of the UserSolutions;
- Transformed the homepage chart to use actual dynamic values;
- Created an endpoint for the stats;
This commit is contained in:
Tiago Ribeiro
2023-04-20 00:20:20 +01:00
parent d61592b73e
commit 87f7b717fc
22 changed files with 5468 additions and 829 deletions

4580
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -44,6 +44,7 @@
}, },
"devDependencies": { "devDependencies": {
"@types/lodash": "^4.14.191", "@types/lodash": "^4.14.191",
"@wixc3/react-board": "^2.2.0",
"autoprefixer": "^10.4.13", "autoprefixer": "^10.4.13",
"postcss": "^8.4.21", "postcss": "^8.4.21",
"tailwindcss": "^3.2.4" "tailwindcss": "^3.2.4"

View File

@@ -70,7 +70,7 @@ function WordsPopout({words, isOpen, onCancel, onAnswer}: WordsPopoutProps) {
); );
} }
export default function FillBlanks({id, allowRepetition, prompt, solutions, text, words, onNext, onBack}: FillBlanksExercise & CommonProps) { export default function FillBlanks({id, allowRepetition, type, prompt, solutions, text, words, onNext, onBack}: FillBlanksExercise & CommonProps) {
const [userSolutions, setUserSolutions] = useState<{id: string; solution: string}[]>([]); const [userSolutions, setUserSolutions] = useState<{id: string; solution: string}[]>([]);
const [currentBlankId, setCurrentBlankId] = useState<string>(); const [currentBlankId, setCurrentBlankId] = useState<string>();
@@ -128,7 +128,7 @@ export default function FillBlanks({id, allowRepetition, prompt, solutions, text
</span> </span>
</div> </div>
<div className="self-end flex flex-col items-center md:items-start md:flex-row gap-8"> <div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />
@@ -137,7 +137,7 @@ export default function FillBlanks({id, allowRepetition, prompt, solutions, text
</button> </button>
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
onClick={() => onNext({id, solutions: userSolutions, score: calculateScore()})}> onClick={() => onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type})}>
Next Next
<div className="absolute right-4"> <div className="absolute right-4">
<Icon path={mdiArrowRight} color="white" size={1} /> <Icon path={mdiArrowRight} color="white" size={1} />

View File

@@ -3,11 +3,11 @@ import {MatchSentencesExercise} from "@/interfaces/exam";
import {mdiArrowLeft, mdiArrowRight} from "@mdi/js"; import {mdiArrowLeft, mdiArrowRight} from "@mdi/js";
import Icon from "@mdi/react"; import Icon from "@mdi/react";
import clsx from "clsx"; import clsx from "clsx";
import {useState} from "react"; import {Fragment, useState} from "react";
import LineTo from "react-lineto"; import LineTo from "react-lineto";
import {CommonProps} from "."; import {CommonProps} from ".";
export default function MatchSentences({id, options, prompt, sentences, onNext, onBack}: MatchSentencesExercise & CommonProps) { export default function MatchSentences({id, options, type, prompt, sentences, onNext, onBack}: MatchSentencesExercise & CommonProps) {
const [selectedQuestion, setSelectedQuestion] = useState<string>(); const [selectedQuestion, setSelectedQuestion] = useState<string>();
const [userSolutions, setUserSolutions] = useState<{question: string; option: string}[]>([]); const [userSolutions, setUserSolutions] = useState<{question: string; option: string}[]>([]);
@@ -31,7 +31,14 @@ export default function MatchSentences({id, options, prompt, sentences, onNext,
return ( return (
<> <>
<div className="flex flex-col items-center gap-8"> <div className="flex flex-col items-center gap-8">
<span className="text-lg font-medium text-center px-48">{prompt}</span> <span className="text-base md:text-lg font-medium text-center px-2 md:px-4 lg:px-48">
{prompt.split("\\n").map((line, index) => (
<Fragment key={index}>
{line}
<br />
</Fragment>
))}
</span>
<div className="grid grid-cols-2 gap-16 place-items-center"> <div className="grid grid-cols-2 gap-16 place-items-center">
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{sentences.map(({sentence, id, color}) => ( {sentences.map(({sentence, id, color}) => (
@@ -85,7 +92,7 @@ export default function MatchSentences({id, options, prompt, sentences, onNext,
</div> </div>
</div> </div>
<div className="self-end flex gap-8"> <div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />
@@ -94,7 +101,7 @@ export default function MatchSentences({id, options, prompt, sentences, onNext,
</button> </button>
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
onClick={() => onNext({id, solutions: userSolutions, score: calculateScore()})}> onClick={() => onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type})}>
Next Next
<div className="absolute right-4"> <div className="absolute right-4">
<Icon path={mdiArrowRight} color="white" size={1} /> <Icon path={mdiArrowRight} color="white" size={1} />

View File

@@ -83,7 +83,7 @@ function Question({
); );
} }
export default function MultipleChoice({id, prompt, questions, onNext, onBack}: MultipleChoiceExercise & CommonProps) { export default function MultipleChoice({id, prompt, type, questions, onNext, onBack}: MultipleChoiceExercise & CommonProps) {
const [userSolutions, setUserSolutions] = useState<{question: string; option: string}[]>([]); const [userSolutions, setUserSolutions] = useState<{question: string; option: string}[]>([]);
const [questionIndex, setQuestionIndex] = useState(0); const [questionIndex, setQuestionIndex] = useState(0);
@@ -101,7 +101,7 @@ export default function MultipleChoice({id, prompt, questions, onNext, onBack}:
const next = () => { const next = () => {
if (questionIndex === questions.length - 1) { if (questionIndex === questions.length - 1) {
onNext({id, solutions: userSolutions, score: calculateScore()}); onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type});
} else { } else {
setQuestionIndex((prev) => prev + 1); setQuestionIndex((prev) => prev + 1);
} }
@@ -127,7 +127,8 @@ export default function MultipleChoice({id, prompt, questions, onNext, onBack}:
/> />
)} )}
</div> </div>
<div className="self-end flex gap-8">
<div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={back}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={back}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />

View File

@@ -7,7 +7,7 @@ import {CommonProps} from ".";
import {Fragment, useEffect, useState} from "react"; import {Fragment, useEffect, useState} from "react";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
export default function Speaking({id, title, text, prompts, onNext, onBack}: SpeakingExercise & CommonProps) { export default function Speaking({id, title, text, type, prompts, onNext, onBack}: SpeakingExercise & CommonProps) {
return ( return (
<div className="flex flex-col h-full w-2/3 items-center justify-center gap-8"> <div className="flex flex-col h-full w-2/3 items-center justify-center gap-8">
<div className="flex flex-col max-w-2xl gap-4"> <div className="flex flex-col max-w-2xl gap-4">
@@ -32,7 +32,7 @@ export default function Speaking({id, title, text, prompts, onNext, onBack}: Spe
</div> </div>
</div> </div>
<div className="self-end flex gap-8"> <div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />
@@ -41,7 +41,7 @@ export default function Speaking({id, title, text, prompts, onNext, onBack}: Spe
</button> </button>
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
onClick={() => onNext({id, solutions: [], score: {correct: 0, total: 0}})}> onClick={() => onNext({exercise: id, solutions: [], score: {correct: 0, total: 0}, type})}>
Next Next
<div className="absolute right-4"> <div className="absolute right-4">
<Icon path={mdiArrowRight} color="white" size={1} /> <Icon path={mdiArrowRight} color="white" size={1} />

View File

@@ -42,7 +42,7 @@ function Blank({
); );
} }
export default function WriteBlanks({id, prompt, maxWords, solutions, text, onNext, onBack}: WriteBlanksExercise & CommonProps) { export default function WriteBlanks({id, prompt, type, maxWords, solutions, text, onNext, onBack}: WriteBlanksExercise & CommonProps) {
const [userSolutions, setUserSolutions] = useState<{id: string; solution: string}[]>([]); const [userSolutions, setUserSolutions] = useState<{id: string; solution: string}[]>([]);
const calculateScore = () => { const calculateScore = () => {
@@ -88,7 +88,7 @@ export default function WriteBlanks({id, prompt, maxWords, solutions, text, onNe
</span> </span>
</div> </div>
<div className="self-end flex gap-8"> <div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />
@@ -97,7 +97,7 @@ export default function WriteBlanks({id, prompt, maxWords, solutions, text, onNe
</button> </button>
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
onClick={() => onNext({id, solutions: userSolutions, score: calculateScore()})}> onClick={() => onNext({exercise: id, solutions: userSolutions, score: calculateScore(), type})}>
Next Next
<div className="absolute right-4"> <div className="absolute right-4">
<Icon path={mdiArrowRight} color="white" size={1} /> <Icon path={mdiArrowRight} color="white" size={1} />

View File

@@ -7,7 +7,7 @@ import {CommonProps} from ".";
import {Fragment, useEffect, useState} from "react"; import {Fragment, useEffect, useState} from "react";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
export default function Writing({id, prompt, info, wordCounter, onNext, onBack}: WritingExercise & CommonProps) { export default function Writing({id, prompt, info, type, wordCounter, onNext, onBack}: WritingExercise & CommonProps) {
const [inputText, setInputText] = useState(""); const [inputText, setInputText] = useState("");
const [isSubmitEnabled, setIsSubmitEnabled] = useState(false); const [isSubmitEnabled, setIsSubmitEnabled] = useState(false);
@@ -49,7 +49,7 @@ export default function Writing({id, prompt, info, wordCounter, onNext, onBack}:
placeholder="Write your text here..." placeholder="Write your text here..."
/> />
<div className="self-end flex gap-8"> <div className="self-end flex flex-col-reverse items-center w-full md:justify-between md:items-start md:flex-row gap-8">
<button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}> <button className={clsx("btn btn-wide gap-4 relative text-white", errorButtonStyle)} onClick={onBack}>
<div className="absolute left-4"> <div className="absolute left-4">
<Icon path={mdiArrowLeft} color="white" size={1} /> <Icon path={mdiArrowLeft} color="white" size={1} />
@@ -61,7 +61,7 @@ export default function Writing({id, prompt, info, wordCounter, onNext, onBack}:
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
disabled={!isSubmitEnabled} disabled={!isSubmitEnabled}
onClick={() => onNext({id, solutions: [inputText], score: {correct: 1, total: 1}})}> onClick={() => onNext({exercise: id, solutions: [inputText], score: {correct: 1, total: 1}, type})}>
Next Next
</button> </button>
</div> </div>
@@ -70,7 +70,7 @@ export default function Writing({id, prompt, info, wordCounter, onNext, onBack}:
<button <button
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
disabled={!isSubmitEnabled} disabled={!isSubmitEnabled}
onClick={() => onNext({id, solutions: [inputText], score: {correct: 1, total: 1}})}> onClick={() => onNext({exercise: id, solutions: [inputText], score: {correct: 1, total: 1}, type})}>
Next Next
<div className="absolute right-4"> <div className="absolute right-4">
<Icon path={mdiArrowRight} color="white" size={1} /> <Icon path={mdiArrowRight} color="white" size={1} />

View File

@@ -54,11 +54,11 @@ export default function Finish({user, scores, modules, onViewResults}: Props) {
<div className="w-full h-full relative"> <div className="w-full h-full relative">
<section className="h-full w-full flex flex-col items-center justify-center gap-4"> <section className="h-full w-full flex flex-col items-center justify-center gap-4">
<ProfileLevel user={user} className="h-1/2" /> <ProfileLevel user={user} className="h-1/2" />
<div className="h-2/3 w-1/2 flex flex-col items-center gap-4"> <div className="h-2/3 w-2/3 flex flex-col items-center gap-4">
<div className="rounded-xl p-4 items-center flex justify-center gap-4"> <div className="rounded-xl p-2 md:p-4 items-center flex lg:justify-center gap-2 md:gap-4 max-w-[100%] overflow-auto">
{modules.map((module) => ( {modules.map((module) => (
<div <div
className={`flex flex-col gap-12 min-w-[176px] items-center justify-center border-2 border-ielts-${module} bg-ielts-${module}-transparent p-4 rounded-xl text-white font-semibold`} className={`flex flex-col gap-12 min-w-[176px] items-center justify-center border-2 border-ielts-${module} bg-ielts-${module}-transparent py-4 px-2 rounded-xl text-white font-semibold`}
key={module}> key={module}>
<div className="flex flex-col items-center"> <div className="flex flex-col items-center">
<Icon path={ICONS[module]} color="white" size={2} /> <Icon path={ICONS[module]} color="white" size={2} />

View File

@@ -20,7 +20,7 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.id !== solution.id), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
if (exerciseIndex + 1 < exam.exercises.length) { if (exerciseIndex + 1 < exam.exercises.length) {
@@ -29,7 +29,9 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
} }
if (solution) { if (solution) {
onFinish([...userSolutions.filter((x) => x.id !== solution.id), solution].map((x) => ({...x, module: "listening", exam: exam.id}))); onFinish(
[...userSolutions.filter((x) => x.exercise !== solution.exercise), solution].map((x) => ({...x, module: "listening", exam: exam.id})),
);
} else { } else {
onFinish(userSolutions.map((x) => ({...x, module: "listening", exam: exam.id}))); onFinish(userSolutions.map((x) => ({...x, module: "listening", exam: exam.id})));
} }
@@ -53,14 +55,16 @@ export default function Listening({exam, showSolutions = false, onFinish}: Props
)} )}
</div> </div>
)} )}
<div className="bg-gray-300 rounded-xl p-4 flex flex-col gap-4 items-center w-full overflow-auto"> <div className="rounded-xl flex flex-col gap-4 items-center w-full overflow-auto">
{exam.audio.repeatableTimes > 0 && ( {exam.audio.repeatableTimes > 0 && (
<>{exam.audio.repeatableTimes <= timesListened && <span>You are no longer allowed to listen to the audio again.</span>}</> <>{exam.audio.repeatableTimes <= timesListened && <span>You are no longer allowed to listen to the audio again.</span>}</>
)} )}
{exam.audio.repeatableTimes > 0 && timesListened < exam.audio.repeatableTimes && (
<audio preload="auto" controls autoPlay onPlay={() => setTimesListened((prev) => prev + 1)}> <audio preload="auto" controls autoPlay onPlay={() => setTimesListened((prev) => prev + 1)}>
<source src={exam.audio.source} type="audio/mpeg" /> <source src={exam.audio.source} type="audio/mpeg" />
Your browser does not support the audio element Your browser does not support the audio element
</audio> </audio>
)}
</div> </div>
</> </>
); );

View File

@@ -80,7 +80,7 @@ export default function Reading({exam, showSolutions = false, onFinish}: Props)
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.id !== solution.id), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
if (exerciseIndex + 1 < exam.exercises.length) { if (exerciseIndex + 1 < exam.exercises.length) {
@@ -89,7 +89,9 @@ export default function Reading({exam, showSolutions = false, onFinish}: Props)
} }
if (solution) { if (solution) {
onFinish([...userSolutions.filter((x) => x.id !== solution.id), solution].map((x) => ({...x, module: "reading", exam: exam.id}))); onFinish(
[...userSolutions.filter((x) => x.exercise !== solution.exercise), solution].map((x) => ({...x, module: "reading", exam: exam.id})),
);
} else { } else {
onFinish(userSolutions.map((x) => ({...x, module: "reading", exam: exam.id}))); onFinish(userSolutions.map((x) => ({...x, module: "reading", exam: exam.id})));
} }

View File

@@ -20,7 +20,7 @@ export default function Speaking({exam, showSolutions = false, onFinish}: Props)
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.id !== solution.id), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
if (exerciseIndex + 1 < exam.exercises.length) { if (exerciseIndex + 1 < exam.exercises.length) {
@@ -29,7 +29,9 @@ export default function Speaking({exam, showSolutions = false, onFinish}: Props)
} }
if (solution) { if (solution) {
onFinish([...userSolutions.filter((x) => x.id !== solution.id), solution].map((x) => ({...x, module: "speaking", exam: exam.id}))); onFinish(
[...userSolutions.filter((x) => x.exercise !== solution.exercise), solution].map((x) => ({...x, module: "speaking", exam: exam.id})),
);
} else { } else {
onFinish(userSolutions.map((x) => ({...x, module: "speaking", exam: exam.id}))); onFinish(userSolutions.map((x) => ({...x, module: "speaking", exam: exam.id})));
} }

View File

@@ -20,7 +20,7 @@ export default function Writing({exam, showSolutions = false, onFinish}: Props)
const nextExercise = (solution?: UserSolution) => { const nextExercise = (solution?: UserSolution) => {
if (solution) { if (solution) {
setUserSolutions((prev) => [...prev.filter((x) => x.id !== solution.id), solution]); setUserSolutions((prev) => [...prev.filter((x) => x.exercise !== solution.exercise), solution]);
} }
if (exerciseIndex + 1 < exam.exercises.length) { if (exerciseIndex + 1 < exam.exercises.length) {
@@ -29,7 +29,9 @@ export default function Writing({exam, showSolutions = false, onFinish}: Props)
} }
if (solution) { if (solution) {
onFinish([...userSolutions.filter((x) => x.id !== solution.id), solution].map((x) => ({...x, module: "writing", exam: exam.id}))); onFinish(
[...userSolutions.filter((x) => x.exercise !== solution.exercise), solution].map((x) => ({...x, module: "writing", exam: exam.id})),
);
} else { } else {
onFinish(userSolutions.map((x) => ({...x, module: "writing", exam: exam.id}))); onFinish(userSolutions.map((x) => ({...x, module: "writing", exam: exam.id})));
} }

19
src/hooks/useStats.tsx Normal file
View File

@@ -0,0 +1,19 @@
import {Stat, User} from "@/interfaces/user";
import axios from "axios";
import {useEffect, useState} from "react";
export default function useStats() {
const [stats, setStats] = useState<Stat[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
useEffect(() => {
setIsLoading(true);
axios
.get<Stat[]>("/api/stats")
.then((response) => setStats(response.data))
.finally(() => setIsLoading(false));
}, []);
return {stats, isLoading, isError};
}

View File

@@ -28,11 +28,12 @@ export interface UserSolution {
solutions: any[]; solutions: any[];
module?: Module; module?: Module;
exam?: string; exam?: string;
type: string;
score: { score: {
correct: number; correct: number;
total: number; total: number;
}; };
id: string; exercise: string;
} }
export interface WritingExam { export interface WritingExam {

View File

@@ -3,6 +3,7 @@ import {Module} from "@/interfaces";
export type UserResults = {[key in Module]: ModuleResult}; export type UserResults = {[key in Module]: ModuleResult};
interface ModuleResult { interface ModuleResult {
exams: string[];
score: number; score: number;
total: number; total: number;
} }

View File

@@ -1,3 +1,6 @@
import {Module} from ".";
import {UserSolution} from "./exam";
export interface User { export interface User {
email: string; email: string;
name: string; name: string;
@@ -7,4 +10,16 @@ export interface User {
type: Type; type: Type;
} }
export interface Stat {
user: string;
exam: string;
exercise: string;
module: Module;
solutions: any[];
score: {
correct: number;
total: number;
};
}
export type Type = "student" | "teacher" | "admin" | "owner" | "developer"; export type Type = "student" | "teacher" | "admin" | "owner" | "developer";

View File

@@ -26,7 +26,7 @@ async function login(req: NextApiRequest, res: NextApiResponse) {
const user = docUser.data() as User; const user = docUser.data() as User;
req.session.user = user; req.session.user = {...user, id: userId};
await req.session.save(); await req.session.save();
res.status(200).json({user: {...user, id: userId}}); res.status(200).json({user: {...user, id: userId}});

View File

@@ -0,0 +1,47 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type {NextApiRequest, NextApiResponse} from "next";
import {app} from "@/firebase";
import {getFirestore, collection, getDocs, query, where, doc, setDoc, addDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat} from "@/interfaces/user";
const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method === "GET") return get(req, res);
if (req.method === "POST") return post(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ok: false});
return;
}
const user = req.session.user;
const q = query(collection(db, "stats"), where("user", "==", user.id));
const snapshot = await getDocs(q);
res.status(200).json(
snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
})),
);
}
async function post(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ok: false});
return;
}
const stats = req.body as Stat[];
await stats.forEach(async (stat) => await addDoc(collection(db, "stats"), stat));
res.status(200).json({ok: true});
}

View File

@@ -14,7 +14,7 @@ import Finish from "@/exams/Finish";
import axios from "axios"; import axios from "axios";
import {withIronSessionSsr} from "iron-session/next"; import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {User} from "@/interfaces/user"; import {Stat, User} from "@/interfaces/user";
import Speaking from "@/exams/Speaking"; import Speaking from "@/exams/Speaking";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
@@ -37,11 +37,12 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
}, sessionOptions); }, sessionOptions);
export default function Page({user}: {user: User}) { export default function Page({user}: {user: User}) {
const [userSolutions, setUserSolutions] = useState<UserSolution[]>([]);
const [selectedModules, setSelectedModules] = useState<Module[]>([]); const [selectedModules, setSelectedModules] = useState<Module[]>([]);
const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [showSolutions, setShowSolutions] = useState(false);
const [moduleIndex, setModuleIndex] = useState(0); const [moduleIndex, setModuleIndex] = useState(0);
const [exam, setExam] = useState<Exam>(); const [exam, setExam] = useState<Exam>();
const [userSolutions, setUserSolutions] = useState<UserSolution[]>([]);
const [showSolutions, setShowSolutions] = useState(false);
const [timer, setTimer] = useState(-1); const [timer, setTimer] = useState(-1);
useEffect(() => { useEffect(() => {
@@ -54,6 +55,25 @@ export default function Page({user}: {user: User}) {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex]); }, [selectedModules, moduleIndex]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded) {
const stats: Stat[] = userSolutions.map((solution) => ({
...solution,
exam: solution.exam!,
module: solution.module!,
user: user.id,
}));
axios
.post<{ok: boolean}>("/api/stats", stats)
.then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false));
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]);
useEffect(() => { useEffect(() => {
if (exam) { if (exam) {
setTimer(exam.minTimer * 60); setTimer(exam.minTimer * 60);
@@ -87,15 +107,15 @@ export default function Page({user}: {user: User}) {
}; };
const updateExamWithUserSolutions = (exam: Exam): Exam => { const updateExamWithUserSolutions = (exam: Exam): Exam => {
const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.id)?.solutions})); const exercises = exam.exercises.map((x) => Object.assign(x, {userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions}));
return Object.assign(exam, exercises); return Object.assign(exam, exercises);
}; };
const onFinish = (solutions: UserSolution[]) => { const onFinish = (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.id); const solutionIds = solutions.map((x) => x.exercise);
setUserSolutions((prev) => [...prev.filter((x) => !solutionIds.includes(x.id)), ...solutions]); setUserSolutions((prev) => [...prev.filter((x) => !solutionIds.includes(x.exercise)), ...solutions]);
setModuleIndex((prev) => prev + 1); setModuleIndex((prev) => prev + 1);
}; };

View File

@@ -14,8 +14,11 @@ import JSON_RESULTS from "@/demo/user_results.json";
import {withIronSessionSsr} from "iron-session/next"; import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {User} from "@/interfaces/user"; import {Stat, User} from "@/interfaces/user";
import {useEffect, useState} from "react"; import {useEffect, useState} from "react";
import useStats from "@/hooks/useStats";
import {Module} from "@/interfaces";
import {UserResults} from "@/interfaces/results";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -38,8 +41,46 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
export default function Home({user}: {user: User}) { export default function Home({user}: {user: User}) {
const [showEndExam, setShowEndExam] = useState(false); const [showEndExam, setShowEndExam] = useState(false);
const {stats, isLoading} = useStats();
useEffect(() => setShowEndExam(window.innerWidth <= 960), []); useEffect(() => setShowEndExam(window.innerWidth <= 960), []);
useEffect(() => console.log(stats), [stats]);
const formatStatsToChart = (data: Stat[]): UserResults => {
const result: UserResults = {
reading: {
exams: [],
score: 0,
total: 0,
},
listening: {
exams: [],
score: 0,
total: 0,
},
writing: {
exams: [],
score: 0,
total: 0,
},
speaking: {
exams: [],
score: 0,
total: 0,
},
};
data.forEach((stat) => {
if (result[stat.module].exams)
result[stat.module] = {
exams: [...result[stat.module].exams.filter((x) => x !== stat.exam), stat.exam],
total: result[stat.module].score + (result[stat.module].exams.includes(stat.exam) ? 0 : 1),
score: result[stat.module].total + 1,
};
});
return result;
};
return ( return (
<> <>
@@ -59,9 +100,11 @@ export default function Home({user}: {user: User}) {
<section className="w-full lg:w-1/2 h-full flex items-center"> <section className="w-full lg:w-1/2 h-full flex items-center">
<ProfileCard user={user} className="text-black self-start" /> <ProfileCard user={user} className="text-black self-start" />
</section> </section>
{!isLoading && stats && (
<section className="w-full lg:w-1/3 h-full flex items-center justify-center"> <section className="w-full lg:w-1/3 h-full flex items-center justify-center">
<UserResultChart results={JSON_RESULTS} resultKey="total" label="Total exams" className="w-2/3" /> <UserResultChart results={formatStatsToChart(stats)} resultKey="total" label="Total exams" className="w-2/3" />
</section> </section>
)}
</section> </section>
</div> </div>
</main> </main>

1454
yarn.lock

File diff suppressed because it is too large Load Diff