ENCOA-90: Updated the instances of Level test to use the Grading System

This commit is contained in:
Tiago Ribeiro
2024-08-27 00:18:01 +01:00
parent a0b8521f0a
commit 0aba6355ed
6 changed files with 360 additions and 350 deletions

View File

@@ -1,298 +1,303 @@
import React from 'react'; import React from "react";
import { BsClock, BsXCircle } from 'react-icons/bs'; import {BsClock, BsXCircle} from "react-icons/bs";
import clsx from 'clsx'; import clsx from "clsx";
import { Stat, User } from '@/interfaces/user'; import {Stat, User} from "@/interfaces/user";
import { Module } from "@/interfaces"; import {Module} from "@/interfaces";
import ai_usage from "@/utils/ai.detection"; import ai_usage from "@/utils/ai.detection";
import { calculateBandScore } from "@/utils/score"; import {calculateBandScore} from "@/utils/score";
import moment from 'moment'; import moment from "moment";
import { Assignment } from '@/interfaces/results'; import {Assignment} from "@/interfaces/results";
import { uuidv4 } from "@firebase/util"; import {uuidv4} from "@firebase/util";
import { useRouter } from "next/router"; import {useRouter} from "next/router";
import { uniqBy } from "lodash"; import {uniqBy} from "lodash";
import { sortByModule } from "@/utils/moduleUtils"; import {sortByModule} from "@/utils/moduleUtils";
import { convertToUserSolutions } from "@/utils/stats"; import {convertToUserSolutions} from "@/utils/stats";
import { getExamById } from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import { Exam, UserSolution } from '@/interfaces/exam'; import {Exam, UserSolution} from "@/interfaces/exam";
import ModuleBadge from './ModuleBadge'; import ModuleBadge from "./ModuleBadge";
const formatTimestamp = (timestamp: string | number) => { const formatTimestamp = (timestamp: string | number) => {
const time = typeof timestamp === "string" ? parseInt(timestamp) : timestamp; const time = typeof timestamp === "string" ? parseInt(timestamp) : timestamp;
const date = moment(time); const date = moment(time);
const formatter = "YYYY/MM/DD - HH:mm"; const formatter = "YYYY/MM/DD - HH:mm";
return date.format(formatter); return date.format(formatter);
}; };
const aggregateScoresByModule = (stats: Stat[]): { module: Module; total: number; missing: number; correct: number }[] => { const aggregateScoresByModule = (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};
} = { } = {
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,
}, },
}; };
stats.forEach((x) => { stats.forEach((x) => {
scores[x.module!] = { scores[x.module!] = {
total: scores[x.module!].total + x.score.total, total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct, correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing, missing: scores[x.module!].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]}));
}; };
interface StatsGridItemProps { interface StatsGridItemProps {
width?: string | undefined; width?: string | undefined;
height?: string | undefined; height?: string | undefined;
examNumber?: number | undefined; examNumber?: number | undefined;
stats: Stat[]; stats: Stat[];
timestamp: string | number; timestamp: string | number;
user: User, user: User;
assignments: Assignment[]; assignments: Assignment[];
users: User[]; users: User[];
training?: boolean, training?: boolean;
selectedTrainingExams?: string[]; selectedTrainingExams?: string[];
maxTrainingExams?: number; maxTrainingExams?: number;
setSelectedTrainingExams?: React.Dispatch<React.SetStateAction<string[]>>; setSelectedTrainingExams?: React.Dispatch<React.SetStateAction<string[]>>;
setExams: (exams: Exam[]) => void; setExams: (exams: Exam[]) => void;
setShowSolutions: (show: boolean) => void; setShowSolutions: (show: boolean) => void;
setUserSolutions: (solutions: UserSolution[]) => void; setUserSolutions: (solutions: UserSolution[]) => void;
setSelectedModules: (modules: Module[]) => void; setSelectedModules: (modules: Module[]) => void;
setInactivity: (inactivity: number) => void; setInactivity: (inactivity: number) => void;
setTimeSpent: (time: number) => void; setTimeSpent: (time: number) => void;
renderPdfIcon: (session: string, color: string, textColor: string) => React.ReactNode; renderPdfIcon: (session: string, color: string, textColor: string) => React.ReactNode;
} }
const StatsGridItem: React.FC<StatsGridItemProps> = ({ const StatsGridItem: React.FC<StatsGridItemProps> = ({
stats, stats,
timestamp, timestamp,
user, user,
assignments, assignments,
users, users,
training, training,
selectedTrainingExams, selectedTrainingExams,
setSelectedTrainingExams, setSelectedTrainingExams,
setExams, setExams,
setShowSolutions, setShowSolutions,
setUserSolutions, setUserSolutions,
setSelectedModules, setSelectedModules,
setInactivity, setInactivity,
setTimeSpent, setTimeSpent,
renderPdfIcon, renderPdfIcon,
width = undefined, width = undefined,
height = undefined, height = undefined,
examNumber = undefined, examNumber = undefined,
maxTrainingExams = undefined maxTrainingExams = undefined,
}) => { }) => {
const router = useRouter(); const router = useRouter();
const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0); const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
const total = stats.reduce((accumulator, current) => accumulator + current.score.total, 0); const total = stats.reduce((accumulator, current) => accumulator + current.score.total, 0);
const aggregatedScores = aggregateScoresByModule(stats).filter((x) => x.total > 0); const aggregatedScores = aggregateScoresByModule(stats).filter((x) => x.total > 0);
const assignmentID = stats.reduce((_, current) => current.assignment as any, ""); const assignmentID = stats.reduce((_, current) => current.assignment as any, "");
const assignment = assignments.find((a) => a.id === assignmentID); const assignment = assignments.find((a) => a.id === assignmentID);
const isDisabled = stats.some((x) => x.isDisabled); const isDisabled = stats.some((x) => x.isDisabled);
const aiUsage = Math.round(ai_usage(stats) * 100); const aiUsage = Math.round(ai_usage(stats) * 100);
const aggregatedLevels = aggregatedScores.map((x) => ({ const aggregatedLevels = aggregatedScores.map((x) => ({
module: x.module, module: x.module,
level: calculateBandScore(x.correct, x.total, x.module, user.focus), level: calculateBandScore(x.correct, x.total, x.module, user.focus),
})); }));
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 { timeSpent, inactivity, session } = stats[0]; const {timeSpent, inactivity, session} = stats[0];
const selectExam = () => { const selectExam = () => {
if (training && !isDisabled && typeof maxTrainingExams !== "undefined" && typeof setSelectedTrainingExams !== "undefined" && typeof timestamp == "string") { if (
setSelectedTrainingExams(prevExams => { training &&
const uniqueExams = [...new Set(stats.map(stat => `${stat.module}-${stat.date}`))]; !isDisabled &&
const indexes = uniqueExams.map(exam => prevExams.indexOf(exam)).filter(index => index !== -1); typeof maxTrainingExams !== "undefined" &&
if (indexes.length > 0) { typeof setSelectedTrainingExams !== "undefined" &&
const newExams = [...prevExams]; typeof timestamp == "string"
indexes.sort((a, b) => b - a).forEach(index => { ) {
newExams.splice(index, 1); setSelectedTrainingExams((prevExams) => {
}); const uniqueExams = [...new Set(stats.map((stat) => `${stat.module}-${stat.date}`))];
return newExams; const indexes = uniqueExams.map((exam) => prevExams.indexOf(exam)).filter((index) => index !== -1);
} else { if (indexes.length > 0) {
if (prevExams.length + uniqueExams.length <= maxTrainingExams) { const newExams = [...prevExams];
return [...prevExams, ...uniqueExams]; indexes
} else { .sort((a, b) => b - a)
return prevExams; .forEach((index) => {
} newExams.splice(index, 1);
} });
}); return newExams;
} else { } else {
const examPromises = uniqBy(stats, "exam").map((stat) => { if (prevExams.length + uniqueExams.length <= maxTrainingExams) {
return getExamById(stat.module, stat.exam); return [...prevExams, ...uniqueExams];
}); } else {
return prevExams;
}
}
});
} else {
const examPromises = uniqBy(stats, "exam").map((stat) => {
return getExamById(stat.module, stat.exam);
});
if (isDisabled) return; 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);
if (!!inactivity) setInactivity(inactivity); if (!!inactivity) setInactivity(inactivity);
setUserSolutions(convertToUserSolutions(stats)); setUserSolutions(convertToUserSolutions(stats));
setShowSolutions(true); setShowSolutions(true);
setExams(exams.map((x) => x!).sort(sortByModule)); setExams(exams.map((x) => x!).sort(sortByModule));
setSelectedModules( setSelectedModules(
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");
} }
}); });
} }
}; };
const shouldRenderPDFIcon = () => { const shouldRenderPDFIcon = () => {
if(assignment) { if (assignment) {
return assignment.released; return assignment.released;
} }
return true; return true;
} };
const content = ( const content = (
<> <>
<div className="w-full flex justify-between -md:items-center 2xl:items-center"> <div className="w-full flex justify-between -md:items-center 2xl:items-center">
<div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2"> <div className="flex flex-col md:gap-1 -md:gap-2 2xl:gap-2">
<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 className="text-sm flex gap-2 items-center tooltip" data-tip="Time Spent"> <span 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 className="text-sm flex gap-2 items-center tooltip" data-tip="Inactivity"> <span 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>
)} )}
</div> </div>
</div> </div>
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<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>
{shouldRenderPDFIcon() && renderPdfIcon(session, textColor, textColor)} {shouldRenderPDFIcon() && renderPdfIcon(session, textColor, textColor)}
</div> </div>
{examNumber === undefined ? ( {examNumber === undefined ? (
<> <>
{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>
)}> </div>
<span className="text-xs">AI Usage</span> )}
</div> </>
)} ) : (
</> <div className="flex justify-end">
) : ( <span className="font-semibold bg-gray-200 text-gray-800 px-2.5 py-0.5 rounded-full mt-0.5">{examNumber}</span>
<div className='flex justify-end'> </div>
<span className="font-semibold bg-gray-200 text-gray-800 px-2.5 py-0.5 rounded-full mt-0.5">{examNumber}</span> )}
</div> </div>
)} </div>
</div>
</div>
<div className="w-full flex flex-col gap-1"> <div className="w-full flex flex-col gap-1">
<div className={clsx( <div className={clsx("grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2", examNumber !== undefined && "pr-10")}>
"grid grid-cols-4 gap-2 place-items-start w-full -md:mt-2", {aggregatedLevels.map(({module, level}) => (
examNumber !== undefined && "pr-10" <ModuleBadge key={module} module={module} level={level} />
)}> ))}
{aggregatedLevels.map(({ module, level }) => ( </div>
<ModuleBadge key={module} module={module} level={level} />
))}
</div>
{assignment && ( {assignment && (
<span className="font-light text-sm"> <span className="font-light text-sm">
Assignment: {assignment.name}, Teacher: {users.find((u) => u.id === assignment.assigner)?.name} Assignment: {assignment.name}, Teacher: {users.find((u) => u.id === assignment.assigner)?.name}
</span> </span>
)} )}
</div> </div>
</> </>
); );
return ( return (
<> <>
<div <div
key={uuidv4()} key={uuidv4()}
className={clsx( className={clsx(
"flex flex-col justify-between gap-4 border border-mti-gray-platinum p-4 cursor-pointer rounded-xl transition ease-in-out duration-300 -md:hidden", "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.7 && "hover:border-mti-red", correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose", correct / total < 0.3 && "hover:border-mti-rose",
typeof selectedTrainingExams !== "undefined" && typeof timestamp === "string" && selectedTrainingExams.some(exam => exam.includes(timestamp)) && "border-2 border-slate-600", typeof selectedTrainingExams !== "undefined" &&
)} typeof timestamp === "string" &&
onClick={examNumber === undefined ? selectExam : undefined} selectedTrainingExams.some((exam) => exam.includes(timestamp)) &&
style={{ "border-2 border-slate-600",
...(width !== undefined && { width }), )}
...(height !== undefined && { height }), onClick={examNumber === undefined ? selectExam : undefined}
}} style={{
data-tip="This exam is still being evaluated..." ...(width !== undefined && {width}),
role="button"> ...(height !== undefined && {height}),
{content} }}
</div> data-tip="This exam is still being evaluated..."
<div role="button">
key={uuidv4()} {content}
className={clsx( </div>
"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", <div
correct / total >= 0.7 && "hover:border-mti-purple", key={uuidv4()}
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red", className={clsx(
correct / total < 0.3 && "hover:border-mti-rose", "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",
data-tip="Your screen size is too small to view previous exams." correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
style={{ correct / total < 0.3 && "hover:border-mti-rose",
...(width !== undefined && { width }), )}
...(height !== undefined && { height }), data-tip="Your screen size is too small to view previous exams."
}} style={{
role="button"> ...(width !== undefined && {width}),
{content} ...(height !== undefined && {height}),
</div> }}
</> role="button">
); {content}
</div>
</>
);
}; };
export default StatsGridItem; export default StatsGridItem;

View File

@@ -3,6 +3,7 @@ import ProgressBar from "@/components/Low/ProgressBar";
import InviteCard from "@/components/Medium/InviteCard"; import InviteCard from "@/components/Medium/InviteCard";
import ProfileSummary from "@/components/ProfileSummary"; import ProfileSummary from "@/components/ProfileSummary";
import useAssignments from "@/hooks/useAssignments"; import useAssignments from "@/hooks/useAssignments";
import useGradingSystem from "@/hooks/useGrading";
import useInvites from "@/hooks/useInvites"; import useInvites from "@/hooks/useInvites";
import useStats from "@/hooks/useStats"; import useStats from "@/hooks/useStats";
import useUsers from "@/hooks/useUsers"; import useUsers from "@/hooks/useUsers";
@@ -13,7 +14,7 @@ import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams"; import {getExamById} from "@/utils/exams";
import {getUserCorporate} from "@/utils/groups"; import {getUserCorporate} from "@/utils/groups";
import {countExamModules, countFullExams, MODULE_ARRAY, sortByModule, sortByModuleName} from "@/utils/moduleUtils"; import {countExamModules, countFullExams, MODULE_ARRAY, sortByModule, sortByModuleName} from "@/utils/moduleUtils";
import {getLevelLabel, getLevelScore} from "@/utils/score"; import {getGradingLabel, getLevelLabel, getLevelScore} from "@/utils/score";
import {averageScore, groupBySession} from "@/utils/stats"; import {averageScore, groupBySession} from "@/utils/stats";
import {CreateOrderActions, CreateOrderData, OnApproveActions, OnApproveData, OrderResponseBody} from "@paypal/paypal-js"; import {CreateOrderActions, CreateOrderData, OnApproveActions, OnApproveData, OrderResponseBody} from "@paypal/paypal-js";
import {PayPalButtons} from "@paypal/react-paypal-js"; import {PayPalButtons} from "@paypal/react-paypal-js";
@@ -34,8 +35,9 @@ interface Props {
export default function StudentDashboard({user}: Props) { export default function StudentDashboard({user}: Props) {
const [corporateUserToShow, setCorporateUserToShow] = useState<CorporateUser>(); const [corporateUserToShow, setCorporateUserToShow] = useState<CorporateUser>();
const {stats} = useStats(user.id, !user?.id);
const {users} = useUsers(); const {users} = useUsers();
const {gradingSystem} = useGradingSystem();
const {stats} = useStats(user.id, !user?.id);
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({assignees: user?.id}); const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({assignees: user?.id});
const {invites, isLoading: isInvitesLoading, reload: reloadInvites} = useInvites({to: user.id}); const {invites, isLoading: isInvitesLoading, reload: reloadInvites} = useInvites({to: user.id});
@@ -173,10 +175,7 @@ export default function StudentDashboard({user}: Props) {
<div <div
className="tooltip flex h-full w-full items-center justify-end pl-8 md:hidden" className="tooltip flex h-full w-full items-center justify-end pl-8 md:hidden"
data-tip="Your screen size is too small to perform an assignment"> data-tip="Your screen size is too small to perform an assignment">
<Button <Button disabled={!assignment.start} className="h-full w-full !rounded-xl" variant="outline">
disabled={!assignment.start}
className="h-full w-full !rounded-xl"
variant="outline">
Start Start
</Button> </Button>
</div> </div>
@@ -243,7 +242,7 @@ export default function StudentDashboard({user}: Props) {
<div className="flex w-full justify-between"> <div className="flex w-full justify-between">
<span className="text-sm font-bold md:font-extrabold">{capitalize(module)}</span> <span className="text-sm font-bold md:font-extrabold">{capitalize(module)}</span>
<span className="text-mti-gray-dim text-sm font-normal"> <span className="text-mti-gray-dim text-sm font-normal">
{module === "level" && `English Level: ${getLevelLabel(level).join(" / ")}`} {module === "level" && !!gradingSystem && `English Level: ${getGradingLabel(level, gradingSystem.steps)}`}
{module !== "level" && `Level ${level} / Level 9 (Desired Level: ${desiredLevel})`} {module !== "level" && `Level ${level} / Level 9 (Desired Level: ${desiredLevel})`}
</span> </span>
</div> </div>
@@ -252,9 +251,9 @@ export default function StudentDashboard({user}: Props) {
<ProgressBar <ProgressBar
color={module} color={module}
label="" label=""
mark={Math.round((desiredLevel * 100) / 9)} mark={module === "level" ? undefined : Math.round((desiredLevel * 100) / 9)}
markLabel={`Desired Level: ${desiredLevel}`} markLabel={`Desired Level: ${desiredLevel}`}
percentage={Math.round((level * 100) / 9)} percentage={module === "level" ? level : Math.round((level * 100) / 9)}
className="h-2 w-full" className="h-2 w-full"
/> />
</div> </div>

View File

@@ -4,7 +4,7 @@ import {moduleResultText} from "@/constants/ielts";
import {Module} from "@/interfaces"; import {Module} from "@/interfaces";
import {User} from "@/interfaces/user"; import {User} from "@/interfaces/user";
import useExamStore from "@/stores/examStore"; import useExamStore from "@/stores/examStore";
import {calculateBandScore} from "@/utils/score"; import {calculateBandScore, getGradingLabel} from "@/utils/score";
import clsx from "clsx"; import clsx from "clsx";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
@@ -24,8 +24,9 @@ import {LevelScore} from "@/constants/ielts";
import {getLevelScore} from "@/utils/score"; import {getLevelScore} from "@/utils/score";
import {capitalize} from "lodash"; import {capitalize} from "lodash";
import Modal from "@/components/Modal"; import Modal from "@/components/Modal";
import { UserSolution } from "@/interfaces/exam"; import {UserSolution} from "@/interfaces/exam";
import ai_usage from "@/utils/ai.detection"; import ai_usage from "@/utils/ai.detection";
import useGradingSystem from "@/hooks/useGrading";
interface Score { interface Score {
module: Module; module: Module;
@@ -53,8 +54,8 @@ export default function Finish({user, scores, modules, information, solutions, i
const [isExtraInformationOpen, setIsExtraInformationOpen] = useState(false); const [isExtraInformationOpen, setIsExtraInformationOpen] = useState(false);
const aiUsage = Math.round(ai_usage(solutions) * 100); const aiUsage = Math.round(ai_usage(solutions) * 100);
const exams = useExamStore((state) => state.exams); const exams = useExamStore((state) => state.exams);
const {gradingSystem} = useGradingSystem();
useEffect(() => setSelectedScore(scores.find((x) => x.module === selectedModule)!), [scores, selectedModule]); useEffect(() => setSelectedScore(scores.find((x) => x.module === selectedModule)!), [scores, selectedModule]);
@@ -94,10 +95,10 @@ export default function Finish({user, scores, modules, information, solutions, i
const showLevel = (level: number) => { const showLevel = (level: number) => {
if (selectedModule === "level") { if (selectedModule === "level") {
const [levelStr, grade] = getLevelScore(level); const label = getGradingLabel(level, gradingSystem?.steps || []);
return ( return (
<div className="flex flex-col items-center justify-center gap-1"> <div className="flex flex-col items-center justify-center gap-1">
<span className="text-xl font-bold">{levelStr}</span> <span className="text-xl font-bold">{label}</span>
</div> </div>
); );
} }
@@ -155,26 +156,24 @@ export default function Finish({user, scores, modules, information, solutions, i
)} )}
{modules.includes("writing") && ( {modules.includes("writing") && (
<div className="flex w-full justify-between items-center"> <div className="flex w-full justify-between items-center">
<div <div
onClick={() => setSelectedModule("writing")} onClick={() => setSelectedModule("writing")}
className={clsx( className={clsx(
"hover:bg-ielts-writing flex cursor-pointer items-center gap-2 rounded-xl p-4 transition duration-300 ease-in-out hover:text-white hover:shadow-lg", "hover:bg-ielts-writing flex cursor-pointer items-center gap-2 rounded-xl p-4 transition duration-300 ease-in-out hover:text-white hover:shadow-lg",
selectedModule === "writing" ? "bg-ielts-writing text-white" : "bg-mti-gray-smoke text-ielts-writing", selectedModule === "writing" ? "bg-ielts-writing text-white" : "bg-mti-gray-smoke text-ielts-writing",
)}> )}>
<BsPen className="h-6 w-6" /> <BsPen className="h-6 w-6" />
<span className="font-semibold">Writing</span> <span className="font-semibold">Writing</span>
</div>
{aiUsage >= 50 && user.type !== "student" && (
<div className={clsx(
"flex items-center justify-center border px-3 h-full rounded",
{
'bg-orange-100 border-orange-400 text-orange-700': aiUsage < 80,
'bg-red-100 border-red-400 text-red-700': aiUsage >= 80,
}
)}>
<span className="text-xs">AI Usage</span>
</div> </div>
)} {aiUsage >= 50 && user.type !== "student" && (
<div
className={clsx("flex items-center justify-center border px-3 h-full rounded", {
"bg-orange-100 border-orange-400 text-orange-700": aiUsage < 80,
"bg-red-100 border-red-400 text-red-700": aiUsage >= 80,
})}>
<span className="text-xs">AI Usage</span>
</div>
)}
</div> </div>
)} )}
{modules.includes("speaking") && ( {modules.includes("speaking") && (

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,24 +12,25 @@ 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, LevelExam, UserSolution, Variant } from "@/interfaces/exam"; import {Exam, LevelExam, 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 { evaluateSpeakingAnswer, evaluateWritingAnswer } from "@/utils/evaluation"; import {evaluateSpeakingAnswer, evaluateWritingAnswer} from "@/utils/evaluation";
import { defaultExamUserSolutions, getExam } from "@/utils/exams"; 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";
import clsx from "clsx"; import clsx from "clsx";
import useGradingSystem from "@/hooks/useGrading";
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);
@@ -44,21 +45,21 @@ export default function ExamPage({ page }: Props) {
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 { 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((state) => state); const {selectedModules, setSelectedModules} = useExamStore((state) => state);
const { inactivity, setInactivity } = useExamStore((state) => state); const {inactivity, setInactivity} = useExamStore((state) => state);
const { bgColor, setBgColor } = useExamStore((state) => state); const {bgColor, setBgColor} = useExamStore((state) => state);
const setShuffleMaps = useExamStore((state) => state.setShuffles) const setShuffleMaps = useExamStore((state) => state.setShuffles);
const { user } = useUser({ redirectTo: "/login" }); const {user} = useUser({redirectTo: "/login"});
const router = useRouter(); const router = useRouter();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -205,9 +206,7 @@ export default function ExamPage({ page }: Props) {
}); });
useEffect(() => { useEffect(() => {
if (showSolutions) { if (showSolutions) setModuleIndex(-1);
setModuleIndex(-1);
}
}, [setModuleIndex, showSolutions]); }, [setModuleIndex, showSolutions]);
useEffect(() => { useEffect(() => {
@@ -261,11 +260,11 @@ export default function ExamPage({ page }: Props) {
date: new Date().getTime(), date: new Date().getTime(),
isDisabled: solution.isDisabled, isDisabled: solution.isDisabled,
shuffleMaps: solution.shuffleMaps, shuffleMaps: solution.shuffleMaps,
...(assignment ? { assignment: assignment.id } : {}), ...(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));
} }
@@ -277,18 +276,13 @@ export default function ExamPage({ page }: Props) {
}, [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]);
useEffect(() => { useEffect(() => {
if (exam && exam.module === "level" && exam.parts[0].intro && !showSolutions) setBgColor("bg-ielts-level-light");
if (exam && exam.module === "level" && exam.parts[0].intro && !showSolutions) { }, [exam, showSolutions, setBgColor]);
setBgColor("bg-ielts-level-light");
}
}, [exam, showSolutions, setBgColor])
const checkIfStatsHaveBeenEvaluated = (ids: string[]) => { const checkIfStatsHaveBeenEvaluated = (ids: string[]) => {
setTimeout(async () => { setTimeout(async () => {
@@ -333,7 +327,7 @@ export default function ExamPage({ page }: Props) {
), ),
}), }),
); );
return Object.assign(exam, { parts }); return Object.assign(exam, {parts});
} }
const exercises = exam.exercises.map((x) => const exercises = exam.exercises.map((x) =>
@@ -341,7 +335,7 @@ export default function ExamPage({ page }: Props) {
userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions, userSolutions: userSolutions.find((y) => x.id === y.exercise)?.solutions,
}), }),
); );
return Object.assign(exam, { exercises }); return Object.assign(exam, {exercises});
}; };
const onFinish = async (solutions: UserSolution[]) => { const onFinish = async (solutions: UserSolution[]) => {
@@ -396,7 +390,7 @@ export default function ExamPage({ page }: Props) {
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,
@@ -438,7 +432,7 @@ export default function ExamPage({ page }: Props) {
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 = () => {
@@ -472,7 +466,7 @@ export default function ExamPage({ page }: Props) {
onViewResults={(index?: number) => { onViewResults={(index?: number) => {
if (exams[0].module === "level") { if (exams[0].module === "level") {
const levelExam = exams[0] as LevelExam; const levelExam = exams[0] as LevelExam;
const allExercises = levelExam.parts.flatMap(part => part.exercises); const allExercises = levelExam.parts.flatMap((part) => part.exercises);
const exerciseOrderMap = new Map(allExercises.map((ex, index) => [ex.id, index])); const exerciseOrderMap = new Map(allExercises.map((ex, index) => [ex.id, index]));
const orderedSolutions = userSolutions.slice().sort((a, b) => { const orderedSolutions = userSolutions.slice().sort((a, b) => {
const indexA = exerciseOrderMap.get(a.exercise) ?? Infinity; const indexA = exerciseOrderMap.get(a.exercise) ?? Infinity;
@@ -480,7 +474,6 @@ export default function ExamPage({ page }: Props) {
return indexA - indexB; return indexA - indexB;
}); });
setUserSolutions(orderedSolutions); setUserSolutions(orderedSolutions);
} else { } else {
setUserSolutions(userSolutions); setUserSolutions(userSolutions);
} }

View File

@@ -34,7 +34,8 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
const snapshot = await getDoc(doc(db, "grading", req.session.user.id)); const snapshot = await getDoc(doc(db, "grading", req.session.user.id));
if (snapshot.exists()) return res.status(200).json(snapshot.data()); if (snapshot.exists()) return res.status(200).json(snapshot.data());
if (req.session.user.type !== "teacher" && req.session.user.type !== "student") return res.status(200).json(CEFR_STEPS); if (req.session.user.type !== "teacher" && req.session.user.type !== "student")
return res.status(200).json({steps: CEFR_STEPS, user: req.session.user.id});
const corporate = await getUserCorporate(req.session.user.id); const corporate = await getUserCorporate(req.session.user.id);
if (!corporate) return res.status(200).json(CEFR_STEPS); if (!corporate) return res.status(200).json(CEFR_STEPS);
@@ -42,7 +43,7 @@ async function get(req: NextApiRequest, res: NextApiResponse) {
const corporateSnapshot = await getDoc(doc(db, "grading", corporate.id)); const corporateSnapshot = await getDoc(doc(db, "grading", corporate.id));
if (corporateSnapshot.exists()) return res.status(200).json(snapshot.data()); if (corporateSnapshot.exists()) return res.status(200).json(snapshot.data());
return res.status(200).json(CEFR_STEPS); return res.status(200).json({steps: CEFR_STEPS, user: req.session.user.id});
} }
async function post(req: NextApiRequest, res: NextApiResponse) { async function post(req: NextApiRequest, res: NextApiResponse) {

View File

@@ -1,5 +1,4 @@
import {Module} from "@/interfaces"; import {Module, Step} from "@/interfaces";
import {LevelScore} from "@/constants/ielts";
import {Stat, User} from "@/interfaces/user"; import {Stat, User} from "@/interfaces/user";
type Type = "academic" | "general"; type Type = "academic" | "general";
@@ -135,6 +134,8 @@ export const calculateBandScore = (correct: number, total: number, module: Modul
const marking = moduleMarkings[module][type]; const marking = moduleMarkings[module][type];
const percentage = (correct * 100) / total; const percentage = (correct * 100) / total;
if (module === "level") return percentage;
for (const value of Object.keys(marking) for (const value of Object.keys(marking)
.map((x) => parseFloat(x)) .map((x) => parseFloat(x))
.sort((a, b) => b - a)) { .sort((a, b) => b - a)) {
@@ -147,7 +148,11 @@ export const calculateBandScore = (correct: number, total: number, module: Modul
}; };
export const calculateAverageLevel = (levels: {[key in Module]: number}) => { export const calculateAverageLevel = (levels: {[key in Module]: number}) => {
return Object.keys(levels).reduce((accumulator, current) => levels[current as Module] + accumulator, 0) / 5; return (
Object.keys(levels)
.filter((x) => x !== "level")
.reduce((accumulator, current) => levels[current as Module] + accumulator, 0) / 4
);
}; };
export const getLevelScore = (level: number) => { export const getLevelScore = (level: number) => {
@@ -180,6 +185,14 @@ export const getLevelLabel = (level: number) => {
return ["Proficiency", "C2"]; return ["Proficiency", "C2"];
}; };
export const getGradingLabel = (score: number, grading: Step[]) => {
for (const step of grading) {
if (score >= step.min && score <= step.max) return step.label;
}
return "N/A";
};
export const averageLevelCalculator = (users: User[], studentStats: Stat[]) => { export const averageLevelCalculator = (users: User[], studentStats: Stat[]) => {
const formattedStats = studentStats const formattedStats = studentStats
.map((s) => ({ .map((s) => ({