Updated the dashboard to the v2 version

This commit is contained in:
Tiago Ribeiro
2024-10-03 11:32:43 +01:00
parent 3d4a604aa2
commit b5200c88fc
14 changed files with 2181 additions and 1552 deletions

View File

@@ -1,249 +1,249 @@
import clsx from "clsx"; import clsx from "clsx";
import {IconType} from "react-icons"; import { IconType } from "react-icons";
import {MdSpaceDashboard} from "react-icons/md"; import { MdSpaceDashboard } from "react-icons/md";
import { import {
BsFileEarmarkText, BsFileEarmarkText,
BsClockHistory, BsClockHistory,
BsPencil, BsPencil,
BsGraphUp, BsGraphUp,
BsChevronBarRight, BsChevronBarRight,
BsChevronBarLeft, BsChevronBarLeft,
BsShieldFill, BsShieldFill,
BsCloudFill, BsCloudFill,
BsCurrencyDollar, BsCurrencyDollar,
BsClipboardData, BsClipboardData,
BsFileLock, BsFileLock,
BsPeople, BsPeople,
} from "react-icons/bs"; } from "react-icons/bs";
import {CiDumbbell} from "react-icons/ci"; import { CiDumbbell } from "react-icons/ci";
import {RiLogoutBoxFill} from "react-icons/ri"; import { RiLogoutBoxFill } from "react-icons/ri";
import {SlPencil} from "react-icons/sl"; import { SlPencil } from "react-icons/sl";
import {FaAward} from "react-icons/fa"; import { FaAward } from "react-icons/fa";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router"; import { useRouter } from "next/router";
import axios from "axios"; import axios from "axios";
import FocusLayer from "@/components/FocusLayer"; import FocusLayer from "@/components/FocusLayer";
import {preventNavigation} from "@/utils/navigation.disabled"; import { preventNavigation } from "@/utils/navigation.disabled";
import {useEffect, useState} from "react"; import { useEffect, useState } from "react";
import usePreferencesStore from "@/stores/preferencesStore"; import usePreferencesStore from "@/stores/preferencesStore";
import {User} from "@/interfaces/user"; import { User } from "@/interfaces/user";
import useTicketsListener from "@/hooks/useTicketsListener"; import useTicketsListener from "@/hooks/useTicketsListener";
import {checkAccess, getTypesOfUser} from "@/utils/permissions"; import { checkAccess, getTypesOfUser } from "@/utils/permissions";
import usePermissions from "@/hooks/usePermissions"; import usePermissions from "@/hooks/usePermissions";
interface Props { interface Props {
path: string; path: string;
navDisabled?: boolean; navDisabled?: boolean;
focusMode?: boolean; focusMode?: boolean;
onFocusLayerMouseEnter?: () => void; onFocusLayerMouseEnter?: () => void;
className?: string; className?: string;
user: User; user: User;
} }
interface NavProps { interface NavProps {
Icon: IconType; Icon: IconType;
label: string; label: string;
path: string; path: string;
keyPath: string; keyPath: string;
disabled?: boolean; disabled?: boolean;
isMinimized?: boolean; isMinimized?: boolean;
badge?: number; badge?: number;
} }
const Nav = ({Icon, label, path, keyPath, disabled = false, isMinimized = false, badge}: NavProps) => { const Nav = ({ Icon, label, path, keyPath, disabled = false, isMinimized = false, badge }: NavProps) => {
return ( return (
<Link <Link
href={!disabled ? keyPath : ""} href={!disabled ? keyPath : ""}
className={clsx( className={clsx(
"flex items-center gap-4 rounded-full p-4 text-gray-500 hover:text-white", "flex items-center gap-4 rounded-full p-4 text-gray-500 hover:text-white",
"transition-all duration-300 ease-in-out relative", "transition-all duration-300 ease-in-out relative",
disabled ? "hover:bg-mti-gray-dim cursor-not-allowed" : "hover:bg-mti-purple-light cursor-pointer", disabled ? "hover:bg-mti-gray-dim cursor-not-allowed" : "hover:bg-mti-purple-light cursor-pointer",
(keyPath === "/" ? path === keyPath : path.startsWith(keyPath)) && "bg-mti-purple-light text-white", path.startsWith(keyPath) && "bg-mti-purple-light text-white",
isMinimized ? "w-fit" : "w-full min-w-[200px] px-8 2xl:min-w-[220px]", isMinimized ? "w-fit" : "w-full min-w-[200px] px-8 2xl:min-w-[220px]",
)}> )}>
<Icon size={24} /> <Icon size={24} />
{!isMinimized && <span className="text-lg font-semibold">{label}</span>} {!isMinimized && <span className="text-lg font-semibold">{label}</span>}
{!!badge && badge > 0 && ( {!!badge && badge > 0 && (
<div <div
className={clsx( className={clsx(
"bg-mti-purple-light h-5 w-5 text-xs rounded-full flex items-center justify-center text-white", "bg-mti-purple-light h-5 w-5 text-xs rounded-full flex items-center justify-center text-white",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
isMinimized && "absolute right-0 top-0", isMinimized && "absolute right-0 top-0",
)}> )}>
{badge} {badge}
</div> </div>
)} )}
</Link> </Link>
); );
}; };
export default function Sidebar({path, navDisabled = false, focusMode = false, user, onFocusLayerMouseEnter, className}: Props) { export default function Sidebar({ path, navDisabled = false, focusMode = false, user, onFocusLayerMouseEnter, className }: Props) {
const router = useRouter(); const router = useRouter();
const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]); const [isMinimized, toggleMinimize] = usePreferencesStore((state) => [state.isSidebarMinimized, state.toggleSidebarMinimized]);
const {totalAssignedTickets} = useTicketsListener(user.id); const { totalAssignedTickets } = useTicketsListener(user.id);
const {permissions} = usePermissions(user.id); const { permissions } = usePermissions(user.id);
const logout = async () => { const logout = async () => {
axios.post("/api/logout").finally(() => { axios.post("/api/logout").finally(() => {
setTimeout(() => router.reload(), 500); setTimeout(() => router.reload(), 500);
}); });
}; };
const disableNavigation = preventNavigation(navDisabled, focusMode); const disableNavigation = preventNavigation(navDisabled, focusMode);
return ( return (
<section <section
className={clsx( className={clsx(
"relative flex h-full flex-col justify-between bg-transparent px-4 py-4 pb-8", "relative flex h-full flex-col justify-between bg-transparent px-4 py-4 pb-8",
isMinimized ? "w-fit" : "-xl:w-fit w-1/6", isMinimized ? "w-fit" : "-xl:w-fit w-1/6",
className, className,
)}> )}>
<div className="-xl:hidden flex-col gap-3 xl:flex"> <div className="-xl:hidden flex-col gap-3 xl:flex">
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/dashboard" isMinimized={isMinimized} />
{checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExams") && ( {checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExams") && (
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={isMinimized} />
)} )}
{checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExercises") && ( {checkAccess(user, ["student", "teacher", "developer"], permissions, "viewExercises") && (
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={isMinimized} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={isMinimized} />
)} )}
{checkAccess(user, ["developer", "admin", "mastercorporate", "corporate", "teacher", "student"], permissions) && ( {checkAccess(user, ["developer", "admin", "mastercorporate", "corporate", "teacher", "student"], permissions) && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsPeople} Icon={BsPeople}
label="Classrooms" label="Classrooms"
path={path} path={path}
keyPath="/classrooms" keyPath="/classrooms"
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={isMinimized} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={isMinimized} /> <Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={isMinimized} />
)} )}
{checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], permissions, "viewPaymentRecords") && ( {checkAccess(user, ["admin", "developer", "agent", "corporate", "mastercorporate"], permissions, "viewPaymentRecords") && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsCurrencyDollar} Icon={BsCurrencyDollar}
label="Payment Record" label="Payment Record"
path={path} path={path}
keyPath="/payment-record" keyPath="/payment-record"
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
{checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"]) && ( {checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"]) && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsShieldFill} Icon={BsShieldFill}
label="Settings" label="Settings"
path={path} path={path}
keyPath="/settings" keyPath="/settings"
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
{checkAccess(user, ["admin", "developer", "agent"], permissions, "viewTickets") && ( {checkAccess(user, ["admin", "developer", "agent"], permissions, "viewTickets") && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsClipboardData} Icon={BsClipboardData}
label="Tickets" label="Tickets"
path={path} path={path}
keyPath="/tickets" keyPath="/tickets"
isMinimized={isMinimized} isMinimized={isMinimized}
badge={totalAssignedTickets} badge={totalAssignedTickets}
/> />
)} )}
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && ( {checkAccess(user, ["developer", "admin", "corporate", "mastercorporate"]) && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsCloudFill} Icon={BsCloudFill}
label="Generation" label="Generation"
path={path} path={path}
keyPath="/generation" keyPath="/generation"
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
{checkAccess(user, ["developer", "admin", "corporate", "mastercorporate", "agent"]) && ( {checkAccess(user, ["developer", "admin", "corporate", "mastercorporate", "agent"]) && (
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsFileLock} Icon={BsFileLock}
label="Permissions" label="Permissions"
path={path} path={path}
keyPath="/permissions" keyPath="/permissions"
isMinimized={isMinimized} isMinimized={isMinimized}
/> />
)} )}
</div> </div>
<div className="-xl:flex flex-col gap-3 xl:hidden"> <div className="-xl:flex flex-col gap-3 xl:hidden">
<Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={MdSpaceDashboard} label="Dashboard" path={path} keyPath="/" isMinimized={true} />
<Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsFileEarmarkText} label="Exams" path={path} keyPath="/exam" isMinimized={true} />
<Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsPencil} label="Exercises" path={path} keyPath="/exercises" isMinimized={true} />
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewStats") && (
<Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsGraphUp} label="Stats" path={path} keyPath="/stats" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsClockHistory} label="Record" path={path} keyPath="/record" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && ( {checkAccess(user, getTypesOfUser(["agent"]), permissions, "viewRecords") && (
<Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={CiDumbbell} label="Training" path={path} keyPath="/training" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["student"])) && ( {checkAccess(user, getTypesOfUser(["student"])) && (
<Nav disabled={disableNavigation} Icon={BsShieldFill} label="Settings" path={path} keyPath="/settings" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsShieldFill} label="Settings" path={path} keyPath="/settings" isMinimized={true} />
)} )}
{checkAccess(user, getTypesOfUser(["student"])) && ( {checkAccess(user, getTypesOfUser(["student"])) && (
<Nav disabled={disableNavigation} Icon={BsShieldFill} label="Permissions" path={path} keyPath="/permissions" isMinimized={true} /> <Nav disabled={disableNavigation} Icon={BsShieldFill} label="Permissions" path={path} keyPath="/permissions" isMinimized={true} />
)} )}
{checkAccess(user, ["developer"]) && ( {checkAccess(user, ["developer"]) && (
<> <>
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsCloudFill} Icon={BsCloudFill}
label="Generation" label="Generation"
path={path} path={path}
keyPath="/generation" keyPath="/generation"
isMinimized={true} isMinimized={true}
/> />
<Nav <Nav
disabled={disableNavigation} disabled={disableNavigation}
Icon={BsFileLock} Icon={BsFileLock}
label="Permissions" label="Permissions"
path={path} path={path}
keyPath="/permissions" keyPath="/permissions"
isMinimized={true} isMinimized={true}
/> />
</> </>
)} )}
</div> </div>
<div className="2xl:fixed bottom-12 flex flex-col gap-0 -2xl:mt-8"> <div className="2xl:fixed bottom-12 flex flex-col gap-0 -2xl:mt-8">
<div <div
role="button" role="button"
tabIndex={1} tabIndex={1}
onClick={toggleMinimize} onClick={toggleMinimize}
className={clsx( className={clsx(
"hover:text-mti-rose -xl:hidden flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out", "hover:text-mti-rose -xl:hidden flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out",
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8", isMinimized ? "w-fit" : "w-full min-w-[250px] px-8",
)}> )}>
{isMinimized ? <BsChevronBarRight size={24} /> : <BsChevronBarLeft size={24} />} {isMinimized ? <BsChevronBarRight size={24} /> : <BsChevronBarLeft size={24} />}
{!isMinimized && <span className="text-lg font-medium">Minimize</span>} {!isMinimized && <span className="text-lg font-medium">Minimize</span>}
</div> </div>
<div <div
role="button" role="button"
tabIndex={1} tabIndex={1}
onClick={focusMode ? () => {} : logout} onClick={focusMode ? () => { } : logout}
className={clsx( className={clsx(
"hover:text-mti-rose flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out", "hover:text-mti-rose flex cursor-pointer items-center gap-4 rounded-full p-4 text-black transition duration-300 ease-in-out",
isMinimized ? "w-fit" : "w-full min-w-[250px] px-8", isMinimized ? "w-fit" : "w-full min-w-[250px] px-8",
)}> )}>
<RiLogoutBoxFill size={24} /> <RiLogoutBoxFill size={24} />
{!isMinimized && <span className="-xl:hidden text-lg font-medium">Log Out</span>} {!isMinimized && <span className="-xl:hidden text-lg font-medium">Log Out</span>}
</div> </div>
</div> </div>
{focusMode && <FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />} {focusMode && <FocusLayer onFocusLayerMouseEnter={onFocusLayerMouseEnter} />}
</section> </section>
); );
} }

View File

@@ -49,7 +49,6 @@ export default function AssignmentCard({
const renderUnarchiveIcon = useAssignmentUnarchive(id, reload); const renderUnarchiveIcon = useAssignmentUnarchive(id, reload);
const renderReleaseIcon = useAssignmentRelease(id, reload); const renderReleaseIcon = useAssignmentRelease(id, reload);
const calculateAverageModuleScore = (module: Module) => { const calculateAverageModuleScore = (module: Module) => {
const resultModuleBandScores = results.map((r) => { const resultModuleBandScores = results.map((r) => {
const moduleStats = r.stats.filter((s) => s.module === module); const moduleStats = r.stats.filter((s) => s.module === module);
@@ -65,26 +64,26 @@ export default function AssignmentCard({
const uniqModules = uniqBy(exams, (x) => x.module); const uniqModules = uniqBy(exams, (x) => x.module);
const shouldRenderPDF = () => { const shouldRenderPDF = () => {
if(released && allowDownload) { if (released && allowDownload) {
// in order to be downloadable, the assignment has to be released // in order to be downloadable, the assignment has to be released
// the component should have the allowDownload prop // the component should have the allowDownload prop
// and the assignment should not have the level module // and the assignment should not have the level module
return uniqModules.every(({ module }) => module !== 'level'); return uniqModules.every(({module}) => module !== "level");
} }
return false; return false;
} };
const shouldRenderExcel = () => { const shouldRenderExcel = () => {
if(released && allowExcelDownload) { if (released && allowExcelDownload) {
// in order to be downloadable, the assignment has to be released // in order to be downloadable, the assignment has to be released
// the component should have the allowExcelDownload prop // the component should have the allowExcelDownload prop
// and the assignment should have the level module // and the assignment should have the level module
return uniqModules.some(({ module }) => module === 'level'); return uniqModules.some(({module}) => module === "level");
} }
return false; return false;
} };
return ( return (
<div <div

View File

@@ -0,0 +1,421 @@
import Button from "@/components/Low/Button";
import ProgressBar from "@/components/Low/ProgressBar";
import Modal from "@/components/Modal";
import useUsers from "@/hooks/useUsers";
import {Module} from "@/interfaces";
import {Assignment} from "@/interfaces/results";
import {Group, Stat, User} from "@/interfaces/user";
import useExamStore from "@/stores/examStore";
import {getExamById} from "@/utils/exams";
import {sortByModule} from "@/utils/moduleUtils";
import {calculateBandScore} from "@/utils/score";
import {convertToUserSolutions} from "@/utils/stats";
import {getUserName} from "@/utils/users";
import axios from "axios";
import clsx from "clsx";
import {capitalize, uniqBy} from "lodash";
import moment from "moment";
import {useRouter} from "next/router";
import {BsBook, BsChevronLeft, BsClipboard, BsHeadphones, BsMegaphone, BsPen} from "react-icons/bs";
import {toast} from "react-toastify";
import {futureAssignmentFilter} from "@/utils/assignments";
import {withIronSessionSsr} from "iron-session/next";
import {checkAccess} from "@/utils/permissions";
import {mapBy, serialize} from "@/utils";
import {getAssignment} from "@/utils/assignments.be";
import {getEntitiesUsers, getUsers} from "@/utils/users.be";
import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
import {sessionOptions} from "@/lib/session";
import {EntityWithRoles} from "@/interfaces/entity";
import Head from "next/head";
import Layout from "@/components/High/Layout";
import Separator from "@/components/Low/Separator";
import Link from "next/link";
export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
const user = req.session.user as User | undefined;
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
if (!checkAccess(user, ["admin", "developer", "corporate", "teacher", "mastercorporate"]))
return {
redirect: {
destination: "/dashboard",
permanent: false,
},
};
res.setHeader("Cache-Control", "public, s-maxage=10, stale-while-revalidate=59");
const {id} = params as {id: string};
const entityIDS = mapBy(user.entities, "id") || [];
const assignment = await getAssignment(id);
if (!assignment)
return {
redirect: {
destination: "/assignments",
permanent: false,
},
};
const users = await (checkAccess(user, ["developer", "admin"]) ? getUsers() : getEntitiesUsers(entityIDS));
const entities = await (checkAccess(user, ["developer", "admin"]) ? getEntitiesWithRoles() : getEntitiesWithRoles(entityIDS));
const groups = await (checkAccess(user, ["developer", "admin"]) ? getGroups() : getGroupsByEntities(entityIDS));
return {props: serialize({user, users, entities, assignment, groups})};
}, sessionOptions);
interface Props {
user: User;
users: User[];
assignment: Assignment;
groups: Group[];
entities: EntityWithRoles[];
}
export default function AssignmentView({user, users, entities, groups, assignment}: Props) {
const setExams = useExamStore((state) => state.setExams);
const setShowSolutions = useExamStore((state) => state.setShowSolutions);
const setUserSolutions = useExamStore((state) => state.setUserSolutions);
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
const router = useRouter();
const deleteAssignment = async () => {
if (!confirm("Are you sure you want to delete this assignment?")) return;
axios
.delete(`/api/assignments/${assignment?.id}`)
.then(() => toast.success(`Successfully deleted the assignment "${assignment?.name}".`))
.catch(() => toast.error("Something went wrong, please try again later."))
.finally(() => router.push("/assignments"));
};
const startAssignment = () => {
if (assignment) {
axios
.post(`/api/assignments/${assignment.id}/start`)
.then(() => {
toast.success(`The assignment "${assignment.name}" has been started successfully!`);
router.replace(router.asPath);
})
.catch((e) => {
console.log(e);
toast.error("Something went wrong, please try again later!");
});
}
};
const formatTimestamp = (timestamp: string) => {
const date = moment(parseInt(timestamp));
const formatter = "YYYY/MM/DD - HH:mm";
return date.format(formatter);
};
const calculateAverageModuleScore = (module: Module) => {
if (!assignment) return -1;
const resultModuleBandScores = assignment.results.map((r) => {
const moduleStats = r.stats.filter((s) => s.module === module);
const correct = moduleStats.reduce((acc, curr) => acc + curr.score.correct, 0);
const total = moduleStats.reduce((acc, curr) => acc + curr.score.total, 0);
return calculateBandScore(correct, total, module, r.type);
});
return resultModuleBandScores.length === 0 ? -1 : resultModuleBandScores.reduce((acc, curr) => acc + curr, 0) / assignment.results.length;
};
const aggregateScoresByModule = (stats: Stat[]): {module: Module; total: number; missing: number; correct: number}[] => {
const scores: {
[key in Module]: {total: number; missing: number; correct: number};
} = {
reading: {
total: 0,
correct: 0,
missing: 0,
},
listening: {
total: 0,
correct: 0,
missing: 0,
},
writing: {
total: 0,
correct: 0,
missing: 0,
},
speaking: {
total: 0,
correct: 0,
missing: 0,
},
level: {
total: 0,
correct: 0,
missing: 0,
},
};
stats.forEach((x) => {
scores[x.module!] = {
total: scores[x.module!].total + x.score.total,
correct: scores[x.module!].correct + x.score.correct,
missing: scores[x.module!].missing + x.score.missing,
};
});
return Object.keys(scores)
.filter((x) => scores[x as Module].total > 0)
.map((x) => ({module: x as Module, ...scores[x as Module]}));
};
const customContent = (stats: Stat[], user: string, focus: "academic" | "general") => {
const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
const total = stats.reduce((accumulator, current) => accumulator + current.score.total, 0);
const aggregatedScores = aggregateScoresByModule(stats).filter((x) => x.total > 0);
const aggregatedLevels = aggregatedScores.map((x) => ({
module: x.module,
level: calculateBandScore(x.correct, x.total, x.module, focus),
}));
const timeSpent = stats[0].timeSpent;
const selectExam = () => {
const examPromises = uniqBy(stats, "exam").map((stat) => getExamById(stat.module, stat.exam));
Promise.all(examPromises).then((exams) => {
if (exams.every((x) => !!x)) {
setUserSolutions(convertToUserSolutions(stats));
setShowSolutions(true);
setExams(exams.map((x) => x!).sort(sortByModule));
setSelectedModules(
exams
.map((x) => x!)
.sort(sortByModule)
.map((x) => x!.module),
);
router.push("/exercises");
}
});
};
const content = (
<>
<div className="-md:items-center flex w-full justify-between 2xl:items-center">
<div className="-md:gap-2 -md:items-center flex md:flex-col md:gap-1 2xl:flex-row 2xl:items-center 2xl:gap-2">
<span className="font-medium">{formatTimestamp(stats[0].date.toString())}</span>
{timeSpent && (
<>
<span className="md:hidden 2xl:flex"> </span>
<span className="text-sm">{Math.floor(timeSpent / 60)} minutes</span>
</>
)}
</div>
<span
className={clsx(
correct / total >= 0.7 && "text-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
correct / total < 0.3 && "text-mti-rose",
)}>
Level{" "}
{(aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length).toFixed(1)}
</span>
</div>
<div className="flex w-full flex-col gap-1">
<div className="-md:mt-2 grid w-full grid-cols-4 place-items-start gap-2">
{aggregatedLevels.map(({module, level}) => (
<div
key={module}
className={clsx(
"-md:px-4 flex w-fit items-center gap-2 rounded-xl py-2 text-white md:px-2 xl:px-4",
module === "reading" && "bg-ielts-reading",
module === "listening" && "bg-ielts-listening",
module === "writing" && "bg-ielts-writing",
module === "speaking" && "bg-ielts-speaking",
module === "level" && "bg-ielts-level",
)}>
{module === "reading" && <BsBook className="h-4 w-4" />}
{module === "listening" && <BsHeadphones className="h-4 w-4" />}
{module === "writing" && <BsPen className="h-4 w-4" />}
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
{module === "level" && <BsClipboard className="h-4 w-4" />}
<span className="text-sm">{level.toFixed(1)}</span>
</div>
))}
</div>
</div>
</>
);
return (
<div className="flex flex-col gap-2">
<span>
{(() => {
const student = users.find((u) => u.id === user);
return `${student?.name} (${student?.email})`;
})()}
</span>
<div
key={user}
className={clsx(
"border-mti-gray-platinum -md:hidden flex cursor-pointer flex-col gap-4 rounded-xl border p-4 transition duration-300 ease-in-out",
correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose",
)}
onClick={selectExam}
role="button">
{content}
</div>
<div
key={user}
className={clsx(
"border-mti-gray-platinum -md:tooltip flex cursor-pointer flex-col gap-4 rounded-xl border p-4 transition duration-300 ease-in-out md:hidden",
correct / total >= 0.7 && "hover:border-mti-purple",
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
correct / total < 0.3 && "hover:border-mti-rose",
)}
data-tip="Your screen size is too small to view previous exams."
role="button">
{content}
</div>
</div>
);
};
const shouldRenderStart = () => {
if (assignment) {
if (futureAssignmentFilter(assignment)) {
return true;
}
}
return false;
};
return (
<>
<Head>
<title>{assignment.name} | EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user}>
<div className="flex flex-col gap-4">
<div className="flex items-center gap-2">
<Link href="/assignments" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">{assignment.name}</h2>
</div>
<Separator />
</div>
<div className="mt-4 flex w-full flex-col gap-4">
<ProgressBar
color="purple"
label={`${assignment?.results.length}/${assignment?.assignees.length} assignees completed`}
className="h-6"
textClassName={
(assignment?.results.length || 0) / (assignment?.assignees.length || 1) < 0.5
? "!text-mti-gray-dim font-light"
: "text-white"
}
percentage={((assignment?.results.length || 0) / (assignment?.assignees.length || 1)) * 100}
/>
<div className="flex items-start gap-8">
<div className="flex flex-col gap-2">
<span>Start Date: {moment(assignment?.startDate).format("DD/MM/YY, HH:mm")}</span>
<span>End Date: {moment(assignment?.endDate).format("DD/MM/YY, HH:mm")}</span>
</div>
<div className="flex flex-col gap-2">
<span>
Assignees:{" "}
{users
.filter((u) => assignment?.assignees.includes(u.id))
.map((u) => `${u.name} (${u.email})`)
.join(", ")}
</span>
<span>Assigner: {getUserName(users.find((x) => x.id === assignment?.assigner))}</span>
</div>
</div>
<div className="flex flex-col gap-2">
<span className="text-xl font-bold">Average Scores</span>
<div className="-md:mt-2 flex w-full items-center gap-4">
{assignment &&
uniqBy(assignment.exams, (x) => x.module).map(({module}) => (
<div
data-tip={capitalize(module)}
key={module}
className={clsx(
"-md:px-4 tooltip flex w-fit items-center gap-2 rounded-xl py-2 text-white md:px-2 xl:px-4",
module === "reading" && "bg-ielts-reading",
module === "listening" && "bg-ielts-listening",
module === "writing" && "bg-ielts-writing",
module === "speaking" && "bg-ielts-speaking",
module === "level" && "bg-ielts-level",
)}>
{module === "reading" && <BsBook className="h-4 w-4" />}
{module === "listening" && <BsHeadphones className="h-4 w-4" />}
{module === "writing" && <BsPen className="h-4 w-4" />}
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
{module === "level" && <BsClipboard className="h-4 w-4" />}
{calculateAverageModuleScore(module) > -1 && (
<span className="text-sm">{calculateAverageModuleScore(module).toFixed(1)}</span>
)}
</div>
))}
</div>
</div>
<div className="flex flex-col gap-2">
<span className="text-xl font-bold">
Results ({assignment?.results.length}/{assignment?.assignees.length})
</span>
<div>
{assignment && assignment?.results.length > 0 && (
<div className="grid w-full grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 xl:gap-6">
{assignment.results.map((r) => customContent(r.stats, r.user, r.type))}
</div>
)}
{assignment && assignment?.results.length === 0 && <span className="ml-1 font-semibold">No results yet...</span>}
</div>
</div>
<div className="flex gap-4 w-full items-center justify-end">
{assignment &&
(assignment.results.length === assignment.assignees.length || moment().isAfter(moment(assignment.endDate))) && (
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={deleteAssignment}>
Delete
</Button>
)}
{/** if the assignment is not deemed as active yet, display start */}
{shouldRenderStart() && (
<Button variant="outline" color="green" className="w-full max-w-[200px]" onClick={startAssignment}>
Start
</Button>
)}
<Button onClick={() => router.push("/assignments")} className="w-full max-w-[200px]">
Close
</Button>
</div>
</div>
</Layout>
</>
);
}

View File

@@ -4,6 +4,7 @@ import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import ProgressBar from "@/components/Low/ProgressBar"; import ProgressBar from "@/components/Low/ProgressBar";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import Separator from "@/components/Low/Separator";
import useExams from "@/hooks/useExams"; import useExams from "@/hooks/useExams";
import {useListSearch} from "@/hooks/useListSearch"; import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination"; import usePagination from "@/hooks/usePagination";
@@ -16,20 +17,22 @@ import {sessionOptions} from "@/lib/session";
import {mapBy, serialize} from "@/utils"; import {mapBy, serialize} from "@/utils";
import {getAssignment} from "@/utils/assignments.be"; import {getAssignment} from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be"; import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be"; import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import {calculateAverageLevel} from "@/utils/score"; import {calculateAverageLevel} from "@/utils/score";
import {getEntitiesUsers} from "@/utils/users.be"; import {getEntitiesUsers, getUsers} from "@/utils/users.be";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next"; import {withIronSessionSsr} from "iron-session/next";
import {capitalize} from "lodash"; import {capitalize} from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import {generate} from "random-words"; import {generate} from "random-words";
import {useEffect, useMemo, useState} from "react"; import {useEffect, useMemo, useState} from "react";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs"; import {BsBook, BsCheckCircle, BsChevronLeft, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => { export const getServerSideProps = withIronSessionSsr(async ({req, res, params}) => {
@@ -66,9 +69,9 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res, params})
}, },
}; };
const users = await getEntitiesUsers(entityIDS); const users = await (checkAccess(user, ["developer", "admin"]) ? getUsers() : getEntitiesUsers(entityIDS));
const entities = await getEntitiesWithRoles(entityIDS); const entities = await (checkAccess(user, ["developer", "admin"]) ? getEntitiesWithRoles() : getEntitiesWithRoles(entityIDS));
const groups = await getGroupsByEntities(entityIDS); const groups = await (checkAccess(user, ["developer", "admin"]) ? getGroups() : getGroupsByEntities(entityIDS));
return {props: serialize({user, users, entities, assignment, groups})}; return {props: serialize({user, users, entities, assignment, groups})};
}, sessionOptions); }, sessionOptions);
@@ -209,141 +212,127 @@ export default function AssignmentsPage({assignment, user, users, entities, grou
}; };
return ( return (
<Layout user={user}> <>
<div className="w-full flex flex-col gap-4"> <Head>
<section className="w-full grid -md:grid-cols-1 md:grid-cols-3 place-items-center -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8 px-8"> <title>Edit {assignment.name} | EnCoach</title>
<div <meta
onClick={!selectedModules.includes("level") ? () => toggleModule("reading") : undefined} name="description"
className={clsx( content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer", />
selectedModules.includes("reading") ? "border-mti-purple-light" : "border-mti-gray-platinum", <meta name="viewport" content="width=device-width, initial-scale=1" />
)}> <link rel="icon" href="/favicon.ico" />
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-reading top-1/2 -translate-y-1/2 left-0 -translate-x-1/2"> </Head>
<BsBook className="text-white w-7 h-7" /> <Layout user={user}>
</div> <div className="flex flex-col gap-4">
<span className="ml-8 font-semibold">Reading</span> <div className="flex items-center gap-2">
{!selectedModules.includes("reading") && !selectedModules.includes("level") && ( <Link href="/assignments" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" /> <BsChevronLeft />
)} </Link>
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />} <h2 className="font-bold text-2xl">Edit {assignment.name}</h2>
{selectedModules.includes("reading") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div> </div>
<div <Separator />
onClick={!selectedModules.includes("level") ? () => toggleModule("listening") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("listening") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-listening top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsHeadphones className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Listening</span>
{!selectedModules.includes("listening") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("listening") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={
(!selectedModules.includes("level") && selectedModules.length === 0) || selectedModules.includes("level")
? () => toggleModule("level")
: undefined
}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("level") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-level top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsClipboard className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Level</span>
{!selectedModules.includes("level") && selectedModules.length === 0 && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{!selectedModules.includes("level") && selectedModules.length > 0 && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("level") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("writing") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("writing") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-writing top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsPen className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Writing</span>
{!selectedModules.includes("writing") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("writing") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("speaking") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("speaking") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-speaking top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsMegaphone className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Speaking</span>
{!selectedModules.includes("speaking") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("speaking") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
</section>
<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />
<Select
label="Entity"
options={entities.map((e) => ({value: e.id, label: e.label}))}
onChange={(v) => setEntity(v ? v.value! : undefined)}
defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
/>
</div> </div>
<div className="w-full flex flex-col gap-4">
<section className="w-full grid -md:grid-cols-1 md:grid-cols-3 place-items-center -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8 px-8">
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("reading") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("reading") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-reading top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsBook className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Reading</span>
{!selectedModules.includes("reading") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("reading") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("listening") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("listening") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-listening top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsHeadphones className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Listening</span>
{!selectedModules.includes("listening") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("listening") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={
(!selectedModules.includes("level") && selectedModules.length === 0) || selectedModules.includes("level")
? () => toggleModule("level")
: undefined
}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("level") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-level top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsClipboard className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Level</span>
{!selectedModules.includes("level") && selectedModules.length === 0 && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{!selectedModules.includes("level") && selectedModules.length > 0 && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("level") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("writing") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("writing") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-writing top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsPen className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Writing</span>
{!selectedModules.includes("writing") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("writing") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("speaking") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("speaking") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-speaking top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsMegaphone className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Speaking</span>
{!selectedModules.includes("speaking") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("speaking") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
</section>
<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8"> <div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<div className="flex flex-col gap-2"> <Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />
<label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label> <Select
<ReactDatePicker label="Entity"
className={clsx( options={entities.map((e) => ({value: e.id, label: e.label}))}
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", onChange={(v) => setEntity(v ? v.value! : undefined)}
"hover:border-mti-purple tooltip z-10", defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
"transition duration-300 ease-in-out",
)}
popperClassName="!z-20"
filterTime={(date) => moment(date).isSameOrAfter(new Date())}
dateFormat="dd/MM/yyyy HH:mm"
selected={startDate}
showTimeSelect
onChange={(date) => setStartDate(date)}
/> />
</div> </div>
<div className="flex flex-col gap-2">
<label className="font-normal text-base text-mti-gray-dim">End Date *</label> <div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<ReactDatePicker
className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"hover:border-mti-purple tooltip z-10",
"transition duration-300 ease-in-out",
)}
popperClassName="!z-20"
filterTime={(date) => moment(date).isAfter(startDate)}
dateFormat="dd/MM/yyyy HH:mm"
selected={endDate}
showTimeSelect
onChange={(date) => setEndDate(date)}
/>
</div>
{autoStart && (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label> <label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label>
<ReactDatePicker <ReactDatePicker
className={clsx( className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
@@ -353,146 +342,118 @@ export default function AssignmentsPage({assignment, user, users, entities, grou
popperClassName="!z-20" popperClassName="!z-20"
filterTime={(date) => moment(date).isSameOrAfter(new Date())} filterTime={(date) => moment(date).isSameOrAfter(new Date())}
dateFormat="dd/MM/yyyy HH:mm" dateFormat="dd/MM/yyyy HH:mm"
selected={autoStartDate} selected={startDate}
showTimeSelect showTimeSelect
onChange={(date) => setAutoStartDate(date)} onChange={(date) => setStartDate(date)}
/> />
</div> </div>
)} <div className="flex flex-col gap-2">
</div> <label className="font-normal text-base text-mti-gray-dim">End Date *</label>
<ReactDatePicker
{selectedModules.includes("speaking") && ( className={clsx(
<div className="flex flex-col gap-3 w-full"> "p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label> "hover:border-mti-purple tooltip z-10",
<Select "transition duration-300 ease-in-out",
value={{ )}
value: instructorGender, popperClassName="!z-20"
label: capitalize(instructorGender), filterTime={(date) => moment(date).isAfter(startDate)}
}} dateFormat="dd/MM/yyyy HH:mm"
onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)} selected={endDate}
disabled={!selectedModules.includes("speaking") || !!assignment} showTimeSelect
options={[ onChange={(date) => setEndDate(date)}
{value: "male", label: "Male"}, />
{value: "female", label: "Female"}, </div>
{value: "varied", label: "Varied"}, {autoStart && (
]} <div className="flex flex-col gap-2">
/> <label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label>
</div> <ReactDatePicker
)} className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
{selectedModules.length > 0 && ( "hover:border-mti-purple tooltip z-10",
<div className="flex flex-col gap-3 w-full"> "transition duration-300 ease-in-out",
<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}> )}
Random Exams popperClassName="!z-20"
</Checkbox> filterTime={(date) => moment(date).isSameOrAfter(new Date())}
{!useRandomExams && ( dateFormat="dd/MM/yyyy HH:mm"
<div className="grid md:grid-cols-2 w-full gap-4"> selected={autoStartDate}
{selectedModules.map((module) => ( showTimeSelect
<div key={module} className="flex flex-col gap-3 w-full"> onChange={(date) => setAutoStartDate(date)}
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label> />
<Select
value={{
value: examIDs.find((e) => e.module === module)?.id || null,
label: examIDs.find((e) => e.module === module)?.id || "",
}}
onChange={(value) =>
value
? setExamIDs((prev) => [...prev.filter((x) => x.module !== module), {id: value.value!, module}])
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
}
options={exams
.filter((x) => !x.isDiagnostic && x.module === module)
.map((x) => ({value: x.id, label: x.id}))}
/>
</div>
))}
</div> </div>
)} )}
</div> </div>
)}
<section className="w-full flex flex-col gap-4"> {selectedModules.includes("speaking") && (
<span className="font-semibold">Assignees ({assignees.length} selected)</span> <div className="flex flex-col gap-3 w-full">
<div className="grid grid-cols-5 gap-4"> <label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label>
{classrooms.map((g) => ( <Select
<button value={{
key={g.id} value: instructorGender,
onClick={() => { label: capitalize(instructorGender),
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
if (groupStudentIds.every((u) => assignees.includes(u))) {
setAssignees((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
} else {
setAssignees((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
}
}} }}
className={clsx( onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)}
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", disabled={!selectedModules.includes("speaking") || !!assignment}
"transition duration-300 ease-in-out", options={[
users.filter((u) => g.participants.includes(u.id)).every((u) => assignees.includes(u.id)) && {value: "male", label: "Male"},
"!bg-mti-purple-light !text-white", {value: "female", label: "Female"},
)}> {value: "varied", label: "Varied"},
{g.name} ]}
</button> />
))} </div>
</div> )}
<div className="w-full flex items-center gap-4"> {selectedModules.length > 0 && (
{renderStudentSearch()} <div className="flex flex-col gap-3 w-full">
{renderStudentPagination()} <Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
</div> Random Exams
</Checkbox>
{!useRandomExams && (
<div className="grid md:grid-cols-2 w-full gap-4">
{selectedModules.map((module) => (
<div key={module} className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
<Select
value={{
value: examIDs.find((e) => e.module === module)?.id || null,
label: examIDs.find((e) => e.module === module)?.id || "",
}}
onChange={(value) =>
value
? setExamIDs((prev) => [
...prev.filter((x) => x.module !== module),
{id: value.value!, module},
])
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
}
options={exams
.filter((x) => !x.isDiagnostic && x.module === module)
.map((x) => ({value: x.id, label: x.id}))}
/>
</div>
))}
</div>
)}
</div>
)}
<div className="flex flex-wrap -md:justify-center gap-4"> <section className="w-full flex flex-col gap-4">
{studentRows.map((user) => ( <span className="font-semibold">Assignees ({assignees.length} selected)</span>
<div
onClick={() => toggleAssignee(user)}
className={clsx(
"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
"transition ease-in-out duration-300",
assignees.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
)}
key={user.id}>
<span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span>
</span>
<ProgressBar
color="purple"
textClassName="!text-mti-black/80"
label={`Level ${calculateAverageLevel(user.levels)}`}
percentage={(calculateAverageLevel(user.levels) / 9) * 100}
className="h-6"
/>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "}
{groups
.filter((g) => g.participants.includes(user.id))
.map((g) => g.name)
.join(", ")}
</span>
</div>
))}
</div>
</section>
{user.type !== "teacher" && (
<section className="w-full flex flex-col gap-3">
<span className="font-semibold">Teachers ({teachers.length} selected)</span>
<div className="grid grid-cols-5 gap-4"> <div className="grid grid-cols-5 gap-4">
{classrooms.map((g) => ( {classrooms.map((g) => (
<button <button
key={g.id} key={g.id}
onClick={() => { onClick={() => {
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id); const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
if (groupStudentIds.every((u) => teachers.includes(u))) { if (groupStudentIds.every((u) => assignees.includes(u))) {
setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a))); setAssignees((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
} else { } else {
setTeachers((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]); setAssignees((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
} }
}} }}
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",
users.filter((u) => g.participants.includes(u.id)).every((u) => teachers.includes(u.id)) && users.filter((u) => g.participants.includes(u.id)).every((u) => assignees.includes(u.id)) &&
"!bg-mti-purple-light !text-white", "!bg-mti-purple-light !text-white",
)}> )}>
{g.name} {g.name}
@@ -501,24 +462,31 @@ export default function AssignmentsPage({assignment, user, users, entities, grou
</div> </div>
<div className="w-full flex items-center gap-4"> <div className="w-full flex items-center gap-4">
{renderTeacherSearch()} {renderStudentSearch()}
{renderTeacherPagination()} {renderStudentPagination()}
</div> </div>
<div className="flex flex-wrap -md:justify-center gap-4"> <div className="flex flex-wrap -md:justify-center gap-4">
{teacherRows.map((user) => ( {studentRows.map((user) => (
<div <div
onClick={() => toggleTeacher(user)} onClick={() => toggleAssignee(user)}
className={clsx( className={clsx(
"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72", "p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
teachers.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum", assignees.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
)} )}
key={user.id}> key={user.id}>
<span className="flex flex-col gap-0 justify-center"> <span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span> <span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span> <span className="text-sm opacity-80">{user.email}</span>
</span> </span>
<ProgressBar
color="purple"
textClassName="!text-mti-black/80"
label={`Level ${calculateAverageLevel(user.levels)}`}
percentage={(calculateAverageLevel(user.levels) / 9) * 100}
className="h-6"
/>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2"> <span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "} Groups:{" "}
{groups {groups
@@ -530,65 +498,123 @@ export default function AssignmentsPage({assignment, user, users, entities, grou
))} ))}
</div> </div>
</section> </section>
)}
<div className="flex gap-4 w-full items-end"> {user.type !== "teacher" && (
<Checkbox isChecked={variant === "full"} onChange={() => setVariant((prev) => (prev === "full" ? "partial" : "full"))}> <section className="w-full flex flex-col gap-3">
Full length exams <span className="font-semibold">Teachers ({teachers.length} selected)</span>
</Checkbox> <div className="grid grid-cols-5 gap-4">
<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}> {classrooms.map((g) => (
Generate different exams <button
</Checkbox> key={g.id}
<Checkbox isChecked={released} onChange={() => setReleased((d) => !d)}> onClick={() => {
Auto release results const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
</Checkbox> if (groupStudentIds.every((u) => teachers.includes(u))) {
<Checkbox isChecked={autoStart} onChange={() => setAutostart((d) => !d)}> setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
Auto start exam } else {
</Checkbox> setTeachers((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
}
}}
className={clsx(
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
"transition duration-300 ease-in-out",
users.filter((u) => g.participants.includes(u.id)).every((u) => teachers.includes(u.id)) &&
"!bg-mti-purple-light !text-white",
)}>
{g.name}
</button>
))}
</div>
<div className="w-full flex items-center gap-4">
{renderTeacherSearch()}
{renderTeacherPagination()}
</div>
<div className="flex flex-wrap -md:justify-center gap-4">
{teacherRows.map((user) => (
<div
onClick={() => toggleTeacher(user)}
className={clsx(
"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
"transition ease-in-out duration-300",
teachers.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
)}
key={user.id}>
<span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span>
</span>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "}
{groups
.filter((g) => g.participants.includes(user.id))
.map((g) => g.name)
.join(", ")}
</span>
</div>
))}
</div>
</section>
)}
<div className="flex gap-4 w-full items-end">
<Checkbox isChecked={variant === "full"} onChange={() => setVariant((prev) => (prev === "full" ? "partial" : "full"))}>
Full length exams
</Checkbox>
<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}>
Generate different exams
</Checkbox>
<Checkbox isChecked={released} onChange={() => setReleased((d) => !d)}>
Auto release results
</Checkbox>
<Checkbox isChecked={autoStart} onChange={() => setAutostart((d) => !d)}>
Auto start exam
</Checkbox>
</div>
<div className="flex gap-4 w-full justify-end">
<Button
className="w-full max-w-[200px]"
variant="outline"
onClick={() => router.push("/assignments")}
disabled={isLoading}
isLoading={isLoading}>
Cancel
</Button>
<Button
className="w-full max-w-[200px]"
color="green"
variant="outline"
onClick={startAssignment}
disabled={isLoading || moment().isAfter(startDate)}
isLoading={isLoading}>
Start
</Button>
<Button
className="w-full max-w-[200px]"
color="red"
variant="outline"
onClick={deleteAssignment}
disabled={isLoading}
isLoading={isLoading}>
Delete
</Button>
<Button
disabled={
selectedModules.length === 0 ||
!name ||
!startDate ||
!endDate ||
assignees.length === 0 ||
(!useRandomExams && examIDs.length < selectedModules.length)
}
className="w-full max-w-[200px]"
onClick={createAssignment}
isLoading={isLoading}>
Update
</Button>
</div>
</div> </div>
<div className="flex gap-4 w-full justify-end"> </Layout>
<Button </>
className="w-full max-w-[200px]"
variant="outline"
onClick={() => router.push("/assignments")}
disabled={isLoading}
isLoading={isLoading}>
Cancel
</Button>
<Button
className="w-full max-w-[200px]"
color="green"
variant="outline"
onClick={startAssignment}
disabled={isLoading || moment().isAfter(startDate)}
isLoading={isLoading}>
Start
</Button>
<Button
className="w-full max-w-[200px]"
color="red"
variant="outline"
onClick={deleteAssignment}
disabled={isLoading}
isLoading={isLoading}>
Delete
</Button>
<Button
disabled={
selectedModules.length === 0 ||
!name ||
!startDate ||
!endDate ||
assignees.length === 0 ||
(!useRandomExams && examIDs.length < selectedModules.length)
}
className="w-full max-w-[200px]"
onClick={createAssignment}
isLoading={isLoading}>
Update
</Button>
</div>
</div>
</Layout>
); );
} }

View File

@@ -4,6 +4,7 @@ import Checkbox from "@/components/Low/Checkbox";
import Input from "@/components/Low/Input"; import Input from "@/components/Low/Input";
import ProgressBar from "@/components/Low/ProgressBar"; import ProgressBar from "@/components/Low/ProgressBar";
import Select from "@/components/Low/Select"; import Select from "@/components/Low/Select";
import Separator from "@/components/Low/Separator";
import useExams from "@/hooks/useExams"; import useExams from "@/hooks/useExams";
import {useListSearch} from "@/hooks/useListSearch"; import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination"; import usePagination from "@/hooks/usePagination";
@@ -15,20 +16,22 @@ import {Group, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {mapBy, serialize} from "@/utils"; import {mapBy, serialize} from "@/utils";
import {getEntitiesWithRoles} from "@/utils/entities.be"; import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be"; import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import {calculateAverageLevel} from "@/utils/score"; import {calculateAverageLevel} from "@/utils/score";
import {getEntitiesUsers} from "@/utils/users.be"; import {getEntitiesUsers, getUsers} from "@/utils/users.be";
import axios from "axios"; import axios from "axios";
import clsx from "clsx"; import clsx from "clsx";
import {withIronSessionSsr} from "iron-session/next"; import {withIronSessionSsr} from "iron-session/next";
import {capitalize} from "lodash"; import {capitalize} from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head";
import Link from "next/link";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import {generate} from "random-words"; import {generate} from "random-words";
import {useEffect, useMemo, useState} from "react"; import {useEffect, useMemo, useState} from "react";
import ReactDatePicker from "react-datepicker"; import ReactDatePicker from "react-datepicker";
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs"; import {BsBook, BsCheckCircle, BsChevronLeft, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
import {toast} from "react-toastify"; import {toast} from "react-toastify";
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => { export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
@@ -53,9 +56,9 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
const entityIDS = mapBy(user.entities, "id") || []; const entityIDS = mapBy(user.entities, "id") || [];
const users = await getEntitiesUsers(entityIDS); const users = await (checkAccess(user, ["developer", "admin"]) ? getUsers() : getEntitiesUsers(entityIDS));
const entities = await getEntitiesWithRoles(entityIDS); const entities = await (checkAccess(user, ["developer", "admin"]) ? getEntitiesWithRoles() : getEntitiesWithRoles(entityIDS));
const groups = await getGroupsByEntities(entityIDS); const groups = await (checkAccess(user, ["developer", "admin"]) ? getGroups() : getGroupsByEntities(entityIDS));
return {props: serialize({user, users, entities, groups})}; return {props: serialize({user, users, entities, groups})};
}, sessionOptions); }, sessionOptions);
@@ -169,141 +172,127 @@ export default function AssignmentsPage({user, users, groups, entities}: Props)
}; };
return ( return (
<Layout user={user}> <>
<div className="w-full flex flex-col gap-4"> <Head>
<section className="w-full grid -md:grid-cols-1 md:grid-cols-3 place-items-center -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8 px-8"> <title>Create Assignment | EnCoach</title>
<div <meta
onClick={!selectedModules.includes("level") ? () => toggleModule("reading") : undefined} name="description"
className={clsx( content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer", />
selectedModules.includes("reading") ? "border-mti-purple-light" : "border-mti-gray-platinum", <meta name="viewport" content="width=device-width, initial-scale=1" />
)}> <link rel="icon" href="/favicon.ico" />
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-reading top-1/2 -translate-y-1/2 left-0 -translate-x-1/2"> </Head>
<BsBook className="text-white w-7 h-7" /> <Layout user={user}>
</div> <div className="flex flex-col gap-4">
<span className="ml-8 font-semibold">Reading</span> <div className="flex items-center gap-2">
{!selectedModules.includes("reading") && !selectedModules.includes("level") && ( <Link href="/assignments" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" /> <BsChevronLeft />
)} </Link>
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />} <h2 className="font-bold text-2xl">Create Assignment</h2>
{selectedModules.includes("reading") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div> </div>
<div <Separator />
onClick={!selectedModules.includes("level") ? () => toggleModule("listening") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("listening") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-listening top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsHeadphones className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Listening</span>
{!selectedModules.includes("listening") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("listening") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={
(!selectedModules.includes("level") && selectedModules.length === 0) || selectedModules.includes("level")
? () => toggleModule("level")
: undefined
}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("level") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-level top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsClipboard className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Level</span>
{!selectedModules.includes("level") && selectedModules.length === 0 && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{!selectedModules.includes("level") && selectedModules.length > 0 && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("level") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("writing") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("writing") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-writing top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsPen className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Writing</span>
{!selectedModules.includes("writing") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("writing") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("speaking") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("speaking") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-speaking top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsMegaphone className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Speaking</span>
{!selectedModules.includes("speaking") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("speaking") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
</section>
<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />
<Select
label="Entity"
options={entities.map((e) => ({value: e.id, label: e.label}))}
onChange={(v) => setEntity(v ? v.value! : undefined)}
defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
/>
</div> </div>
<div className="w-full flex flex-col gap-4">
<section className="w-full grid -md:grid-cols-1 md:grid-cols-3 place-items-center -md:flex-col -md:items-center -md:gap-12 justify-between gap-8 mt-8 px-8">
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("reading") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("reading") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-reading top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsBook className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Reading</span>
{!selectedModules.includes("reading") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("reading") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("listening") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("listening") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-listening top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsHeadphones className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Listening</span>
{!selectedModules.includes("listening") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("listening") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={
(!selectedModules.includes("level") && selectedModules.length === 0) || selectedModules.includes("level")
? () => toggleModule("level")
: undefined
}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("level") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-level top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsClipboard className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Level</span>
{!selectedModules.includes("level") && selectedModules.length === 0 && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{!selectedModules.includes("level") && selectedModules.length > 0 && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("level") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("writing") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("writing") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-writing top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsPen className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Writing</span>
{!selectedModules.includes("writing") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("writing") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
<div
onClick={!selectedModules.includes("level") ? () => toggleModule("speaking") : undefined}
className={clsx(
"w-52 relative max-w-xs flex items-center bg-mti-white-alt transition duration-300 ease-in-out border p-5 rounded-xl gap-8 cursor-pointer",
selectedModules.includes("speaking") ? "border-mti-purple-light" : "border-mti-gray-platinum",
)}>
<div className="absolute w-16 h-16 flex items-center justify-center rounded-full bg-ielts-speaking top-1/2 -translate-y-1/2 left-0 -translate-x-1/2">
<BsMegaphone className="text-white w-7 h-7" />
</div>
<span className="ml-8 font-semibold">Speaking</span>
{!selectedModules.includes("speaking") && !selectedModules.includes("level") && (
<div className="border border-mti-gray-platinum w-8 h-8 rounded-full" />
)}
{selectedModules.includes("level") && <BsXCircle className="text-mti-red-light w-8 h-8" />}
{selectedModules.includes("speaking") && <BsCheckCircle className="text-mti-purple-light w-8 h-8" />}
</div>
</section>
<div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8"> <div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<div className="flex flex-col gap-2"> <Input type="text" name="name" onChange={(e) => setName(e)} defaultValue={name} label="Assignment Name" required />
<label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label> <Select
<ReactDatePicker label="Entity"
className={clsx( options={entities.map((e) => ({value: e.id, label: e.label}))}
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", onChange={(v) => setEntity(v ? v.value! : undefined)}
"hover:border-mti-purple tooltip z-10", defaultValue={{value: entities[0]?.id, label: entities[0]?.label}}
"transition duration-300 ease-in-out",
)}
popperClassName="!z-20"
filterTime={(date) => moment(date).isSameOrAfter(new Date())}
dateFormat="dd/MM/yyyy HH:mm"
selected={startDate}
showTimeSelect
onChange={(date) => setStartDate(date)}
/> />
</div> </div>
<div className="flex flex-col gap-2">
<label className="font-normal text-base text-mti-gray-dim">End Date *</label> <div className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
<ReactDatePicker
className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
"hover:border-mti-purple tooltip z-10",
"transition duration-300 ease-in-out",
)}
popperClassName="!z-20"
filterTime={(date) => moment(date).isAfter(startDate)}
dateFormat="dd/MM/yyyy HH:mm"
selected={endDate}
showTimeSelect
onChange={(date) => setEndDate(date)}
/>
</div>
{autoStart && (
<div className="flex flex-col gap-2"> <div className="flex flex-col gap-2">
<label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label> <label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label>
<ReactDatePicker <ReactDatePicker
className={clsx( className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer", "p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
@@ -313,146 +302,118 @@ export default function AssignmentsPage({user, users, groups, entities}: Props)
popperClassName="!z-20" popperClassName="!z-20"
filterTime={(date) => moment(date).isSameOrAfter(new Date())} filterTime={(date) => moment(date).isSameOrAfter(new Date())}
dateFormat="dd/MM/yyyy HH:mm" dateFormat="dd/MM/yyyy HH:mm"
selected={autoStartDate} selected={startDate}
showTimeSelect showTimeSelect
onChange={(date) => setAutoStartDate(date)} onChange={(date) => setStartDate(date)}
/> />
</div> </div>
)} <div className="flex flex-col gap-2">
</div> <label className="font-normal text-base text-mti-gray-dim">End Date *</label>
<ReactDatePicker
{selectedModules.includes("speaking") && ( className={clsx(
<div className="flex flex-col gap-3 w-full"> "p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label> "hover:border-mti-purple tooltip z-10",
<Select "transition duration-300 ease-in-out",
value={{ )}
value: instructorGender, popperClassName="!z-20"
label: capitalize(instructorGender), filterTime={(date) => moment(date).isAfter(startDate)}
}} dateFormat="dd/MM/yyyy HH:mm"
onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)} selected={endDate}
disabled={!selectedModules.includes("speaking")} showTimeSelect
options={[ onChange={(date) => setEndDate(date)}
{value: "male", label: "Male"}, />
{value: "female", label: "Female"}, </div>
{value: "varied", label: "Varied"}, {autoStart && (
]} <div className="flex flex-col gap-2">
/> <label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label>
</div> <ReactDatePicker
)} className={clsx(
"p-6 w-full min-h-[70px] flex justify-center text-sm font-normal rounded-full border focus:outline-none cursor-pointer",
{selectedModules.length > 0 && ( "hover:border-mti-purple tooltip z-10",
<div className="flex flex-col gap-3 w-full"> "transition duration-300 ease-in-out",
<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}> )}
Random Exams popperClassName="!z-20"
</Checkbox> filterTime={(date) => moment(date).isSameOrAfter(new Date())}
{!useRandomExams && ( dateFormat="dd/MM/yyyy HH:mm"
<div className="grid md:grid-cols-2 w-full gap-4"> selected={autoStartDate}
{selectedModules.map((module) => ( showTimeSelect
<div key={module} className="flex flex-col gap-3 w-full"> onChange={(date) => setAutoStartDate(date)}
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label> />
<Select
value={{
value: examIDs.find((e) => e.module === module)?.id || null,
label: examIDs.find((e) => e.module === module)?.id || "",
}}
onChange={(value) =>
value
? setExamIDs((prev) => [...prev.filter((x) => x.module !== module), {id: value.value!, module}])
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
}
options={exams
.filter((x) => !x.isDiagnostic && x.module === module)
.map((x) => ({value: x.id, label: x.id}))}
/>
</div>
))}
</div> </div>
)} )}
</div> </div>
)}
<section className="w-full flex flex-col gap-4"> {selectedModules.includes("speaking") && (
<span className="font-semibold">Assignees ({assignees.length} selected)</span> <div className="flex flex-col gap-3 w-full">
<div className="grid grid-cols-5 gap-4"> <label className="font-normal text-base text-mti-gray-dim">Speaking Instructor&apos;s Gender</label>
{classrooms.map((g) => ( <Select
<button value={{
key={g.id} value: instructorGender,
onClick={() => { label: capitalize(instructorGender),
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
if (groupStudentIds.every((u) => assignees.includes(u))) {
setAssignees((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
} else {
setAssignees((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
}
}} }}
className={clsx( onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)}
"bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light", disabled={!selectedModules.includes("speaking")}
"transition duration-300 ease-in-out", options={[
users.filter((u) => g.participants.includes(u.id)).every((u) => assignees.includes(u.id)) && {value: "male", label: "Male"},
"!bg-mti-purple-light !text-white", {value: "female", label: "Female"},
)}> {value: "varied", label: "Varied"},
{g.name} ]}
</button> />
))} </div>
</div> )}
<div className="w-full flex items-center gap-4"> {selectedModules.length > 0 && (
{renderStudentSearch()} <div className="flex flex-col gap-3 w-full">
{renderStudentPagination()} <Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
</div> Random Exams
</Checkbox>
{!useRandomExams && (
<div className="grid md:grid-cols-2 w-full gap-4">
{selectedModules.map((module) => (
<div key={module} className="flex flex-col gap-3 w-full">
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
<Select
value={{
value: examIDs.find((e) => e.module === module)?.id || null,
label: examIDs.find((e) => e.module === module)?.id || "",
}}
onChange={(value) =>
value
? setExamIDs((prev) => [
...prev.filter((x) => x.module !== module),
{id: value.value!, module},
])
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
}
options={exams
.filter((x) => !x.isDiagnostic && x.module === module)
.map((x) => ({value: x.id, label: x.id}))}
/>
</div>
))}
</div>
)}
</div>
)}
<div className="flex flex-wrap -md:justify-center gap-4"> <section className="w-full flex flex-col gap-4">
{studentRows.map((user) => ( <span className="font-semibold">Assignees ({assignees.length} selected)</span>
<div
onClick={() => toggleAssignee(user)}
className={clsx(
"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
"transition ease-in-out duration-300",
assignees.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
)}
key={user.id}>
<span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span>
</span>
<ProgressBar
color="purple"
textClassName="!text-mti-black/80"
label={`Level ${calculateAverageLevel(user.levels)}`}
percentage={(calculateAverageLevel(user.levels) / 9) * 100}
className="h-6"
/>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "}
{groups
.filter((g) => g.participants.includes(user.id))
.map((g) => g.name)
.join(", ")}
</span>
</div>
))}
</div>
</section>
{user.type !== "teacher" && (
<section className="w-full flex flex-col gap-3">
<span className="font-semibold">Teachers ({teachers.length} selected)</span>
<div className="grid grid-cols-5 gap-4"> <div className="grid grid-cols-5 gap-4">
{classrooms.map((g) => ( {classrooms.map((g) => (
<button <button
key={g.id} key={g.id}
onClick={() => { onClick={() => {
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id); const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
if (groupStudentIds.every((u) => teachers.includes(u))) { if (groupStudentIds.every((u) => assignees.includes(u))) {
setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a))); setAssignees((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
} else { } else {
setTeachers((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]); setAssignees((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
} }
}} }}
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",
users.filter((u) => g.participants.includes(u.id)).every((u) => teachers.includes(u.id)) && users.filter((u) => g.participants.includes(u.id)).every((u) => assignees.includes(u.id)) &&
"!bg-mti-purple-light !text-white", "!bg-mti-purple-light !text-white",
)}> )}>
{g.name} {g.name}
@@ -461,24 +422,31 @@ export default function AssignmentsPage({user, users, groups, entities}: Props)
</div> </div>
<div className="w-full flex items-center gap-4"> <div className="w-full flex items-center gap-4">
{renderTeacherSearch()} {renderStudentSearch()}
{renderTeacherPagination()} {renderStudentPagination()}
</div> </div>
<div className="flex flex-wrap -md:justify-center gap-4"> <div className="flex flex-wrap -md:justify-center gap-4">
{teacherRows.map((user) => ( {studentRows.map((user) => (
<div <div
onClick={() => toggleTeacher(user)} onClick={() => toggleAssignee(user)}
className={clsx( className={clsx(
"p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72", "p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
"transition ease-in-out duration-300", "transition ease-in-out duration-300",
teachers.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum", assignees.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
)} )}
key={user.id}> key={user.id}>
<span className="flex flex-col gap-0 justify-center"> <span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span> <span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span> <span className="text-sm opacity-80">{user.email}</span>
</span> </span>
<ProgressBar
color="purple"
textClassName="!text-mti-black/80"
label={`Level ${calculateAverageLevel(user.levels)}`}
percentage={(calculateAverageLevel(user.levels) / 9) * 100}
className="h-6"
/>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2"> <span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "} Groups:{" "}
{groups {groups
@@ -490,48 +458,106 @@ export default function AssignmentsPage({user, users, groups, entities}: Props)
))} ))}
</div> </div>
</section> </section>
)}
<div className="flex gap-4 w-full items-end"> {user.type !== "teacher" && (
<Checkbox isChecked={variant === "full"} onChange={() => setVariant((prev) => (prev === "full" ? "partial" : "full"))}> <section className="w-full flex flex-col gap-3">
Full length exams <span className="font-semibold">Teachers ({teachers.length} selected)</span>
</Checkbox> <div className="grid grid-cols-5 gap-4">
<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}> {classrooms.map((g) => (
Generate different exams <button
</Checkbox> key={g.id}
<Checkbox isChecked={released} onChange={() => setReleased((d) => !d)}> onClick={() => {
Auto release results const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
</Checkbox> if (groupStudentIds.every((u) => teachers.includes(u))) {
<Checkbox isChecked={autoStart} onChange={() => setAutostart((d) => !d)}> setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
Auto start exam } else {
</Checkbox> setTeachers((prev) => [...prev.filter((a) => !groupStudentIds.includes(a)), ...groupStudentIds]);
</div> }
<div className="flex gap-4 w-full justify-end"> }}
<Button className={clsx(
className="w-full max-w-[200px]" "bg-mti-purple-ultralight text-mti-purple px-4 py-2 rounded-full hover:text-white hover:bg-mti-purple-light",
variant="outline" "transition duration-300 ease-in-out",
onClick={() => router.push("/assignments")} users.filter((u) => g.participants.includes(u.id)).every((u) => teachers.includes(u.id)) &&
disabled={isLoading} "!bg-mti-purple-light !text-white",
isLoading={isLoading}> )}>
Cancel {g.name}
</Button> </button>
))}
</div>
<Button <div className="w-full flex items-center gap-4">
disabled={ {renderTeacherSearch()}
selectedModules.length === 0 || {renderTeacherPagination()}
!name || </div>
!startDate ||
!endDate || <div className="flex flex-wrap -md:justify-center gap-4">
assignees.length === 0 || {teacherRows.map((user) => (
(!useRandomExams && examIDs.length < selectedModules.length) <div
} onClick={() => toggleTeacher(user)}
className="w-full max-w-[200px]" className={clsx(
onClick={createAssignment} "p-4 flex flex-col gap-2 rounded-xl border cursor-pointer w-72",
isLoading={isLoading}> "transition ease-in-out duration-300",
Create teachers.includes(user.id) ? "border-mti-purple" : "border-mti-gray-platinum",
</Button> )}
key={user.id}>
<span className="flex flex-col gap-0 justify-center">
<span className="font-semibold">{user.name}</span>
<span className="text-sm opacity-80">{user.email}</span>
</span>
<span className="text-mti-black/80 text-sm whitespace-pre-wrap mt-2">
Groups:{" "}
{groups
.filter((g) => g.participants.includes(user.id))
.map((g) => g.name)
.join(", ")}
</span>
</div>
))}
</div>
</section>
)}
<div className="flex gap-4 w-full items-end">
<Checkbox isChecked={variant === "full"} onChange={() => setVariant((prev) => (prev === "full" ? "partial" : "full"))}>
Full length exams
</Checkbox>
<Checkbox isChecked={generateMultiple} onChange={() => setGenerateMultiple((d) => !d)}>
Generate different exams
</Checkbox>
<Checkbox isChecked={released} onChange={() => setReleased((d) => !d)}>
Auto release results
</Checkbox>
<Checkbox isChecked={autoStart} onChange={() => setAutostart((d) => !d)}>
Auto start exam
</Checkbox>
</div>
<div className="flex gap-4 w-full justify-end">
<Button
className="w-full max-w-[200px]"
variant="outline"
onClick={() => router.push("/assignments")}
disabled={isLoading}
isLoading={isLoading}>
Cancel
</Button>
<Button
disabled={
selectedModules.length === 0 ||
!name ||
!startDate ||
!endDate ||
assignees.length === 0 ||
(!useRandomExams && examIDs.length < selectedModules.length)
}
className="w-full max-w-[200px]"
onClick={createAssignment}
isLoading={isLoading}>
Create
</Button>
</div>
</div> </div>
</div> </Layout>
</Layout> </>
); );
} }

View File

@@ -1,6 +1,9 @@
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
import Separator from "@/components/Low/Separator";
import AssignmentCard from "@/dashboards/AssignmentCard"; import AssignmentCard from "@/dashboards/AssignmentCard";
import AssignmentView from "@/dashboards/AssignmentView"; import AssignmentView from "@/dashboards/AssignmentView";
import {useListSearch} from "@/hooks/useListSearch";
import usePagination from "@/hooks/usePagination";
import {Assignment} from "@/interfaces/results"; import {Assignment} from "@/interfaces/results";
import {CorporateUser, Group, User} from "@/interfaces/user"; import {CorporateUser, Group, User} from "@/interfaces/user";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
@@ -13,13 +16,14 @@ import {
pastAssignmentFilter, pastAssignmentFilter,
startHasExpiredAssignmentFilter, startHasExpiredAssignmentFilter,
} from "@/utils/assignments"; } from "@/utils/assignments";
import {getEntitiesAssignments} from "@/utils/assignments.be"; import {getAssignments, getEntitiesAssignments} from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be"; import {getEntitiesWithRoles} from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be"; import {getGroups, getGroupsByEntities} from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions"; import {checkAccess} from "@/utils/permissions";
import {getEntitiesUsers} from "@/utils/users.be"; import {getEntitiesUsers, getUsers} from "@/utils/users.be";
import {withIronSessionSsr} from "iron-session/next"; import {withIronSessionSsr} from "iron-session/next";
import {groupBy} from "lodash"; import {groupBy} from "lodash";
import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router"; import {useRouter} from "next/router";
import {useMemo, useState} from "react"; import {useMemo, useState} from "react";
@@ -47,14 +51,16 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
const entityIDS = mapBy(user.entities, "id") || []; const entityIDS = mapBy(user.entities, "id") || [];
const users = await getEntitiesUsers(entityIDS); const users = await (checkAccess(user, ["developer", "admin"]) ? getUsers() : getEntitiesUsers(entityIDS));
const entities = await getEntitiesWithRoles(entityIDS); const entities = await (checkAccess(user, ["developer", "admin"]) ? getEntitiesWithRoles() : getEntitiesWithRoles(entityIDS));
const assignments = await getEntitiesAssignments(entityIDS); const assignments = await (checkAccess(user, ["developer", "admin"]) ? getAssignments() : getEntitiesAssignments(entityIDS));
const groups = await getGroupsByEntities(entityIDS); const groups = await (checkAccess(user, ["developer", "admin"]) ? getGroups() : getGroupsByEntities(entityIDS));
return {props: serialize({user, users, entities, assignments, groups})}; return {props: serialize({user, users, entities, assignments, groups})};
}, sessionOptions); }, sessionOptions);
const SEARCH_FIELDS = [["name"]];
interface Props { interface Props {
assignments: Assignment[]; assignments: Assignment[];
corporateAssignments?: ({corporate?: CorporateUser} & Assignment)[]; corporateAssignments?: ({corporate?: CorporateUser} & Assignment)[];
@@ -64,124 +70,159 @@ interface Props {
} }
export default function AssignmentsPage({assignments, corporateAssignments, user, users, groups}: Props) { export default function AssignmentsPage({assignments, corporateAssignments, user, users, groups}: Props) {
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>(); const activeAssignments = useMemo(() => assignments.filter(activeAssignmentFilter), [assignments]);
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false); const plannedAssignments = useMemo(() => assignments.filter(futureAssignmentFilter), [assignments]);
const pastAssignments = useMemo(() => assignments.filter(pastAssignmentFilter), [assignments]);
const displayAssignmentView = useMemo(() => !!selectedAssignment && !isCreatingAssignment, [selectedAssignment, isCreatingAssignment]); const startExpiredAssignments = useMemo(() => assignments.filter(startHasExpiredAssignmentFilter), [assignments]);
const archivedAssignments = useMemo(() => assignments.filter(archivedAssignmentFilter), [assignments]);
const assignmentsPastExpiredStart = assignments.filter(startHasExpiredAssignmentFilter);
const router = useRouter(); const router = useRouter();
const {rows: activeRows, renderSearch: renderActive} = useListSearch(SEARCH_FIELDS, activeAssignments);
const {rows: plannedRows, renderSearch: renderPlanned} = useListSearch(SEARCH_FIELDS, plannedAssignments);
const {rows: pastRows, renderSearch: renderPast} = useListSearch(SEARCH_FIELDS, pastAssignments);
const {rows: expiredRows, renderSearch: renderExpired} = useListSearch(SEARCH_FIELDS, startExpiredAssignments);
const {rows: archivedRows, renderSearch: renderArchived} = useListSearch(SEARCH_FIELDS, archivedAssignments);
const {items: activeItems, renderMinimal: paginationActive} = usePagination(activeRows, 16);
const {items: plannedItems, renderMinimal: paginationPlanned} = usePagination(plannedRows, 16);
const {items: pastItems, renderMinimal: paginationPast} = usePagination(pastRows, 16);
const {items: expiredItems, renderMinimal: paginationExpired} = usePagination(expiredRows, 16);
const {items: archivedItems, renderMinimal: paginationArchived} = usePagination(archivedRows, 16);
return ( return (
<Layout user={user}> <>
{displayAssignmentView && ( <Head>
<AssignmentView <title>Assignments | EnCoach</title>
users={users} <meta
isOpen={displayAssignmentView} name="description"
onClose={() => { content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
setSelectedAssignment(undefined);
setIsCreatingAssignment(false);
}}
assignment={selectedAssignment}
/> />
)} <meta name="viewport" content="width=device-width, initial-scale=1" />
<div className="w-full flex justify-between items-center"> <link rel="icon" href="/favicon.ico" />
<div className="flex items-center gap-2"> </Head>
<Link href="/dashboard" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl"> <Layout user={user}>
<BsChevronLeft /> <div className="flex flex-col gap-4">
</Link> <div className="flex items-center gap-2">
<h2 className="font-bold text-2xl">Assignments</h2> <Link href="/dashboard" className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
<BsChevronLeft />
</Link>
<h2 className="font-bold text-2xl">Assignments</h2>
</div>
<Separator />
</div> </div>
</div> <div className="flex flex-col gap-2">
<div className="flex flex-col gap-2"> <span className="text-lg font-bold">Active Assignments Status</span>
<span className="text-lg font-bold">Active Assignments Status</span> <div className="flex items-center gap-4">
<div className="flex items-center gap-4"> <span>
<span> <b>Total:</b> {activeAssignments.reduce((acc, curr) => acc + curr.results.length, 0)}/
<b>Total:</b> {assignments.filter(activeAssignmentFilter).reduce((acc, curr) => acc + curr.results.length, 0)}/ {activeAssignments.reduce((acc, curr) => curr.exams.length + acc, 0)}
{assignments.filter(activeAssignmentFilter).reduce((acc, curr) => curr.exams.length + acc, 0)} </span>
</span> {Object.keys(groupBy(corporateAssignments, (x) => x.corporate?.id)).map((x) => (
{Object.keys(groupBy(corporateAssignments, (x) => x.corporate?.id)).map((x) => ( <div key={x}>
<div key={x}> <span className="font-semibold">{getUserCompanyName(users.find((u) => u.id === x)!, users, groups)}: </span>
<span className="font-semibold">{getUserCompanyName(users.find((u) => u.id === x)!, users, groups)}: </span> <span>
<span> {groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.results.length + acc, 0)}/
{groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.results.length + acc, 0)}/ {groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.exams.length + acc, 0)}
{groupBy(corporateAssignments, (x) => x.corporate?.id)[x].reduce((acc, curr) => curr.exams.length + acc, 0)} </span>
</span> </div>
</div> ))}
))} </div>
</div> </div>
</div>
<section className="flex flex-col gap-4"> <section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeAssignmentFilter).length})</h2> <h2 className="text-2xl font-semibold">Active Assignments ({activeAssignments.length})</h2>
<div className="flex flex-wrap gap-2"> <div className="w-full flex items-center gap-4">
{assignments.filter(activeAssignmentFilter).map((a) => ( {renderActive()}
<AssignmentCard {...a} users={users} onClick={() => setSelectedAssignment(a)} key={a.id} /> {paginationActive()}
))} </div>
</div> <div className="flex flex-wrap gap-2">
</section> {activeItems.map((a) => (
<section className="flex flex-col gap-4"> <AssignmentCard {...a} users={users} onClick={() => router.push(`/assignments/${a.id}`)} key={a.id} />
<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureAssignmentFilter).length})</h2> ))}
<div className="flex flex-wrap gap-2"> </div>
<Link </section>
href="/assignments/creator"
className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300"> <section className="flex flex-col gap-4">
<BsPlus className="text-6xl" /> <h2 className="text-2xl font-semibold">Planned Assignments ({plannedAssignments.length})</h2>
<span className="text-lg">New Assignment</span> <div className="w-full flex items-center gap-4">
</Link> {renderPlanned()}
{assignments.filter(futureAssignmentFilter).map((a) => ( {paginationPlanned()}
<AssignmentCard {...a} users={users} onClick={() => router.push(`/assignments/creator/${a.id}`)} key={a.id} /> </div>
))} <div className="flex flex-wrap gap-2">
</div> <Link
</section> href="/assignments/creator"
<section className="flex flex-col gap-4"> className="w-[250px] h-[200px] flex flex-col gap-2 items-center justify-center bg-white hover:bg-mti-purple-ultralight text-mti-purple-light hover:text-mti-purple-dark border border-mti-gray-platinum hover:drop-shadow p-4 cursor-pointer rounded-xl transition ease-in-out duration-300">
<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastAssignmentFilter).length})</h2> <BsPlus className="text-6xl" />
<div className="flex flex-wrap gap-2"> <span className="text-lg">New Assignment</span>
{assignments.filter(pastAssignmentFilter).map((a) => ( </Link>
<AssignmentCard {plannedItems.map((a) => (
{...a} <AssignmentCard {...a} users={users} onClick={() => router.push(`/assignments/creator/${a.id}`)} key={a.id} />
users={users} ))}
onClick={() => setSelectedAssignment(a)} </div>
key={a.id} </section>
allowDownload
allowArchive <section className="flex flex-col gap-4">
allowExcelDownload <h2 className="text-2xl font-semibold">Past Assignments ({pastAssignments.length})</h2>
/> <div className="w-full flex items-center gap-4">
))} {renderPast()}
</div> {paginationPast()}
</section> </div>
<section className="flex flex-col gap-4"> <div className="flex flex-wrap gap-2">
<h2 className="text-2xl font-semibold">Assignments start expired ({assignmentsPastExpiredStart.length})</h2> {pastItems.map((a) => (
<div className="flex flex-wrap gap-2"> <AssignmentCard
{assignments.filter(startHasExpiredAssignmentFilter).map((a) => ( {...a}
<AssignmentCard users={users}
{...a} onClick={() => router.push(`/assignments/${a.id}`)}
users={users} key={a.id}
onClick={() => setSelectedAssignment(a)} allowDownload
key={a.id} allowArchive
allowDownload allowExcelDownload
allowArchive />
allowExcelDownload ))}
/> </div>
))} </section>
</div> <section className="flex flex-col gap-4">
</section> <h2 className="text-2xl font-semibold">Assignments start expired ({startExpiredAssignments.length})</h2>
<section className="flex flex-col gap-4"> <div className="w-full flex items-center gap-4">
<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedAssignmentFilter).length})</h2> {renderExpired()}
<div className="flex flex-wrap gap-2"> {paginationExpired()}
{assignments.filter(archivedAssignmentFilter).map((a) => ( </div>
<AssignmentCard <div className="flex flex-wrap gap-2">
{...a} {expiredItems.map((a) => (
users={users} <AssignmentCard
onClick={() => setSelectedAssignment(a)} {...a}
key={a.id} users={users}
allowDownload onClick={() => router.push(`/assignments/${a.id}`)}
allowUnarchive key={a.id}
allowExcelDownload allowDownload
/> allowArchive
))} allowExcelDownload
</div> />
</section> ))}
</Layout> </div>
</section>
<section className="flex flex-col gap-4">
<h2 className="text-2xl font-semibold">Archived Assignments ({archivedAssignments.length})</h2>
<div className="w-full flex items-center gap-4">
{renderArchived()}
{paginationArchived()}
</div>
<div className="flex flex-wrap gap-2">
{archivedItems.map((a) => (
<AssignmentCard
{...a}
users={users}
onClick={() => router.push(`/assignments/${a.id}`)}
key={a.id}
allowDownload
allowUnarchive
allowExcelDownload
/>
))}
</div>
</section>
</Layout>
</>
); );
} }

View File

@@ -96,7 +96,7 @@ export default function Home({user, groups}: Props) {
return ( return (
<> <>
<Head> <Head>
<title>Groups | EnCoach</title> <title>Classrooms | EnCoach</title>
<meta <meta
name="description" name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop." content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
@@ -105,18 +105,16 @@ export default function Home({user, groups}: Props) {
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<ToastContainer /> <ToastContainer />
{user && ( <Layout user={user} className="!gap-4">
<Layout user={user} className="!gap-4"> <section className="flex flex-col gap-4 w-full h-full">
<section className="flex flex-col gap-4 w-full h-full"> <div className="flex flex-col gap-4">
<div className="flex flex-col gap-4"> <h2 className="font-bold text-2xl">Classrooms</h2>
<h2 className="font-bold text-2xl">Classrooms</h2> <Separator />
<Separator /> </div>
</div>
<CardList<GroupWithUsers> list={groups} searchFields={SEARCH_FIELDS} renderCard={renderCard} firstCard={firstCard} /> <CardList<GroupWithUsers> list={groups} searchFields={SEARCH_FIELDS} renderCard={renderCard} firstCard={firstCard} />
</section> </section>
</Layout> </Layout>
)}
</> </>
); );
} }

View File

@@ -20,6 +20,7 @@ import {uniqBy} from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router";
import {useMemo} from "react"; import {useMemo} from "react";
import { import {
BsBank, BsBank,
@@ -79,6 +80,8 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]); const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]); const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
const router = useRouter();
const averageLevelCalculator = (studentStats: Stat[]) => { const averageLevelCalculator = (studentStats: Stat[]) => {
const formattedStats = studentStats const formattedStats = studentStats
.map((s) => ({ .map((s) => ({
@@ -128,16 +131,46 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
<ToastContainer /> <ToastContainer />
<Layout user={user}> <Layout user={user}>
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center"> <section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" /> <IconCard
<IconCard Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" /> onClick={() => router.push("/lists/users?type=student")}
<IconCard Icon={BsBank} label="Corporates" value={corporates.length} color="purple" /> Icon={BsPersonFill}
<IconCard Icon={BsBank} label="Master Corporates" value={masterCorporates.length} color="purple" /> label="Students"
value={students.length}
color="purple"
/>
<IconCard
onClick={() => router.push("/lists/users?type=teacher")}
Icon={BsPencilSquare}
label="Teachers"
value={teachers.length}
color="purple"
/>
<IconCard
Icon={BsBank}
onClick={() => router.push("/lists/users?type=corporate")}
label="Corporates"
value={corporates.length}
color="purple"
/>
<IconCard
Icon={BsBank}
onClick={() => router.push("/lists/users?type=mastercorporate")}
label="Master Corporates"
value={masterCorporates.length}
color="purple"
/>
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" /> <IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" /> <IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" /> <IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" /> <IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" /> <IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
<IconCard Icon={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" /> <IconCard
Icon={BsEnvelopePaper}
onClick={() => router.push("/assignments")}
label="Assignments"
value={assignments.filter((a) => !a.archived).length}
color="purple"
/>
</section> </section>
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between"> <section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">

View File

@@ -1,229 +1,229 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
import IconCard from "@/dashboards/IconCard"; import IconCard from "@/dashboards/IconCard";
import {Module} from "@/interfaces"; import { Module } from "@/interfaces";
import {EntityWithRoles} from "@/interfaces/entity"; import { EntityWithRoles } from "@/interfaces/entity";
import {Assignment} from "@/interfaces/results"; import { Assignment } from "@/interfaces/results";
import {Group, Stat, User} from "@/interfaces/user"; import { Group, Stat, User } from "@/interfaces/user";
import {sessionOptions} from "@/lib/session"; import { sessionOptions } from "@/lib/session";
import {dateSorter, filterBy, mapBy, serialize} from "@/utils"; import { dateSorter, filterBy, mapBy, serialize } from "@/utils";
import {getEntitiesAssignments} from "@/utils/assignments.be"; import { getEntitiesAssignments } from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be"; import { getEntitiesWithRoles } from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be"; import { getGroupsByEntities } from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions"; import { checkAccess } from "@/utils/permissions";
import {calculateAverageLevel, calculateBandScore} from "@/utils/score"; import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
import {groupByExam} from "@/utils/stats"; import { groupByExam } from "@/utils/stats";
import {getStatsByUsers} from "@/utils/stats.be"; import { getStatsByUsers } from "@/utils/stats.be";
import {getEntitiesUsers} from "@/utils/users.be"; import { getEntitiesUsers } from "@/utils/users.be";
import {withIronSessionSsr} from "iron-session/next"; import { withIronSessionSsr } from "iron-session/next";
import {uniqBy} from "lodash"; import { uniqBy } from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import { useRouter } from "next/router";
import {useRouter} from "next/router"; import { useMemo } from "react";
import {useMemo} from "react";
import { import {
BsClipboard2Data, BsClipboard2Data,
BsClock, BsClock,
BsEnvelopePaper, BsEnvelopePaper,
BsPaperclip, BsPaperclip,
BsPencilSquare, BsPencilSquare,
BsPeople, BsPeople,
BsPeopleFill, BsPeopleFill,
BsPersonFill, BsPersonFill,
BsPersonFillGear, BsPersonFillGear,
} from "react-icons/bs"; } from "react-icons/bs";
import {ToastContainer} from "react-toastify"; import { ToastContainer } from "react-toastify";
interface Props { interface Props {
user: User; user: User;
users: User[]; users: User[];
entities: EntityWithRoles[]; entities: EntityWithRoles[];
assignments: Assignment[]; assignments: Assignment[];
stats: Stat[]; stats: Stat[];
groups: Group[]; groups: Group[];
} }
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => { export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
const user = req.session.user as User | undefined; const user = req.session.user as User | undefined;
if (!user) { if (!user) {
return { return {
redirect: { redirect: {
destination: "/login", destination: "/login",
permanent: false, permanent: false,
}, },
}; };
} }
if (!checkAccess(user, ["admin", "developer", "corporate"])) if (!checkAccess(user, ["admin", "developer", "corporate"]))
return { return {
redirect: { redirect: {
destination: "/dashboard", destination: "/dashboard",
permanent: false, permanent: false,
}, },
}; };
const entityIDS = mapBy(user.entities, "id") || []; const entityIDS = mapBy(user.entities, "id") || [];
const users = await getEntitiesUsers(entityIDS); const users = await getEntitiesUsers(entityIDS);
const entities = await getEntitiesWithRoles(entityIDS); const entities = await getEntitiesWithRoles(entityIDS);
const assignments = await getEntitiesAssignments(entityIDS); const assignments = await getEntitiesAssignments(entityIDS);
const stats = await getStatsByUsers(users.map((u) => u.id)); const stats = await getStatsByUsers(users.map((u) => u.id));
const groups = await getGroupsByEntities(entityIDS); const groups = await getGroupsByEntities(entityIDS);
return {props: serialize({user, users, entities, assignments, stats, groups})}; return { props: serialize({ user, users, entities, assignments, stats, groups }) };
}, sessionOptions); }, sessionOptions);
export default function Dashboard({user, users, entities, assignments, stats, groups}: Props) { export default function Dashboard({ user, users, entities, assignments, stats, groups }: Props) {
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]); const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]); const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
const router = useRouter(); const router = useRouter();
const averageLevelCalculator = (studentStats: Stat[]) => { const averageLevelCalculator = (studentStats: Stat[]) => {
const formattedStats = studentStats const formattedStats = studentStats
.map((s) => ({ .map((s) => ({
focus: students.find((u) => u.id === s.user)?.focus, focus: students.find((u) => u.id === s.user)?.focus,
score: s.score, score: s.score,
module: s.module, module: s.module,
})) }))
.filter((f) => !!f.focus); .filter((f) => !!f.focus);
const bandScores = formattedStats.map((s) => ({ const bandScores = formattedStats.map((s) => ({
module: s.module, module: s.module,
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!), level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
})); }));
const levels: {[key in Module]: number} = { const levels: { [key in Module]: number } = {
reading: 0, reading: 0,
listening: 0, listening: 0,
writing: 0, writing: 0,
speaking: 0, speaking: 0,
level: 0, level: 0,
}; };
bandScores.forEach((b) => (levels[b.module] += b.level)); bandScores.forEach((b) => (levels[b.module] += b.level));
return calculateAverageLevel(levels); return calculateAverageLevel(levels);
}; };
const UserDisplay = (displayUser: User) => ( const UserDisplay = (displayUser: User) => (
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"> <div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" /> <img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
<div className="flex flex-col gap-1 items-start"> <div className="flex flex-col gap-1 items-start">
<span>{displayUser.name}</span> <span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span> <span className="text-sm opacity-75">{displayUser.email}</span>
</div> </div>
</div> </div>
); );
return ( return (
<> <>
<Head> <Head>
<title>EnCoach</title> <title>EnCoach</title>
<meta <meta
name="description" name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop." content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/> />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<ToastContainer /> <ToastContainer />
<Layout user={user}> <Layout user={user}>
<div className="w-full flex flex-col gap-4"> <div className="w-full flex flex-col gap-4">
{entities.length > 0 && ( {entities.length > 0 && (
<div className="w-fit self-end bg-neutral-200 px-2 rounded-lg py-1"> <div className="w-fit self-end bg-neutral-200 px-2 rounded-lg py-1">
<b>{mapBy(entities, "label")?.join(", ")}</b> <b>{mapBy(entities, "label")?.join(", ")}</b>
</div> </div>
)} )}
<section className="grid grid-cols-5 -md:grid-cols-2 place-items-center gap-4 text-center"> <section className="grid grid-cols-5 -md:grid-cols-2 place-items-center gap-4 text-center">
<IconCard <IconCard
onClick={() => router.push("/lists/users?type=student")} onClick={() => router.push("/lists/users?type=student")}
Icon={BsPersonFill} Icon={BsPersonFill}
label="Students" label="Students"
value={students.length} value={students.length}
color="purple" color="purple"
/> />
<IconCard <IconCard
onClick={() => router.push("/lists/users?type=teacher")} onClick={() => router.push("/lists/users?type=teacher")}
Icon={BsPencilSquare} Icon={BsPencilSquare}
label="Teachers" label="Teachers"
value={teachers.length} value={teachers.length}
color="purple" color="purple"
/> />
<IconCard <IconCard
onClick={() => router.push("/classrooms")} onClick={() => router.push("/classrooms")}
Icon={BsPeople} Icon={BsPeople}
label="Classrooms" label="Classrooms"
value={groups.length} value={groups.length}
color="purple" color="purple"
/> />
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" /> <IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" /> <IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" /> <IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" /> <IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
<IconCard <IconCard
Icon={BsClock} Icon={BsClock}
label="Expiration Date" label="Expiration Date"
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"} value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
color="rose" color="rose"
/> />
<IconCard <IconCard
Icon={BsEnvelopePaper} Icon={BsEnvelopePaper}
className="col-span-2" className="col-span-2"
label="Assignments" onClick={() => router.push("/assignments")}
value={assignments.filter((a) => !a.archived).length} label="Assignments"
color="purple" value={assignments.filter((a) => !a.archived).length}
/> color="purple"
</section> />
</div> </section>
</div>
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between"> <section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest students</span> <span className="p-4">Latest students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate")) .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest teachers</span> <span className="p-4">Latest teachers</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{teachers {teachers
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate")) .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest level students</span> <span className="p-4">Highest level students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels)) .sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest exam count students</span> <span className="p-4">Highest exam count students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort( .sort(
(a, b) => (a, b) =>
Object.keys(groupByExam(filterBy(stats, "user", b))).length - Object.keys(groupByExam(filterBy(stats, "user", b))).length -
Object.keys(groupByExam(filterBy(stats, "user", a))).length, Object.keys(groupByExam(filterBy(stats, "user", a))).length,
) )
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
</section> </section>
</Layout> </Layout>
</> </>
); );
} }

View File

@@ -20,6 +20,7 @@ import {uniqBy} from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router";
import {useMemo} from "react"; import {useMemo} from "react";
import { import {
BsBank, BsBank,
@@ -56,7 +57,7 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
}; };
} }
if (!checkAccess(user, ["developer"])) if (!checkAccess(user, ["admin", "developer"]))
return { return {
redirect: { redirect: {
destination: "/dashboard", destination: "/dashboard",
@@ -79,6 +80,8 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]); const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]); const masterCorporates = useMemo(() => users.filter((u) => u.type === "mastercorporate"), [users]);
const router = useRouter();
const averageLevelCalculator = (studentStats: Stat[]) => { const averageLevelCalculator = (studentStats: Stat[]) => {
const formattedStats = studentStats const formattedStats = studentStats
.map((s) => ({ .map((s) => ({
@@ -128,16 +131,46 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
<ToastContainer /> <ToastContainer />
<Layout user={user}> <Layout user={user}>
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center"> <section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" /> <IconCard
<IconCard Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" /> onClick={() => router.push("/lists/users?type=student")}
<IconCard Icon={BsBank} label="Corporates" value={corporates.length} color="purple" /> Icon={BsPersonFill}
<IconCard Icon={BsBank} label="Master Corporates" value={masterCorporates.length} color="purple" /> label="Students"
value={students.length}
color="purple"
/>
<IconCard
onClick={() => router.push("/lists/users?type=teacher")}
Icon={BsPencilSquare}
label="Teachers"
value={teachers.length}
color="purple"
/>
<IconCard
Icon={BsBank}
onClick={() => router.push("/lists/users?type=corporate")}
label="Corporates"
value={corporates.length}
color="purple"
/>
<IconCard
Icon={BsBank}
onClick={() => router.push("/lists/users?type=mastercorporate")}
label="Master Corporates"
value={masterCorporates.length}
color="purple"
/>
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" /> <IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" /> <IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" /> <IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" /> <IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" /> <IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
<IconCard Icon={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" /> <IconCard
Icon={BsEnvelopePaper}
onClick={() => router.push("/assignments")}
label="Assignments"
value={assignments.filter((a) => !a.archived).length}
color="purple"
/>
</section> </section>
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between"> <section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">

View File

@@ -1,201 +1,220 @@
/* eslint-disable @next/next/no-img-element */ /* eslint-disable @next/next/no-img-element */
import Layout from "@/components/High/Layout"; import Layout from "@/components/High/Layout";
import IconCard from "@/dashboards/IconCard"; import IconCard from "@/dashboards/IconCard";
import {Module} from "@/interfaces"; import { Module } from "@/interfaces";
import {EntityWithRoles} from "@/interfaces/entity"; import { EntityWithRoles } from "@/interfaces/entity";
import {Assignment} from "@/interfaces/results"; import { Assignment } from "@/interfaces/results";
import {Group, Stat, User} from "@/interfaces/user"; import { Group, Stat, User } from "@/interfaces/user";
import {sessionOptions} from "@/lib/session"; import { sessionOptions } from "@/lib/session";
import {dateSorter, filterBy, mapBy, serialize} from "@/utils"; import { dateSorter, filterBy, mapBy, serialize } from "@/utils";
import {getEntitiesAssignments} from "@/utils/assignments.be"; import { getEntitiesAssignments } from "@/utils/assignments.be";
import {getEntitiesWithRoles} from "@/utils/entities.be"; import { getEntitiesWithRoles } from "@/utils/entities.be";
import {getGroupsByEntities} from "@/utils/groups.be"; import { getGroupsByEntities } from "@/utils/groups.be";
import {checkAccess} from "@/utils/permissions"; import { checkAccess } from "@/utils/permissions";
import {calculateAverageLevel, calculateBandScore} from "@/utils/score"; import { calculateAverageLevel, calculateBandScore } from "@/utils/score";
import {groupByExam} from "@/utils/stats"; import { groupByExam } from "@/utils/stats";
import {getStatsByUsers} from "@/utils/stats.be"; import { getStatsByUsers } from "@/utils/stats.be";
import {getEntitiesUsers} from "@/utils/users.be"; import { getEntitiesUsers } from "@/utils/users.be";
import {withIronSessionSsr} from "iron-session/next"; import { withIronSessionSsr } from "iron-session/next";
import {uniqBy} from "lodash"; import { uniqBy } from "lodash";
import moment from "moment"; import moment from "moment";
import Head from "next/head"; import Head from "next/head";
import Link from "next/link"; import Link from "next/link";
import {useRouter} from "next/router"; import { useRouter } from "next/router";
import {useMemo} from "react"; import { useMemo } from "react";
import { import {
BsBank, BsBank,
BsClipboard2Data, BsClipboard2Data,
BsClock, BsClock,
BsEnvelopePaper, BsEnvelopePaper,
BsPaperclip, BsPaperclip,
BsPencilSquare, BsPencilSquare,
BsPeople, BsPeople,
BsPeopleFill, BsPeopleFill,
BsPersonFill, BsPersonFill,
BsPersonFillGear, BsPersonFillGear,
} from "react-icons/bs"; } from "react-icons/bs";
import {ToastContainer} from "react-toastify"; import { ToastContainer } from "react-toastify";
interface Props { interface Props {
user: User; user: User;
users: User[]; users: User[];
entities: EntityWithRoles[]; entities: EntityWithRoles[];
assignments: Assignment[]; assignments: Assignment[];
stats: Stat[]; stats: Stat[];
groups: Group[]; groups: Group[];
} }
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => { export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
const user = req.session.user as User | undefined; const user = req.session.user as User | undefined;
if (!user) { if (!user) {
return { return {
redirect: { redirect: {
destination: "/login", destination: "/login",
permanent: false, permanent: false,
}, },
}; };
} }
if (!checkAccess(user, ["admin", "developer", "mastercorporate"])) if (!checkAccess(user, ["admin", "developer", "mastercorporate"]))
return { return {
redirect: { redirect: {
destination: "/dashboard", destination: "/dashboard",
permanent: false, permanent: false,
}, },
}; };
const entityIDS = mapBy(user.entities, "id") || []; const entityIDS = mapBy(user.entities, "id") || [];
const users = await getEntitiesUsers(entityIDS); const users = await getEntitiesUsers(entityIDS);
const entities = await getEntitiesWithRoles(entityIDS); const entities = await getEntitiesWithRoles(entityIDS);
const assignments = await getEntitiesAssignments(entityIDS); const assignments = await getEntitiesAssignments(entityIDS);
const stats = await getStatsByUsers(users.map((u) => u.id)); const stats = await getStatsByUsers(users.map((u) => u.id));
const groups = await getGroupsByEntities(entityIDS); const groups = await getGroupsByEntities(entityIDS);
return {props: serialize({user, users, entities, assignments, stats, groups})}; return { props: serialize({ user, users, entities, assignments, stats, groups }) };
}, sessionOptions); }, sessionOptions);
export default function Dashboard({user, users, entities, assignments, stats, groups}: Props) { export default function Dashboard({ user, users, entities, assignments, stats, groups }: Props) {
const students = useMemo(() => users.filter((u) => u.type === "student"), [users]); const students = useMemo(() => users.filter((u) => u.type === "student"), [users]);
const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]); const teachers = useMemo(() => users.filter((u) => u.type === "teacher"), [users]);
const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]); const corporates = useMemo(() => users.filter((u) => u.type === "corporate"), [users]);
const router = useRouter(); const router = useRouter();
const averageLevelCalculator = (studentStats: Stat[]) => { const averageLevelCalculator = (studentStats: Stat[]) => {
const formattedStats = studentStats const formattedStats = studentStats
.map((s) => ({ .map((s) => ({
focus: students.find((u) => u.id === s.user)?.focus, focus: students.find((u) => u.id === s.user)?.focus,
score: s.score, score: s.score,
module: s.module, module: s.module,
})) }))
.filter((f) => !!f.focus); .filter((f) => !!f.focus);
const bandScores = formattedStats.map((s) => ({ const bandScores = formattedStats.map((s) => ({
module: s.module, module: s.module,
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!), level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
})); }));
const levels: {[key in Module]: number} = { const levels: { [key in Module]: number } = {
reading: 0, reading: 0,
listening: 0, listening: 0,
writing: 0, writing: 0,
speaking: 0, speaking: 0,
level: 0, level: 0,
}; };
bandScores.forEach((b) => (levels[b.module] += b.level)); bandScores.forEach((b) => (levels[b.module] += b.level));
return calculateAverageLevel(levels); return calculateAverageLevel(levels);
}; };
const UserDisplay = (displayUser: User) => ( const UserDisplay = (displayUser: User) => (
<div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"> <div className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" /> <img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
<div className="flex flex-col gap-1 items-start"> <div className="flex flex-col gap-1 items-start">
<span>{displayUser.name}</span> <span>{displayUser.name}</span>
<span className="text-sm opacity-75">{displayUser.email}</span> <span className="text-sm opacity-75">{displayUser.email}</span>
</div> </div>
</div> </div>
); );
return ( return (
<> <>
<Head> <Head>
<title>EnCoach</title> <title>EnCoach</title>
<meta <meta
name="description" name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop." content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/> />
<meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" /> <link rel="icon" href="/favicon.ico" />
</Head> </Head>
<ToastContainer /> <ToastContainer />
<Layout user={user}> <Layout user={user}>
<section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center"> <section className="grid grid-cols-5 place-items-center -md:grid-cols-2 gap-4 text-center">
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" /> <IconCard
<IconCard Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" /> onClick={() => router.push("/lists/users?type=student")}
<IconCard Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" /> Icon={BsPersonFill}
<IconCard onClick={() => router.push("/classrooms")} Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" /> label="Students"
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" /> value={students.length}
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" /> color="purple"
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" /> />
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" /> <IconCard
<IconCard Icon={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" /> onClick={() => router.push("/lists/users?type=teacher")}
<IconCard Icon={BsPencilSquare}
Icon={BsClock} label="Teachers"
label="Expiration Date" value={teachers.length}
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"} color="purple"
color="rose" />
/> <IconCard
</section> onClick={() => router.push("/lists/users?type=corporate")} Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" />
<IconCard onClick={() => router.push("/classrooms")} Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
<IconCard Icon={BsPeopleFill} label="Entities" value={entities.length} color="purple" />
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
<IconCard Icon={BsPersonFillGear} label="Student Performance" value={students.length} color="purple" />
<IconCard
Icon={BsEnvelopePaper}
onClick={() => router.push("/assignments")}
label="Assignments"
value={assignments.filter((a) => !a.archived).length}
color="purple"
/>
<IconCard
Icon={BsClock}
label="Expiration Date"
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
color="rose"
/>
</section>
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between"> <section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest students</span> <span className="p-4">Latest students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate")) .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Latest teachers</span> <span className="p-4">Latest teachers</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{teachers {teachers
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate")) .sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest level students</span> <span className="p-4">Highest level students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels)) .sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
<div className="bg-white border shadow flex flex-col rounded-xl w-full"> <div className="bg-white border shadow flex flex-col rounded-xl w-full">
<span className="p-4">Highest exam count students</span> <span className="p-4">Highest exam count students</span>
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide"> <div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
{students {students
.sort( .sort(
(a, b) => (a, b) =>
Object.keys(groupByExam(filterBy(stats, "user", b))).length - Object.keys(groupByExam(filterBy(stats, "user", b))).length -
Object.keys(groupByExam(filterBy(stats, "user", a))).length, Object.keys(groupByExam(filterBy(stats, "user", a))).length,
) )
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
</div> </div>
</div> </div>
</section> </section>
</Layout> </Layout>
</> </>
); );
} }

View File

@@ -132,7 +132,13 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
/> />
<IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" /> <IconCard Icon={BsClipboard2Data} label="Exams Performed" value={uniqBy(stats, "exam").length} color="purple" />
<IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" /> <IconCard Icon={BsPaperclip} label="Average Level" value={averageLevelCalculator(stats).toFixed(1)} color="purple" />
<IconCard Icon={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" /> <IconCard
Icon={BsEnvelopePaper}
onClick={() => router.push("/assignments")}
label="Assignments"
value={assignments.filter((a) => !a.archived).length}
color="purple"
/>
</section> </section>
</div> </div>

View File

@@ -1,40 +1,6 @@
/* eslint-disable @next/next/no-img-element */ import {User} from "@/interfaces/user";
import Head from "next/head";
import Navbar from "@/components/Navbar";
import {BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone} from "react-icons/bs";
import {withIronSessionSsr} from "iron-session/next";
import {sessionOptions} from "@/lib/session"; import {sessionOptions} from "@/lib/session";
import {useEffect, useState} from "react"; import {withIronSessionSsr} from "iron-session/next";
import {averageScore, groupBySession, totalExams} from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Diagnostic from "@/components/Diagnostic";
import {ToastContainer} from "react-toastify";
import {capitalize} from "lodash";
import {Module} from "@/interfaces";
import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import {calculateAverageLevel} from "@/utils/score";
import axios from "axios";
import DemographicInformationInput from "@/components/DemographicInformationInput";
import moment from "moment";
import Link from "next/link";
import {MODULE_ARRAY} from "@/utils/moduleUtils";
import ProfileSummary from "@/components/ProfileSummary";
import StudentDashboard from "@/dashboards/Student";
import AdminDashboard from "@/dashboards/Admin";
import CorporateDashboard from "@/dashboards/Corporate";
import TeacherDashboard from "@/dashboards/Teacher";
import AgentDashboard from "@/dashboards/Agent";
import MasterCorporateDashboard from "@/dashboards/MasterCorporate";
import PaymentDue from "./(status)/PaymentDue";
import {useRouter} from "next/router";
import {PayPalScriptProvider} from "@paypal/react-paypal-js";
import {CorporateUser, MasterCorporateUser, Type, User, userTypes} from "@/interfaces/user";
import Select from "react-select";
import {USER_TYPE_LABELS} from "@/resources/user";
import {checkAccess, getTypesOfUser} from "@/utils/permissions";
import {getUserCorporate} from "@/utils/groups.be";
import {getUsers} from "@/utils/users.be";
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => { export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
const user = req.session.user as User | undefined; const user = req.session.user as User | undefined;
@@ -48,158 +14,14 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
}; };
} }
const linkedCorporate = (await getUserCorporate(user.id)) || null;
return { return {
props: {user, linkedCorporate}, redirect: {
destination: `/dashboard/${user.type}`,
permanent: false,
},
}; };
}, sessionOptions); }, sessionOptions);
interface Props { export default function Dashboard() {
user: User; return <div></div>;
linkedCorporate?: CorporateUser | MasterCorporateUser;
}
export default function Home({user: propsUser, linkedCorporate}: Props) {
const [user, setUser] = useState(propsUser);
const [showDiagnostics, setShowDiagnostics] = useState(false);
const [showDemographicInput, setShowDemographicInput] = useState(false);
const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
const {mutateUser} = useUser({redirectTo: "/login"});
const router = useRouter();
useEffect(() => {
if (user) {
// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
setShowDiagnostics(user.isFirstLogin && user.type === "student");
}
}, [user]);
const checkIfUserExpired = () => {
const expirationDate = user!.subscriptionExpirationDate;
if (expirationDate === null || expirationDate === undefined) return false;
if (moment(expirationDate).isAfter(moment(new Date()))) return false;
return true;
};
if (user && (user.status === "paymentDue" || user.status === "disabled" || checkIfUserExpired())) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
{user.status === "disabled" && (
<Layout user={user} navDisabled>
<div className="flex flex-col items-center justify-center text-center w-full gap-4">
<span className="font-bold text-lg">Your account has been disabled!</span>
<span>Please contact an administrator if you believe this to be a mistake.</span>
</div>
</Layout>
)}
{(user.status === "paymentDue" || checkIfUserExpired()) && <PaymentDue hasExpired user={user} reload={router.reload} />}
</>
);
}
if (user && showDemographicInput) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user} navDisabled>
<DemographicInformationInput
mutateUser={(user) => {
setUser(user);
mutateUser(user);
}}
user={user}
/>
</Layout>
</>
);
}
if (user && showDiagnostics) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user} navDisabled>
<Diagnostic user={user} onFinish={() => setShowDiagnostics(false)} />
</Layout>
</>
);
}
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<Layout user={user}>
{checkAccess(user, ["student"]) && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
{checkAccess(user, ["teacher"]) && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
{checkAccess(user, ["corporate"]) && <CorporateDashboard linkedCorporate={linkedCorporate} user={user as CorporateUser} />}
{checkAccess(user, ["mastercorporate"]) && <MasterCorporateDashboard user={user as MasterCorporateUser} />}
{checkAccess(user, ["agent"]) && <AgentDashboard user={user} />}
{checkAccess(user, ["admin"]) && <AdminDashboard user={user} />}
{checkAccess(user, ["developer"]) && (
<>
<Select
options={userTypes.map((u) => ({
value: u,
label: USER_TYPE_LABELS[u],
}))}
value={{
value: selectedScreen,
label: USER_TYPE_LABELS[selectedScreen],
}}
onChange={(value) => (value ? setSelectedScreen(value.value) : setSelectedScreen("admin"))}
/>
{selectedScreen === "student" && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
{selectedScreen === "teacher" && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
{selectedScreen === "corporate" && (
<CorporateDashboard linkedCorporate={linkedCorporate} user={user as unknown as CorporateUser} />
)}
{selectedScreen === "mastercorporate" && <MasterCorporateDashboard user={user as unknown as MasterCorporateUser} />}
{selectedScreen === "agent" && <AgentDashboard user={user} />}
{selectedScreen === "admin" && <AdminDashboard user={user} />}
</>
)}
</Layout>
)}
</>
);
} }

205
src/pages/v1/index.tsx Normal file
View File

@@ -0,0 +1,205 @@
/* eslint-disable @next/next/no-img-element */
import Head from "next/head";
import Navbar from "@/components/Navbar";
import { BsFileEarmarkText, BsPencil, BsStar, BsBook, BsHeadphones, BsPen, BsMegaphone } from "react-icons/bs";
import { withIronSessionSsr } from "iron-session/next";
import { sessionOptions } from "@/lib/session";
import { useEffect, useState } from "react";
import { averageScore, groupBySession, totalExams } from "@/utils/stats";
import useUser from "@/hooks/useUser";
import Diagnostic from "@/components/Diagnostic";
import { ToastContainer } from "react-toastify";
import { capitalize } from "lodash";
import { Module } from "@/interfaces";
import ProgressBar from "@/components/Low/ProgressBar";
import Layout from "@/components/High/Layout";
import { calculateAverageLevel } from "@/utils/score";
import axios from "axios";
import DemographicInformationInput from "@/components/DemographicInformationInput";
import moment from "moment";
import Link from "next/link";
import { MODULE_ARRAY } from "@/utils/moduleUtils";
import ProfileSummary from "@/components/ProfileSummary";
import StudentDashboard from "@/dashboards/Student";
import AdminDashboard from "@/dashboards/Admin";
import CorporateDashboard from "@/dashboards/Corporate";
import TeacherDashboard from "@/dashboards/Teacher";
import AgentDashboard from "@/dashboards/Agent";
import MasterCorporateDashboard from "@/dashboards/MasterCorporate";
import PaymentDue from "../(status)/PaymentDue";
import { useRouter } from "next/router";
import { PayPalScriptProvider } from "@paypal/react-paypal-js";
import { CorporateUser, MasterCorporateUser, Type, User, userTypes } from "@/interfaces/user";
import Select from "react-select";
import { USER_TYPE_LABELS } from "@/resources/user";
import { checkAccess, getTypesOfUser } from "@/utils/permissions";
import { getUserCorporate } from "@/utils/groups.be";
import { getUsers } from "@/utils/users.be";
export const getServerSideProps = withIronSessionSsr(async ({ req, res }) => {
const user = req.session.user as User | undefined;
if (!user) {
return {
redirect: {
destination: "/login",
permanent: false,
},
};
}
const linkedCorporate = (await getUserCorporate(user.id)) || null;
return {
props: { user, linkedCorporate },
};
}, sessionOptions);
interface Props {
user: User;
linkedCorporate?: CorporateUser | MasterCorporateUser;
}
export default function Home({ user: propsUser, linkedCorporate }: Props) {
const [user, setUser] = useState(propsUser);
const [showDiagnostics, setShowDiagnostics] = useState(false);
const [showDemographicInput, setShowDemographicInput] = useState(false);
const [selectedScreen, setSelectedScreen] = useState<Type>("admin");
const { mutateUser } = useUser({ redirectTo: "/login" });
const router = useRouter();
useEffect(() => {
if (user) {
// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
setShowDiagnostics(user.isFirstLogin && user.type === "student");
}
}, [user]);
const checkIfUserExpired = () => {
const expirationDate = user!.subscriptionExpirationDate;
if (expirationDate === null || expirationDate === undefined) return false;
if (moment(expirationDate).isAfter(moment(new Date()))) return false;
return true;
};
if (user && (user.status === "paymentDue" || user.status === "disabled" || checkIfUserExpired())) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
{user.status === "disabled" && (
<Layout user={user} navDisabled>
<div className="flex flex-col items-center justify-center text-center w-full gap-4">
<span className="font-bold text-lg">Your account has been disabled!</span>
<span>Please contact an administrator if you believe this to be a mistake.</span>
</div>
</Layout>
)}
{(user.status === "paymentDue" || checkIfUserExpired()) && <PaymentDue hasExpired user={user} reload={router.reload} />}
</>
);
}
if (user && showDemographicInput) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user} navDisabled>
<DemographicInformationInput
mutateUser={(user) => {
setUser(user);
mutateUser(user);
}}
user={user}
/>
</Layout>
</>
);
}
if (user && showDiagnostics) {
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<Layout user={user} navDisabled>
<Diagnostic user={user} onFinish={() => setShowDiagnostics(false)} />
</Layout>
</>
);
}
return (
<>
<Head>
<title>EnCoach</title>
<meta
name="description"
content="A training platform for the IELTS exam provided by the Muscat Training Institute and developed by eCrop."
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" href="/favicon.ico" />
</Head>
<ToastContainer />
{user && (
<Layout user={user}>
{checkAccess(user, ["student"]) && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
{checkAccess(user, ["teacher"]) && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
{checkAccess(user, ["corporate"]) && <CorporateDashboard linkedCorporate={linkedCorporate} user={user as CorporateUser} />}
{checkAccess(user, ["mastercorporate"]) && <MasterCorporateDashboard user={user as MasterCorporateUser} />}
{checkAccess(user, ["agent"]) && <AgentDashboard user={user} />}
{checkAccess(user, ["admin"]) && <AdminDashboard user={user} />}
{checkAccess(user, ["developer"]) && (
<>
<Select
options={userTypes.map((u) => ({
value: u,
label: USER_TYPE_LABELS[u],
}))}
value={{
value: selectedScreen,
label: USER_TYPE_LABELS[selectedScreen],
}}
onChange={(value) => (value ? setSelectedScreen(value.value) : setSelectedScreen("admin"))}
/>
{selectedScreen === "student" && <StudentDashboard linkedCorporate={linkedCorporate} user={user} />}
{selectedScreen === "teacher" && <TeacherDashboard linkedCorporate={linkedCorporate} user={user} />}
{selectedScreen === "corporate" && (
<CorporateDashboard linkedCorporate={linkedCorporate} user={user as unknown as CorporateUser} />
)}
{selectedScreen === "mastercorporate" && <MasterCorporateDashboard user={user as unknown as MasterCorporateUser} />}
{selectedScreen === "agent" && <AgentDashboard user={user} />}
{selectedScreen === "admin" && <AdminDashboard user={user} />}
</>
)}
</Layout>
)}
</>
);
}