- Created a Diagnostics component;

- Corrected the history code;
This commit is contained in:
Tiago Ribeiro
2023-05-27 15:45:03 +01:00
parent 2b34bf8f0b
commit 23b3703b67
7 changed files with 163 additions and 24 deletions

View File

@@ -0,0 +1,86 @@
import {infoButtonStyle} from "@/constants/buttonStyles";
import {Module} from "@/interfaces";
import {User} from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import axios from "axios";
import clsx from "clsx";
import {useRouter} from "next/router";
import {useEffect, useState} from "react";
import {ToastContainer, toast} from "react-toastify";
interface Props {
user: User;
}
const DIAGNOSTIC_EXAMS = [
["reading", ""],
["listening", ""],
["writing", ""],
["speaking", ""],
];
export default function Diagnostic({user}: Props) {
const [focus, setFocus] = useState<"academic" | "general">();
const [isInsert, setIsInsert] = useState(false);
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const selectExam = () => {
const examPromises = DIAGNOSTIC_EXAMS.map((exam) => getExamById(exam[0] as Module, exam[1]));
Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) {
setExams(exams.map((x) => x!));
setSelectedModules(exams.map((x) => x!.module));
router.push("/exam");
}
});
};
const onPerformDiagnosis = async () => {
axios
.post("/api/users/update", {focus, isFirstLogin: false})
.then(selectExam)
.catch(() => {
toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
});
};
useEffect(() => {
toast.error("Something went wrong, please try again later!", {toastId: "user-update-error"});
}, []);
if (!focus) {
return (
<div className="bg-white p-16 rounded-2xl flex flex-col items-center justify-center gap-8 h-96 relative shadow-md">
<h2 className="absolute top-8 font-semibold text-xl">What is your focus?</h2>
<div className="flex flex-col gap-4 justify-self-stretch">
<button onClick={() => setFocus("academic")} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
Academic
</button>
<button onClick={() => setFocus("general")} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
General
</button>
</div>
</div>
);
}
return (
<div className="bg-white p-16 rounded-2xl flex flex-col items-center justify-center gap-8 h-96 relative shadow-md">
<h2 className="absolute top-8 font-semibold text-xl">What is your current IELTS level?</h2>
<div className="flex flex-col gap-4">
<button onClick={() => setIsInsert(true)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
Insert my IELTS level
</button>
<button onClick={onPerformDiagnosis} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
Perform a Diagnosis Test
</button>
</div>
</div>
);
}

View File

@@ -11,6 +11,7 @@ export interface ReadingExam {
exercises: Exercise[]; exercises: Exercise[];
module: "reading"; module: "reading";
minTimer: number; minTimer: number;
type: "academic" | "general";
} }
export interface ListeningExam { export interface ListeningExam {

View File

@@ -6,6 +6,8 @@ export interface User {
profilePicture: string; profilePicture: string;
id: string; id: string;
experience: number; experience: number;
isFirstLogin: boolean;
focus: "academic" | "general";
type: Type; type: Type;
} }

View File

@@ -0,0 +1,26 @@
// 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, getDoc, doc, setDoc} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {User} from "@/interfaces/user";
const db = getFirestore(app);
export default withIronSessionApiRoute(handler, sessionOptions);
async function handler(req: NextApiRequest, res: NextApiResponse) {
if (!req.session.user) {
res.status(401).json({ok: false});
return;
}
const docUser = await getDoc(doc(db, "users", req.session.user.id));
const user = docUser.data() as User;
const userRef = doc(db, "users", user.id);
setDoc(userRef, req.body, {merge: true});
res.status(200).json({ok: true});
}

View File

@@ -24,6 +24,8 @@ import {toast} from "react-toastify";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import Icon from "@mdi/react"; import Icon from "@mdi/react";
import {mdiArrowRight, mdiChevronRight} from "@mdi/js"; import {mdiArrowRight, mdiChevronRight} from "@mdi/js";
import {uniqBy} from "lodash";
import {getExamById} from "@/utils/exams";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -64,27 +66,6 @@ export default function History({user}: {user: User}) {
} }
}, [stats, isStatsLoading]); }, [stats, isStatsLoading]);
const getExam = async (module: Module): Promise<Exam | undefined> => {
const examRequest = await axios<Exam[]>(`/api/exam/${module}`);
if (examRequest.status !== 200) {
toast.error("Something went wrong!");
return undefined;
}
const newExam = examRequest.data;
switch (module) {
case "reading":
return newExam.shift() as ReadingExam;
case "listening":
return newExam.shift() as ListeningExam;
case "writing":
return newExam.shift() as WritingExam;
case "speaking":
return newExam.shift() as SpeakingExam;
}
};
const formatTimestamp = (timestamp: string) => { const formatTimestamp = (timestamp: string) => {
const date = moment(parseInt(timestamp)); const date = moment(parseInt(timestamp));
const formatter = "YYYY/MM/DD - HH:mm"; const formatter = "YYYY/MM/DD - HH:mm";
@@ -100,9 +81,7 @@ export default function History({user}: {user: User}) {
const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0); const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0);
const selectExam = () => { const selectExam = () => {
const examPromises = formatModuleTotalStats(dateStats) const examPromises = uniqBy(dateStats, "exam").map((stat) => getExamById(stat.module, stat.exam));
.filter((x) => x.value > 0)
.map((module) => getExam(module.label.toLowerCase() as Module));
Promise.all(examPromises).then((exams) => { Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) { if (exams.every((x) => !!x)) {

View File

@@ -11,6 +11,8 @@ import useStats from "@/hooks/useStats";
import {averageScore, formatModuleTotalStats, totalExams} from "@/utils/stats"; import {averageScore, formatModuleTotalStats, totalExams} from "@/utils/stats";
import {Divider} from "primereact/divider"; import {Divider} from "primereact/divider";
import useUser from "@/hooks/useUser"; import useUser from "@/hooks/useUser";
import Diagnostic from "@/components/Diagnostic";
import {ToastContainer} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -41,6 +43,25 @@ export default function Home() {
useEffect(() => setShowEndExam(window.innerWidth <= 960), []); useEffect(() => setShowEndExam(window.innerWidth <= 960), []);
useEffect(() => setWindowWidth(window.innerWidth), []); useEffect(() => setWindowWidth(window.innerWidth), []);
if (user && user.isFirstLogin) {
return (
<>
<Head>
<title>IELTS GPT | Muscat Training Institute</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className="w-full h-full min-h-[100vh] flex flex-col items-center justify-center bg-neutral-100 text-black">
<Diagnostic user={user} />
</main>
</>
);
}
return ( return (
<> <>
<Head> <Head>
@@ -52,6 +73,7 @@ export default function Home() {
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<ToastContainer />
{user && ( {user && (
<main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-black"> <main className="w-full h-full min-h-[100vh] flex flex-col items-center bg-neutral-100 text-black">
<Navbar userType={user.type} profilePicture={user.profilePicture} showExamEnd={showEndExam} /> <Navbar userType={user.type} profilePicture={user.profilePicture} showExamEnd={showEndExam} />

23
src/utils/exams.ts Normal file
View File

@@ -0,0 +1,23 @@
import {Module} from "@/interfaces";
import {Exam, ReadingExam, ListeningExam, WritingExam, SpeakingExam} from "@/interfaces/exam";
import axios from "axios";
export const getExamById = async (module: Module, id: string): Promise<Exam | undefined> => {
const examRequest = await axios<Exam>(`/api/exam/${module}/${id}`);
if (examRequest.status !== 200) {
return undefined;
}
const newExam = examRequest.data;
switch (module) {
case "reading":
return newExam as ReadingExam;
case "listening":
return newExam as ListeningExam;
case "writing":
return newExam as WritingExam;
case "speaking":
return newExam as SpeakingExam;
}
};