Merge branch 'develop' into master-corporate

This commit is contained in:
Joao Ramos
2024-07-24 09:50:53 +01:00
10 changed files with 729 additions and 912 deletions

View File

@@ -60,7 +60,6 @@ export default function InteractiveSpeaking({
setIsLoading(true); setIsLoading(true);
const answer = await saveAnswer(questionIndex); const answer = await saveAnswer(questionIndex);
console.log(questionIndex + 1 < prompts.length, questionIndex, prompts.length);
if (questionIndex + 1 < prompts.length) { if (questionIndex + 1 < prompts.length) {
setQuestionIndex(questionIndex + 1); setQuestionIndex(questionIndex + 1);
setIsLoading(false); setIsLoading(false);

View File

@@ -87,10 +87,6 @@ export default function MatchSentences({id, options, type, prompt, sentences, us
return {total, correct, missing}; return {total, correct, missing};
}; };
useEffect(() => {
console.log(answers);
}, [answers]);
useEffect(() => { useEffect(() => {
if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type}); if (hasExamEnded) onNext({exercise: id, solutions: answers, score: calculateScore(), type});
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps

View File

@@ -20,7 +20,6 @@ interface Props {
export default function PaymobPayment({user, price, setIsPaymentLoading, currency, duration, duration_unit, onSuccess}: Props) { export default function PaymobPayment({user, price, setIsPaymentLoading, currency, duration, duration_unit, onSuccess}: Props) {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
console.log(user.id);
const router = useRouter(); const router = useRouter();

View File

@@ -124,7 +124,7 @@ export default function Writing({id, type, prompt, attachment, userSolutions, on
return ( return (
<div <div
className={clsx( className={clsx(
"bg-ielts-speaking text-ielts-speaking-light rounded-xl px-4 py-2", "bg-ielts-writing text-ielts-writing-light rounded-xl px-4 py-2",
typeof taskResponse !== "number" && "tooltip", typeof taskResponse !== "number" && "tooltip",
)} )}
data-tip={typeof taskResponse !== "number" ? taskResponse.comment : ""} data-tip={typeof taskResponse !== "number" ? taskResponse.comment : ""}

View File

@@ -47,8 +47,6 @@ export default function BatchCodeGenerator({user}: {user: User}) {
readAs: "ArrayBuffer", readAs: "ArrayBuffer",
}); });
useEffect(() => console.log(expiryDate), [expiryDate]);
useEffect(() => { useEffect(() => {
if (!isExpiryDateEnabled) setExpiryDate(null); if (!isExpiryDateEnabled) setExpiryDate(null);
}, [isExpiryDateEnabled]); }, [isExpiryDateEnabled]);

View File

@@ -131,7 +131,6 @@ export default function UserList({
filteredUsers, filteredUsers,
sortFunction sortFunction
); );
console.log(sortedUsers);
setDisplayUsers([...sortedUsers]); setDisplayUsers([...sortedUsers]);
} }
@@ -234,7 +233,7 @@ export default function UserList({
const actionColumn = ({ row }: { row: { original: User } }) => { const actionColumn = ({ row }: { row: { original: User } }) => {
return ( return (
<div className="flex gap-4"> <div className="flex gap-4">
{PERMISSIONS.updateUser[row.original.type].includes(user.type) && ( {PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
<Popover className="relative"> <Popover className="relative">
<Popover.Button> <Popover.Button>
<div data-tip="Change Type" className="cursor-pointer tooltip"> <div data-tip="Change Type" className="cursor-pointer tooltip">
@@ -298,7 +297,7 @@ export default function UserList({
</Popover> </Popover>
)} )}
{!row.original.isVerified && {!row.original.isVerified &&
PERMISSIONS.updateUser[row.original.type].includes(user.type) && ( PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
<div <div
data-tip="Verify User" data-tip="Verify User"
className="cursor-pointer tooltip" className="cursor-pointer tooltip"
@@ -307,7 +306,7 @@ export default function UserList({
<BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" /> <BsCheck className="hover:text-mti-purple-light transition ease-in-out duration-300" />
</div> </div>
)} )}
{PERMISSIONS.updateUser[row.original.type].includes(user.type) && ( {PERMISSIONS.updateUser[row.original.type]?.includes(user.type) && (
<div <div
data-tip={ data-tip={
row.original.status === "disabled" row.original.status === "disabled"
@@ -324,7 +323,7 @@ export default function UserList({
)} )}
</div> </div>
)} )}
{PERMISSIONS.deleteUser[row.original.type].includes(user.type) && ( {PERMISSIONS.deleteUser[row.original.type]?.includes(user.type) && (
<div <div
data-tip="Delete" data-tip="Delete"
className="cursor-pointer tooltip" className="cursor-pointer tooltip"
@@ -351,13 +350,13 @@ export default function UserList({
cell: ({ row, getValue }) => ( cell: ({ row, getValue }) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type].includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
user.type user.type
) && ) &&
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer" "underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
)} )}
onClick={() => onClick={() =>
PERMISSIONS.updateExpiryDate[row.original.type].includes(user.type) PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
? setSelectedUser(row.original) ? setSelectedUser(row.original)
: null : null
} }
@@ -467,13 +466,13 @@ export default function UserList({
cell: ({ row, getValue }) => ( cell: ({ row, getValue }) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type].includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
user.type user.type
) && ) &&
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer" "underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
)} )}
onClick={() => onClick={() =>
PERMISSIONS.updateExpiryDate[row.original.type].includes(user.type) PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
? setSelectedUser(row.original) ? setSelectedUser(row.original)
: null : null
} }
@@ -498,13 +497,13 @@ export default function UserList({
cell: ({ row, getValue }) => ( cell: ({ row, getValue }) => (
<div <div
className={clsx( className={clsx(
PERMISSIONS.updateExpiryDate[row.original.type].includes( PERMISSIONS.updateExpiryDate[row.original.type]?.includes(
user.type user.type
) && ) &&
"underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer" "underline text-mti-purple-light hover:text-mti-purple-dark transition ease-in-out duration-300 cursor-pointer"
)} )}
onClick={() => onClick={() =>
PERMISSIONS.updateExpiryDate[row.original.type].includes(user.type) PERMISSIONS.updateExpiryDate[row.original.type]?.includes(user.type)
? setSelectedUser(row.original) ? setSelectedUser(row.original)
: null : null
} }

View File

@@ -357,7 +357,7 @@ export default function ExamPage({page}: Props) {
exercise, exercise,
solutions.find((x) => x.exercise === exercise.id)!, solutions.find((x) => x.exercise === exercise.id)!,
evaluationID, evaluationID,
index === 0 ? 1 : 2, index + 1,
); );
}), }),
) )

View File

@@ -1,11 +1,5 @@
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import { import {Difficulty, LevelExam, MultipleChoiceExercise, MultipleChoiceQuestion, LevelPart} from "@/interfaces/exam";
Difficulty,
LevelExam,
MultipleChoiceExercise,
MultipleChoiceQuestion,
LevelPart,
} 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";
@@ -21,13 +15,7 @@ import { v4 } from "uuid";
const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"]; const DIFFICULTIES: Difficulty[] = ["easy", "medium", "hard"];
const QuestionDisplay = ({ const QuestionDisplay = ({question, onUpdate}: {question: MultipleChoiceQuestion; onUpdate: (question: MultipleChoiceQuestion) => void}) => {
question,
onUpdate,
}: {
question: MultipleChoiceQuestion;
onUpdate: (question: MultipleChoiceQuestion) => void;
}) => {
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [options, setOptions] = useState(question.options); const [options, setOptions] = useState(question.options);
const [answer, setAnswer] = useState(question.solution); const [answer, setAnswer] = useState(question.solution);
@@ -39,32 +27,17 @@ const QuestionDisplay = ({
</span> </span>
<div className="flex flex-col gap-1"> <div className="flex flex-col gap-1">
{question.options.map((option, index) => ( {question.options.map((option, index) => (
<span key={option.id} className={clsx(answer === option.id && "font-bold")}>
<span <span
key={option.id} className={clsx("font-semibold", answer === option.id ? "text-mti-green-light" : "text-ielts-level")}
className={clsx(answer === option.id && "font-bold")} onClick={() => setAnswer(option.id)}>
>
<span
className={clsx(
"font-semibold",
answer === option.id
? "text-mti-green-light"
: "text-ielts-level"
)}
onClick={() => setAnswer(option.id)}
>
({option.id}) ({option.id})
</span>{" "} </span>{" "}
{isEditing ? ( {isEditing ? (
<input <input
defaultValue={option.text} defaultValue={option.text}
className="w-60" className="w-60"
onChange={(e) => onChange={(e) => setOptions((prev) => prev.map((x, idx) => (idx === index ? {...x, text: e.target.value} : x)))}
setOptions((prev) =>
prev.map((x, idx) =>
idx === index ? { ...x, text: e.target.value } : x
)
)
}
/> />
) : ( ) : (
<span>{option.text}</span> <span>{option.text}</span>
@@ -76,8 +49,7 @@ const QuestionDisplay = ({
{!isEditing && ( {!isEditing && (
<button <button
onClick={() => setIsEditing(true)} onClick={() => setIsEditing(true)}
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300" className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300">
>
<BsPencilSquare /> <BsPencilSquare />
</button> </button>
)} )}
@@ -88,14 +60,12 @@ const QuestionDisplay = ({
onUpdate({...question, options, solution: answer}); onUpdate({...question, options, solution: answer});
setIsEditing(false); setIsEditing(false);
}} }}
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300" className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300">
>
<BsCheck /> <BsCheck />
</button> </button>
<button <button
onClick={() => setIsEditing(false)} onClick={() => setIsEditing(false)}
className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300" className="p-2 border border-neutral-300 bg-white rounded-xl hover:drop-shadow transition ease-in-out duration-300">
>
<BsX /> <BsX />
</button> </button>
</> </>
@@ -105,15 +75,7 @@ const QuestionDisplay = ({
); );
}; };
const TaskTab = ({ const TaskTab = ({exam, difficulty, setExam}: {exam?: LevelPart; difficulty: Difficulty; setExam: (exam: LevelPart) => void}) => {
exam,
difficulty,
setExam,
}: {
exam?: LevelPart;
difficulty: Difficulty;
setExam: (exam: LevelPart) => void;
}) => {
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const generate = () => { const generate = () => {
@@ -125,10 +87,7 @@ const TaskTab = ({
.get(`/api/exam/level/generate/level?${url.toString()}`) .get(`/api/exam/level/generate/level?${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."
);
setExam(result.data); setExam(result.data);
}) })
.catch((error) => { .catch((error) => {
@@ -145,11 +104,8 @@ const TaskTab = ({
...exam, ...exam,
exercises: exam.exercises.map((x) => ({ exercises: exam.exercises.map((x) => ({
...x, ...x,
questions: (x as MultipleChoiceExercise).questions.map((q) => questions: (x as MultipleChoiceExercise).questions.map((q) => (q.id === question.id ? question : q)),
q.id === question.id ? question : q })),
),
}),
),
}; };
console.log(updatedExam); console.log(updatedExam);
setExam(updatedExam as any); setExam(updatedExam as any);
@@ -164,9 +120,8 @@ const TaskTab = ({
className={clsx( className={clsx(
"bg-ielts-level/70 border border-ielts-level text-white w-full px-6 py-6 rounded-xl h-[70px]", "bg-ielts-level/70 border border-ielts-level text-white w-full px-6 py-6 rounded-xl h-[70px]",
"hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed", "hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300" "transition ease-in-out duration-300",
)} )}>
>
{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} />
@@ -178,12 +133,8 @@ const TaskTab = ({
</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-level")} />
className={clsx("loading loading-infinity w-32 text-ielts-level")} <span className={clsx("font-bold text-2xl text-ielts-level")}>Generating...</span>
/>
<span className={clsx("font-bold text-2xl text-ielts-level")}>
Generating...
</span>
</div> </div>
)} )}
{exam && ( {exam && (
@@ -196,20 +147,14 @@ const TaskTab = ({
return ( return (
<div key={ex.id} className="w-full h-full flex flex-col gap-2"> <div key={ex.id} className="w-full h-full flex flex-col gap-2">
<div className="flex gap-2"> <div className="flex gap-2">
<span className="text-xl font-semibold"> <span className="text-xl font-semibold">Multiple Choice</span>
Multiple Choice
</span>
<span className="rounded-xl bg-white border border-ielts-level p-1 px-4 w-fit"> <span className="rounded-xl bg-white border border-ielts-level p-1 px-4 w-fit">
{exercise.questions.length} questions {exercise.questions.length} questions
</span> </span>
</div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{exercise.questions.map((question) => ( {exercise.questions.map((question) => (
<QuestionDisplay <QuestionDisplay question={question} onUpdate={onUpdate} key={question.id} />
question={question}
onUpdate={onUpdate}
key={question.id}
/>
))} ))}
</div> </div>
</div> </div>
@@ -225,9 +170,7 @@ const LevelGeneration = () => {
const [generatedExam, setGeneratedExam] = useState<LevelPart>(); const [generatedExam, setGeneratedExam] = useState<LevelPart>();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const [resultingExam, setResultingExam] = useState<LevelExam>(); const [resultingExam, setResultingExam] = useState<LevelExam>();
const [difficulty, setDifficulty] = useState<Difficulty>( const [difficulty, setDifficulty] = useState<Difficulty>(sample(DIFFICULTIES)!);
sample(DIFFICULTIES)!
);
const router = useRouter(); const router = useRouter();
@@ -237,12 +180,9 @@ const LevelGeneration = () => {
const loadExam = async (examId: string) => { const loadExam = async (examId: string) => {
const exam = await getExamById("level", examId.trim()); const exam = await getExamById("level", 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;
} }
@@ -274,18 +214,14 @@ const LevelGeneration = () => {
.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("This new exam has been generated successfully! Check the ID in our browser's console.");
"This new exam has been generated successfully! Check the ID in our browser's console."
);
setResultingExam(result.data); setResultingExam(result.data);
setGeneratedExam(undefined); setGeneratedExam(undefined);
}) })
.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));
}; };
@@ -294,17 +230,13 @@ const LevelGeneration = () => {
<> <>
<div className="flex gap-4 w-1/2"> <div className="flex gap-4 w-1/2">
<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)}}
/> />
</div> </div>
@@ -317,21 +249,14 @@ const LevelGeneration = () => {
"w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-level/70", "w-full rounded-lg py-2.5 text-sm font-medium leading-5 text-ielts-level/70",
"ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-level focus:outline-none focus:ring-2", "ring-white ring-opacity-60 ring-offset-2 ring-offset-ielts-level 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-level",
? "bg-white shadow"
: "text-blue-100 hover:bg-white/[0.12] hover:text-ielts-level"
) )
} }>
>
Exam Exam
</Tab> </Tab>
</Tab.List> </Tab.List>
<Tab.Panels> <Tab.Panels>
<TaskTab <TaskTab difficulty={difficulty} exam={generatedExam} setExam={setGeneratedExam} />
difficulty={difficulty}
exam={generatedExam}
setExam={setGeneratedExam}
/>
</Tab.Panels> </Tab.Panels>
</Tab.Group> </Tab.Group>
<div className="w-full flex justify-end gap-4"> <div className="w-full flex justify-end gap-4">
@@ -342,9 +267,8 @@ const LevelGeneration = () => {
className={clsx( className={clsx(
"bg-white border border-ielts-level text-ielts-level w-full max-w-[200px] rounded-xl h-[70px] self-end", "bg-white border border-ielts-level text-ielts-level w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-level hover:text-white disabled:bg-ielts-level/40 disabled:cursor-not-allowed", "hover:bg-ielts-level hover:text-white disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300" "transition ease-in-out duration-300",
)} )}>
>
Perform Exam Perform Exam
</button> </button>
)} )}
@@ -356,9 +280,8 @@ const LevelGeneration = () => {
"bg-ielts-level/70 border border-ielts-level text-white w-full max-w-[200px] rounded-xl h-[70px] self-end", "bg-ielts-level/70 border border-ielts-level text-white w-full max-w-[200px] rounded-xl h-[70px] self-end",
"hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed", "hover:bg-ielts-level disabled:bg-ielts-level/40 disabled:cursor-not-allowed",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
!generatedExam && "tooltip" !generatedExam && "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

@@ -18,17 +18,7 @@ import { sortByModule } from "@/utils/moduleUtils";
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
import clsx from "clsx"; import clsx from "clsx";
import {calculateBandScore} from "@/utils/score"; import {calculateBandScore} from "@/utils/score";
import { import {BsBook, BsClipboard, BsClock, BsHeadphones, BsMegaphone, BsPen, BsPersonDash, BsPersonFillX, BsXCircle} from "react-icons/bs";
BsBook,
BsClipboard,
BsClock,
BsHeadphones,
BsMegaphone,
BsPen,
BsPersonDash,
BsPersonFillX,
BsXCircle,
} from "react-icons/bs";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import useGroups from "@/hooks/useGroups"; import useGroups from "@/hooks/useGroups";
import {shouldRedirectHome} from "@/utils/navigation.disabled"; import {shouldRedirectHome} from "@/utils/navigation.disabled";
@@ -68,15 +58,10 @@ const defaultSelectableCorporate = {
}; };
export default function History({user}: {user: User}) { export default function History({user}: {user: User}) {
const [statsUserId, setStatsUserId] = useRecordStore((state) => [ const [statsUserId, setStatsUserId] = useRecordStore((state) => [state.selectedUser, state.setSelectedUser]);
state.selectedUser,
state.setSelectedUser,
]);
// const [statsUserId, setStatsUserId] = useState<string | undefined>(user.id); // 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< const [filter, setFilter] = useState<"months" | "weeks" | "days" | "assignments">();
"months" | "weeks" | "days" | "assignments"
>();
const {assignments} = useAssignments({}); const {assignments} = useAssignments({});
const {users} = useUsers(); const {users} = useUsers();
@@ -106,8 +91,8 @@ export default function History({ user }: { user: User }) {
) )
return false; return false;
return true; return true;
}) }),
) ),
); );
} }
}, [stats, isStatsLoading]); }, [stats, isStatsLoading]);
@@ -129,8 +114,7 @@ export default function History({ user }: { user: User }) {
const filteredStats: {[key: string]: Stat[]} = {}; const filteredStats: {[key: string]: Stat[]} = {};
Object.keys(stats).forEach((timestamp) => { Object.keys(stats).forEach((timestamp) => {
if (timestamp >= filterDate) if (timestamp >= filterDate) filteredStats[timestamp] = stats[timestamp];
filteredStats[timestamp] = stats[timestamp];
}); });
return filteredStats; return filteredStats;
@@ -140,14 +124,8 @@ export default function History({ user }: { user: User }) {
const filteredStats: {[key: string]: Stat[]} = {}; const filteredStats: {[key: string]: Stat[]} = {};
Object.keys(stats).forEach((timestamp) => { Object.keys(stats).forEach((timestamp) => {
if ( if (stats[timestamp].map((s) => s.assignment === undefined).includes(false))
stats[timestamp] filteredStats[timestamp] = [...stats[timestamp].filter((s) => !!s.assignment)];
.map((s) => s.assignment === undefined)
.includes(false)
)
filteredStats[timestamp] = [
...stats[timestamp].filter((s) => !!s.assignment),
];
}); });
return filteredStats; return filteredStats;
@@ -163,9 +141,7 @@ export default function History({ user }: { user: User }) {
return date.format(formatter); return date.format(formatter);
}; };
const aggregateScoresByModule = ( const aggregateScoresByModule = (stats: Stat[]): {module: Module; total: number; missing: number; correct: number}[] => {
stats: Stat[]
): { module: Module; total: number; missing: number; correct: number }[] => {
const scores: { const scores: {
[key in Module]: {total: number; missing: number; correct: number}; [key in Module]: {total: number; missing: number; correct: number};
} = { } = {
@@ -213,21 +189,10 @@ export default function History({ user }: { user: User }) {
if (!groupedStats) return <></>; if (!groupedStats) return <></>;
const dateStats = groupedStats[timestamp]; const dateStats = groupedStats[timestamp];
const correct = dateStats.reduce( const correct = dateStats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
(accumulator, current) => accumulator + current.score.correct, const total = dateStats.reduce((accumulator, current) => accumulator + current.score.total, 0);
0 const aggregatedScores = aggregateScoresByModule(dateStats).filter((x) => x.total > 0);
); const assignmentID = dateStats.reduce((_, current) => current.assignment as any, "");
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 assignment = assignments.find((a) => a.id === assignmentID);
const isDisabled = dateStats.some((x) => x.isDisabled); const isDisabled = dateStats.some((x) => x.isDisabled);
@@ -244,6 +209,8 @@ export default function History({ user }: { user: User }) {
return getExamById(stat.module, stat.exam); return getExamById(stat.module, stat.exam);
}); });
if (isDisabled) return;
Promise.all(examPromises).then((exams) => { Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) { if (exams.every((x) => !!x)) {
if (!!timeSpent) setTimeSpent(timeSpent); if (!!timeSpent) setTimeSpent(timeSpent);
@@ -256,7 +223,7 @@ export default function History({ user }: { user: User }) {
exams exams
.map((x) => x!) .map((x) => x!)
.sort(sortByModule) .sort(sortByModule)
.map((x) => x!.module) .map((x) => x!.module),
); );
router.push("/exercises"); router.push("/exercises");
} }
@@ -266,7 +233,7 @@ export default function History({ user }: { user: User }) {
const textColor = clsx( const textColor = clsx(
correct / total >= 0.7 && "text-mti-purple", correct / total >= 0.7 && "text-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red", correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
correct / total < 0.3 && "text-mti-rose" correct / total < 0.3 && "text-mti-rose",
); );
const content = ( const content = (
@@ -276,18 +243,12 @@ export default function History({ user }: { user: User }) {
<span className="font-medium">{formatTimestamp(timestamp)}</span> <span className="font-medium">{formatTimestamp(timestamp)}</span>
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
{!!timeSpent && ( {!!timeSpent && (
<span <span className="text-sm flex gap-2 items-center tooltip" data-tip="Time Spent">
className="text-sm flex gap-2 items-center tooltip"
data-tip="Time Spent"
>
<BsClock /> {Math.floor(timeSpent / 60)} minutes <BsClock /> {Math.floor(timeSpent / 60)} minutes
</span> </span>
)} )}
{!!inactivity && ( {!!inactivity && (
<span <span className="text-sm flex gap-2 items-center tooltip" data-tip="Inactivity">
className="text-sm flex gap-2 items-center tooltip"
data-tip="Inactivity"
>
<BsXCircle /> {Math.floor(inactivity / 60)} minutes <BsXCircle /> {Math.floor(inactivity / 60)} minutes
</span> </span>
)} )}
@@ -296,12 +257,7 @@ 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>
@@ -318,9 +274,8 @@ export default function History({ user }: { user: User }) {
module === "listening" && "bg-ielts-listening", module === "listening" && "bg-ielts-listening",
module === "writing" && "bg-ielts-writing", module === "writing" && "bg-ielts-writing",
module === "speaking" && "bg-ielts-speaking", module === "speaking" && "bg-ielts-speaking",
module === "level" && "bg-ielts-level" module === "level" && "bg-ielts-level",
)} )}>
>
{module === "reading" && <BsBook className="w-4 h-4" />} {module === "reading" && <BsBook className="w-4 h-4" />}
{module === "listening" && <BsHeadphones className="w-4 h-4" />} {module === "listening" && <BsHeadphones className="w-4 h-4" />}
{module === "writing" && <BsPen className="w-4 h-4" />} {module === "writing" && <BsPen className="w-4 h-4" />}
@@ -333,8 +288,7 @@ export default function History({ user }: { user: User }) {
{assignment && ( {assignment && (
<span className="font-light text-sm"> <span className="font-light text-sm">
Assignment: {assignment.name}, Teacher:{" "} Assignment: {assignment.name}, Teacher: {users.find((u) => u.id === assignment.assigner)?.name}
{users.find((u) => u.id === assignment.assigner)?.name}
</span> </span>
)} )}
</div> </div>
@@ -349,15 +303,12 @@ export default function History({ user }: { user: User }) {
"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", "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", isDisabled && "grayscale tooltip",
correct / total >= 0.7 && "hover:border-mti-purple", correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.7 && correct / total < 0.3 && "hover:border-mti-rose",
"hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose"
)} )}
onClick={isDisabled ? () => null : selectExam} onClick={selectExam}
data-tip="This exam is still being evaluated..." data-tip="This exam is still being evaluated..."
role="button" role="button">
>
{content} {content}
</div> </div>
<div <div
@@ -365,14 +316,11 @@ export default function History({ user }: { user: User }) {
className={clsx( 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", "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.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.7 && correct / total < 0.3 && "hover:border-mti-rose",
"hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose"
)} )}
data-tip="Your screen size is too small to view previous exams." data-tip="Your screen size is too small to view previous exams."
role="button" role="button">
>
{content} {content}
</div> </div>
</> </>
@@ -389,20 +337,15 @@ export default function History({ user }: { user: User }) {
})), })),
]; ];
const [selectedCorporate, setSelectedCorporate] = useState<string>( const [selectedCorporate, setSelectedCorporate] = useState<string>(defaultSelectableCorporate.value);
defaultSelectableCorporate.value
);
const getUsersList = (): User[] => { const getUsersList = (): User[] => {
if (selectedCorporate) { if (selectedCorporate) {
// get groups for that corporate // get groups for that corporate
const selectedCorporateGroups = allGroups.filter( const selectedCorporateGroups = allGroups.filter((x) => x.admin === selectedCorporate);
(x) => x.admin === selectedCorporate
);
// get the teacher ids for that group // get the teacher ids for that group
const selectedCorporateGroupsParticipants = const selectedCorporateGroupsParticipants = selectedCorporateGroups.flatMap((x) => x.participants);
selectedCorporateGroups.flatMap((x) => x.participants);
// // search for groups for these teachers // // search for groups for these teachers
// const teacherGroups = allGroups.filter((x) => { // const teacherGroups = allGroups.filter((x) => {
@@ -413,9 +356,7 @@ export default function History({ user }: { user: User }) {
// ...selectedCorporateGroupsParticipants, // ...selectedCorporateGroupsParticipants,
// ...teacherGroups.flatMap((x) => x.participants), // ...teacherGroups.flatMap((x) => x.participants),
// ]; // ];
const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => const userListWithUsers = selectedCorporateGroupsParticipants.map((x) => users.find((y) => y.id === x)) as User[];
users.find((y) => y.id === x)
) as User[];
return userListWithUsers.filter((x) => x); return userListWithUsers.filter((x) => x);
} }
@@ -426,9 +367,7 @@ export default function History({ user }: { user: User }) {
const getSelectedUser = () => { const getSelectedUser = () => {
if (selectedCorporate) { if (selectedCorporate) {
const userInCorporate = corporateFilteredUserList.find( const userInCorporate = corporateFilteredUserList.find((x) => x.id === statsUserId);
(x) => x.id === statsUserId
);
return userInCorporate || corporateFilteredUserList[0]; return userInCorporate || corporateFilteredUserList[0];
} }
@@ -463,34 +402,21 @@ export default function History({ user }: { user: User }) {
<div className="xl:w-3/4"> <div className="xl:w-3/4">
{(user.type === "developer" || user.type === "admin") && ( {(user.type === "developer" || user.type === "admin") && (
<> <>
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">Corporate</label>
Corporate
</label>
<Select <Select
options={selectableCorporates} options={selectableCorporates}
value={selectableCorporates.find( value={selectableCorporates.find((x) => x.value === selectedCorporate)}
(x) => x.value === selectedCorporate onChange={(value) => setSelectedCorporate(value?.value || "")}
)}
onChange={(value) =>
setSelectedCorporate(value?.value || "")
}
styles={{ styles={{
menuPortal: (base) => ({...base, zIndex: 9999}), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}></Select>
></Select> <label className="font-normal text-base text-mti-gray-dim">User</label>
<label className="font-normal text-base text-mti-gray-dim">
User
</label>
<Select <Select
options={corporateFilteredUserList.map((x) => ({ options={corporateFilteredUserList.map((x) => ({
@@ -503,29 +429,20 @@ export default function History({ user }: { user: User }) {
menuPortal: (base) => ({...base, zIndex: 9999}), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}
/> />
</> </>
)} )}
{(user.type === "corporate" || user.type === "teacher") && {(user.type === "corporate" || user.type === "teacher") && groups.length > 0 && (
groups.length > 0 && (
<> <>
<label className="font-normal text-base text-mti-gray-dim"> <label className="font-normal text-base text-mti-gray-dim">User</label>
User
</label>
<Select <Select
options={users options={users
.filter((x) => .filter((x) => groups.flatMap((y) => y.participants).includes(x.id))
groups.flatMap((y) => y.participants).includes(x.id)
)
.map((x) => ({ .map((x) => ({
value: x.id, value: x.id,
label: `${x.name} - ${x.email}`, label: `${x.name} - ${x.email}`,
@@ -536,11 +453,7 @@ export default function History({ user }: { user: User }) {
menuPortal: (base) => ({...base, zIndex: 9999}), menuPortal: (base) => ({...base, zIndex: 9999}),
option: (styles, state) => ({ option: (styles, state) => ({
...styles, ...styles,
backgroundColor: state.isFocused backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
? "#D5D9F0"
: state.isSelected
? "#7872BF"
: "white",
color: state.isFocused ? "black" : styles.color, color: state.isFocused ? "black" : styles.color,
}), }),
}} }}
@@ -553,59 +466,49 @@ export default function History({ user }: { user: User }) {
className={clsx( className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", "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", "transition duration-300 ease-in-out",
filter === "assignments" && "!bg-mti-purple-light !text-white" filter === "assignments" && "!bg-mti-purple-light !text-white",
)} )}
onClick={() => toggleFilter("assignments")} onClick={() => toggleFilter("assignments")}>
>
Assignments Assignments
</button> </button>
<button <button
className={clsx( className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", "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", "transition duration-300 ease-in-out",
filter === "months" && "!bg-mti-purple-light !text-white" filter === "months" && "!bg-mti-purple-light !text-white",
)} )}
onClick={() => toggleFilter("months")} onClick={() => toggleFilter("months")}>
>
Last month Last month
</button> </button>
<button <button
className={clsx( className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", "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", "transition duration-300 ease-in-out",
filter === "weeks" && "!bg-mti-purple-light !text-white" filter === "weeks" && "!bg-mti-purple-light !text-white",
)} )}
onClick={() => toggleFilter("weeks")} onClick={() => toggleFilter("weeks")}>
>
Last week Last week
</button> </button>
<button <button
className={clsx( className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", "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", "transition duration-300 ease-in-out",
filter === "days" && "!bg-mti-purple-light !text-white" filter === "days" && "!bg-mti-purple-light !text-white",
)} )}
onClick={() => toggleFilter("days")} onClick={() => toggleFilter("days")}>
>
Last day Last day
</button> </button>
</div> </div>
</div> </div>
{groupedStats && {groupedStats && Object.keys(groupedStats).length > 0 && !isStatsLoading && (
Object.keys(groupedStats).length > 0 &&
!isStatsLoading && (
<div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full gap-4 xl:gap-6"> <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 w-full gap-4 xl:gap-6">
{Object.keys(filterStatsByDate(groupedStats)) {Object.keys(filterStatsByDate(groupedStats))
.sort((a, b) => parseInt(b) - parseInt(a)) .sort((a, b) => parseInt(b) - parseInt(a))
.map(customContent)} .map(customContent)}
</div> </div>
)} )}
{groupedStats && {groupedStats && Object.keys(groupedStats).length === 0 && !isStatsLoading && (
Object.keys(groupedStats).length === 0 && <span className="font-semibold ml-1">No record to display...</span>
!isStatsLoading && (
<span className="font-semibold ml-1">
No record to display...
</span>
)} )}
</Layout> </Layout>
)} )}

View File

@@ -51,7 +51,7 @@ export const evaluateSpeakingAnswer = async (
case "speaking": case "speaking":
return {...(await evaluateSpeakingExercise(exercise, exercise.id, solution, id, task)), id} as UserSolution; return {...(await evaluateSpeakingExercise(exercise, exercise.id, solution, id, task)), id} as UserSolution;
case "interactiveSpeaking": case "interactiveSpeaking":
return {...(await evaluateInteractiveSpeakingExercise(exercise.id, solution, id, exercise.variant)), id} as UserSolution; return {...(await evaluateInteractiveSpeakingExercise(exercise.id, solution, id, task === 3 ? "final" : "initial")), id} as UserSolution;
default: default:
return undefined; return undefined;
} }