Merge branch 'main' into task/design/dashboard-redesign

This commit is contained in:
Tiago Ribeiro
2023-05-29 11:57:37 +01:00
13 changed files with 240 additions and 35 deletions

View File

@@ -0,0 +1,119 @@
import {infoButtonStyle} from "@/constants/buttonStyles";
import {BAND_SCORES} from "@/constants/ielts";
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 {capitalize} from "lodash";
import {useRouter} from "next/router";
import {useState} from "react";
import {toast} from "react-toastify";
interface Props {
user: User;
onFinish: () => void;
}
const DIAGNOSTIC_EXAMS = [
["reading", "CurQtQoxWmHaJHeN0JW2"],
["listening", "Y6cMao8kUcVnPQOo6teV"],
["writing", "hbueuDaEZXV37EW7I12A"],
["speaking", "QVFm4pdcziJQZN2iUTDo"],
];
export default function Diagnostic({onFinish}: Props) {
const [focus, setFocus] = useState<"academic" | "general">();
const [isInsert, setIsInsert] = useState(false);
const [levels, setLevels] = useState({reading: 0, listening: 0, writing: 0, speaking: 0});
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 updateUser = (callback: () => void) => {
axios
.patch("/api/users/update", {focus, levels, isFirstLogin: false})
.then(callback)
.catch(() => {
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>
);
}
if (isInsert) {
return (
<div className="bg-white p-16 rounded-2xl flex flex-col items-center justify-center gap-8 shadow-md">
<h2 className="font-semibold text-xl">What is your level?</h2>
<div className="flex w-full flex-col gap-4 justify-self-stretch">
{Object.keys(levels).map((module) => (
<div key={module} className="flex items-center gap-4 justify-between">
<span className="font-medium text-lg">{capitalize(module)}</span>
<input
type="number"
className={clsx(
"input input-bordered bg-white w-24",
!BAND_SCORES[module as Module].includes(levels[module as keyof typeof levels]) && "input-error",
)}
value={levels[module as keyof typeof levels]}
min={0}
max={9}
step={0.5}
onChange={(e) => setLevels((prev) => ({...prev, [module]: parseFloat(e.target.value)}))}
/>
</div>
))}
</div>
<button
onClick={() => updateUser(onFinish)}
className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}
disabled={!Object.keys(levels).every((module) => BAND_SCORES[module as Module].includes(levels[module as keyof typeof levels]))}>
Next
</button>
</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={() => updateUser(selectExam)} className={clsx("btn btn-wide gap-4 relative text-white", infoButtonStyle)}>
Perform a Diagnosis Test
</button>
</div>
</div>
);
}

View File

@@ -1,3 +1,4 @@
/* eslint-disable @next/next/no-img-element */
import {errorButtonStyle, infoButtonStyle} from "@/constants/buttonStyles";
import {WritingExercise} from "@/interfaces/exam";
import {mdiArrowLeft, mdiArrowRight} from "@mdi/js";
@@ -7,7 +8,7 @@ import {CommonProps} from ".";
import {Fragment, useEffect, useState} from "react";
import {toast} from "react-toastify";
export default function Writing({id, prompt, info, type, wordCounter, onNext, onBack}: WritingExercise & CommonProps) {
export default function Writing({id, prompt, info, type, wordCounter, attachment, onNext, onBack}: WritingExercise & CommonProps) {
const [inputText, setInputText] = useState("");
const [isSubmitEnabled, setIsSubmitEnabled] = useState(false);
@@ -40,6 +41,7 @@ export default function Writing({id, prompt, info, type, wordCounter, onNext, on
<span>
You should write {wordCounter.type === "min" ? "at least" : "at most"} {wordCounter.limit} words.
</span>
{attachment && <img src={attachment} alt="Exercise attachment" />}
</div>
<textarea

8
src/constants/ielts.ts Normal file
View File

@@ -0,0 +1,8 @@
import {Module} from "@/interfaces";
export const BAND_SCORES: {[key in Module]: number[]} = {
reading: [0, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9],
listening: [0, 2.5, 3, 3.5, 4, 4.5, 5, 5.5, 6, 6.5, 7, 7.5, 8, 8.5, 9],
writing: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
speaking: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
};

View File

@@ -1,13 +1,14 @@
/* eslint-disable @next/next/no-img-element */
import Icon from "@mdi/react";
import {mdiAccountVoice, mdiArrowLeft, mdiArrowRight, mdiBookOpen, mdiHeadphones, mdiPen} from "@mdi/js";
import {useState} from "react";
import {useEffect, useState} from "react";
import {Module} from "@/interfaces";
import clsx from "clsx";
import {useRouter} from "next/router";
import {errorButtonStyle, infoButtonStyle} from "@/constants/buttonStyles";
import ProfileLevel from "@/components/ProfileLevel";
import {User} from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
interface Props {
user: User;
@@ -16,6 +17,7 @@ interface Props {
export default function Selection({user, onStart}: Props) {
const [selectedModules, setSelectedModules] = useState<Module[]>([]);
const router = useRouter();
const toggleModule = (module: Module) => {

View File

@@ -11,6 +11,8 @@ export interface ReadingExam {
exercises: Exercise[];
module: "reading";
minTimer: number;
type: "academic" | "general";
isDiagnostic: boolean;
}
export interface ListeningExam {
@@ -22,6 +24,7 @@ export interface ListeningExam {
exercises: Exercise[];
module: "listening";
minTimer: number;
isDiagnostic: boolean;
}
export interface UserSolution {
@@ -41,6 +44,7 @@ export interface WritingExam {
id: string;
exercises: Exercise[];
minTimer: number;
isDiagnostic: boolean;
}
interface WordCounter {
@@ -53,6 +57,7 @@ export interface SpeakingExam {
module: "speaking";
exercises: Exercise[];
minTimer: number;
isDiagnostic: boolean;
}
export type Exercise =
@@ -69,6 +74,7 @@ export interface WritingExercise {
info: string; //* The information about the task, like the amount of time they should spend on it
prompt: string; //* The context given to the user containing what they should write about
wordCounter: WordCounter; //* The minimum or maximum amount of words that should be written
attachment?: string; //* The url for an image to work as an attachment to show the user
userSolutions: {
id: string;
solution: string;

View File

@@ -6,6 +6,9 @@ export interface User {
profilePicture: string;
id: string;
experience: number;
isFirstLogin: boolean;
focus: "academic" | "general";
levels: {[key in Module]: number};
type: Type;
}

View File

@@ -1,7 +1,7 @@
// 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} from "firebase/firestore";
import {getFirestore, collection, getDocs, query, where} from "firebase/firestore";
import {withIronSessionApiRoute} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
@@ -16,8 +16,10 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
}
const {module} = req.query as {module: string};
const moduleRef = collection(db, module);
const q = query(moduleRef, where("isDiagnostic", "==", false));
const snapshot = await getDocs(collection(db, module));
const snapshot = await getDocs(q);
res.status(200).json(
snapshot.docs.map((doc) => ({

View File

@@ -0,0 +1,23 @@
// 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 userRef = doc(db, "users", req.session.user.id);
await setDoc(userRef, req.body, {merge: true});
res.status(200).json({ok: true});
}

View File

@@ -14,11 +14,11 @@ import Finish from "@/exams/Finish";
import axios from "axios";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat, User} from "@/interfaces/user";
import {Stat} from "@/interfaces/user";
import Speaking from "@/exams/Speaking";
import {v4 as uuidv4} from "uuid";
import useUser from "@/hooks/useUser";
import useExamStore, {ExamState} from "@/stores/examStore";
import useExamStore from "@/stores/examStore";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -67,7 +67,7 @@ export default function Page() {
useEffect(() => {
(async () => {
if (selectedModules.length > 0) {
if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map(getExam);
Promise.all(examPromises).then((values) => {
if (values.every((x) => !!x)) {
@@ -76,11 +76,11 @@ export default function Page() {
});
}
})();
}, [selectedModules, setExams]);
}, [selectedModules, setExams, exams]);
useEffect(() => {
(async () => {
if (selectedModules.length > 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded) {
if (selectedModules.length > 0 && exams.length === 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded) {
const newStats: Stat[] = userSolutions.map((solution) => ({
...solution,
session: sessionId,

View File

@@ -24,6 +24,9 @@ import {toast} from "react-toastify";
import {useRouter} from "next/router";
import Icon from "@mdi/react";
import {mdiArrowRight, mdiChevronRight} from "@mdi/js";
import {uniqBy} from "lodash";
import {getExamById} from "@/utils/exams";
import {sortByModule} from "@/utils/moduleUtils";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -64,27 +67,6 @@ export default function History({user}: {user: User}) {
}
}, [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 date = moment(parseInt(timestamp));
const formatter = "YYYY/MM/DD - HH:mm";
@@ -100,16 +82,19 @@ export default function History({user}: {user: User}) {
const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0);
const selectExam = () => {
const examPromises = formatModuleTotalStats(dateStats)
.filter((x) => x.value > 0)
.map((module) => getExam(module.label.toLowerCase() as Module));
const examPromises = uniqBy(dateStats, "exam").map((stat) => getExamById(stat.module, stat.exam));
Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) {
setUserSolutions(convertToUserSolutions(dateStats));
setShowSolutions(true);
setExams(exams.map((x) => x!));
setSelectedModules(exams.map((x) => x!.module));
setExams(exams.map((x) => x!).sort(sortByModule));
setSelectedModules(
exams
.map((x) => x!)
.sort(sortByModule)
.map((x) => x!.module),
);
router.push("/exam");
}
});

View File

@@ -12,6 +12,8 @@ import {averageScore, formatModuleTotalStats, totalExams} from "@/utils/stats";
import {Divider} from "primereact/divider";
import useUser from "@/hooks/useUser";
import Sidebar from "@/components/Sidebar";
import Diagnostic from "@/components/Diagnostic";
import {ToastContainer} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user;
@@ -35,12 +37,35 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
export default function Home() {
const [showEndExam, setShowEndExam] = useState(false);
const [windowWidth, setWindowWidth] = useState(0);
const [showDiagnostics, setShowDiagnostics] = useState(false);
const {stats, isLoading} = useStats();
const {user} = useUser({redirectTo: "/login"});
useEffect(() => setShowEndExam(window.innerWidth <= 960), []);
useEffect(() => setWindowWidth(window.innerWidth), []);
useEffect(() => {
if (user) setShowDiagnostics(user.isFirstLogin);
}, [user]);
if (user && showDiagnostics) {
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} onFinish={() => setShowDiagnostics(false)} />
</main>
</>
);
}
return (
<>
@@ -53,6 +78,7 @@ export default function Home() {
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<main className="w-full h-full min-h-[100vh] flex flex-col bg-mti-gray text-black">
<Navbar user={user} />

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;
}
};

View File

@@ -1,8 +1,14 @@
import {Module} from "@/interfaces";
const MODULE_ARRAY: Module[] = ["reading", "listening", "writing", "speaking"];
export const moduleLabels: {[key in Module]: string} = {
listening: "Listening",
reading: "Reading",
speaking: "Speaking",
writing: "Writing",
};
export const sortByModule = (a: {module: Module}, b: {module: Module}) => {
return MODULE_ARRAY.findIndex((x) => a.module === x) - MODULE_ARRAY.findIndex((x) => b.module === x);
};