Merge branch 'develop' into ENCOA-38/add-validity-date-for-discounts

This commit is contained in:
Tiago Ribeiro
2024-05-23 19:22:31 +01:00
9 changed files with 999 additions and 1234 deletions

View File

@@ -16,9 +16,13 @@ function Question({
}: MultipleChoiceQuestion & {userSolution: string | undefined; onSelectOption?: (option: string) => void; showSolution?: boolean}) { }: MultipleChoiceQuestion & {userSolution: string | undefined; onSelectOption?: (option: string) => void; showSolution?: boolean}) {
return ( return (
<div className="flex flex-col gap-10"> <div className="flex flex-col gap-10">
<span className=""> {isNaN(Number(id)) ? (
{id} - {prompt} <span className="">{prompt}</span>
</span> ) : (
<span className="">
{id} - {prompt}
</span>
)}
<div className="flex flex-wrap gap-4 justify-between"> <div className="flex flex-wrap gap-4 justify-between">
{variant === "image" && {variant === "image" &&
options.map((option) => ( options.map((option) => (

View File

@@ -27,9 +27,13 @@ function Question({
return ( return (
<div className="flex flex-col items-center gap-4"> <div className="flex flex-col items-center gap-4">
<span> {isNaN(Number(id)) ? (
{id} - {prompt} <span className="">{prompt}</span>
</span> ) : (
<span className="">
{id} - {prompt}
</span>
)}
<div className="grid grid-cols-4 gap-4 place-items-center"> <div className="grid grid-cols-4 gap-4 place-items-center">
{variant === "image" && {variant === "image" &&
options.map((option) => ( options.map((option) => (

View File

@@ -1,6 +1,6 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import { Module } from "@/interfaces"; import {Module} from "@/interfaces";
import { useEffect, useState } from "react"; import {useEffect, useState} from "react";
import AbandonPopup from "@/components/AbandonPopup"; import AbandonPopup from "@/components/AbandonPopup";
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
@@ -12,567 +12,447 @@ import Selection from "@/exams/Selection";
import Speaking from "@/exams/Speaking"; import Speaking from "@/exams/Speaking";
import Writing from "@/exams/Writing"; import Writing from "@/exams/Writing";
import useUser from "@/hooks/useUser"; import useUser from "@/hooks/useUser";
import { Exam, UserSolution, Variant } from "@/interfaces/exam"; import {Exam, UserSolution, Variant} from "@/interfaces/exam";
import { Stat } from "@/interfaces/user"; import {Stat} from "@/interfaces/user";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import { import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
evaluateSpeakingAnswer, import {defaultExamUserSolutions, getExam} from "@/utils/exams";
evaluateWritingAnswer,
} from "@/utils/evaluation";
import { defaultExamUserSolutions, getExam } from "@/utils/exams";
import axios from "axios"; import axios from "axios";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import { toast, ToastContainer } from "react-toastify"; import {toast, ToastContainer} from "react-toastify";
import { v4 as uuidv4 } from "uuid"; import {v4 as uuidv4} from "uuid";
import useSessions from "@/hooks/useSessions"; import useSessions from "@/hooks/useSessions";
import ShortUniqueId from "short-unique-id"; import ShortUniqueId from "short-unique-id";
interface Props { interface Props {
page: "exams" | "exercises"; page: "exams" | "exercises";
} }
export default function ExamPage({ page }: Props) { export default function ExamPage({page}: Props) {
const [variant, setVariant] = useState<Variant>("full"); const [variant, setVariant] = useState<Variant>("full");
const [avoidRepeated, setAvoidRepeated] = useState(false); const [avoidRepeated, setAvoidRepeated] = useState(false);
const [hasBeenUploaded, setHasBeenUploaded] = useState(false); const [hasBeenUploaded, setHasBeenUploaded] = useState(false);
const [showAbandonPopup, setShowAbandonPopup] = useState(false); const [showAbandonPopup, setShowAbandonPopup] = useState(false);
const [isEvaluationLoading, setIsEvaluationLoading] = useState(false); const [isEvaluationLoading, setIsEvaluationLoading] = useState(false);
const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState< const [statsAwaitingEvaluation, setStatsAwaitingEvaluation] = useState<string[]>([]);
string[] const [timeSpent, setTimeSpent] = useState(0);
>([]);
const [timeSpent, setTimeSpent] = useState(0);
const resetStore = useExamStore((state) => state.reset); const resetStore = useExamStore((state) => state.reset);
const assignment = useExamStore((state) => state.assignment); const assignment = useExamStore((state) => state.assignment);
const initialTimeSpent = useExamStore((state) => state.timeSpent); const initialTimeSpent = useExamStore((state) => state.timeSpent);
const examStore = useExamStore; const examStore = useExamStore;
const { exam, setExam } = useExamStore((state) => state); const {exam, setExam} = useExamStore((state) => state);
const { exams, setExams } = useExamStore((state) => state); const {exams, setExams} = useExamStore((state) => state);
const { sessionId, setSessionId } = useExamStore((state) => state); const {sessionId, setSessionId} = useExamStore((state) => state);
const { partIndex, setPartIndex } = useExamStore((state) => state); const {partIndex, setPartIndex} = useExamStore((state) => state);
const { moduleIndex, setModuleIndex } = useExamStore((state) => state); const {moduleIndex, setModuleIndex} = useExamStore((state) => state);
const { questionIndex, setQuestionIndex } = useExamStore((state) => state); const {questionIndex, setQuestionIndex} = useExamStore((state) => state);
const { exerciseIndex, setExerciseIndex } = useExamStore((state) => state); const {exerciseIndex, setExerciseIndex} = useExamStore((state) => state);
const { userSolutions, setUserSolutions } = useExamStore((state) => state); const {userSolutions, setUserSolutions} = useExamStore((state) => state);
const { showSolutions, setShowSolutions } = useExamStore((state) => state); const {showSolutions, setShowSolutions} = useExamStore((state) => state);
const { selectedModules, setSelectedModules } = useExamStore( const {selectedModules, setSelectedModules} = useExamStore((state) => state);
(state) => state,
);
const { user } = useUser({ redirectTo: "/login" }); const {user} = useUser({redirectTo: "/login"});
const router = useRouter(); const router = useRouter();
const reset = () => { const reset = () => {
resetStore(); resetStore();
setVariant("full"); setVariant("full");
setAvoidRepeated(false); setAvoidRepeated(false);
setHasBeenUploaded(false); setHasBeenUploaded(false);
setShowAbandonPopup(false); setShowAbandonPopup(false);
setIsEvaluationLoading(false); setIsEvaluationLoading(false);
setStatsAwaitingEvaluation([]); setStatsAwaitingEvaluation([]);
setTimeSpent(0); setTimeSpent(0);
}; };
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
const saveSession = async () => { const saveSession = async () => {
console.log("Saving your session..."); console.log("Saving your session...");
await axios.post("/api/sessions", { await axios.post("/api/sessions", {
id: sessionId, id: sessionId,
sessionId, sessionId,
date: new Date().toISOString(), date: new Date().toISOString(),
userSolutions, userSolutions,
moduleIndex, moduleIndex,
selectedModules, selectedModules,
assignment, assignment,
timeSpent, timeSpent,
exams, exams,
exam, exam,
partIndex, partIndex,
exerciseIndex, exerciseIndex,
questionIndex, questionIndex,
user: user?.id, user: user?.id,
}); });
}; };
useEffect( useEffect(() => setTimeSpent((prev) => prev + initialTimeSpent), [initialTimeSpent]);
() => setTimeSpent((prev) => prev + initialTimeSpent),
[initialTimeSpent],
);
useEffect(() => { useEffect(() => {
if (userSolutions.length === 0 && exams.length > 0) { if (userSolutions.length === 0 && exams.length > 0) {
const defaultSolutions = exams.map(defaultExamUserSolutions).flat(); const defaultSolutions = exams.map(defaultExamUserSolutions).flat();
setUserSolutions(defaultSolutions); setUserSolutions(defaultSolutions);
} }
}, [exams, setUserSolutions, userSolutions]); }, [exams, setUserSolutions, userSolutions]);
useEffect(() => { useEffect(() => {
if ( if (
sessionId.length > 0 && sessionId.length > 0 &&
userSolutions.length > 0 && userSolutions.length > 0 &&
selectedModules.length > 0 && selectedModules.length > 0 &&
exams.length > 0 && exams.length > 0 &&
!!exam && !!exam &&
timeSpent > 0 && timeSpent > 0 &&
!showSolutions && !showSolutions &&
moduleIndex < selectedModules.length moduleIndex < selectedModules.length
) )
saveSession(); saveSession();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [ }, [assignment, exam, exams, moduleIndex, selectedModules, sessionId, userSolutions, user, exerciseIndex, partIndex, questionIndex]);
assignment,
exam,
exams,
moduleIndex,
selectedModules,
sessionId,
userSolutions,
user,
exerciseIndex,
partIndex,
questionIndex,
]);
useEffect(() => { useEffect(() => {
if ( if (timeSpent % 20 === 0 && timeSpent > 0 && moduleIndex < selectedModules.length && !showSolutions) saveSession();
timeSpent % 20 === 0 && // eslint-disable-next-line react-hooks/exhaustive-deps
timeSpent > 0 && }, [timeSpent]);
moduleIndex < selectedModules.length &&
!showSolutions
)
saveSession();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [timeSpent]);
useEffect(() => { useEffect(() => {
if (selectedModules.length > 0 && sessionId.length === 0) { if (selectedModules.length > 0 && sessionId.length === 0) {
const shortUID = new ShortUniqueId(); const shortUID = new ShortUniqueId();
setSessionId(shortUID.randomUUID(8)); setSessionId(shortUID.randomUUID(8));
} }
}, [setSessionId, selectedModules, sessionId]); }, [setSessionId, selectedModules, sessionId]);
useEffect(() => { useEffect(() => {
if (user?.type === "developer") console.log(exam); if (user?.type === "developer") console.log(exam);
}, [exam, user]); }, [exam, user]);
useEffect(() => { useEffect(() => {
if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) { if (selectedModules.length > 0 && timeSpent === 0 && !showSolutions) {
const timerInterval = setInterval(() => { const timerInterval = setInterval(() => {
setTimeSpent((prev) => prev + 1); setTimeSpent((prev) => prev + 1);
}, 1000); }, 1000);
return () => { return () => {
clearInterval(timerInterval); clearInterval(timerInterval);
}; };
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules.length]); }, [selectedModules.length]);
useEffect(() => { useEffect(() => {
if (showSolutions) setModuleIndex(-1); if (showSolutions) setModuleIndex(-1);
}, [setModuleIndex, showSolutions]); }, [setModuleIndex, showSolutions]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if ( if (selectedModules.length > 0 && exams.length > 0 && moduleIndex < selectedModules.length) {
selectedModules.length > 0 && const nextExam = exams[moduleIndex];
exams.length > 0 &&
moduleIndex < selectedModules.length
) {
const nextExam = exams[moduleIndex];
if (partIndex === -1 && nextExam.module !== "listening") if (partIndex === -1 && nextExam.module !== "listening") setPartIndex(0);
setPartIndex(0); if (exerciseIndex === -1 && !["reading", "listening"].includes(nextExam?.module)) setExerciseIndex(0);
if ( setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
exerciseIndex === -1 && }
!["reading", "listening"].includes(nextExam?.module) })();
) // eslint-disable-next-line react-hooks/exhaustive-deps
setExerciseIndex(0); }, [selectedModules, moduleIndex, exams]);
setExam(nextExam ? updateExamWithUserSolutions(nextExam) : undefined);
}
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, exams]);
useEffect(() => { useEffect(() => {
(async () => { (async () => {
if (selectedModules.length > 0 && exams.length === 0) { if (selectedModules.length > 0 && exams.length === 0) {
const examPromises = selectedModules.map((module) => const examPromises = selectedModules.map((module) =>
getExam( getExam(
module, module,
avoidRepeated, avoidRepeated,
variant, variant,
user?.type === "student" || user?.type === "developer" user?.type === "student" || user?.type === "developer" ? user.preferredGender : undefined,
? user.preferredGender ),
: undefined, );
), Promise.all(examPromises).then((values) => {
); if (values.every((x) => !!x)) {
Promise.all(examPromises).then((values) => { setExams(values.map((x) => x!));
if (values.every((x) => !!x)) { } else {
setExams(values.map((x) => x!)); toast.error("Something went wrong, please try again");
} else { setTimeout(router.reload, 500);
toast.error("Something went wrong, please try again"); }
setTimeout(router.reload, 500); });
} }
}); })();
} // eslint-disable-next-line react-hooks/exhaustive-deps
})(); }, [selectedModules, setExams, exams]);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, setExams, exams]);
useEffect(() => { useEffect(() => {
if ( if (selectedModules.length > 0 && exams.length !== 0 && moduleIndex >= selectedModules.length && !hasBeenUploaded && !showSolutions) {
selectedModules.length > 0 && const newStats: Stat[] = userSolutions.map((solution) => ({
exams.length !== 0 && ...solution,
moduleIndex >= selectedModules.length && id: solution.id || uuidv4(),
!hasBeenUploaded && timeSpent,
!showSolutions session: sessionId,
) { exam: solution.exam!,
const newStats: Stat[] = userSolutions.map((solution) => ({ module: solution.module!,
...solution, user: user?.id || "",
id: solution.id || uuidv4(), date: new Date().getTime(),
timeSpent, isDisabled: solution.isDisabled,
session: sessionId, ...(assignment ? {assignment: assignment.id} : {}),
exam: solution.exam!, }));
module: solution.module!,
user: user?.id || "",
date: new Date().getTime(),
isDisabled: solution.isDisabled,
...(assignment ? { assignment: assignment.id } : {}),
}));
axios axios
.post<{ ok: boolean }>("/api/stats", newStats) .post<{ok: boolean}>("/api/stats", newStats)
.then((response) => setHasBeenUploaded(response.data.ok)) .then((response) => setHasBeenUploaded(response.data.ok))
.catch(() => setHasBeenUploaded(false)); .catch(() => setHasBeenUploaded(false));
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [selectedModules, moduleIndex, hasBeenUploaded]); }, [selectedModules, moduleIndex, hasBeenUploaded]);
useEffect(() => { useEffect(() => {
setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0); setIsEvaluationLoading(statsAwaitingEvaluation.length !== 0);
}, [statsAwaitingEvaluation]); }, [statsAwaitingEvaluation]);
useEffect(() => { useEffect(() => {
if (statsAwaitingEvaluation.length > 0) { if (statsAwaitingEvaluation.length > 0) {
checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation); checkIfStatsHaveBeenEvaluated(statsAwaitingEvaluation);
} }
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [statsAwaitingEvaluation]); }, [statsAwaitingEvaluation]);
const checkIfStatsHaveBeenEvaluated = (ids: string[]) => { const checkIfStatsHaveBeenEvaluated = (ids: string[]) => {
setTimeout(async () => { setTimeout(async () => {
try { try {
const awaitedStats = await Promise.all( const awaitedStats = await Promise.all(ids.map(async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data));
ids.map( const solutionsEvaluated = awaitedStats.every((stat) => stat.solutions.every((x) => x.evaluation !== null));
async (id) => (await axios.get<Stat>(`/api/stats/${id}`)).data, if (solutionsEvaluated) {
), const statsUserSolutions: UserSolution[] = awaitedStats.map((stat) => ({
); id: stat.id,
const solutionsEvaluated = awaitedStats.every((stat) => exercise: stat.exercise,
stat.solutions.every((x) => x.evaluation !== null), score: stat.score,
); solutions: stat.solutions,
if (solutionsEvaluated) { type: stat.type,
const statsUserSolutions: UserSolution[] = awaitedStats.map( exam: stat.exam,
(stat) => ({ module: stat.module,
id: stat.id, }));
exercise: stat.exercise,
score: stat.score,
solutions: stat.solutions,
type: stat.type,
exam: stat.exam,
module: stat.module,
}),
);
const updatedUserSolutions = userSolutions.map((x) => { const updatedUserSolutions = userSolutions.map((x) => {
const respectiveSolution = statsUserSolutions.find( const respectiveSolution = statsUserSolutions.find((y) => y.exercise === x.exercise);
(y) => y.exercise === x.exercise, return respectiveSolution ? respectiveSolution : x;
); });
return respectiveSolution ? respectiveSolution : x;
});
setUserSolutions(updatedUserSolutions); setUserSolutions(updatedUserSolutions);
return setStatsAwaitingEvaluation((prev) => return setStatsAwaitingEvaluation((prev) => prev.filter((x) => !ids.includes(x)));
prev.filter((x) => !ids.includes(x)), }
);
}
return checkIfStatsHaveBeenEvaluated(ids); return checkIfStatsHaveBeenEvaluated(ids);
} catch { } catch {
return checkIfStatsHaveBeenEvaluated(ids); return checkIfStatsHaveBeenEvaluated(ids);
} }
}, 5 * 1000); }, 5 * 1000);
}; };
const updateExamWithUserSolutions = (exam: Exam): Exam => { const updateExamWithUserSolutions = (exam: Exam): Exam => {
if (exam.module === "reading" || exam.module === "listening") { if (exam.module === "reading" || exam.module === "listening") {
const parts = exam.parts.map((p) => const parts = exam.parts.map((p) =>
Object.assign(p, { Object.assign(p, {
exercises: p.exercises.map((x) => exercises: p.exercises.map((x) =>
Object.assign(x, { Object.assign(x, {
userSolutions: userSolutions.find((y) => x.id === y.exercise) userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
?.solutions, }),
}), ),
), }),
}), );
); return Object.assign(exam, {parts});
return Object.assign(exam, { parts }); }
}
const exercises = exam.exercises.map((x) => const exercises = exam.exercises.map((x) =>
Object.assign(x, { Object.assign(x, {
userSolutions: userSolutions.find((y) => x.id === y.exercise) userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
?.solutions, }),
}), );
); return Object.assign(exam, {exercises});
return Object.assign(exam, { exercises }); };
};
const onFinish = async (solutions: UserSolution[]) => { const onFinish = async (solutions: UserSolution[]) => {
const solutionIds = solutions.map((x) => x.exercise); const solutionIds = solutions.map((x) => x.exercise);
const solutionExams = solutions.map((x) => x.exam); const solutionExams = solutions.map((x) => x.exam);
let newSolutions = [...solutions]; let newSolutions = [...solutions];
if (exam && !solutionExams.includes(exam.id)) return; if (exam && !solutionExams.includes(exam.id)) return;
if ( if (exam && (exam.module === "writing" || exam.module === "speaking") && solutions.length > 0 && !showSolutions) {
exam && setHasBeenUploaded(true);
(exam.module === "writing" || exam.module === "speaking") && setIsEvaluationLoading(true);
solutions.length > 0 &&
!showSolutions
) {
setHasBeenUploaded(true);
setIsEvaluationLoading(true);
const responses: UserSolution[] = ( const responses: UserSolution[] = (
await Promise.all( await Promise.all(
exam.exercises.map(async (exercise, index) => { exam.exercises.map(async (exercise, index) => {
const evaluationID = uuidv4(); const evaluationID = uuidv4();
if (exercise.type === "writing") if (exercise.type === "writing")
return await evaluateWritingAnswer( return await evaluateWritingAnswer(exercise, index + 1, solutions.find((x) => x.exercise === exercise.id)!, evaluationID);
exercise,
index + 1,
solutions.find((x) => x.exercise === exercise.id)!,
evaluationID,
);
if ( if (exercise.type === "interactiveSpeaking" || exercise.type === "speaking")
exercise.type === "interactiveSpeaking" || return await evaluateSpeakingAnswer(
exercise.type === "speaking" exercise,
) solutions.find((x) => x.exercise === exercise.id)!,
return await evaluateSpeakingAnswer( evaluationID,
exercise, index === 0 ? 1 : 2,
solutions.find((x) => x.exercise === exercise.id)!, );
evaluationID, }),
); )
}), ).filter((x) => !!x) as UserSolution[];
)
).filter((x) => !!x) as UserSolution[];
newSolutions = [ newSolutions = [...newSolutions.filter((x) => !responses.map((y) => y.exercise).includes(x.exercise)), ...responses];
...newSolutions.filter( setStatsAwaitingEvaluation((prev) => [...prev, ...responses.filter((x) => !!x).map((r) => (r as any).id)]);
(x) => !responses.map((y) => y.exercise).includes(x.exercise), setHasBeenUploaded(false);
), }
...responses,
];
setStatsAwaitingEvaluation((prev) => [
...prev,
...responses.filter((x) => !!x).map((r) => (r as any).id),
]);
setHasBeenUploaded(false);
}
axios.get("/api/stats/update"); axios.get("/api/stats/update");
setUserSolutions([ setUserSolutions([...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), ...newSolutions]);
...userSolutions.filter((x) => !solutionIds.includes(x.exercise)), setModuleIndex(moduleIndex + 1);
...newSolutions,
]);
setModuleIndex(moduleIndex + 1);
setPartIndex(-1); setPartIndex(-1);
setExerciseIndex(-1); setExerciseIndex(-1);
setQuestionIndex(0); setQuestionIndex(0);
}; };
const aggregateScoresByModule = (): { const aggregateScoresByModule = (): {
module: Module; module: Module;
total: number; total: number;
missing: number; missing: number;
correct: 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};
} = { } = {
reading: { reading: {
total: 0, total: 0,
correct: 0, correct: 0,
missing: 0, missing: 0,
}, },
listening: { listening: {
total: 0, total: 0,
correct: 0, correct: 0,
missing: 0, missing: 0,
}, },
writing: { writing: {
total: 0, total: 0,
correct: 0, correct: 0,
missing: 0, missing: 0,
}, },
speaking: { speaking: {
total: 0, total: 0,
correct: 0, correct: 0,
missing: 0, missing: 0,
}, },
level: { level: {
total: 0, total: 0,
correct: 0, correct: 0,
missing: 0, missing: 0,
}, },
}; };
userSolutions.forEach((x) => { userSolutions.forEach((x) => {
const examModule = const examModule =
x.module || x.module || (x.type === "writing" ? "writing" : x.type === "speaking" || x.type === "interactiveSpeaking" ? "speaking" : undefined);
(x.type === "writing"
? "writing"
: x.type === "speaking" || x.type === "interactiveSpeaking"
? "speaking"
: undefined);
scores[examModule!] = { scores[examModule!] = {
total: scores[examModule!].total + x.score.total, total: scores[examModule!].total + x.score.total,
correct: scores[examModule!].correct + x.score.correct, correct: scores[examModule!].correct + x.score.correct,
missing: scores[examModule!].missing + x.score.missing, missing: scores[examModule!].missing + x.score.missing,
}; };
}); });
return Object.keys(scores) return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0) .filter((x) => scores[x as Module].total > 0)
.map((x) => ({ module: x as Module, ...scores[x as Module] })); .map((x) => ({module: x as Module, ...scores[x as Module]}));
}; };
const renderScreen = () => { const renderScreen = () => {
if (selectedModules.length === 0) { if (selectedModules.length === 0) {
return ( return (
<Selection <Selection
page={page} page={page}
user={user!} user={user!}
disableSelection={page === "exams"} disableSelection={page === "exams"}
onStart={(modules: Module[], avoid: boolean, variant: Variant) => { onStart={(modules: Module[], avoid: boolean, variant: Variant) => {
setModuleIndex(0); setModuleIndex(0);
setAvoidRepeated(avoid); setAvoidRepeated(avoid);
setSelectedModules(modules); setSelectedModules(modules);
setVariant(variant); setVariant(variant);
}} }}
/> />
); );
} }
if (moduleIndex >= selectedModules.length || moduleIndex === -1) { if (moduleIndex >= selectedModules.length || moduleIndex === -1) {
return ( return (
<Finish <Finish
isLoading={isEvaluationLoading} isLoading={isEvaluationLoading}
user={user!} user={user!}
modules={selectedModules} modules={selectedModules}
onViewResults={(index?: number) => { onViewResults={(index?: number) => {
setShowSolutions(true); setShowSolutions(true);
setModuleIndex(index || 0); setModuleIndex(index || 0);
setExerciseIndex( setExerciseIndex(["reading", "listening"].includes(exams[0].module) ? -1 : 0);
["reading", "listening"].includes(exams[0].module) ? -1 : 0, setPartIndex(exams[0].module === "listening" ? -1 : 0);
); setExam(exams[0]);
setPartIndex(exams[0].module === "listening" ? -1 : 0); }}
setExam(exams[0]); scores={aggregateScoresByModule()}
}} />
scores={aggregateScoresByModule()} );
/> }
);
}
if (exam && exam.module === "reading") { if (exam && exam.module === "reading") {
return ( return <Reading exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Reading }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "listening") { if (exam && exam.module === "listening") {
return ( return <Listening exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Listening }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "writing") { if (exam && exam.module === "writing") {
return ( return <Writing exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Writing }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "speaking") { if (exam && exam.module === "speaking") {
return ( return <Speaking exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Speaking }
exam={exam}
onFinish={onFinish}
showSolutions={showSolutions}
/>
);
}
if (exam && exam.module === "level") { if (exam && exam.module === "level") {
return ( return <Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} />;
<Level exam={exam} onFinish={onFinish} showSolutions={showSolutions} /> }
);
}
return <>Loading...</>; return <>Loading...</>;
}; };
return ( return (
<> <>
<ToastContainer /> <ToastContainer />
{user && ( {user && (
<Layout <Layout
user={user} user={user}
className="justify-between" className="justify-between"
focusMode={ focusMode={selectedModules.length !== 0 && !showSolutions && moduleIndex < selectedModules.length}
selectedModules.length !== 0 && onFocusLayerMouseEnter={() => setShowAbandonPopup(true)}>
!showSolutions && <>
moduleIndex < selectedModules.length {renderScreen()}
} {!showSolutions && moduleIndex < selectedModules.length && (
onFocusLayerMouseEnter={() => setShowAbandonPopup(true)} <AbandonPopup
> isOpen={showAbandonPopup}
<> abandonPopupTitle="Leave Exercise"
{renderScreen()} abandonPopupDescription="Are you sure you want to leave the exercise? Your progress will be saved and this exam can be resumed on the Dashboard."
{!showSolutions && moduleIndex < selectedModules.length && ( abandonConfirmButtonText="Confirm"
<AbandonPopup onAbandon={() => {
isOpen={showAbandonPopup} reset();
abandonPopupTitle="Leave Exercise" }}
abandonPopupDescription="Are you sure you want to leave the exercise? Your progress will be saved and this exam can be resumed on the Dashboard." onCancel={() => setShowAbandonPopup(false)}
abandonConfirmButtonText="Confirm" />
onAbandon={() => { )}
reset(); </>
}} </Layout>
onCancel={() => setShowAbandonPopup(false)} )}
/> </>
)} );
</>
</Layout>
)}
</>
);
} }

View File

@@ -121,12 +121,12 @@ export default function PaymentDue({user, hasExpired = false, clientID, reload}:
</span> </span>
</div> </div>
<div className="flex w-full flex-col items-start gap-2"> <div className="flex w-full flex-col items-start gap-2">
{!appliedDiscount && ( {appliedDiscount === 0 && (
<span className="text-2xl"> <span className="text-2xl">
{p.price} {p.currency} {p.price} {p.currency}
</span> </span>
)} )}
{appliedDiscount && ( {appliedDiscount > 0 && (
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<span className="text-2xl line-through"> <span className="text-2xl line-through">
{p.price} {p.currency} {p.price} {p.currency}

View File

@@ -30,6 +30,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
const audioFile = files.audio; const audioFile = files.audio;
const audioFileRef = ref(storage, `speaking_recordings/${fields.id}.wav`); const audioFileRef = ref(storage, `speaking_recordings/${fields.id}.wav`);
const task = parseInt(fields.task.toString());
const binary = fs.readFileSync((audioFile as any).path).buffer; const binary = fs.readFileSync((audioFile as any).path).buffer;
const snapshot = await uploadBytes(audioFileRef, binary); const snapshot = await uploadBytes(audioFileRef, binary);
@@ -39,7 +40,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
res.status(200).json(null); res.status(200).json(null);
console.log("🌱 - Still processing"); console.log("🌱 - Still processing");
const backendRequest = await evaluate({answers: [{question: fields.question, answer: path}]}); const backendRequest = await evaluate({answer: path, question: fields.question}, task);
console.log("🌱 - Process complete"); console.log("🌱 - Process complete");
const correspondingStat = await getCorrespondingStat(fields.id, 1); const correspondingStat = await getCorrespondingStat(fields.id, 1);
@@ -76,14 +77,14 @@ async function getCorrespondingStat(id: string, index: number): Promise<Stat> {
return getCorrespondingStat(id, index + 1); return getCorrespondingStat(id, index + 1);
} }
async function evaluate(body: {answers: object[]}): Promise<AxiosResponse> { async function evaluate(body: {answer: string; question: string}, task: number): Promise<AxiosResponse> {
const backendRequest = await axios.post(`${process.env.BACKEND_URL}/speaking_task_3`, body, { const backendRequest = await axios.post(`${process.env.BACKEND_URL}/speaking_task_${task}`, body, {
headers: { headers: {
Authorization: `Bearer ${process.env.BACKEND_JWT}`, Authorization: `Bearer ${process.env.BACKEND_JWT}`,
}, },
}); });
if (typeof backendRequest.data === "string") return evaluate(body); if (typeof backendRequest.data === "string") return evaluate(body, task);
return backendRequest; return backendRequest;
} }

View File

@@ -90,7 +90,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
if (updatedUser.status || updatedUser.type === "corporate") { if (updatedUser.status || updatedUser.type === "corporate") {
// there's no await as this does not affect the user // there's no await as this does not affect the user
propagateStatusChange(queryId, updatedUser.status); propagateStatusChange(queryId, updatedUser.status);
propagateExpiryDateChanges(queryId, user.subscriptionExpirationDate || null, updatedUser.subscriptionExpirationDate || null); propagateExpiryDateChanges(queryId, user.subscriptionExpirationDate, updatedUser.subscriptionExpirationDate || null);
} }
res.status(200).json({ok: true}); res.status(200).json({ok: true});

File diff suppressed because it is too large Load Diff

View File

@@ -45,10 +45,11 @@ export const evaluateSpeakingAnswer = async (
exercise: SpeakingExercise | InteractiveSpeakingExercise, exercise: SpeakingExercise | InteractiveSpeakingExercise,
solution: UserSolution, solution: UserSolution,
id: string, id: string,
task: number,
): Promise<UserSolution | undefined> => { ): Promise<UserSolution | undefined> => {
switch (exercise?.type) { switch (exercise?.type) {
case "speaking": case "speaking":
return {...(await evaluateSpeakingExercise(exercise, exercise.id, solution, id)), 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)), id} as UserSolution; return {...(await evaluateInteractiveSpeakingExercise(exercise.id, solution, id)), id} as UserSolution;
default: default:
@@ -66,6 +67,7 @@ const evaluateSpeakingExercise = async (
exerciseId: string, exerciseId: string,
solution: UserSolution, solution: UserSolution,
id: string, id: string,
task: number,
): Promise<UserSolution | undefined> => { ): Promise<UserSolution | undefined> => {
const formData = new FormData(); const formData = new FormData();
@@ -81,6 +83,7 @@ const evaluateSpeakingExercise = async (
`${exercise.text.replaceAll("\n", "")}` + (exercise.prompts.length > 0 ? `You should talk about: ${exercise.prompts.join(", ")}` : ""); `${exercise.text.replaceAll("\n", "")}` + (exercise.prompts.length > 0 ? `You should talk about: ${exercise.prompts.join(", ")}` : "");
formData.append("question", evaluationQuestion); formData.append("question", evaluationQuestion);
formData.append("id", id); formData.append("id", id);
formData.append("task", task.toString());
const config = { const config = {
headers: { headers: {

View File

@@ -67,7 +67,7 @@ export const propagateStatusChange = (userId: string, status: UserStatus) =>
}); });
}); });
export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null, subscriptionExpirationDate: Date | null) => export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Date | null | undefined, subscriptionExpirationDate: Date | null) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
getDoc(doc(db, "users", userId)) getDoc(doc(db, "users", userId))
.then((docUser) => { .then((docUser) => {
@@ -93,6 +93,7 @@ export const propagateExpiryDateChanges = (userId: string, initialExpiryDate: Da
.then(async (data) => { .then(async (data) => {
const filtered = data.filter((x) => { const filtered = data.filter((x) => {
if (x === null) return false; if (x === null) return false;
if (!x.subscriptionExpirationDate && !initialExpiryDate) return true;
if (x.subscriptionExpirationDate !== initialExpiryDate) return false; if (x.subscriptionExpirationDate !== initialExpiryDate) return false;
return true; return true;
}) as User[]; }) as User[];