Merge branch 'develop' into feature/update-permission-ui

This commit is contained in:
Tiago Ribeiro
2024-07-30 23:20:16 +01:00
10 changed files with 906 additions and 989 deletions

View File

@@ -4,7 +4,7 @@ import ReactSelect, {GroupBase, StylesConfig} from "react-select";
interface Option { interface Option {
[key: string]: any; [key: string]: any;
value: string; value: string | null;
label: string; label: string;
} }

View File

@@ -2,7 +2,7 @@ import Input from "@/components/Low/Input";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import {Module} from "@/interfaces"; import {Module} from "@/interfaces";
import clsx from "clsx"; import clsx from "clsx";
import {useState} from "react"; import {useEffect, useState} from "react";
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs"; import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
import {generate} from "random-words"; import {generate} from "random-words";
import {capitalize} from "lodash"; import {capitalize} from "lodash";
@@ -20,6 +20,7 @@ import {Assignment} from "@/interfaces/results";
import Checkbox from "@/components/Low/Checkbox"; import Checkbox from "@/components/Low/Checkbox";
import {InstructorGender, Variant} from "@/interfaces/exam"; import {InstructorGender, Variant} from "@/interfaces/exam";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import useExams from "@/hooks/useExams";
interface Props { interface Props {
isCreating: boolean; isCreating: boolean;
@@ -43,6 +44,14 @@ export default function AssignmentCreator({isCreating, assignment, assigner, gro
const [instructorGender, setInstructorGender] = useState<InstructorGender>(assignment?.instructorGender || "varied"); const [instructorGender, setInstructorGender] = useState<InstructorGender>(assignment?.instructorGender || "varied");
// creates a new exam for each assignee or just one exam for all assignees // creates a new exam for each assignee or just one exam for all assignees
const [generateMultiple, setGenerateMultiple] = useState<boolean>(false); const [generateMultiple, setGenerateMultiple] = useState<boolean>(false);
const [useRandomExams, setUseRandomExams] = useState(true);
const [examIDs, setExamIDs] = useState<{id: string; module: Module}[]>([]);
const {exams} = useExams();
useEffect(() => {
setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module)));
}, [selectedModules]);
const toggleModule = (module: Module) => { const toggleModule = (module: Module) => {
const modules = selectedModules.filter((x) => x !== module); const modules = selectedModules.filter((x) => x !== module);
@@ -60,6 +69,7 @@ export default function AssignmentCreator({isCreating, assignment, assigner, gro
assignees, assignees,
name, name,
startDate, startDate,
examIDs: !useRandomExams ? examIDs : undefined,
endDate, endDate,
selectedModules, selectedModules,
generateMultiple, generateMultiple,
@@ -228,6 +238,7 @@ export default function AssignmentCreator({isCreating, assignment, assigner, gro
</div> </div>
</div> </div>
{selectedModules.includes("speaking") && (
<div className="flex flex-col gap-3 w-full"> <div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label> <label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label>
<Select <Select
@@ -241,6 +252,38 @@ export default function AssignmentCreator({isCreating, assignment, assigner, gro
]} ]}
/> />
</div> </div>
)}
{selectedModules.length > 0 && (
<div className="flex flex-col gap-3 w-full">
<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
Random Exams
</Checkbox>
{!useRandomExams && (
<div className="grid md:grid-cols-2 w-full gap-4">
{selectedModules.map((module) => (
<div key={module} className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
<Select
value={{
value: examIDs.find((e) => e.module === module)?.id || null,
label: examIDs.find((e) => e.module === module)?.id || "",
}}
onChange={(value) =>
value
? setExamIDs((prev) => [...prev.filter((x) => x.module !== module), {id: value.value!, module}])
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
}
options={exams
.filter((x) => !x.isDiagnostic && x.module === module)
.map((x) => ({value: x.id, label: x.id}))}
/>
</div>
))}
</div>
)}
</div>
)}
<section className="w-full flex flex-col gap-3"> <section className="w-full flex flex-col gap-3">
<span className="font-semibold">Assignees ({assignees.length} selected)</span> <span className="font-semibold">Assignees ({assignees.length} selected)</span>
@@ -322,7 +365,14 @@ export default function AssignmentCreator({isCreating, assignment, assigner, gro
</Button> </Button>
)} )}
<Button <Button
disabled={selectedModules.length === 0 || !name || !startDate || !endDate || assignees.length === 0} disabled={
selectedModules.length === 0 ||
!name ||
!startDate ||
!endDate ||
assignees.length === 0 ||
(!!examIDs && examIDs.length < selectedModules.length)
}
className="w-full max-w-[200px]" className="w-full max-w-[200px]"
onClick={createAssignment} onClick={createAssignment}
isLoading={isLoading}> isLoading={isLoading}>

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> <label className="font-normal text-base text-mti-gray-dim">Exercise Type</label>
<Select <Select
options={Object.keys(TYPES).map((key) => ({value: key, label: TYPES[key]}))} 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"]}} value={{value: section?.type || "multiple_choice_4", label: TYPES[section?.type || "multiple_choice_4"]}}
/> />
</div> </div>

View File

@@ -1,24 +1,25 @@
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit"; import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import Select from "@/components/Low/Select"; 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 useExamStore from "@/stores/examStore";
import { getExamById } from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import { playSound } from "@/utils/sound"; import {playSound} from "@/utils/sound";
import { convertCamelCaseToReadable } from "@/utils/string"; import {convertCamelCaseToReadable} from "@/utils/string";
import { Tab } from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import { capitalize, sample } from "lodash"; import {capitalize, sample} from "lodash";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import { useEffect, useState, Dispatch, SetStateAction } from "react"; import {useEffect, useState, Dispatch, SetStateAction} from "react";
import { BsArrowRepeat, BsCheck } from "react-icons/bs"; import {BsArrowRepeat, BsCheck} from "react-icons/bs";
import { toast } from "react-toastify"; import {toast} from "react-toastify";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit"; import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
import {generate} from "random-words";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; 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 = { const WRITE_BLANKS_QUESTIONS = {
type: "writeBlanksQuestions", type: "writeBlanksQuestions",
label: "Write the Blanks: Questions", label: "Write the Blanks: Questions",
@@ -46,7 +47,7 @@ const PartTab = ({
}: { }: {
part?: ListeningPart; part?: ListeningPart;
difficulty: Difficulty; difficulty: Difficulty;
availableTypes: { type: string; label: string }[]; availableTypes: {type: string; label: string}[];
index: number; index: number;
setPart: (part?: ListeningPart) => void; setPart: (part?: ListeningPart) => void;
updatePart: Dispatch<SetStateAction<ListeningPart | undefined>>; updatePart: Dispatch<SetStateAction<ListeningPart | undefined>>;
@@ -65,17 +66,10 @@ const PartTab = ({
setPart(undefined); setPart(undefined);
setIsLoading(true); setIsLoading(true);
axios axios
.get( .get(`/api/exam/listening/generate/listening_section_${index}${topic || types ? `?${url.toString()}` : ""}`)
`/api/exam/listening/generate/listening_section_${index}${
topic || types ? `?${url.toString()}` : ""
}`
)
.then((result) => { .then((result) => {
playSound(typeof result.data === "string" ? "error" : "check"); playSound(typeof result.data === "string" ? "error" : "check");
if (typeof result.data === "string") if (typeof result.data === "string") return toast.error("Something went wrong, please try to generate again.");
return toast.error(
"Something went wrong, please try to generate again."
);
setPart(result.data); setPart(result.data);
}) })
.catch((error) => { .catch((error) => {
@@ -98,9 +92,7 @@ const PartTab = ({
updateExercise={(data: any) => updateExercise={(data: any) =>
updatePart((part?: ListeningPart) => { updatePart((part?: ListeningPart) => {
if (part) { if (part) {
const exercises = part.exercises.map((x) => const exercises = part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)) as Exercise[];
x.id === exercise.id ? { ...x, ...data } : x
) as Exercise[];
const updatedPart = { const updatedPart = {
...part, ...part,
exercises, exercises,
@@ -127,9 +119,7 @@ const PartTab = ({
if (part) { if (part) {
return { return {
...part, ...part,
exercises: part.exercises.map((x) => exercises: part.exercises.map((x) => (x.id === exercise.id ? {...x, ...data} : x)),
x.id === exercise.id ? { ...x, ...data } : x
),
} as ListeningPart; } as ListeningPart;
} }
@@ -145,19 +135,12 @@ const PartTab = ({
}); });
}; };
const toggleType = (type: string) => const toggleType = (type: string) => setTypes((prev) => (prev.includes(type) ? [...prev.filter((x) => x !== type)] : [...prev, type]));
setTypes((prev) =>
prev.includes(type)
? [...prev.filter((x) => x !== type)]
: [...prev, type]
);
return ( return (
<Tab.Panel className="w-full bg-ielts-listening/20 min-h-[600px] h-full rounded-xl p-6 flex flex-col gap-4"> <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"> <div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Exercises</label>
Exercises
</label>
<div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between"> <div className="flex flex-row -2xl:flex-wrap w-full gap-4 -md:justify-center justify-between">
{availableTypes.map((x) => ( {availableTypes.map((x) => (
<span <span
@@ -168,24 +151,15 @@ const PartTab = ({
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
!types.includes(x.type) !types.includes(x.type)
? "bg-white border-mti-gray-platinum" ? "bg-white border-mti-gray-platinum"
: "bg-ielts-listening/70 border-ielts-listening text-white" : "bg-ielts-listening/70 border-ielts-listening text-white",
)} )}>
>
{x.label} {x.label}
</span> </span>
))} ))}
</div> </div>
</div> </div>
<div className="flex gap-4 items-end"> <div className="flex gap-4 items-end">
<Input <Input type="text" placeholder="Grand Canyon..." name="topic" label="Topic" onChange={setTopic} roundness="xl" defaultValue={topic} />
type="text"
placeholder="Grand Canyon..."
name="topic"
label="Topic"
onChange={setTopic}
roundness="xl"
defaultValue={topic}
/>
<button <button
onClick={generate} onClick={generate}
disabled={isLoading || types.length === 0} disabled={isLoading || types.length === 0}
@@ -194,9 +168,8 @@ const PartTab = ({
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px]", "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", "hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
isLoading && "tooltip" isLoading && "tooltip",
)} )}>
>
{isLoading ? ( {isLoading ? (
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} /> <BsArrowRepeat className="text-white animate-spin" size={25} />
@@ -208,14 +181,8 @@ const PartTab = ({
</div> </div>
{isLoading && ( {isLoading && (
<div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center"> <div className="w-fit h-fit mt-12 self-center animate-pulse flex flex-col gap-8 items-center">
<span <span className={clsx("loading loading-infinity w-32 text-ielts-listening")} />
className={clsx( <span className={clsx("font-bold text-2xl text-ielts-listening")}>Generating...</span>
"loading loading-infinity w-32 text-ielts-listening"
)}
/>
<span className={clsx("font-bold text-2xl text-ielts-listening")}>
Generating...
</span>
</div> </div>
)} )}
{part && ( {part && (
@@ -223,19 +190,12 @@ const PartTab = ({
<div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide"> <div className="flex flex-col gap-2 w-full overflow-y-scroll scrollbar-hide">
<div className="flex gap-4"> <div className="flex gap-4">
{part.exercises.map((x) => ( {part.exercises.map((x) => (
<span <span className="rounded-xl bg-white border border-ielts-listening p-1 px-4" key={x.id}>
className="rounded-xl bg-white border border-ielts-listening p-1 px-4"
key={x.id}
>
{x.type && convertCamelCaseToReadable(x.type)} {x.type && convertCamelCaseToReadable(x.type)}
</span> </span>
))} ))}
</div> </div>
{typeof part.text === "string" && ( {typeof part.text === "string" && <span className="w-full h-96">{part.text.replaceAll("\n\n", " ")}</span>}
<span className="w-full h-96">
{part.text.replaceAll("\n\n", " ")}
</span>
)}
{typeof part.text !== "string" && ( {typeof part.text !== "string" && (
<div className="w-full h-96 flex flex-col gap-2"> <div className="w-full h-96 flex flex-col gap-2">
{part.text.conversation.map((x, index) => ( {part.text.conversation.map((x, index) => (
@@ -276,9 +236,7 @@ const ListeningGeneration = () => {
const [minTimer, setMinTimer] = useState(30); const [minTimer, setMinTimer] = useState(30);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<ListeningExam>(); const [resultingExam, setResultingExam] = useState<ListeningExam>();
const [difficulty, setDifficulty] = useState<Difficulty>( const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
sample(DIFFICULTIES)!
);
useEffect(() => { useEffect(() => {
const part1Timer = part1 ? 5 : 0; const part1Timer = part1 ? 5 : 0;
@@ -297,14 +255,14 @@ const ListeningGeneration = () => {
const submitExam = () => { const submitExam = () => {
const parts = [part1, part2, part3, part4].filter((x) => !!x); const parts = [part1, part2, part3, part4].filter((x) => !!x);
console.log({ parts }); console.log({parts});
if (parts.length === 0) if (parts.length === 0) return toast.error("Please generate at least one section!");
return toast.error("Please generate at least one section!");
setIsLoading(true); setIsLoading(true);
axios axios
.post(`/api/exam/listening/generate/listening`, { .post(`/api/exam/listening/generate/listening`, {
id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
parts, parts,
minTimer, minTimer,
difficulty, difficulty,
@@ -312,9 +270,7 @@ const ListeningGeneration = () => {
.then((result) => { .then((result) => {
playSound("sent"); playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`); console.log(`Generated Exam ID: ${result.data.id}`);
toast.success( toast.success(`Generated Exam ID: ${result.data.id}`);
"This new exam has been generated successfully! Check the ID in our browser's console."
);
setResultingExam(result.data); setResultingExam(result.data);
setPart1(undefined); setPart1(undefined);
@@ -333,12 +289,9 @@ const ListeningGeneration = () => {
const loadExam = async (examId: string) => { const loadExam = async (examId: string) => {
const exam = await getExamById("listening", examId.trim()); const exam = await getExamById("listening", examId.trim());
if (!exam) { if (!exam) {
toast.error( toast.error("Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID", {
"Unknown Exam ID! Please make sure you selected the right module and entered the right exam ID",
{
toastId: "invalid-exam-id", toastId: "invalid-exam-id",
} });
);
return; return;
} }
@@ -353,9 +306,7 @@ const ListeningGeneration = () => {
<> <>
<div className="flex gap-4 w-1/2"> <div className="flex gap-4 w-1/2">
<div className="flex flex-col gap-3"> <div className="flex flex-col gap-3">
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Timer</label>
Timer
</label>
<Input <Input
type="number" type="number"
name="minTimer" name="minTimer"
@@ -365,18 +316,14 @@ const ListeningGeneration = () => {
/> />
</div> </div>
<div className="flex flex-col gap-3 w-full"> <div className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Difficulty</label>
Difficulty
</label>
<Select <Select
options={DIFFICULTIES.map((x) => ({ options={DIFFICULTIES.map((x) => ({
value: x, value: x,
label: capitalize(x), label: capitalize(x),
}))} }))}
onChange={(value) => onChange={(value) => (value ? setDifficulty(value.value as Difficulty) : null)}
value ? setDifficulty(value.value as Difficulty) : null value={{value: difficulty, label: capitalize(difficulty)}}
}
value={{ value: difficulty, label: capitalize(difficulty) }}
disabled={!!part1 || !!part2 || !!part3 || !!part4} disabled={!!part1 || !!part2 || !!part3 || !!part4}
/> />
</div> </div>
@@ -384,59 +331,47 @@ const ListeningGeneration = () => {
<Tab.Group> <Tab.Group>
<Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1"> <Tab.List className="flex space-x-1 rounded-xl bg-ielts-listening/20 p-1">
<Tab <Tab
className={({ selected }) => className={({selected}) =>
clsx( 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", "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", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
} }>
>
Section 1 {part1 && <BsCheck />} Section 1 {part1 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({ selected }) => className={({selected}) =>
clsx( 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", "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", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
} }>
>
Section 2 {part2 && <BsCheck />} Section 2 {part2 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({ selected }) => className={({selected}) =>
clsx( 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", "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", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
} }>
>
Section 3 {part3 && <BsCheck />} Section 3 {part3 && <BsCheck />}
</Tab> </Tab>
<Tab <Tab
className={({ selected }) => className={({selected}) =>
clsx( 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", "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", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-listening focus:outline-none focus:ring-2",
"transition duration-300 ease-in-out", "transition duration-300 ease-in-out",
selected selected ? "bg-white shadow" : "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-listening"
) )
} }>
>
Section 4 {part4 && <BsCheck />} Section 4 {part4 && <BsCheck />}
</Tab> </Tab>
</Tab.List> </Tab.List>
@@ -445,12 +380,7 @@ const ListeningGeneration = () => {
{ {
part: part1, part: part1,
setPart: setPart1, setPart: setPart1,
types: [ types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS, WRITE_BLANKS_FILL, WRITE_BLANKS_FORM],
MULTIPLE_CHOICE,
WRITE_BLANKS_QUESTIONS,
WRITE_BLANKS_FILL,
WRITE_BLANKS_FORM,
],
}, },
{ {
part: part2, part: part2,
@@ -465,14 +395,9 @@ const ListeningGeneration = () => {
{ {
part: part4, part: part4,
setPart: setPart4, setPart: setPart4,
types: [ types: [MULTIPLE_CHOICE, WRITE_BLANKS_QUESTIONS, WRITE_BLANKS_FILL, WRITE_BLANKS_FORM],
MULTIPLE_CHOICE,
WRITE_BLANKS_QUESTIONS,
WRITE_BLANKS_FILL,
WRITE_BLANKS_FORM,
],
}, },
].map(({ part, setPart, types }, index) => ( ].map(({part, setPart, types}, index) => (
<PartTab <PartTab
part={part} part={part}
difficulty={difficulty} difficulty={difficulty}
@@ -493,9 +418,8 @@ const ListeningGeneration = () => {
className={clsx( className={clsx(
"bg-white border border-ielts-listening text-ielts-listening w-full max-w-[200px] rounded-xl h-[70px] self-end", "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", "hover:bg-ielts-listening hover:text-white disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300" "transition ease-in-out duration-300",
)} )}>
>
Perform Exam Perform Exam
</button> </button>
)} )}
@@ -507,9 +431,8 @@ const ListeningGeneration = () => {
"bg-ielts-listening/70 border border-ielts-listening text-white w-full max-w-[200px] rounded-xl h-[70px] self-end", "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", "hover:bg-ielts-listening disabled:bg-ielts-listening/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
!part1 && !part2 && !part3 && !part4 && "tooltip" !part1 && !part2 && !part3 && !part4 && "tooltip",
)} )}>
>
{isLoading ? ( {isLoading ? (
<div className="flex items-center justify-center"> <div className="flex items-center justify-center">
<BsArrowRepeat className="text-white animate-spin" size={25} /> <BsArrowRepeat className="text-white animate-spin" size={25} />

View File

@@ -5,6 +5,7 @@ import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import {playSound} from "@/utils/sound"; import {playSound} from "@/utils/sound";
import {convertCamelCaseToReadable} from "@/utils/string"; import {convertCamelCaseToReadable} from "@/utils/string";
import {generate} from "random-words";
import {Tab} from "@headlessui/react"; import {Tab} from "@headlessui/react";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; 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 TrueFalseEdit from "@/components/Generation/true.false.edit";
import WriteBlanksEdit from "@/components/Generation/write.blanks.edit"; import WriteBlanksEdit from "@/components/Generation/write.blanks.edit";
import MatchSentencesEdit from "@/components/Generation/match.sentences.edit"; import MatchSentencesEdit from "@/components/Generation/match.sentences.edit";
import MultipleChoiceEdit from "@/components/Generation/multiple.choice.edit";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; 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": case "writeBlanks":
return ( return (
<> <>
@@ -282,7 +306,7 @@ const ReadingGeneration = () => {
isDiagnostic: false, isDiagnostic: false,
minTimer, minTimer,
module: "reading", module: "reading",
id: v4(), id: generate({minLength: 4, maxLength: 8, min: 3, max: 5, join: " ", formatter: capitalize}),
type: "academic", type: "academic",
variant: parts.length === 3 ? "full" : "partial", variant: parts.length === 3 ? "full" : "partial",
difficulty, difficulty,
@@ -293,7 +317,7 @@ const ReadingGeneration = () => {
.then((result) => { .then((result) => {
playSound("sent"); playSound("sent");
console.log(`Generated Exam ID: ${result.data.id}`); 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); setResultingExam(result.data);
setPart1(undefined); setPart1(undefined);

View File

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

View File

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

View File

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

View File

@@ -28,7 +28,6 @@ import {usePDFDownload} from "@/hooks/usePDFDownload";
import useRecordStore from "@/stores/recordStore"; import useRecordStore from "@/stores/recordStore";
import ai_usage from "@/utils/ai.detection"; import ai_usage from "@/utils/ai.detection";
export const getServerSideProps = withIronSessionSsr(({req, res}) => { export const getServerSideProps = withIronSessionSsr(({req, res}) => {
const user = req.session.user; const user = req.session.user;
@@ -263,18 +262,18 @@ export default function History({user}: {user: User}) {
<div className="flex flex-row gap-2"> <div className="flex flex-row gap-2">
<span className={textColor}> <span className={textColor}>
Level{" "} Level{" "}
{(aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length).toFixed(1)} {(
aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length
).toFixed(1)}
</span> </span>
{renderPdfIcon(session, textColor, textColor)} {renderPdfIcon(session, textColor, textColor)}
</div> </div>
{aiUsage >= 50 && user.type !== "student" && ( {aiUsage >= 50 && user.type !== "student" && (
<div className={clsx( <div
"ml-auto border px-1 rounded w-fit mr-1", className={clsx("ml-auto border px-1 rounded w-fit mr-1", {
{ "bg-orange-100 border-orange-400 text-orange-700": aiUsage < 80,
'bg-orange-100 border-orange-400 text-orange-700': aiUsage < 80, "bg-red-100 border-red-400 text-red-700": aiUsage >= 80,
'bg-red-100 border-red-400 text-red-700': aiUsage >= 80, })}>
}
)}>
<span className="text-xs">AI Usage</span> <span className="text-xs">AI Usage</span>
</div> </div>
)} )}
@@ -442,7 +441,7 @@ export default function History({user}: {user: User}) {
label: `${x.name} - ${x.email}`, label: `${x.name} - ${x.email}`,
}))} }))}
value={selectedUserSelectValue} value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value)} onChange={(value) => setStatsUserId(value?.value!)}
styles={{ styles={{
menuPortal: (base) => ({...base, zIndex: 9999}), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
@@ -466,7 +465,7 @@ export default function History({user}: {user: User}) {
label: `${x.name} - ${x.email}`, label: `${x.name} - ${x.email}`,
}))} }))}
value={selectedUserSelectValue} value={selectedUserSelectValue}
onChange={(value) => setStatsUserId(value?.value)} onChange={(value) => setStatsUserId(value?.value!)}
styles={{ styles={{
menuPortal: (base) => ({...base, zIndex: 9999}), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({

View File

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