Merged develop into settings-import-users

This commit is contained in:
Tiago Ribeiro
2024-08-07 06:47:59 +00:00
42 changed files with 4452 additions and 1813 deletions

View File

@@ -1,154 +1,223 @@
import {PERMISSIONS} from "@/constants/userPermissions";
import { useMemo } from "react";
import { PERMISSIONS } from "@/constants/userPermissions";
import useExams from "@/hooks/useExams";
import useUsers from "@/hooks/useUsers";
import {Module} from "@/interfaces";
import {Exam} from "@/interfaces/exam";
import {Type, User} from "@/interfaces/user";
import { Module } from "@/interfaces";
import { Exam } from "@/interfaces/exam";
import { Type, User } from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {countExercises} from "@/utils/moduleUtils";
import {createColumnHelper, flexRender, getCoreRowModel, useReactTable} from "@tanstack/react-table";
import { getExamById } from "@/utils/exams";
import { countExercises } from "@/utils/moduleUtils";
import {
createColumnHelper,
flexRender,
getCoreRowModel,
useReactTable,
} from "@tanstack/react-table";
import axios from "axios";
import clsx from "clsx";
import {capitalize} from "lodash";
import {useRouter} from "next/router";
import {BsCheck, BsTrash, BsUpload} from "react-icons/bs";
import {toast} from "react-toastify";
import { capitalize } from "lodash";
import { useRouter } from "next/router";
import { BsCheck, BsTrash, BsUpload } from "react-icons/bs";
import { toast } from "react-toastify";
const CLASSES: {[key in Module]: string} = {
reading: "text-ielts-reading",
listening: "text-ielts-listening",
speaking: "text-ielts-speaking",
writing: "text-ielts-writing",
level: "text-ielts-level",
const CLASSES: { [key in Module]: string } = {
reading: "text-ielts-reading",
listening: "text-ielts-listening",
speaking: "text-ielts-speaking",
writing: "text-ielts-writing",
level: "text-ielts-level",
};
const columnHelper = createColumnHelper<Exam>();
export default function ExamList({user}: {user: User}) {
const {exams, reload} = useExams();
export default function ExamList({ user }: { user: User }) {
const { exams, reload } = useExams();
const { users } = useUsers();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const parsedExams = useMemo(() => {
return exams.map((exam) => {
if (exam.createdBy) {
const user = users.find((u) => u.id === exam.createdBy);
if (!user) return exam;
const router = useRouter();
return {
...exam,
createdBy: user.type === "developer" ? "system" : user.name,
};
}
const loadExam = async (module: Module, examId: string) => {
const exam = await getExamById(module, examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return exam;
});
}, [exams, users]);
return;
}
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
setExams([exam]);
setSelectedModules([module]);
const router = useRouter();
router.push("/exercises");
};
const loadExam = async (module: Module, examId: string) => {
const exam = await getExamById(module, examId.trim());
if (!exam) {
toast.error(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id",
}
);
const deleteExam = async (exam: Exam) => {
if (!confirm(`Are you sure you want to delete this ${capitalize(exam.module)} exam?`)) return;
return;
}
axios
.delete(`/api/exam/${exam.module}/${exam.id}`)
.then(() => toast.success(`Deleted the "${exam.id}" exam`))
.catch((reason) => {
if (reason.response.status === 404) {
toast.error("Exam not found!");
return;
}
setExams([exam]);
setSelectedModules([module]);
if (reason.response.status === 403) {
toast.error("You do not have permission to delete this exam!");
return;
}
router.push("/exercises");
};
toast.error("Something went wrong, please try again later.");
})
.finally(reload);
};
const deleteExam = async (exam: Exam) => {
if (
!confirm(
`Are you sure you want to delete this ${capitalize(exam.module)} exam?`
)
)
return;
const getTotalExercises = (exam: Exam) => {
if (exam.module === "reading" || exam.module === "listening" || exam.module === "level") {
return countExercises(exam.parts.flatMap((x) => x.exercises));
}
axios
.delete(`/api/exam/${exam.module}/${exam.id}`)
.then(() => toast.success(`Deleted the "${exam.id}" exam`))
.catch((reason) => {
if (reason.response.status === 404) {
toast.error("Exam not found!");
return;
}
return countExercises(exam.exercises);
};
if (reason.response.status === 403) {
toast.error("You do not have permission to delete this exam!");
return;
}
const defaultColumns = [
columnHelper.accessor("id", {
header: "ID",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("module", {
header: "Module",
cell: (info) => <span className={CLASSES[info.getValue()]}>{capitalize(info.getValue())}</span>,
}),
columnHelper.accessor((x) => getTotalExercises(x), {
header: "Exercises",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("minTimer", {
header: "Timer",
cell: (info) => <>{info.getValue()} minute(s)</>,
}),
{
header: "",
id: "actions",
cell: ({row}: {row: {original: Exam}}) => {
return (
<div className="flex gap-4">
<div
data-tip="Load exam"
className="cursor-pointer tooltip"
onClick={async () => await loadExam(row.original.module, row.original.id)}>
<BsUpload className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
{PERMISSIONS.examManagement.delete.includes(user.type) && (
<div data-tip="Delete" className="cursor-pointer tooltip" onClick={() => deleteExam(row.original)}>
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
)}
</div>
);
},
},
];
toast.error("Something went wrong, please try again later.");
})
.finally(reload);
};
const table = useReactTable({
data: exams,
columns: defaultColumns,
getCoreRowModel: getCoreRowModel(),
});
const getTotalExercises = (exam: Exam) => {
if (
exam.module === "reading" ||
exam.module === "listening" ||
exam.module === "level"
) {
return countExercises(exam.parts.flatMap((x) => x.exercises));
}
return (
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th className="p-4 text-left" key={header.id}>
{header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody className="px-2">
{table.getRowModel().rows.map((row) => (
<tr className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2" key={row.id}>
{row.getVisibleCells().map((cell) => (
<td className="px-4 py-2" key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
);
return countExercises(exam.exercises);
};
const defaultColumns = [
columnHelper.accessor("id", {
header: "ID",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("module", {
header: "Module",
cell: (info) => (
<span className={CLASSES[info.getValue()]}>
{capitalize(info.getValue())}
</span>
),
}),
columnHelper.accessor((x) => getTotalExercises(x), {
header: "Exercises",
cell: (info) => info.getValue(),
}),
columnHelper.accessor("minTimer", {
header: "Timer",
cell: (info) => <>{info.getValue()} minute(s)</>,
}),
columnHelper.accessor("createdAt", {
header: "Created At",
cell: (info) => {
const value = info.getValue();
if (value) {
return new Date(value).toLocaleDateString();
}
return null;
},
}),
columnHelper.accessor("createdBy", {
header: "Created By",
cell: (info) => info.getValue(),
}),
{
header: "",
id: "actions",
cell: ({ row }: { row: { original: Exam } }) => {
return (
<div className="flex gap-4">
<div
data-tip="Load exam"
className="cursor-pointer tooltip"
onClick={async () =>
await loadExam(row.original.module, row.original.id)
}
>
<BsUpload className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
{PERMISSIONS.examManagement.delete.includes(user.type) && (
<div
data-tip="Delete"
className="cursor-pointer tooltip"
onClick={() => deleteExam(row.original)}
>
<BsTrash className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div>
)}
</div>
);
},
},
];
const table = useReactTable({
data: parsedExams,
columns: defaultColumns,
getCoreRowModel: getCoreRowModel(),
});
return (
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
<thead>
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<th className="p-4 text-left" key={header.id}>
{header.isPlaceholder
? null
: flexRender(
header.column.columnDef.header,
header.getContext()
)}
</th>
))}
</tr>
))}
</thead>
<tbody className="px-2">
{table.getRowModel().rows.map((row) => (
<tr
className="odd:bg-white even:bg-mti-purple-ultralight/40 rounded-lg py-2"
key={row.id}
>
{row.getVisibleCells().map((cell) => (
<td className="px-4 py-2" key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</tr>
))}
</tbody>
</table>
);
}

View File

@@ -193,7 +193,7 @@ const TaskTab = ({section, setSection}: {section: LevelSection; setSection: (sec
<label className="font-normal text-base text-mti-gray-dim">Exercise Type</label>
<Select
options={Object.keys(TYPES).map((key) => ({value: key, label: TYPES[key]}))}
onChange={(e) => setSection({...section, type: e!.value})}
onChange={(e) => setSection({...section, type: e!.value!})}
value={{value: section?.type || "multiple_choice_4", label: TYPES[section?.type || "multiple_choice_4"]}}
/>
</div>
@@ -296,7 +296,7 @@ const LevelGeneration = () => {
module: "level",
difficulty,
variant: "full",
isDiagnostic: true,
isDiagnostic: false,
parts: parts
.map((part, index) => {
const currentExercise = result.data.exercises[`exercise_${index + 1}`] as any;

View File

@@ -1,526 +1,449 @@
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import { Difficulty, Exercise, ListeningExam } from "@/interfaces/exam";
import {Difficulty, Exercise, ListeningExam} from "@/interfaces/exam";
import useExamStore from "@/stores/examStore";
import { getExamById } from "@/utils/exams";
import { playSound } from "@/utils/sound";
import { convertCamelCaseToReadable } from "@/utils/string";
import { Tab } from "@headlessui/react";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import { capitalize, sample } from "lodash";
import { useRouter } from "next/router";
import { useEffect, useState, Dispatch, SetStateAction } from "react";
import { BsArrowRepeat, BsCheck } from "react-icons/bs";
import { toast } from "react-toastify";
import {capitalize, sample} from "lodash";
import {useRouter} from "next/router";
import {useEffect, useState, Dispatch, SetStateAction} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
import {generate} from "random-words";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
const MULTIPLE_CHOICE = { type: "multipleChoice", label: "Multiple Choice" };
const MULTIPLE_CHOICE = {type: "multipleChoice", label: "Multiple Choice"};
const WRITE_BLANKS_QUESTIONS = {
type: "writeBlanksQuestions",
label: "Write the Blanks: Questions",
type: "writeBlanksQuestions",
label: "Write the Blanks: Questions",
};
const WRITE_BLANKS_FILL = {
type: "writeBlanksFill",
label: "Write the Blanks: Fill",
type: "writeBlanksFill",
label: "Write the Blanks: Fill",
};
const WRITE_BLANKS_FORM = {
type: "writeBlanksForm",
label: "Write the Blanks: Form",
type: "writeBlanksForm",
label: "Write the Blanks: Form",
};
const MULTIPLE_CHOICE_3 = {
type: "multipleChoice3Options",
label: "Multiple Choice",
type: "multipleChoice3Options",
label: "Multiple Choice",
};
const PartTab = ({
part,
difficulty,
availableTypes,
index,
setPart,
updatePart,
part,
difficulty,
availableTypes,
index,
setPart,
updatePart,
}: {
part?: ListeningPart;
difficulty: Difficulty;
availableTypes: { type: string; label: string }[];
index: number;
setPart: (part?: ListeningPart) => void;
updatePart: Dispatch<SetStateAction<ListeningPart | undefined>>;
part?: ListeningPart;
difficulty: Difficulty;
availableTypes: {type: string; label: string}[];
index: number;
setPart: (part?: ListeningPart) => void;
updatePart: Dispatch<SetStateAction<ListeningPart | undefined>>;
}) => {
const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [types, setTypes] = useState<string[]>([]);
const [topic, setTopic] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [types, setTypes] = useState<string[]>([]);
const generate = () => {
const url = new URLSearchParams();
url.append("difficulty", difficulty);
const generate = () => {
const url = new URLSearchParams();
url.append("difficulty", difficulty);
if (topic) url.append("topic", topic);
if (types) types.forEach((t) => url.append("exercises", t));
if (topic) url.append("topic", topic);
if (types) types.forEach((t) => url.append("exercises", t));
setPart(undefined);
setIsLoading(true);
axios
.get(
`/api/exam/listening/generate/listening_section_${index}${
topic || types ? `?${url.toString()}` : ""
}`
)
.then((result) => {
playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string")
return toast.error(
"Something went wrong, please try to generate again."
);
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
setPart(undefined);
setIsLoading(true);
axios
.get(`/api/exam/listening/generate/listening_section_${index}${topic || types ? `?${url.toString()}` : ""}`)
.then((result) => {
playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const renderExercises = () => {
return part?.exercises.map((exercise) => {
switch (exercise.type) {
case "multipleChoice":
return (
<>
<h1>Exercise: Multiple Choice</h1>
<MultipleChoiceEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) =>
updatePart((part?: ListeningPart) => {
if (part) {
const exercises = part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
) as Exercise[];
const updatedPart = {
...part,
exercises,
} as ListeningPart;
return updatedPart;
}
const renderExercises = () => {
return part?.exercises.map((exercise) => {
switch (exercise.type) {
case "multipleChoice":
return (
<>
<h1>Exercise: Multiple Choice</h1>
<MultipleChoiceEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) =>
updatePart((part?: ListeningPart) => {
if (part) {
const exercises = part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)) as Exercise[];
const updatedPart = {
...part,
exercises,
} as ListeningPart;
return updatedPart;
}
return part;
})
}
/>
</>
);
// TODO: This might be broken as they all returns the same
case "writeBlanks":
return (
<>
<h1>Exercise: Write Blanks</h1>
<WriteBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ListeningPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) =>
x.id === exercise.id ? { ...x, ...data } : x
),
} as ListeningPart;
}
return part;
})
}
/>
</>
);
// TODO: This might be broken as they all returns the same
case "writeBlanks":
return (
<>
<h1>Exercise: Write Blanks</h1>
<WriteBlanksEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ListeningPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
} as ListeningPart;
}
return part;
});
}}
/>
</>
);
default:
return null;
}
});
};
return part;
});
}}
/>
</>
);
default:
return null;
}
});
};
const toggleType = (type: string) =>
setTypes((prev) =>
prev.includes(type)
? [...prev.filter((x) => x !== type)]
: [...prev, type]
);
const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));
return (
<Tab.Panel className="w-full bg-ielts-listening/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">
Exercises
</label>
<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
{availableTypes.map((x) => (
<span
onClick={() => toggleType(x.type)}
key={x.type}
className={clsx(
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!types.includes(x.type)
? "bg-white border-mti-gray-platinum"
: "bg-ielts-listening/70 border-ielts-listening text-white"
)}
>
{x.label}
</span>
))}
</div>
</div>
<div className="flex gap-4 items-end">
<Input
type="text"
placeholder="Grand Canyon..."
name="topic"
label="Topic"
onChange={setTopic}
roundness="xl"
defaultValue={topic}
/>
<button
onClick={generate}
disabled={isLoading || types.length === 0}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px]",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
</div>
{isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span
className={clsx(
"loading loading-infinity w-32 text-ielts-listening"
)}
/>
<span className={clsx("font-bold text-2xl text-ielts-listening")}>
Generating...
</span>
</div>
)}
{part && (
<>
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
<div className="flex gap-4">
{part.exercises.map((x) => (
<span
className="rounded-xl bg-white border border-ielts-listening p-1 px-4"
key={x.id}
>
{x.type && convertCamelCaseToReadable(x.type)}
</span>
))}
</div>
{typeof part.text === "string" && (
<span className="w-full h-96">
{part.text.replaceAll("\n\n", " ")}
</span>
)}
{typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => (
<span key={index} className="flex gap-1">
<span className="font-semibold">{x.name}:</span>
{x.text.replaceAll("\n\n", " ")}
</span>
))}
</div>
)}
</div>
{renderExercises()}
</>
)}
</Tab.Panel>
);
return (
<Tab.Panel className="w-full bg-ielts-listening/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Exercises</label>
<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
{availableTypes.map((x) => (
<span
onClick={() => toggleType(x.type)}
key={x.type}
className={clsx(
"px-6 py-4 w-64 flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"transition duration-300 ease-in-out",
!types.includes(x.type)
? "bg-white border-mti-gray-platinum"
: "bg-ielts-listening/70 border-ielts-listening text-white",
)}>
{x.label}
</span>
))}
</div>
</div>
<div className="flex gap-4 items-end">
<Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} />
<button
onClick={generate}
disabled={isLoading || types.length === 0}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px]",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
</div>
{isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span className={clsx("loading loading-infinity w-32 text-ielts-listening")} />
<span className={clsx("font-bold text-2xl text-ielts-listening")}>Generating...</span>
</div>
)}
{part && (
<>
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
<div className="flex gap-4">
{part.exercises.map((x) => (
<span className="rounded-xl bg-white border border-ielts-listening p-1 px-4" key={x.id}>
{x.type && convertCamelCaseToReadable(x.type)}
</span>
))}
</div>
{typeof part.text === "string" && <span className="w-full h-96">{part.text.replaceAll("\n\n", " ")}</span>}
{typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => (
<span key={index} className="flex gap-1">
<span className="font-semibold">{x.name}:</span>
{x.text.replaceAll("\n\n", " ")}
</span>
))}
</div>
)}
</div>
{renderExercises()}
</>
)}
</Tab.Panel>
);
};
interface ListeningPart {
exercises: Exercise[];
text:
| {
conversation: {
gender: string;
name: string;
text: string;
voice: string;
}[];
}
| string;
exercises: Exercise[];
text:
| {
conversation: {
gender: string;
name: string;
text: string;
voice: string;
}[];
}
| string;
}
const ListeningGeneration = () => {
const [part1, setPart1] = useState<ListeningPart>();
const [part2, setPart2] = useState<ListeningPart>();
const [part3, setPart3] = useState<ListeningPart>();
const [part4, setPart4] = useState<ListeningPart>();
const [minTimer, setMinTimer] = useState(30);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(
sample(DIFFICULTIES)!
);
const [part1, setPart1] = useState<ListeningPart>();
const [part2, setPart2] = useState<ListeningPart>();
const [part3, setPart3] = useState<ListeningPart>();
const [part4, setPart4] = useState<ListeningPart>();
const [minTimer, setMinTimer] = useState(30);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
useEffect(() => {
const part1Timer = part1 ? 5 : 0;
const part2Timer = part2 ? 8 : 0;
const part3Timer = part3 ? 8 : 0;
const part4Timer = part4 ? 9 : 0;
useEffect(() => {
const part1Timer = part1 ? 5 : 0;
const part2Timer = part2 ? 8 : 0;
const part3Timer = part3 ? 8 : 0;
const part4Timer = part4 ? 9 : 0;
const sum = part1Timer + part2Timer + part3Timer + part4Timer;
setMinTimer(sum > 0 ? sum : 5);
}, [part1, part2, part3, part4]);
const sum = part1Timer + part2Timer + part3Timer + part4Timer;
setMinTimer(sum > 0 ? sum : 5);
}, [part1, part2, part3, part4]);
const router = useRouter();
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const submitExam = () => {
const parts = [part1, part2, part3, part4].filter((x) => !!x);
console.log({ parts });
if (parts.length === 0)
return toast.error("Please generate at least one section!");
const submitExam = () => {
const parts = [part1, part2, part3, part4].filter((x) => !!x);
console.log({parts});
if (parts.length === 0) return toast.error("Please generate at least one section!");
setIsLoading(true);
setIsLoading(true);
axios
.post(`/api/exam/listening/generate/listening`, {
parts,
minTimer,
difficulty,
})
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success(
"This new exam has been generated successfully! Check the ID in our browser's console."
);
setResultingExam(result.data);
axios
.post(`/api/exam/listening/generate/listening`, {
id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
parts,
minTimer,
difficulty,
})
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success(`Generated Exam ID: ${result.data.id}`);
setResultingExam(result.data);
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setPart4(undefined);
setDifficulty(sample(DIFFICULTIES)!);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setPart4(undefined);
setDifficulty(sample(DIFFICULTIES)!);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim());
if (!exam) {
toast.error(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id",
}
);
const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return;
}
return;
}
setExams([exam]);
setSelectedModules(["listening"]);
setExams([exam]);
setSelectedModules(["listening"]);
router.push("/exercises");
};
router.push("/exercises");
};
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">
Timer
</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">
Difficulty
</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) =>
value ? setDifficulty(value.value as Difficulty) : null
}
value={{ value: difficulty, label: capitalize(difficulty) }}
disabled={!!part1 || !!part2 || !!part3 || !!part4}
/>
</div>
</div>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1">
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
)
}
>
Section 1 {part1 && <BsCheck />}
</Tab>
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
)
}
>
Section 2 {part2 && <BsCheck />}
</Tab>
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
)
}
>
Section 3 {part3 && <BsCheck />}
</Tab>
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
)
}
>
Section 4 {part4 && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{
part: part1,
setPart: setPart1,
types: [
MULTIPLE_CHOICE,
WRITE_BLANKS_QUESTIONS,
WRITE_BLANKS_FILL,
WRITE_BLANKS_FORM,
],
},
{
part: part2,
setPart: setPart2,
types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS],
},
{
part: part3,
setPart: setPart3,
types: [MULTIPLE_CHOICE_3, WRITE_BLANKS_QUESTIONS],
},
{
part: part4,
setPart: setPart4,
types: [
MULTIPLE_CHOICE,
WRITE_BLANKS_QUESTIONS,
WRITE_BLANKS_FILL,
WRITE_BLANKS_FORM,
],
},
].map(({ part, setPart, types }, index) => (
<PartTab
part={part}
difficulty={difficulty}
availableTypes={types}
index={index + 1}
key={index}
setPart={setPart}
updatePart={setPart}
/>
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300"
)}
>
Perform Exam
</button>
)}
<button
disabled={(!part1 && !part2 && !part3 && !part4) || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!part1 && !part2 && !part3 && !part4 && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Timer</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 15 ? 15 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
value={{value: difficulty, label: capitalize(difficulty)}}
disabled={!!part1 || !!part2 || !!part3 || !!part4}
/>
</div>
</div>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1">
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 1 {part1 && <BsCheck />}
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 2 {part2 && <BsCheck />}
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 3 {part3 && <BsCheck />}
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-listening/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
)
}>
Section 4 {part4 && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{
part: part1,
setPart: setPart1,
types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS, WRITE_BLANKS_FILL, WRITE_BLANKS_FORM],
},
{
part: part2,
setPart: setPart2,
types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS],
},
{
part: part3,
setPart: setPart3,
types: [MULTIPLE_CHOICE_3, WRITE_BLANKS_QUESTIONS],
},
{
part: part4,
setPart: setPart4,
types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS, WRITE_BLANKS_FILL, WRITE_BLANKS_FORM],
},
].map(({part, setPart, types}, index) => (
<PartTab
part={part}
difficulty={difficulty}
availableTypes={types}
index={index + 1}
key={index}
setPart={setPart}
updatePart={setPart}
/>
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
Perform Exam
</button>
)}
<button
disabled={(!part1 && !part2 && !part3 && !part4) || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!part1 && !part2 && !part3 && !part4 && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
};
export default ListeningGeneration;

View File

@@ -5,6 +5,7 @@ import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {generate} from "random-words";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
@@ -18,6 +19,7 @@ import FillBlanksEdit from "@/components/Generation/fill.blanks.edit";
import TrueFalseEdit from "@/components/Generation/true.false.edit";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
import MatchSentencesEdit from "@/components/Generation/match.sentences.edit";
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
@@ -118,6 +120,28 @@ const PartTab = ({
/>
</>
);
case "multipleChoice":
return (
<>
<h1>Exercise: True or False</h1>
<MultipleChoiceEdit
exercise={exercise}
key={exercise.id}
updateExercise={(data: any) => {
updatePart((part?: ReadingPart) => {
if (part) {
return {
...part,
exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
} as ReadingPart;
}
return part;
});
}}
/>
</>
);
case "writeBlanks":
return (
<>
@@ -282,7 +306,7 @@ const ReadingGeneration = () => {
isDiagnostic: false,
minTimer,
module: "reading",
id: v4(),
id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
type: "academic",
variant: parts.length === 3 ? "full" : "partial",
difficulty,
@@ -293,7 +317,7 @@ const ReadingGeneration = () => {
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
toast.success(`Generated Exam ID: ${result.data.id}`);
setResultingExam(result.data);
setPart1(undefined);

View File

@@ -1,503 +1,414 @@
import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select";
import {
Difficulty,
Exercise,
InteractiveSpeakingExercise,
SpeakingExam,
SpeakingExercise,
} from "@/interfaces/exam";
import { AVATARS } from "@/resources/speakingAvatars";
import {Difficulty, Exercise, InteractiveSpeakingExercise, SpeakingExam, SpeakingExercise} from "@/interfaces/exam";
import {AVATARS} from "@/resources/speakingAvatars";
import useExamStore from "@/stores/examStore";
import { getExamById } from "@/utils/exams";
import { playSound } from "@/utils/sound";
import { convertCamelCaseToReadable } from "@/utils/string";
import { Tab } from "@headlessui/react";
import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string";
import {Tab} from "@headlessui/react";
import axios from "axios";
import clsx from "clsx";
import { capitalize, sample, uniq } from "lodash";
import {capitalize, sample, uniq} from "lodash";
import moment from "moment";
import { useRouter } from "next/router";
import { useEffect, useState, Dispatch, SetStateAction } from "react";
import { BsArrowRepeat, BsCheck } from "react-icons/bs";
import { toast } from "react-toastify";
import { v4 } from "uuid";
import {useRouter} from "next/router";
import {generate} from "random-words";
import {useEffect, useState, Dispatch, SetStateAction} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
import {v4} from "uuid";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
const PartTab = ({
part,
index,
difficulty,
setPart,
updatePart,
part,
index,
difficulty,
setPart,
updatePart,
}: {
part?: SpeakingPart;
difficulty: Difficulty;
index: number;
setPart: (part?: SpeakingPart) => void;
updatePart: Dispatch<SetStateAction<SpeakingPart | undefined>>;
part?: SpeakingPart;
difficulty: Difficulty;
index: number;
setPart: (part?: SpeakingPart) => void;
updatePart: Dispatch<SetStateAction<SpeakingPart | undefined>>;
}) => {
const [gender, setGender] = useState<"male" | "female">("male");
const [isLoading, setIsLoading] = useState(false);
const [gender, setGender] = useState<"male" | "female">("male");
const [isLoading, setIsLoading] = useState(false);
const generate = () => {
setPart(undefined);
setIsLoading(true);
const generate = () => {
setPart(undefined);
setIsLoading(true);
const url = new URLSearchParams();
url.append("difficulty", difficulty);
const url = new URLSearchParams();
url.append("difficulty", difficulty);
axios
.get(
`/api/exam/speaking/generate/speaking_task_${index}?${url.toString()}`
)
.then((result) => {
playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string")
return toast.error(
"Something went wrong, please try to generate again."
);
console.log(result.data);
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
axios
.get(`/api/exam/speaking/generate/speaking_task_${index}?${url.toString()}`)
.then((result) => {
playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
console.log(result.data);
setPart(result.data);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong!");
})
.finally(() => setIsLoading(false));
};
const generateVideo = async () => {
if (!part)
return toast.error(
"Please generate the first part before generating the video!"
);
toast.info(
"This will take quite a while, please do not leave this page or close the tab/window."
);
const generateVideo = async () => {
if (!part) return toast.error("Please generate the first part before generating the video!");
toast.info("This will take quite a while, please do not leave this page or close the tab/window.");
const avatar = sample(AVATARS.filter((x) => x.gender === gender));
const avatar = sample(AVATARS.filter((x) => x.gender === gender));
setIsLoading(true);
const initialTime = moment();
setIsLoading(true);
const initialTime = moment();
axios
.post(`/api/exam/speaking/generate/speaking/generate_video_${index}`, {
...part,
avatar: avatar?.id,
})
.then((result) => {
const isError =
typeof result.data === "string" ||
moment().diff(initialTime, "seconds") < 60;
axios
.post(`/api/exam/speaking/generate/speaking/generate_video_${index}`, {
...part,
avatar: avatar?.id,
})
.then((result) => {
const isError = typeof result.data === "string" || moment().diff(initialTime, "seconds") < 60;
playSound(isError ? "error" : "check");
console.log(result.data);
if (isError)
return toast.error(
"Something went wrong, please try to generate the video again."
);
setPart({
...part,
result: { ...result.data, topic: part?.topic },
gender,
avatar,
});
})
.catch((e) => {
toast.error("Something went wrong!");
console.log(e);
})
.finally(() => setIsLoading(false));
};
playSound(isError ? "error" : "check");
console.log(result.data);
if (isError) return toast.error("Something went wrong, please try to generate the video again.");
setPart({
...part,
result: {...result.data, topic: part?.topic},
gender,
avatar,
});
})
.catch((e) => {
toast.error("Something went wrong!");
console.log(e);
})
.finally(() => setIsLoading(false));
};
return (
<Tab.Panel className="w-full bg-ielts-speaking/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">
Gender
</label>
<Select
options={[
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
]}
value={{ value: gender, label: capitalize(gender) }}
onChange={(value) =>
value ? setGender(value.value as typeof gender) : null
}
disabled={isLoading}
/>
</div>
<div className="flex gap-4 items-end">
<button
onClick={generate}
disabled={isLoading}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
<button
onClick={generateVideo}
disabled={isLoading || !part}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate Video"
)}
</button>
</div>
{isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span
className={clsx(
"loading loading-infinity w-32 text-ielts-speaking"
)}
/>
<span className={clsx("font-bold text-2xl text-ielts-speaking")}>
Generating...
</span>
</div>
)}
{part && !isLoading && (
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-96">
<h3 className="text-xl font-semibold">
{!!part.first_topic && !!part.second_topic
? `${part.first_topic} & ${part.second_topic}`
: part.topic}
</h3>
{part.question && <span className="w-full">{part.question}</span>}
{part.questions && (
<div className="flex flex-col gap-1">
{part.questions.map((question, index) => (
<span className="w-full" key={index}>
- {question}
</span>
))}
</div>
)}
{part.prompts && (
<div className="flex flex-col gap-1">
<span className="font-medium">
You should talk about the following things:
</span>
{part.prompts.map((prompt, index) => (
<span className="w-full" key={index}>
- {prompt}
</span>
))}
</div>
)}
{part.result && (
<span className="font-bold mt-4">Video Generated: </span>
)}
{part.avatar && part.gender && (
<span>
<b>Instructor:</b> {part.avatar.name} -{" "}
{capitalize(part.avatar.gender)}
</span>
)}
{part.questions?.map((question, index) => (
<Input
key={index}
type="text"
label="Question"
name="question"
required
value={question}
onChange={
(value) =>
updatePart((part?: SpeakingPart) => {
if (part) {
return {
...part,
questions: part.questions?.map((x, xIndex) =>
xIndex === index ? value : x
),
} as SpeakingPart;
}
return (
<Tab.Panel className="w-full bg-ielts-speaking/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4">
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Gender</label>
<Select
options={[
{value: "male", label: "Male"},
{value: "female", label: "Female"},
]}
value={{value: gender, label: capitalize(gender)}}
onChange={(value) => (value ? setGender(value.value as typeof gender) : null)}
disabled={isLoading}
/>
</div>
<div className="flex gap-4 items-end">
<button
onClick={generate}
disabled={isLoading}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate"
)}
</button>
<button
onClick={generateVideo}
disabled={isLoading || !part}
data-tip="The passage is currently being generated"
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full rounded-xl h-[70px]",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
isLoading && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Generate Video"
)}
</button>
</div>
{isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span className={clsx("loading loading-infinity w-32 text-ielts-speaking")} />
<span className={clsx("font-bold text-2xl text-ielts-speaking")}>Generating...</span>
</div>
)}
{part && !isLoading && (
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide h-96">
<h3 className="text-xl font-semibold">
{!!part.first_topic && !!part.second_topic ? `${part.first_topic} & ${part.second_topic}` : part.topic}
</h3>
{part.question && <span className="w-full">{part.question}</span>}
{part.questions && (
<div className="flex flex-col gap-1">
{part.questions.map((question, index) => (
<span className="w-full" key={index}>
- {question}
</span>
))}
</div>
)}
{part.prompts && (
<div className="flex flex-col gap-1">
<span className="font-medium">You should talk about the following things:</span>
{part.prompts.map((prompt, index) => (
<span className="w-full" key={index}>
- {prompt}
</span>
))}
</div>
)}
{part.result && <span className="font-bold mt-4">Video Generated: </span>}
{part.avatar && part.gender && (
<span>
<b>Instructor:</b> {part.avatar.name} - {capitalize(part.avatar.gender)}
</span>
)}
{part.questions?.map((question, index) => (
<Input
key={index}
type="text"
label="Question"
name="question"
required
value={question}
onChange={(value) =>
updatePart((part?: SpeakingPart) => {
if (part) {
return {
...part,
questions: part.questions?.map((x, xIndex) => (xIndex === index ? value : x)),
} as SpeakingPart;
}
return part;
})
}
/>
))}
</div>
)}
</Tab.Panel>
);
return part;
})
}
/>
))}
</div>
)}
</Tab.Panel>
);
};
interface SpeakingPart {
prompts?: string[];
question?: string;
questions?: string[];
topic: string;
first_topic?: string;
second_topic?: string;
result?: SpeakingExercise | InteractiveSpeakingExercise;
gender?: "male" | "female";
avatar?: (typeof AVATARS)[number];
prompts?: string[];
question?: string;
questions?: string[];
topic: string;
first_topic?: string;
second_topic?: string;
result?: SpeakingExercise | InteractiveSpeakingExercise;
gender?: "male" | "female";
avatar?: (typeof AVATARS)[number];
}
const SpeakingGeneration = () => {
const [part1, setPart1] = useState<SpeakingPart>();
const [part2, setPart2] = useState<SpeakingPart>();
const [part3, setPart3] = useState<SpeakingPart>();
const [minTimer, setMinTimer] = useState(14);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<SpeakingExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(
sample(DIFFICULTIES)!
);
const [part1, setPart1] = useState<SpeakingPart>();
const [part2, setPart2] = useState<SpeakingPart>();
const [part3, setPart3] = useState<SpeakingPart>();
const [minTimer, setMinTimer] = useState(14);
const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<SpeakingExam>();
const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
useEffect(() => {
const parts = [part1, part2, part3].filter((x) => !!x);
setMinTimer(parts.length === 0 ? 5 : parts.length * 5);
}, [part1, part2, part3]);
useEffect(() => {
const parts = [part1, part2, part3].filter((x) => !!x);
setMinTimer(parts.length === 0 ? 5 : parts.length * 5);
}, [part1, part2, part3]);
const router = useRouter();
const router = useRouter();
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const setExams = useExamStore((state) => state.setExams);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const submitExam = () => {
if (!part1?.result && !part2?.result && !part3?.result)
return toast.error("Please generate at least one task!");
const submitExam = () => {
if (!part1?.result && !part2?.result && !part3?.result) return toast.error("Please generate at least one task!");
setIsLoading(true);
setIsLoading(true);
const genders = [part1?.gender, part2?.gender, part3?.gender].filter(
(x) => !!x
);
const genders = [part1?.gender, part2?.gender, part3?.gender].filter((x) => !!x);
const exercises = [part1?.result, part2?.result, part3?.result]
.filter((x) => !!x)
.map((x) => ({
...x,
first_title:
x?.type === "interactiveSpeaking" ? x.first_topic : undefined,
second_title:
x?.type === "interactiveSpeaking" ? x.second_topic : undefined,
}));
const exercises = [part1?.result, part2?.result, part3?.result]
.filter((x) => !!x)
.map((x) => ({
...x,
first_title: x?.type === "interactiveSpeaking" ? x.first_topic : undefined,
second_title: x?.type === "interactiveSpeaking" ? x.second_topic : undefined,
}));
const exam: SpeakingExam = {
id: v4(),
isDiagnostic: false,
exercises: exercises as (
| SpeakingExercise
| InteractiveSpeakingExercise
)[],
minTimer,
variant: minTimer >= 14 ? "full" : "partial",
module: "speaking",
instructorGender: genders.every((x) => x === "male")
? "male"
: genders.every((x) => x === "female")
? "female"
: "varied",
};
const exam: SpeakingExam = {
id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
isDiagnostic: false,
exercises: exercises as (SpeakingExercise | InteractiveSpeakingExercise)[],
minTimer,
variant: minTimer >= 14 ? "full" : "partial",
module: "speaking",
instructorGender: genders.every((x) => x === "male") ? "male" : genders.every((x) => x === "female") ? "female" : "varied",
};
axios
.post(`/api/exam/speaking`, exam)
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success(
"This new exam has been generated successfully! Check the ID in our browser's console."
);
setResultingExam(result.data);
axios
.post(`/api/exam/speaking`, exam)
.then((result) => {
playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success(`Generated Exam ID: ${result.data.id}`);
setResultingExam(result.data);
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setDifficulty(sample(DIFFICULTIES)!);
setMinTimer(14);
})
.catch((error) => {
console.log(error);
toast.error(
"Something went wrong while generating, please try again later."
);
})
.finally(() => setIsLoading(false));
};
setPart1(undefined);
setPart2(undefined);
setPart3(undefined);
setDifficulty(sample(DIFFICULTIES)!);
setMinTimer(14);
})
.catch((error) => {
console.log(error);
toast.error("Something went wrong while generating, please try again later.");
})
.finally(() => setIsLoading(false));
};
const loadExam = async (examId: string) => {
const exam = await getExamById("speaking", examId.trim());
if (!exam) {
toast.error(
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id",
}
);
const loadExam = async (examId: string) => {
const exam = await getExamById("speaking", examId.trim());
if (!exam) {
toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
toastId: "invalid-exam-id",
});
return;
}
return;
}
setExams([exam]);
setSelectedModules(["speaking"]);
setExams([exam]);
setSelectedModules(["speaking"]);
router.push("/exercises");
};
router.push("/exercises");
};
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">
Timer
</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 5 ? 5 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">
Difficulty
</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) =>
value ? setDifficulty(value.value as Difficulty) : null
}
value={{ value: difficulty, label: capitalize(difficulty) }}
disabled={!!part1 || !!part2 || !!part3}
/>
</div>
</div>
return (
<>
<div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim">Timer</label>
<Input
type="number"
name="minTimer"
onChange={(e) => setMinTimer(parseInt(e) < 5 ? 5 : parseInt(e))}
value={minTimer}
className="max-w-[300px]"
/>
</div>
<div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
<Select
options={DIFFICULTIES.map((x) => ({
value: x,
label: capitalize(x),
}))}
onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
value={{value: difficulty, label: capitalize(difficulty)}}
disabled={!!part1 || !!part2 || !!part3}
/>
</div>
</div>
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking"
)
}
>
Exercise 1 {part1 && part1.result && <BsCheck />}
</Tab>
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking"
)
}
>
Exercise 2 {part2 && part2.result && <BsCheck />}
</Tab>
<Tab
className={({ selected }) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking"
)
}
>
Interactive {part3 && part3.result && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{ part: part1, setPart: setPart1 },
{ part: part2, setPart: setPart2 },
{ part: part3, setPart: setPart3 },
].map(({ part, setPart }, index) => (
<PartTab
difficulty={difficulty}
part={part}
index={index + 1}
key={index}
setPart={setPart}
updatePart={setPart}
/>
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-speaking text-ielts-speaking w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking hover:text-white disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300"
)}
>
Perform Exam
</button>
)}
<button
disabled={
(!part1?.result && !part2?.result && !part3?.result) || isLoading
}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!part1 && !part2 && !part3 && "tooltip"
)}
>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
<Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-speaking/20 p-1">
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Exercise 1 {part1 && part1.result && <BsCheck />}
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Exercise 2 {part2 && part2.result && <BsCheck />}
</Tab>
<Tab
className={({selected}) =>
clsx(
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-speaking/70 flex gap-2 items-center justify-center",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-speaking focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out",
selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-speaking",
)
}>
Interactive {part3 && part3.result && <BsCheck />}
</Tab>
</Tab.List>
<Tab.Panels>
{[
{part: part1, setPart: setPart1},
{part: part2, setPart: setPart2},
{part: part3, setPart: setPart3},
].map(({part, setPart}, index) => (
<PartTab difficulty={difficulty} part={part} index={index + 1} key={index} setPart={setPart} updatePart={setPart} />
))}
</Tab.Panels>
</Tab.Group>
<div className="w-full flex justify-end gap-4">
{resultingExam && (
<button
disabled={isLoading}
onClick={() => loadExam(resultingExam.id)}
className={clsx(
"bg-white border border-ielts-speaking text-ielts-speaking w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking hover:text-white disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
)}>
Perform Exam
</button>
)}
<button
disabled={(!part1?.result && !part2?.result && !part3?.result) || isLoading}
data-tip="Please generate all three passages"
onClick={submitExam}
className={clsx(
"bg-ielts-speaking/70 border border-ielts-speaking text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-speaking disabled:bg-ielts-speaking/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300",
!part1 && !part2 && !part3 && "tooltip",
)}>
{isLoading ? (
<div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} />
</div>
) : (
"Submit"
)}
</button>
</div>
</>
);
};
export default SpeakingGeneration;

View File

@@ -9,6 +9,7 @@ import axios from "axios";
import clsx from "clsx";
import {capitalize, sample} from "lodash";
import {useRouter} from "next/router";
import {generate} from "random-words";
import {useEffect, useState} from "react";
import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import {toast} from "react-toastify";
@@ -151,7 +152,7 @@ const WritingGeneration = () => {
minTimer,
module: "writing",
exercises: [...(exercise1 ? [exercise1] : []), ...(exercise2 ? [exercise2] : [])],
id: v4(),
id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
variant: exercise1 && exercise2 ? "full" : "partial",
difficulty,
};
@@ -160,6 +161,7 @@ const WritingGeneration = () => {
.post(`/api/exam/writing`, exam)
.then((result) => {
console.log(`Generated Exam ID: ${result.data.id}`);
toast.success(`Generated Exam ID: ${result.data.id}`);
playSound("sent");
toast.success("This new exam has been generated successfully! Check the ID in our browser's console.");
setResultingExam(result.data);

View File

@@ -102,6 +102,7 @@ const generateExams = async (
async function POST(req: NextApiRequest, res: NextApiResponse) {
const {
examIDs,
selectedModules,
assignees,
// Generate multiple true would generate an unique exam for each user
@@ -111,6 +112,7 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
instructorGender,
...body
} = req.body as {
examIDs?: {id: string; module: Module}[];
selectedModules: Module[];
assignees: string[];
generateMultiple: Boolean;
@@ -121,7 +123,9 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
instructorGender?: InstructorGender;
};
const exams: ExamWithUser[] = await generateExams(generateMultiple, selectedModules, assignees, variant, instructorGender);
const exams: ExamWithUser[] = !!examIDs
? examIDs.flatMap((e) => assignees.map((a) => ({...e, assignee: a})))
: await generateExams(generateMultiple, selectedModules, assignees, variant, instructorGender);
if (exams.length === 0) {
res.status(400).json({ok: false, error: "No exams found for the selected modules"});

View File

@@ -47,7 +47,7 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
}
const {module} = req.query as {module: string};
const exam = {...req.body, module: module};
const exam = {...req.body, module: module, createdBy: req.session.user.id, createdAt: new Date().toISOString()};
await setDoc(doc(db, module, req.body.id), exam);
res.status(200).json(exam);

View File

@@ -0,0 +1,44 @@
import { sessionOptions } from "@/lib/session";
import {app} from "@/firebase";
import { collection, doc, getDoc, getDocs, getFirestore, query } from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";
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;
}
if (req.method === "GET") return get(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
try {
const { id } = req.query;
if (typeof id !== 'string') {
return res.status(400).json({ message: 'Invalid ID' });
}
const docRef = doc(db, "training", id);
const docSnap = await getDoc(docRef);
if (docSnap.exists()) {
res.status(200).json({
id: docSnap.id,
...docSnap.data(),
});
} else {
res.status(404).json({ message: 'Document not found' });
}
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ message: 'An unexpected error occurred' });
}
}

View File

@@ -0,0 +1,51 @@
import { sessionOptions } from "@/lib/session";
import axios from "axios";
import { app } from "@/firebase";
import { collection, doc, getDoc, getDocs, getFirestore, query } from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";
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;
}
if (req.method === "GET") return get(req, res);
if (req.method === "POST") return post(req, res);
}
async function post(req: NextApiRequest, res: NextApiResponse) {
try {
const response = await axios.post(`${process.env.BACKEND_URL}/training_content`, req.body, {
headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`,
},
});
res.status(response.status).json(response.data);
} catch (error) {
res.status(500).json({ message: 'An unexpected error occurred' });
}
}
async function get(req: NextApiRequest, res: NextApiResponse) {
try {
const q = query(collection(db, "training"));
const snapshot = await getDocs(q);
res.status(200).json(
snapshot.docs.map((doc) => ({
id: doc.id,
...doc.data(),
}))
);
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ message: 'An unexpected error occurred' });
}
}

View File

@@ -0,0 +1,44 @@
import { sessionOptions } from "@/lib/session";
import { app } from "@/firebase";
import { collection, doc, documentId, getDoc, getDocs, getFirestore, query, where } from "firebase/firestore";
import { withIronSessionApiRoute } from "iron-session/next";
import { NextApiRequest, NextApiResponse } from "next";
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;
}
if (req.method === "GET") return get(req, res);
}
async function get(req: NextApiRequest, res: NextApiResponse) {
try {
const { ids } = req.query;
if (!ids || !Array.isArray(ids)) {
return res.status(400).json({ message: 'Invalid or missing ids!' });
}
const walkthroughCollection = collection(db, 'walkthrough');
const q = query(walkthroughCollection, where(documentId(), 'in', ids));
const querySnapshot = await getDocs(q);
const documents = querySnapshot.docs.map(doc => ({
id: doc.id,
...doc.data()
}));
res.status(200).json(documents);
} catch (error) {
console.error('Error fetching data:', error);
res.status(500).json({ message: 'An unexpected error occurred' });
}
}

View File

@@ -1,35 +1,30 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session";
import {Stat, User} from "@/interfaces/user";
import {useEffect, useState} from "react";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Stat, User } from "@/interfaces/user";
import { useEffect, useRef, useState } from "react";
import useStats from "@/hooks/useStats";
import {convertToUserSolutions, groupByDate} from "@/utils/stats";
import { groupByDate } from "@/utils/stats";
import moment from "moment";
import useUsers from "@/hooks/useUsers";
import useExamStore from "@/stores/examStore";
import {Module} from "@/interfaces";
import {ToastContainer} from "react-toastify";
import {useRouter} from "next/router";
import {uniqBy} from "lodash";
import {getExamById} from "@/utils/exams";
import {sortByModule} from "@/utils/moduleUtils";
import { ToastContainer } from "react-toastify";
import { useRouter } from "next/router";
import Layout from "@/components/High/Layout";
import clsx from "clsx";
import {calculateBandScore} from "@/utils/score";
import {BsBook, BsClipboard, BsClock, BsHeadphones, BsMegaphone, BsPen, BsPersonDash, BsPersonFillX, BsXCircle} from "react-icons/bs";
import Select from "@/components/Low/Select";
import useGroups from "@/hooks/useGroups";
import {shouldRedirectHome} from "@/utils/navigation.disabled";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import useAssignments from "@/hooks/useAssignments";
import {uuidv4} from "@firebase/util";
import {usePDFDownload} from "@/hooks/usePDFDownload";
import { uuidv4 } from "@firebase/util";
import { usePDFDownload } from "@/hooks/usePDFDownload";
import useRecordStore from "@/stores/recordStore";
import ai_usage from "@/utils/ai.detection";
import useTrainingContentStore from "@/stores/trainingContentStore";
import StatsGridItem from "@/components/StatGridItem";
export const getServerSideProps = withIronSessionSsr(({req, res}) => {
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
const user = req.session.user;
if (!user || !user.isVerified) {
@@ -51,7 +46,7 @@ export const getServerSideProps = withIronSessionSsr(({req, res}) => {
}
return {
props: {user: req.session.user},
props: { user: req.session.user },
};
}, sessionOptions);
@@ -60,16 +55,16 @@ const defaultSelectableCorporate = {
label: "All",
};
export default function History({user}: {user: User}) {
const [statsUserId, setStatsUserId] = useRecordStore((state) => [state.selectedUser, state.setSelectedUser]);
export default function History({ user }: { user: User }) {
const [statsUserId, setStatsUserId, training, setTraining] = useRecordStore((state) => [state.selectedUser, state.setSelectedUser, state.training, state.setTraining]);
// const [statsUserId, setStatsUserId] = useState<string | undefined>(user.id);
const [groupedStats, setGroupedStats] = useState<{[key: string]: Stat[]}>();
const [groupedStats, setGroupedStats] = useState<{ [key: string]: Stat[] }>();
const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
const {assignments} = useAssignments({});
const { assignments } = useAssignments({});
const {users} = useUsers();
const {stats, isLoading: isStatsLoading} = useStats(statsUserId);
const {groups: allGroups} = useGroups();
const { users } = useUsers();
const { stats, isLoading: isStatsLoading } = useStats(statsUserId);
const { groups: allGroups } = useGroups();
const groups = allGroups.filter((x) => x.admin === user.id);
@@ -79,8 +74,8 @@ export default function History({user}: {user: User}) {
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const setInactivity = useExamStore((state) => state.setInactivity);
const setTimeSpent = useExamStore((state) => state.setTimeSpent);
const router = useRouter();
const renderPdfIcon = usePDFDownload("stats");
const router = useRouter();
useEffect(() => {
if (stats && !isStatsLoading) {
@@ -109,22 +104,21 @@ export default function History({user}: {user: User}) {
setFilter((prev) => (prev === value ? undefined : value));
};
const filterStatsByDate = (stats: {[key: string]: Stat[]}) => {
const filterStatsByDate = (stats: { [key: string]: Stat[] }) => {
if (filter && filter !== "assignments") {
const filterDate = moment()
.subtract({[filter as string]: 1})
.subtract({ [filter as string]: 1 })
.format("x");
const filteredStats: {[key: string]: Stat[]} = {};
const filteredStats: { [key: string]: Stat[] } = {};
Object.keys(stats).forEach((timestamp) => {
if (timestamp >= filterDate) filteredStats[timestamp] = stats[timestamp];
});
return filteredStats;
}
if (filter && filter === "assignments") {
const filteredStats: {[key: string]: Stat[]} = {};
const filteredStats: { [key: string]: Stat[] } = {};
Object.keys(stats).forEach((timestamp) => {
if (stats[timestamp].map((s) => s.assignment === undefined).includes(false))
@@ -137,211 +131,62 @@ export default function History({user}: {user: User}) {
return stats;
};
const formatTimestamp = (timestamp: string) => {
const date = moment(parseInt(timestamp));
const formatter = "YYYY/MM/DD - HH:mm";
const MAX_TRAINING_EXAMS = 10;
const [selectedTrainingExams, setSelectedTrainingExams] = useState<string[]>([]);
const setTrainingStats = useTrainingContentStore((state) => state.setStats);
return date.format(formatter);
};
useEffect(() => {
const handleRouteChange = (url: string) => {
setTraining(false)
}
router.events.on('routeChangeStart', handleRouteChange)
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [router.events, setTraining])
const aggregateScoresByModule = (stats: Stat[]): {module: Module; total: number; missing: number; correct: number}[] => {
const scores: {
[key in Module]: {total: number; missing: number; correct: number};
} = {
reading: {
total: 0,
correct: 0,
missing: 0,
},
listening: {
total: 0,
correct: 0,
missing: 0,
},
writing: {
total: 0,
correct: 0,
missing: 0,
},
speaking: {
total: 0,
correct: 0,
missing: 0,
},
level: {
total: 0,
correct: 0,
missing: 0,
},
};
const handleTrainingContentSubmission = () => {
if (groupedStats) {
const groupedStatsByDate = filterStatsByDate(groupedStats);
const allStats = Object.keys(groupedStatsByDate);
const selectedStats = selectedTrainingExams.reduce<Record<string, Stat[]>>((accumulator, moduleAndTimestamp) => {
const timestamp = moduleAndTimestamp.split("-")[1];
if (allStats.includes(timestamp) && !accumulator.hasOwnProperty(timestamp)) {
accumulator[timestamp] = groupedStatsByDate[timestamp];
}
return accumulator;
}, {});
setTrainingStats(Object.values(selectedStats).flat())
router.push("/training");
}
}
stats.forEach((x) => {
scores[x.module!] = {
total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing,
};
});
return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0)
.map((x) => ({module: x as Module, ...scores[x as Module]}));
};
const customContent = (timestamp: string) => {
if (!groupedStats) return <></>;
const dateStats = groupedStats[timestamp];
const correct = dateStats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0);
const aggregatedScores = aggregateScoresByModule(dateStats).filter((x) => x.total > 0);
const assignmentID = dateStats.reduce((_, current) => current.assignment as any, "");
const assignment = assignments.find((a) => a.id === assignmentID);
const isDisabled = dateStats.some((x) => x.isDisabled);
const aiUsage = Math.round(ai_usage(dateStats) * 100);
const aggregatedLevels = aggregatedScores.map((x) => ({
module: x.module,
level: calculateBandScore(x.correct, x.total, x.module, user.focus),
}));
const {timeSpent, inactivity, session} = dateStats[0];
const selectExam = () => {
const examPromises = uniqBy(dateStats, "exam").map((stat) => {
console.log({stat});
return getExamById(stat.module, stat.exam);
});
if (isDisabled) return;
Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) {
if (!!timeSpent) setTimeSpent(timeSpent);
if (!!inactivity) setInactivity(inactivity);
setUserSolutions(convertToUserSolutions(dateStats));
setShowSolutions(true);
setExams(exams.map((x) => x!).sort(sortByModule));
setSelectedModules(
exams
.map((x) => x!)
.sort(sortByModule)
.map((x) => x!.module),
);
router.push("/exercises");
}
});
};
const textColor = clsx(
correct / total >= 0.7 && "text-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
correct / total < 0.3 && "text-mti-rose",
);
const content = (
<>
<div className="w-full flex justify-between -md:items-center 2xl:items-center">
<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
<span className="font-medium">{formatTimestamp(timestamp)}</span>
<div className="flex items-center gap-2">
{!!timeSpent && (
<span className="text-sm flex gap-2 items-center tooltip" data-tip="Time Spent">
<BsClock /> {Math.floor(timeSpent / 60)} minutes
</span>
)}
{!!inactivity && (
<span className="text-sm flex gap-2 items-center tooltip" data-tip="Inactivity">
<BsXCircle /> {Math.floor(inactivity / 60)} minutes
</span>
)}
</div>
</div>
<div className="flex flex-col gap-2">
<div className="flex flex-row gap-2">
<span className={textColor}>
Level{" "}
{(aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length).toFixed(1)}
</span>
{renderPdfIcon(session, textColor, textColor)}
</div>
{aiUsage >= 50 && user.type !== "student" && (
<div className={clsx(
"ml-auto border px-1 rounded w-fit mr-1",
{
'bg-orange-100 border-orange-400 text-orange-700': aiUsage < 80,
'bg-red-100 border-red-400 text-red-700': aiUsage >= 80,
}
)}>
<span className="text-xs">AI Usage</span>
</div>
)}
</div>
</div>
<div className="w-full flex flex-col gap-1">
<div className="grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2">
{aggregatedLevels.map(({module, level}) => (
<div
key={module}
className={clsx(
"flex gap-2 items-center w-fit text-white -md:px-4 xl:px-4 md:px-2 py-2 rounded-xl",
module === "reading" && "bg-ielts-reading",
module === "listening" && "bg-ielts-listening",
module === "writing" && "bg-ielts-writing",
module === "speaking" && "bg-ielts-speaking",
module === "level" && "bg-ielts-level",
)}>
{module === "reading" && <BsBook className="w-4 h-4" />}
{module === "listening" && <BsHeadphones className="w-4 h-4" />}
{module === "writing" && <BsPen className="w-4 h-4" />}
{module === "speaking" && <BsMegaphone className="w-4 h-4" />}
{module === "level" && <BsClipboard className="w-4 h-4" />}
<span className="text-sm">{level.toFixed(1)}</span>
</div>
))}
</div>
{assignment && (
<span className="font-light text-sm">
Assignment: {assignment.name}, Teacher: {users.find((u) => u.id === assignment.assigner)?.name}
</span>
)}
</div>
</>
);
return (
<>
<div
key={uuidv4()}
className={clsx(
"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden",
isDisabled && "grayscale tooltip",
correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose",
)}
onClick={selectExam}
data-tip="This exam is still being evaluated..."
role="button">
{content}
</div>
<div
key={uuidv4()}
className={clsx(
"flex flex-col gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:tooltip md:hidden",
correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose",
)}
data-tip="Your screen size is too small to view previous exams."
role="button">
{content}
</div>
</>
<StatsGridItem
key={uuidv4()}
stats={dateStats}
timestamp={timestamp}
user={user}
assignments={assignments}
users={users}
training={training}
selectedTrainingExams={selectedTrainingExams}
setSelectedTrainingExams={setSelectedTrainingExams}
maxTrainingExams={MAX_TRAINING_EXAMS}
setExams={setExams}
setShowSolutions={setShowSolutions}
setUserSolutions={setUserSolutions}
setSelectedModules={setSelectedModules}
setInactivity={setInactivity}
setTimeSpent={setTimeSpent}
renderPdfIcon={renderPdfIcon}
/>
);
};
@@ -395,13 +240,13 @@ export default function History({user}: {user: User}) {
const selectedUser = getSelectedUser();
const selectedUserSelectValue = selectedUser
? {
value: selectedUser.id,
label: `${selectedUser.name} - ${selectedUser.email}`,
}
value: selectedUser.id,
label: `${selectedUser.name} - ${selectedUser.email}`,
}
: {
value: "",
label: "",
};
value: "",
label: "",
};
return (
<>
<Head>
@@ -418,7 +263,7 @@ export default function History({user}: {user: User}) {
<Layout user={user}>
<div className="w-full flex -xl:flex-col -xl:gap-4 justify-between items-center">
<div className="xl:w-3/4">
{(user.type === "developer" || user.type === "admin") && (
{(user.type === "developer" || user.type === "admin") && !training && (
<>
<label className="font-normal text-base text-mti-gray-dim">Corporate</label>
@@ -427,7 +272,7 @@ export default function History({user}: {user: User}) {
value={selectableCorporates.find((x) => x.value === selectedCorporate)}
onChange={(value) => setSelectedCorporate(value?.value || "")}
styles={{
menuPortal: (base) => ({...base, zIndex: 9999}),
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
@@ -442,9 +287,9 @@ export default function History({user}: {user: User}) {
label: `${x.name} - ${x.email}`,
}))}
value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value)}
onChange={(value) => setStatsUserId(value?.value!)}
styles={{
menuPortal: (base) => ({...base, zIndex: 9999}),
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
@@ -454,7 +299,7 @@ export default function History({user}: {user: User}) {
/>
</>
)}
{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && (
{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && !training && (
<>
<label className="font-normal text-base text-mti-gray-dim">User</label>
@@ -466,9 +311,9 @@ export default function History({user}: {user: User}) {
label: `${x.name} - ${x.email}`,
}))}
value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value)}
onChange={(value) => setStatsUserId(value?.value!)}
styles={{
menuPortal: (base) => ({...base, zIndex: 9999}),
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
@@ -478,6 +323,21 @@ export default function History({user}: {user: User}) {
/>
</>
)}
{(training && (
<div className="flex flex-row">
<div className="font-semibold text-2xl mr-4">Select up to 10 exercises
{`(${selectedTrainingExams.length}/${MAX_TRAINING_EXAMS})`}</div>
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light ml-4 disabled:cursor-not-allowed",
"transition duration-300 ease-in-out",
)}
disabled={selectedTrainingExams.length == 0}
onClick={handleTrainingContentSubmission}>
Submit
</button>
</div>
))}
</div>
<div className="flex gap-4 w-full justify-center xl:justify-end">
<button
@@ -528,6 +388,11 @@ export default function History({user}: {user: User}) {
{groupedStats && Object.keys(groupedStats).length === 0 && !isStatsLoading && (
<span className="font-semibold ml-1">No record to display...</span>
)}
{isStatsLoading && (
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
<span className="loading loading-infinity w-32 bg-mti-green-light" />
</div>
)}
</Layout>
)}
</>

View File

@@ -70,27 +70,33 @@ const SOURCE_OPTIONS = [
type CustomStatus = TicketStatus | "all" | "pending";
const STATUS_OPTIONS = [{
label: 'Pending',
value: 'pending',
filter: (x: Ticket) => x.status !== 'completed',
}, {
label: 'All',
value: 'all',
filter: (x: Ticket) => true,
}, {
label: 'Completed',
value: 'completed',
filter: (x: Ticket) => x.status === 'completed',
}, {
label: 'In Progress',
value: 'in-progress',
filter: (x: Ticket) => x.status === 'in-progress',
}, {
label: 'Submitted',
value: 'submitted',
filter: (x: Ticket) => x.status === 'submitted',
}]
const STATUS_OPTIONS = [
{
label: "Pending",
value: "pending",
filter: (x: Ticket) => x.status !== "completed",
},
{
label: "All",
value: "all",
filter: (x: Ticket) => true,
},
{
label: "Completed",
value: "completed",
filter: (x: Ticket) => x.status === "completed",
},
{
label: "In Progress",
value: "in-progress",
filter: (x: Ticket) => x.status === "in-progress",
},
{
label: "Submitted",
value: "submitted",
filter: (x: Ticket) => x.status === "submitted",
},
];
export default function Tickets() {
const [filteredTickets, setFilteredTickets] = useState<Ticket[]>([]);
@@ -101,7 +107,7 @@ export default function Tickets() {
const [dateSorting, setDateSorting] = useState<"asc" | "desc">("desc");
const [typeFilter, setTypeFilter] = useState<TicketType>();
const [statusFilter, setStatusFilter] = useState<CustomStatus>('pending');
const [statusFilter, setStatusFilter] = useState<CustomStatus>("pending");
const {user} = useUser({redirectTo: "/login"});
const {users} = useUsers();
@@ -116,7 +122,7 @@ export default function Tickets() {
if (user?.type === "agent") filters.push((x: Ticket) => x.assignedTo === user.id);
if (typeFilter) filters.push((x: Ticket) => x.type === typeFilter);
if (statusFilter) {
const filter = STATUS_OPTIONS.find(x => x.value === statusFilter)?.filter;
const filter = STATUS_OPTIONS.find((x) => x.value === statusFilter)?.filter;
if (filter) filters.push(filter);
}
if (assigneeFilter) filters.push((x: Ticket) => x.assignedTo === assigneeFilter);
@@ -242,9 +248,7 @@ export default function Tickets() {
<label className="text-mti-gray-dim text-base font-normal">Status</label>
<Select
options={STATUS_OPTIONS}
value={
STATUS_OPTIONS.find((x) => x.value === statusFilter)
}
value={STATUS_OPTIONS.find((x) => x.value === statusFilter)}
onChange={(value) => setStatusFilter((value?.value as TicketStatus) ?? undefined)}
isClearable
placeholder="Status..."
@@ -278,7 +282,7 @@ export default function Tickets() {
disabled={user.type === "agent"}
value={getAssigneeValue()}
onChange={(value) =>
value ? setAssigneeFilter(value.value === "me" ? user.id : value.value) : setAssigneeFilter(undefined)
value ? setAssigneeFilter(value.value === "me" ? user.id : value.value!) : setAssigneeFilter(undefined)
}
placeholder="Assignee..."
isClearable

View File

@@ -0,0 +1,357 @@
import { useEffect, useState } from 'react';
import { useRouter } from 'next/router';
import axios from 'axios';
import { Tab } from "@headlessui/react";
import { AiOutlineFileSearch } from "react-icons/ai";
import { MdOutlinePlaylistAddCheckCircle, MdOutlineSelfImprovement } from "react-icons/md";
import { BsChatLeftDots } from "react-icons/bs";
import Button from "@/components/Low/Button";
import clsx from "clsx";
import Exercise from "@/training/Exercise";
import TrainingScore from "@/training/TrainingScore";
import { ITrainingContent, ITrainingTip } from "@/training/TrainingInterfaces";
import { Stat, User } from '@/interfaces/user';
import Head from "next/head";
import Layout from "@/components/High/Layout";
import { ToastContainer } from 'react-toastify';
import { withIronSessionSsr } from "iron-session/next";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { sessionOptions } from "@/lib/session";
import qs from 'qs';
import StatsGridItem from '@/components/StatGridItem';
import useExamStore from "@/stores/examStore";
import { usePDFDownload } from "@/hooks/usePDFDownload";
import useAssignments from '@/hooks/useAssignments';
import useUsers from '@/hooks/useUsers';
import Dropdown from "@/components/Dropdown";
import InfiniteCarousel from '@/components/InfiniteCarousel';
import { LuExternalLink } from "react-icons/lu";
import { uniqBy } from 'lodash';
import { getExamById } from '@/utils/exams';
import { convertToUserSolutions } from '@/utils/stats';
import { sortByModule } from '@/utils/moduleUtils';
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
const user = req.session.user;
if (!user || !user.isVerified) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (shouldRedirectHome(user)) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: { user: req.session.user },
};
}, sessionOptions);
const TrainingContent: React.FC<{ user: User }> = ({ user }) => {
// Record stuff
const setExams = useExamStore((state) => state.setExams);
const setShowSolutions = useExamStore((state) => state.setShowSolutions);
const setUserSolutions = useExamStore((state) => state.setUserSolutions);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const setInactivity = useExamStore((state) => state.setInactivity);
const setTimeSpent = useExamStore((state) => state.setTimeSpent);
const renderPdfIcon = usePDFDownload("stats");
const [trainingContent, setTrainingContent] = useState<ITrainingContent | null>(null);
const [loading, setLoading] = useState(true);
const [trainingTips, setTrainingTips] = useState<ITrainingTip[]>([]);
const [currentTipIndex, setCurrentTipIndex] = useState(0);
const { assignments } = useAssignments({});
const { users } = useUsers();
const router = useRouter();
const { id } = router.query;
useEffect(() => {
const fetchTrainingContent = async () => {
if (!id || typeof id !== 'string') return;
try {
setLoading(true);
const response = await axios.get<ITrainingContent>(`/api/training/${id}`);
const trainingContent = response.data;
const withExamsStats = {
...trainingContent,
exams: await Promise.all(trainingContent.exams.map(async (exam) => {
const stats = await Promise.all(exam.stat_ids.map(async (statId) => {
const statResponse = await axios.get<Stat>(`/api/stats/${statId}`);
return statResponse.data;
}));
return { ...exam, stats };
}))
};
const tips = await axios.get<ITrainingTip[]>('/api/training/walkthrough', {
params: { ids: trainingContent.tip_ids },
paramsSerializer: params => qs.stringify(params, { arrayFormat: 'repeat' })
});
setTrainingTips(tips.data);
setTrainingContent(withExamsStats);
} catch (error) {
router.push('/training');
} finally {
setLoading(false);
}
};
fetchTrainingContent();
}, [id]);
const handleNext = () => {
setCurrentTipIndex((prevIndex) => (prevIndex + 1));
};
const handlePrevious = () => {
setCurrentTipIndex((prevIndex) => (prevIndex - 1));
};
const goToExam = (examNumber: number) => {
const stats = trainingContent?.exams[examNumber].stats!;
const examPromises = uniqBy(stats, "exam").map((stat) => {
return getExamById(stat.module, stat.exam);
});
const { timeSpent, inactivity } = stats[0];
Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) {
if (!!timeSpent) setTimeSpent(timeSpent);
if (!!inactivity) setInactivity(inactivity);
setUserSolutions(convertToUserSolutions(stats));
setShowSolutions(true);
setExams(exams.map((x) => x!).sort(sortByModule));
setSelectedModules(
exams
.map((x) => x!)
.sort(sortByModule)
.map((x) => x!.module),
);
router.push("/exercises");
}
});
}
return (
<>
<Head>
<title>Training | EnCoach</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>
<ToastContainer />
<Layout user={user}>
{loading ? (
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
<span className="loading loading-infinity w-32 bg-mti-green-light" />
</div>
) : (trainingContent && (
<div className="flex flex-col gap-8">
<div className="flex flex-row items-center">
<span className="bg-gray-200 text-gray-800 px-3 py-0.5 rounded-full font-semibold text-lg mr-2">{trainingContent.exams.length}</span>
<span>Exams Selected</span>
</div>
<div className='h-[15vh] mb-4'>
<InfiniteCarousel height="150px"
overlay={
<LuExternalLink size={20} />
}
overlayFunc={goToExam}
overlayClassName='bottom-6 right-5 cursor-pointer'
>
{trainingContent.exams.map((exam, examIndex) => (
<StatsGridItem
key={`exam-${examIndex}`}
width='380px'
height='150px'
examNumber={examIndex + 1}
stats={exam.stats || []}
timestamp={exam.date}
user={user}
assignments={assignments}
users={users}
setExams={setExams}
setShowSolutions={setShowSolutions}
setUserSolutions={setUserSolutions}
setSelectedModules={setSelectedModules}
setInactivity={setInactivity}
setTimeSpent={setTimeSpent}
renderPdfIcon={renderPdfIcon}
/>
))}
</InfiniteCarousel>
</div>
<div className='flex flex-col'>
<div className='flex flex-row gap-10 -md:flex-col h-full'>
<div className="flex flex-col rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full max-h-full">
<div className="flex flex-row items-center mb-6 gap-1">
<MdOutlinePlaylistAddCheckCircle color={"#40A1EA"} size={26} />
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>General Evaluation</h2>
</div>
<TrainingScore
trainingContent={trainingContent}
gridView={false}
/>
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
<div className="flex flex-row gap-2 items-center mb-6">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<mask id="mask0_112_168" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
<rect width="24" height="24" fill="#D9D9D9" />
</mask>
<g mask="url(#mask0_112_168)">
<path d="M4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V7H4V19H19V21H4ZM8 17C7.45 17 6.97917 16.8042 6.5875 16.4125C6.19583 16.0208 6 15.55 6 15V3H23V15C23 15.55 22.8042 16.0208 22.4125 16.4125C22.0208 16.8042 21.55 17 21 17H8ZM8 15H21V5H8V15ZM10 12H14V7H10V12ZM15 12H19V10H15V12ZM15 9H19V7H15V9Z" fill="#53B2F9" />
</g>
</svg>
<h3 className="text-xl font-semibold text-[#40A1EA]">Performance Breakdown by Exam:</h3>
</div>
<ul className='overflow-auto scrollbar-hide flex-grow'>
{trainingContent.exams.flatMap((exam, index) => (
<li key={index} className="flex flex-col mb-2 bg-[#22E1B30F] p-4 rounded-xl border">
<div className="flex flex-row font-semibold border-b-2 border-[#D9D9D929] text-[#22E1B3] mb-2">
<div className='flex items-center border-r-2 border-[#D9D9D929] pr-2'>
<span className='mr-1'>Exam</span>
<span className="font-semibold bg-gray-200 text-gray-800 px-2 rounded-full text-sm">{index + 1}</span>
</div>
<span className="pl-2">{exam.score}%</span>
</div>
<div className="flex flex-row items-center gap-2">
<BsChatLeftDots size={16} />
<p className="text-sm">{exam.performance_comment}</p>
</div>
</li>
))}
</ul>
</div>
<div className="flex flex-col rounded-3xl p-6 w-1/2 shadow-training-inset -md:w-full">
<div className='flex flex-col'>
<div className="flex flex-row items-center mb-4 gap-1">
<AiOutlineFileSearch color="#40A1EA" size={24} />
<h3 className="text-xl font-semibold text-[#40A1EA]">Identified Weak Areas</h3>
</div>
<Tab.Group>
<div className="flex flex-col gap-4">
<Tab.List>
<div className="flex flex-row gap-6 overflow-x-auto pb-1 training-scrollbar">
{trainingContent.weak_areas.map((x, index) => (
<Tab
key={index}
className={({ selected }) =>
clsx(
'text-[#53B2F9] pb-2 border-b-2',
'focus:outline-none',
selected ? 'border-[#1B78BE]' : 'border-[#1B78BE0F]'
)
}
>
{x.area}
</Tab>
))}
</div>
</Tab.List>
<Tab.Panels>
{trainingContent.weak_areas.map((x, index) => (
<Tab.Panel
key={index}
className="p-3 bg-[#FBFBFB] rounded-lg border border-[#0000000F]"
>
<p>{x.comment}</p>
</Tab.Panel>
))}
</Tab.Panels>
</div>
</Tab.Group>
</div>
<div className="w-full h-px bg-[#D9D9D929] my-6"></div>
<div className="flex flex-row items-center mb-4 gap-1">
<MdOutlineSelfImprovement color={"#40A1EA"} size={24} />
<h2 className={`text-xl font-semibold text-[#40A1EA]`}>Subjects that Need Improvement</h2>
</div>
<div className="flex flex-grow bg-[#FBFBFB] border rounded-xl p-4">
<div className='flex flex-col'>
<div className="flex flex-row items-center gap-1 mb-4">
<div className="flex items-center justify-center w-[48px] h-[48px]">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<mask id="mask0_112_445" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
<rect width="24" height="24" fill="#D9D9D9" />
</mask>
<g mask="url(#mask0_112_445)">
<path d="M6 17H11V15H6V17ZM16 17H18V15H16V17ZM6 13H11V11H6V13ZM16 13H18V7H16V13ZM6 9H11V7H6V9ZM4 21C3.45 21 2.97917 20.8042 2.5875 20.4125C2.19583 20.0208 2 19.55 2 19V5C2 4.45 2.19583 3.97917 2.5875 3.5875C2.97917 3.19583 3.45 3 4 3H20C20.55 3 21.0208 3.19583 21.4125 3.5875C21.8042 3.97917 22 4.45 22 5V19C22 19.55 21.8042 20.0208 21.4125 20.4125C21.0208 20.8042 20.55 21 20 21H4ZM4 19H20V5H4V19Z" fill="#1C1B1F" />
</g>
</svg>
</div>
<h3 className="text-lg font-semibold">Detailed Breakdown</h3>
</div>
<ul className="flex flex-col flex-grow space-y-4 pb-2 overflow-y-auto scrollbar-hide">
{trainingContent.exams.map((exam, index) => (
<li key={index} className="border rounded-lg bg-white">
<Dropdown title={
<div className='flex flex-row items-center'>
<span className="mr-1">Exam</span>
<span className="font-semibold bg-gray-200 text-gray-800 px-2 rounded-full text-sm mt-0.5">{index + 1}</span>
</div>
} open={index == 0}>
<span>{exam.detailed_summary}</span>
</Dropdown>
</li>
))}
</ul>
</div>
</div>
</div>
</div>
</div>
<div className="flex -md:hidden">
<div className="rounded-3xl p-6 shadow-training-inset w-full">
<div className="flex flex-col p-10">
<Exercise key={currentTipIndex} {...trainingTips[currentTipIndex]} />
</div>
<div className="self-end flex justify-between w-full gap-8 bottom-8 left-0 px-8">
<Button
color="purple"
variant="outline"
onClick={handlePrevious}
disabled={currentTipIndex == 0}
className="max-w-[200px] self-end w-full">
Previous
</Button>
<Button
color="purple"
disabled={currentTipIndex == (trainingTips.length - 1)}
onClick={handleNext}
className="max-w-[200px] self-end w-full">
Next
</Button>
</div>
</div>
</div>
</div>
))}
</Layout>
</>
);
}
export default TrainingContent;

View File

@@ -0,0 +1,405 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { Stat, User } from "@/interfaces/user";
import { ToastContainer } from "react-toastify";
import Layout from "@/components/High/Layout";
import { shouldRedirectHome } from "@/utils/navigation.disabled";
import { use, useEffect, useState } from "react";
import clsx from "clsx";
import { FaPlus } from "react-icons/fa";
import useRecordStore from "@/stores/recordStore";
import router from "next/router";
import useTrainingContentStore from "@/stores/trainingContentStore";
import axios from "axios";
import Select from "@/components/Low/Select";
import useUsers from "@/hooks/useUsers";
import useGroups from "@/hooks/useGroups";
import { ITrainingContent } from "@/training/TrainingInterfaces";
import moment from "moment";
import { uuidv4 } from "@firebase/util";
import TrainingScore from "@/training/TrainingScore";
import ModuleBadge from "@/components/ModuleBadge";
export const getServerSideProps = withIronSessionSsr(({ req, res }) => {
const user = req.session.user;
if (!user || !user.isVerified) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (shouldRedirectHome(user)) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
}
return {
props: { user: req.session.user },
};
}, sessionOptions);
const defaultSelectableCorporate = {
value: "",
label: "All",
};
const Training: React.FC<{ user: User }> = ({ user }) => {
// Record stuff
const { users } = useUsers();
const [selectedCorporate, setSelectedCorporate] = useState<string>(defaultSelectableCorporate.value);
const [statsUserId, setStatsUserId, setRecordTraining] = useRecordStore((state) => [state.selectedUser, state.setSelectedUser, state.setTraining]);
const { groups: allGroups } = useGroups();
const groups = allGroups.filter((x) => x.admin === user.id);
const [filter, setFilter] = useState<"months" | "weeks" | "days">();
const toggleFilter = (value: "months" | "weeks" | "days") => {
setFilter((prev) => (prev === value ? undefined : value));
};
const [stats, setTrainingStats] = useTrainingContentStore((state) => [state.stats, state.setStats]);
const [trainingContent, setTrainingContent] = useState<ITrainingContent[]>([]);
const [isNewContentLoading, setIsNewContentLoading] = useState(stats.length != 0);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [groupedByTrainingContent, setGroupedByTrainingContent] = useState<{ [key: string]: ITrainingContent }>();
useEffect(() => {
const handleRouteChange = (url: string) => {
setTrainingStats([])
}
router.events.on('routeChangeStart', handleRouteChange)
return () => {
router.events.off('routeChangeStart', handleRouteChange)
}
}, [router.events, setTrainingStats])
useEffect(() => {
const postStats = async () => {
try {
const response = await axios.post<{ id: string }>(`/api/training`, stats);
return response.data.id;
} catch (error) {
setIsNewContentLoading(false);
}
};
if (isNewContentLoading) {
postStats().then(id => {
setTrainingStats([]);
if (id) {
router.push(`/training/${id}`)
}
});
}
}, [isNewContentLoading])
useEffect(() => {
const loadTrainingContent = async () => {
try {
const response = await axios.get<ITrainingContent[]>('/api/training');
setTrainingContent(response.data);
setIsLoading(false);
} catch (error) {
setTrainingContent([]);
setIsLoading(false);
}
};
loadTrainingContent();
}, []);
const handleNewTrainingContent = () => {
setRecordTraining(true);
router.push('/record')
}
const filterTrainingContentByDate = (trainingContent: { [key: string]: ITrainingContent }) => {
if (filter) {
const filterDate = moment()
.subtract({ [filter as string]: 1 })
.format("x");
const filteredTrainingContent: { [key: string]: ITrainingContent } = {};
Object.keys(trainingContent).forEach((timestamp) => {
if (timestamp >= filterDate) filteredTrainingContent[timestamp] = trainingContent[timestamp];
});
return filteredTrainingContent;
}
return trainingContent;
};
useEffect(() => {
if (trainingContent.length > 0) {
const grouped = trainingContent.reduce((acc, content) => {
acc[content.created_at] = content;
return acc;
}, {} as { [key: number]: ITrainingContent });
setGroupedByTrainingContent(grouped);
}
}, [trainingContent])
// Record Stuff
const selectableCorporates = [
defaultSelectableCorporate,
...users
.filter((x) => x.type === "corporate")
.map((x) => ({
value: x.id,
label: `${x.name} - ${x.email}`,
})),
];
const getUsersList = (): User[] => {
if (selectedCorporate) {
// get groups for that corporate
const selectedCorporateGroups = allGroups.filter((x) => x.admin === selectedCorporate);
// get the teacher ids for that group
const selectedCorporateGroupsParticipants = selectedCorporateGroups.flatMap((x) => x.participants);
// // search for groups for these teachers
// const teacherGroups = allGroups.filter((x) => {
// return selectedCorporateGroupsParticipants.includes(x.admin);
// });
// const usersList = [
// ...selectedCorporateGroupsParticipants,
// ...teacherGroups.flatMap((x) => x.participants),
// ];
const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => users.find((y) => y.id === x)) as User[];
return userListWithUsers.filter((x) => x);
}
return users || [];
};
const corporateFilteredUserList = getUsersList();
const getSelectedUser = () => {
if (selectedCorporate) {
const userInCorporate = corporateFilteredUserList.find((x) => x.id === statsUserId);
return userInCorporate || corporateFilteredUserList[0];
}
return users.find((x) => x.id === statsUserId) || user;
};
const selectedUser = getSelectedUser();
const selectedUserSelectValue = selectedUser
? {
value: selectedUser.id,
label: `${selectedUser.name} - ${selectedUser.email}`,
}
: {
value: "",
label: "",
};
const formatTimestamp = (timestamp: string) => {
const date = moment(parseInt(timestamp));
const formatter = "YYYY/MM/DD - HH:mm";
return date.format(formatter);
};
const selectTrainingContent = (trainingContent: ITrainingContent) => {
router.push(`/training/${trainingContent.id}`)
};
const trainingContentContainer = (timestamp: string) => {
if (!groupedByTrainingContent) return <></>;
const trainingContent: ITrainingContent = groupedByTrainingContent[timestamp];
const uniqueModules = [...new Set(trainingContent.exams.map(exam => exam.module))];
return (
<>
<div
key={uuidv4()}
className={clsx(
"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden"
)}
onClick={() => selectTrainingContent(trainingContent)}
role="button">
<div className="w-full flex justify-between -md:items-center 2xl:items-center">
<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
<span className="font-medium">{formatTimestamp(timestamp)}</span>
</div>
<div className="flex flex-col gap-2">
<div className="w-full flex flex-row gap-1">
{uniqueModules.map((module) => (
<ModuleBadge key={module} module={module} />
))}
</div>
</div>
</div>
<TrainingScore
trainingContent={trainingContent}
gridView={true}
/>
</div>
</>
);
};
return (
<>
<Head>
<title>Training | EnCoach</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>
<ToastContainer />
<Layout user={user}>
{(isNewContentLoading || isLoading ? (
<div className="absolute left-1/2 top-1/2 flex h-fit w-fit -translate-x-1/2 -translate-y-1/2 animate-pulse flex-col items-center gap-12">
<span className="loading loading-infinity w-32 bg-mti-green-light" />
{isNewContentLoading && (<span className="text-center text-2xl font-bold text-mti-green-light">
Assessing your exams, please be patient...
</span>)}
</div>
) : (
<>
<div className="w-full flex -xl:flex-col -xl:gap-4 justify-between items-center">
<div className="xl:w-3/4">
{(user.type === "developer" || user.type === "admin") && (
<>
<label className="font-normal text-base text-mti-gray-dim">Corporate</label>
<Select
options={selectableCorporates}
value={selectableCorporates.find((x) => x.value === selectedCorporate)}
onChange={(value) => setSelectedCorporate(value?.value || "")}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
color: state.isFocused ? "black" : styles.color,
}),
}}></Select>
<label className="font-normal text-base text-mti-gray-dim">User</label>
<Select
options={corporateFilteredUserList.map((x) => ({
value: x.id,
label: `${x.name} - ${x.email}`,
}))}
value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value!)}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
</>
)}
{(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && (
<>
<label className="font-normal text-base text-mti-gray-dim">User</label>
<Select
options={users
.filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
.map((x) => ({
value: x.id,
label: `${x.name} - ${x.email}`,
}))}
value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value!)}
styles={{
menuPortal: (base) => ({ ...base, zIndex: 9999 }),
option: (styles, state) => ({
...styles,
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
color: state.isFocused ? "black" : styles.color,
}),
}}
/>
</>
)}
{(user.type === "student" && (
<>
<div className="flex items-center">
<div className="font-semibold text-2xl">Generate New Training Material</div>
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light ml-4",
"transition duration-300 ease-in-out",
)}
onClick={handleNewTrainingContent}>
<FaPlus />
</button>
</div>
</>
))}
</div>
<div className="flex gap-4 w-full justify-center xl:justify-end">
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
"transition duration-300 ease-in-out",
filter === "months" && "!bg-mti-purple-light !text-white",
)}
onClick={() => toggleFilter("months")}>
Last month
</button>
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
"transition duration-300 ease-in-out",
filter === "weeks" && "!bg-mti-purple-light !text-white",
)}
onClick={() => toggleFilter("weeks")}>
Last week
</button>
<button
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
"transition duration-300 ease-in-out",
filter === "days" && "!bg-mti-purple-light !text-white",
)}
onClick={() => toggleFilter("days")}>
Last day
</button>
</div>
</div>
{trainingContent.length == 0 && (
<div className="flex flex-grow justify-center items-center">
<span className="font-semibold ml-1">No training content to display...</span>
</div>
)}
{groupedByTrainingContent && Object.keys(groupedByTrainingContent).length > 0 && (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-2 2xl:grid-cols-3 w-full gap-4 xl:gap-6">
{Object.keys(filterTrainingContentByDate(groupedByTrainingContent))
.sort((a, b) => parseInt(b) - parseInt(a))
.map(trainingContentContainer)}
</div>
)}
</>
))}
</Layout>
</>
);
}
export default Training;