Started working on the assignments page
This commit is contained in:
@@ -1,13 +1,26 @@
|
|||||||
|
import {useListSearch} from "@/hooks/useListSearch";
|
||||||
|
import usePagination from "@/hooks/usePagination";
|
||||||
import {Column, flexRender, getCoreRowModel, getSortedRowModel, useReactTable} from "@tanstack/react-table";
|
import {Column, flexRender, getCoreRowModel, getSortedRowModel, useReactTable} from "@tanstack/react-table";
|
||||||
|
import clsx from "clsx";
|
||||||
import {useMemo, useState} from "react";
|
import {useMemo, useState} from "react";
|
||||||
import Button from "./Low/Button";
|
import Button from "./Low/Button";
|
||||||
|
|
||||||
const SIZE = 25;
|
const SIZE = 25;
|
||||||
|
|
||||||
export default function List<T>({data, columns}: {data: T[]; columns: any[]}) {
|
export default function List<T>({
|
||||||
const [page, setPage] = useState(0);
|
data,
|
||||||
|
columns,
|
||||||
|
searchFields = [],
|
||||||
|
pageSize = SIZE,
|
||||||
|
}: {
|
||||||
|
data: T[];
|
||||||
|
columns: any[];
|
||||||
|
searchFields?: string[][];
|
||||||
|
pageSize?: number;
|
||||||
|
}) {
|
||||||
|
const {rows, renderSearch} = useListSearch(searchFields, data);
|
||||||
|
|
||||||
const items = useMemo(() => data.slice(page * SIZE, (page + 1) * SIZE > data.length ? data.length : (page + 1) * SIZE), [data, page]);
|
const {items, page, renderMinimal} = usePagination(rows, pageSize);
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data: items,
|
data: items,
|
||||||
@@ -17,19 +30,10 @@ export default function List<T>({data, columns}: {data: T[]; columns: any[]}) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="w-full h-full flex flex-col gap-2">
|
<div className="w-full h-full flex flex-col gap-6">
|
||||||
<div className="w-full flex gap-2 justify-between">
|
<div className={clsx("w-full flex items-center gap-4", searchFields.length === 0 && "justify-end")}>
|
||||||
<Button className="w-full max-w-[200px]" disabled={page === 0} onClick={() => setPage((prev) => prev - 1)}>
|
{searchFields.length > 0 && renderSearch()}
|
||||||
Previous Page
|
{renderMinimal()}
|
||||||
</Button>
|
|
||||||
<div className="flex items-center gap-4 w-fit">
|
|
||||||
<span className="opacity-80">
|
|
||||||
{page * SIZE + 1} - {(page + 1) * SIZE > data.length ? data.length : (page + 1) * SIZE} / {data.length}
|
|
||||||
</span>
|
|
||||||
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= data.length} onClick={() => setPage((prev) => prev + 1)}>
|
|
||||||
Next Page
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||||
|
|||||||
@@ -18,9 +18,10 @@ interface Props {
|
|||||||
isClearable?: boolean;
|
isClearable?: boolean;
|
||||||
styles?: StylesConfig<Option, boolean, GroupBase<Option>>;
|
styles?: StylesConfig<Option, boolean, GroupBase<Option>>;
|
||||||
className?: string;
|
className?: string;
|
||||||
|
label?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function Select({value, defaultValue, options, placeholder, disabled, onChange, styles, isClearable, className}: Props) {
|
export default function Select({value, defaultValue, options, placeholder, disabled, onChange, styles, isClearable, label, className}: Props) {
|
||||||
const [target, setTarget] = useState<HTMLElement>();
|
const [target, setTarget] = useState<HTMLElement>();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -28,43 +29,46 @@ export default function Select({value, defaultValue, options, placeholder, disab
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ReactSelect
|
<div className="w-full flex flex-col gap-3">
|
||||||
className={
|
{label && <label className="font-normal text-base text-mti-gray-dim">{label}</label>}
|
||||||
styles
|
<ReactSelect
|
||||||
? undefined
|
className={
|
||||||
: clsx(
|
styles
|
||||||
"placeholder:text-mti-gray-cool border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none",
|
? undefined
|
||||||
disabled && "!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
|
: clsx(
|
||||||
className,
|
"placeholder:text-mti-gray-cool border-mti-gray-platinum w-full rounded-full border bg-white px-4 py-4 text-sm font-normal focus:outline-none",
|
||||||
)
|
disabled && "!bg-mti-gray-platinum/40 !text-mti-gray-dim cursor-not-allowed",
|
||||||
}
|
className,
|
||||||
options={options}
|
)
|
||||||
value={value}
|
|
||||||
onChange={onChange as any}
|
|
||||||
placeholder={placeholder}
|
|
||||||
menuPortalTarget={target}
|
|
||||||
defaultValue={defaultValue}
|
|
||||||
styles={
|
|
||||||
styles || {
|
|
||||||
menuPortal: (base) => ({...base, zIndex: 9999}),
|
|
||||||
control: (styles) => ({
|
|
||||||
...styles,
|
|
||||||
paddingLeft: "4px",
|
|
||||||
border: "none",
|
|
||||||
outline: "none",
|
|
||||||
":focus": {
|
|
||||||
outline: "none",
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
option: (styles, state) => ({
|
|
||||||
...styles,
|
|
||||||
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
|
||||||
color: state.isFocused ? "black" : styles.color,
|
|
||||||
}),
|
|
||||||
}
|
}
|
||||||
}
|
options={options}
|
||||||
isDisabled={disabled}
|
value={value}
|
||||||
isClearable={isClearable}
|
onChange={onChange as any}
|
||||||
/>
|
placeholder={placeholder}
|
||||||
|
menuPortalTarget={target}
|
||||||
|
defaultValue={defaultValue}
|
||||||
|
styles={
|
||||||
|
styles || {
|
||||||
|
menuPortal: (base) => ({...base, zIndex: 9999}),
|
||||||
|
control: (styles) => ({
|
||||||
|
...styles,
|
||||||
|
paddingLeft: "4px",
|
||||||
|
border: "none",
|
||||||
|
outline: "none",
|
||||||
|
":focus": {
|
||||||
|
outline: "none",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
option: (styles, state) => ({
|
||||||
|
...styles,
|
||||||
|
backgroundColor: state.isFocused ? "#D5D9F0" : state.isSelected ? "#7872BF" : "white",
|
||||||
|
color: state.isFocused ? "black" : styles.color,
|
||||||
|
}),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
isDisabled={disabled}
|
||||||
|
isClearable={isClearable}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -111,7 +111,14 @@ export default function Sidebar({path, navDisabled = false, focusMode = false, u
|
|||||||
<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 disabled={disableNavigation} Icon={BsPeople} label="Groups" path={path} keyPath="/groups" isMinimized={isMinimized} />
|
<Nav
|
||||||
|
disabled={disableNavigation}
|
||||||
|
Icon={BsPeople}
|
||||||
|
label="Classrooms"
|
||||||
|
path={path}
|
||||||
|
keyPath="/classrooms"
|
||||||
|
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} />
|
||||||
|
|||||||
@@ -2,433 +2,341 @@ import Button from "@/components/Low/Button";
|
|||||||
import ProgressBar from "@/components/Low/ProgressBar";
|
import ProgressBar from "@/components/Low/ProgressBar";
|
||||||
import Modal from "@/components/Modal";
|
import Modal from "@/components/Modal";
|
||||||
import useUsers from "@/hooks/useUsers";
|
import useUsers from "@/hooks/useUsers";
|
||||||
import { Module } from "@/interfaces";
|
import {Module} from "@/interfaces";
|
||||||
import { Assignment } from "@/interfaces/results";
|
import {Assignment} from "@/interfaces/results";
|
||||||
import { Stat, User } from "@/interfaces/user";
|
import {Stat, User} from "@/interfaces/user";
|
||||||
import useExamStore from "@/stores/examStore";
|
import useExamStore from "@/stores/examStore";
|
||||||
import { getExamById } from "@/utils/exams";
|
import {getExamById} from "@/utils/exams";
|
||||||
import { sortByModule } from "@/utils/moduleUtils";
|
import {sortByModule} from "@/utils/moduleUtils";
|
||||||
import { calculateBandScore } from "@/utils/score";
|
import {calculateBandScore} from "@/utils/score";
|
||||||
import { convertToUserSolutions } from "@/utils/stats";
|
import {convertToUserSolutions} from "@/utils/stats";
|
||||||
import { getUserName } from "@/utils/users";
|
import {getUserName} from "@/utils/users";
|
||||||
import axios from "axios";
|
import axios from "axios";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import { capitalize, uniqBy } from "lodash";
|
import {capitalize, uniqBy} from "lodash";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import { useRouter } from "next/router";
|
import {useRouter} from "next/router";
|
||||||
import {
|
import {BsBook, BsClipboard, BsHeadphones, BsMegaphone, BsPen} from "react-icons/bs";
|
||||||
BsBook,
|
import {toast} from "react-toastify";
|
||||||
BsClipboard,
|
import {futureAssignmentFilter} from "@/utils/assignments";
|
||||||
BsHeadphones,
|
|
||||||
BsMegaphone,
|
|
||||||
BsPen,
|
|
||||||
} from "react-icons/bs";
|
|
||||||
import { toast } from "react-toastify";
|
|
||||||
import { futureAssignmentFilter } from "@/utils/assignments";
|
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
isOpen: boolean;
|
isOpen: boolean;
|
||||||
assignment?: Assignment;
|
users: User[];
|
||||||
onClose: () => void;
|
assignment?: Assignment;
|
||||||
|
onClose: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function AssignmentView({ isOpen, assignment, onClose }: Props) {
|
export default function AssignmentView({isOpen, users, assignment, onClose}: Props) {
|
||||||
const { users } = useUsers();
|
const router = useRouter();
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
const setExams = useExamStore((state) => state.setExams);
|
const setExams = useExamStore((state) => state.setExams);
|
||||||
const setShowSolutions = useExamStore((state) => state.setShowSolutions);
|
const setShowSolutions = useExamStore((state) => state.setShowSolutions);
|
||||||
const setUserSolutions = useExamStore((state) => state.setUserSolutions);
|
const setUserSolutions = useExamStore((state) => state.setUserSolutions);
|
||||||
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
|
const setSelectedModules = useExamStore((state) => state.setSelectedModules);
|
||||||
|
|
||||||
const deleteAssignment = async () => {
|
const deleteAssignment = async () => {
|
||||||
if (!confirm("Are you sure you want to delete this assignment?")) return;
|
if (!confirm("Are you sure you want to delete this assignment?")) return;
|
||||||
|
|
||||||
axios
|
axios
|
||||||
.delete(`/api/assignments/${assignment?.id}`)
|
.delete(`/api/assignments/${assignment?.id}`)
|
||||||
.then(() =>
|
.then(() => toast.success(`Successfully deleted the assignment "${assignment?.name}".`))
|
||||||
toast.success(
|
.catch(() => toast.error("Something went wrong, please try again later."))
|
||||||
`Successfully deleted the assignment "${assignment?.name}".`
|
.finally(onClose);
|
||||||
)
|
};
|
||||||
)
|
|
||||||
.catch(() => toast.error("Something went wrong, please try again later."))
|
|
||||||
.finally(onClose);
|
|
||||||
};
|
|
||||||
|
|
||||||
const startAssignment = () => {
|
const startAssignment = () => {
|
||||||
if (assignment) {
|
if (assignment) {
|
||||||
axios
|
axios
|
||||||
.post(`/api/assignments/${assignment.id}/start`)
|
.post(`/api/assignments/${assignment.id}/start`)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
toast.success(
|
toast.success(`The assignment "${assignment.name}" has been started successfully!`);
|
||||||
`The assignment "${assignment.name}" has been started successfully!`
|
})
|
||||||
);
|
.catch((e) => {
|
||||||
})
|
console.log(e);
|
||||||
.catch((e) => {
|
toast.error("Something went wrong, please try again later!");
|
||||||
console.log(e);
|
});
|
||||||
toast.error("Something went wrong, please try again later!");
|
}
|
||||||
});
|
};
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatTimestamp = (timestamp: string) => {
|
const formatTimestamp = (timestamp: string) => {
|
||||||
const date = moment(parseInt(timestamp));
|
const date = moment(parseInt(timestamp));
|
||||||
const formatter = "YYYY/MM/DD - HH:mm";
|
const formatter = "YYYY/MM/DD - HH:mm";
|
||||||
|
|
||||||
return date.format(formatter);
|
return date.format(formatter);
|
||||||
};
|
};
|
||||||
|
|
||||||
const calculateAverageModuleScore = (module: Module) => {
|
const calculateAverageModuleScore = (module: Module) => {
|
||||||
if (!assignment) return -1;
|
if (!assignment) return -1;
|
||||||
|
|
||||||
const resultModuleBandScores = assignment.results.map((r) => {
|
const resultModuleBandScores = assignment.results.map((r) => {
|
||||||
const moduleStats = r.stats.filter((s) => s.module === module);
|
const moduleStats = r.stats.filter((s) => s.module === module);
|
||||||
|
|
||||||
const correct = moduleStats.reduce(
|
const correct = moduleStats.reduce((acc, curr) => acc + curr.score.correct, 0);
|
||||||
(acc, curr) => acc + curr.score.correct,
|
const total = moduleStats.reduce((acc, curr) => acc + curr.score.total, 0);
|
||||||
0
|
return calculateBandScore(correct, total, module, r.type);
|
||||||
);
|
});
|
||||||
const total = moduleStats.reduce(
|
|
||||||
(acc, curr) => acc + curr.score.total,
|
|
||||||
0
|
|
||||||
);
|
|
||||||
return calculateBandScore(correct, total, module, r.type);
|
|
||||||
});
|
|
||||||
|
|
||||||
return resultModuleBandScores.length === 0
|
return resultModuleBandScores.length === 0 ? -1 : resultModuleBandScores.reduce((acc, curr) => acc + curr, 0) / assignment.results.length;
|
||||||
? -1
|
};
|
||||||
: resultModuleBandScores.reduce((acc, curr) => acc + curr, 0) /
|
|
||||||
assignment.results.length;
|
|
||||||
};
|
|
||||||
|
|
||||||
const aggregateScoresByModule = (
|
const aggregateScoresByModule = (stats: Stat[]): {module: Module; total: number; missing: number; correct: number}[] => {
|
||||||
stats: Stat[]
|
const scores: {
|
||||||
): { module: Module; total: number; missing: number; correct: number }[] => {
|
[key in Module]: {total: number; missing: number; correct: number};
|
||||||
const scores: {
|
} = {
|
||||||
[key in Module]: { total: number; missing: number; correct: number };
|
reading: {
|
||||||
} = {
|
total: 0,
|
||||||
reading: {
|
correct: 0,
|
||||||
total: 0,
|
missing: 0,
|
||||||
correct: 0,
|
},
|
||||||
missing: 0,
|
listening: {
|
||||||
},
|
total: 0,
|
||||||
listening: {
|
correct: 0,
|
||||||
total: 0,
|
missing: 0,
|
||||||
correct: 0,
|
},
|
||||||
missing: 0,
|
writing: {
|
||||||
},
|
total: 0,
|
||||||
writing: {
|
correct: 0,
|
||||||
total: 0,
|
missing: 0,
|
||||||
correct: 0,
|
},
|
||||||
missing: 0,
|
speaking: {
|
||||||
},
|
total: 0,
|
||||||
speaking: {
|
correct: 0,
|
||||||
total: 0,
|
missing: 0,
|
||||||
correct: 0,
|
},
|
||||||
missing: 0,
|
level: {
|
||||||
},
|
total: 0,
|
||||||
level: {
|
correct: 0,
|
||||||
total: 0,
|
missing: 0,
|
||||||
correct: 0,
|
},
|
||||||
missing: 0,
|
};
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
stats.forEach((x) => {
|
stats.forEach((x) => {
|
||||||
scores[x.module!] = {
|
scores[x.module!] = {
|
||||||
total: scores[x.module!].total + x.score.total,
|
total: scores[x.module!].total + x.score.total,
|
||||||
correct: scores[x.module!].correct + x.score.correct,
|
correct: scores[x.module!].correct + x.score.correct,
|
||||||
missing: scores[x.module!].missing + x.score.missing,
|
missing: scores[x.module!].missing + x.score.missing,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
return Object.keys(scores)
|
return Object.keys(scores)
|
||||||
.filter((x) => scores[x as Module].total > 0)
|
.filter((x) => scores[x as Module].total > 0)
|
||||||
.map((x) => ({ module: x as Module, ...scores[x as Module] }));
|
.map((x) => ({module: x as Module, ...scores[x as Module]}));
|
||||||
};
|
};
|
||||||
|
|
||||||
const customContent = (
|
const customContent = (stats: Stat[], user: string, focus: "academic" | "general") => {
|
||||||
stats: Stat[],
|
const correct = stats.reduce((accumulator, current) => accumulator + current.score.correct, 0);
|
||||||
user: string,
|
const total = stats.reduce((accumulator, current) => accumulator + current.score.total, 0);
|
||||||
focus: "academic" | "general"
|
const aggregatedScores = aggregateScoresByModule(stats).filter((x) => x.total > 0);
|
||||||
) => {
|
|
||||||
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) => ({
|
const aggregatedLevels = aggregatedScores.map((x) => ({
|
||||||
module: x.module,
|
module: x.module,
|
||||||
level: calculateBandScore(x.correct, x.total, x.module, focus),
|
level: calculateBandScore(x.correct, x.total, x.module, focus),
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const timeSpent = stats[0].timeSpent;
|
const timeSpent = stats[0].timeSpent;
|
||||||
|
|
||||||
const selectExam = () => {
|
const selectExam = () => {
|
||||||
const examPromises = uniqBy(stats, "exam").map((stat) =>
|
const examPromises = uniqBy(stats, "exam").map((stat) => getExamById(stat.module, stat.exam));
|
||||||
getExamById(stat.module, stat.exam)
|
|
||||||
);
|
|
||||||
|
|
||||||
Promise.all(examPromises).then((exams) => {
|
Promise.all(examPromises).then((exams) => {
|
||||||
if (exams.every((x) => !!x)) {
|
if (exams.every((x) => !!x)) {
|
||||||
setUserSolutions(convertToUserSolutions(stats));
|
setUserSolutions(convertToUserSolutions(stats));
|
||||||
setShowSolutions(true);
|
setShowSolutions(true);
|
||||||
setExams(exams.map((x) => x!).sort(sortByModule));
|
setExams(exams.map((x) => x!).sort(sortByModule));
|
||||||
setSelectedModules(
|
setSelectedModules(
|
||||||
exams
|
exams
|
||||||
.map((x) => x!)
|
.map((x) => x!)
|
||||||
.sort(sortByModule)
|
.sort(sortByModule)
|
||||||
.map((x) => x!.module)
|
.map((x) => x!.module),
|
||||||
);
|
);
|
||||||
router.push("/exercises");
|
router.push("/exercises");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
const content = (
|
const content = (
|
||||||
<>
|
<>
|
||||||
<div className="-md:items-center flex w-full justify-between 2xl:items-center">
|
<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">
|
<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">
|
<span className="font-medium">{formatTimestamp(stats[0].date.toString())}</span>
|
||||||
{formatTimestamp(stats[0].date.toString())}
|
{timeSpent && (
|
||||||
</span>
|
<>
|
||||||
{timeSpent && (
|
<span className="md:hidden 2xl:flex">• </span>
|
||||||
<>
|
<span className="text-sm">{Math.floor(timeSpent / 60)} minutes</span>
|
||||||
<span className="md:hidden 2xl:flex">• </span>
|
</>
|
||||||
<span className="text-sm">
|
)}
|
||||||
{Math.floor(timeSpent / 60)} minutes
|
</div>
|
||||||
</span>
|
<span
|
||||||
</>
|
className={clsx(
|
||||||
)}
|
correct / total >= 0.7 && "text-mti-purple",
|
||||||
</div>
|
correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
|
||||||
<span
|
correct / total < 0.3 && "text-mti-rose",
|
||||||
className={clsx(
|
)}>
|
||||||
correct / total >= 0.7 && "text-mti-purple",
|
Level{" "}
|
||||||
correct / total >= 0.3 && correct / total < 0.7 && "text-mti-red",
|
{(aggregatedLevels.reduce((accumulator, current) => accumulator + current.level, 0) / aggregatedLevels.length).toFixed(1)}
|
||||||
correct / total < 0.3 && "text-mti-rose"
|
</span>
|
||||||
)}
|
</div>
|
||||||
>
|
|
||||||
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="flex w-full flex-col gap-1">
|
||||||
<div className="-md:mt-2 grid w-full grid-cols-4 place-items-start gap-2">
|
<div className="-md:mt-2 grid w-full grid-cols-4 place-items-start gap-2">
|
||||||
{aggregatedLevels.map(({ module, level }) => (
|
{aggregatedLevels.map(({module, level}) => (
|
||||||
<div
|
<div
|
||||||
key={module}
|
key={module}
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"-md:px-4 flex w-fit items-center gap-2 rounded-xl py-2 text-white md:px-2 xl:px-4",
|
"-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 === "reading" && "bg-ielts-reading",
|
||||||
module === "listening" && "bg-ielts-listening",
|
module === "listening" && "bg-ielts-listening",
|
||||||
module === "writing" && "bg-ielts-writing",
|
module === "writing" && "bg-ielts-writing",
|
||||||
module === "speaking" && "bg-ielts-speaking",
|
module === "speaking" && "bg-ielts-speaking",
|
||||||
module === "level" && "bg-ielts-level"
|
module === "level" && "bg-ielts-level",
|
||||||
)}
|
)}>
|
||||||
>
|
{module === "reading" && <BsBook className="h-4 w-4" />}
|
||||||
{module === "reading" && <BsBook className="h-4 w-4" />}
|
{module === "listening" && <BsHeadphones className="h-4 w-4" />}
|
||||||
{module === "listening" && <BsHeadphones className="h-4 w-4" />}
|
{module === "writing" && <BsPen className="h-4 w-4" />}
|
||||||
{module === "writing" && <BsPen className="h-4 w-4" />}
|
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
|
||||||
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
|
{module === "level" && <BsClipboard className="h-4 w-4" />}
|
||||||
{module === "level" && <BsClipboard className="h-4 w-4" />}
|
<span className="text-sm">{level.toFixed(1)}</span>
|
||||||
<span className="text-sm">{level.toFixed(1)}</span>
|
</div>
|
||||||
</div>
|
))}
|
||||||
))}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</>
|
||||||
</>
|
);
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<span>
|
<span>
|
||||||
{(() => {
|
{(() => {
|
||||||
const student = users.find((u) => u.id === user);
|
const student = users.find((u) => u.id === user);
|
||||||
return `${student?.name} (${student?.email})`;
|
return `${student?.name} (${student?.email})`;
|
||||||
})()}
|
})()}
|
||||||
</span>
|
</span>
|
||||||
<div
|
<div
|
||||||
key={user}
|
key={user}
|
||||||
className={clsx(
|
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",
|
"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.7 && "hover:border-mti-purple",
|
||||||
correct / total >= 0.3 &&
|
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
|
||||||
correct / total < 0.7 &&
|
correct / total < 0.3 && "hover:border-mti-rose",
|
||||||
"hover:border-mti-red",
|
)}
|
||||||
correct / total < 0.3 && "hover:border-mti-rose"
|
onClick={selectExam}
|
||||||
)}
|
role="button">
|
||||||
onClick={selectExam}
|
{content}
|
||||||
role="button"
|
</div>
|
||||||
>
|
<div
|
||||||
{content}
|
key={user}
|
||||||
</div>
|
className={clsx(
|
||||||
<div
|
"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",
|
||||||
key={user}
|
correct / total >= 0.7 && "hover:border-mti-purple",
|
||||||
className={clsx(
|
correct / total >= 0.3 && correct / total < 0.7 && "hover:border-mti-red",
|
||||||
"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.3 && "hover:border-mti-rose",
|
||||||
correct / total >= 0.7 && "hover:border-mti-purple",
|
)}
|
||||||
correct / total >= 0.3 &&
|
data-tip="Your screen size is too small to view previous exams."
|
||||||
correct / total < 0.7 &&
|
role="button">
|
||||||
"hover:border-mti-red",
|
{content}
|
||||||
correct / total < 0.3 && "hover:border-mti-rose"
|
</div>
|
||||||
)}
|
</div>
|
||||||
data-tip="Your screen size is too small to view previous exams."
|
);
|
||||||
role="button"
|
};
|
||||||
>
|
|
||||||
{content}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const shouldRenderStart = () => {
|
const shouldRenderStart = () => {
|
||||||
if (assignment) {
|
if (assignment) {
|
||||||
if (futureAssignmentFilter(assignment)) {
|
if (futureAssignmentFilter(assignment)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Modal isOpen={isOpen} onClose={onClose} title={assignment?.name}>
|
<Modal isOpen={isOpen} onClose={onClose} title={assignment?.name}>
|
||||||
<div className="mt-4 flex w-full flex-col gap-4">
|
<div className="mt-4 flex w-full flex-col gap-4">
|
||||||
<ProgressBar
|
<ProgressBar
|
||||||
color="purple"
|
color="purple"
|
||||||
label={`${assignment?.results.length}/${assignment?.assignees.length} assignees completed`}
|
label={`${assignment?.results.length}/${assignment?.assignees.length} assignees completed`}
|
||||||
className="h-6"
|
className="h-6"
|
||||||
textClassName={
|
textClassName={
|
||||||
(assignment?.results.length || 0) /
|
(assignment?.results.length || 0) / (assignment?.assignees.length || 1) < 0.5 ? "!text-mti-gray-dim font-light" : "text-white"
|
||||||
(assignment?.assignees.length || 1) <
|
}
|
||||||
0.5
|
percentage={((assignment?.results.length || 0) / (assignment?.assignees.length || 1)) * 100}
|
||||||
? "!text-mti-gray-dim font-light"
|
/>
|
||||||
: "text-white"
|
<div className="flex items-start gap-8">
|
||||||
}
|
<div className="flex flex-col gap-2">
|
||||||
percentage={
|
<span>Start Date: {moment(assignment?.startDate).format("DD/MM/YY, HH:mm")}</span>
|
||||||
((assignment?.results.length || 0) /
|
<span>End Date: {moment(assignment?.endDate).format("DD/MM/YY, HH:mm")}</span>
|
||||||
(assignment?.assignees.length || 1)) *
|
</div>
|
||||||
100
|
<div className="flex flex-col gap-2">
|
||||||
}
|
<span>
|
||||||
/>
|
Assignees:{" "}
|
||||||
<div className="flex items-start gap-8">
|
{users
|
||||||
<div className="flex flex-col gap-2">
|
.filter((u) => assignment?.assignees.includes(u.id))
|
||||||
<span>
|
.map((u) => `${u.name} (${u.email})`)
|
||||||
Start Date:{" "}
|
.join(", ")}
|
||||||
{moment(assignment?.startDate).format("DD/MM/YY, HH:mm")}
|
</span>
|
||||||
</span>
|
<span>Assigner: {getUserName(users.find((x) => x.id === assignment?.assigner))}</span>
|
||||||
<span>
|
</div>
|
||||||
End Date: {moment(assignment?.endDate).format("DD/MM/YY, HH:mm")}
|
</div>
|
||||||
</span>
|
<div className="flex flex-col gap-2">
|
||||||
</div>
|
<span className="text-xl font-bold">Average Scores</span>
|
||||||
<div className="flex flex-col gap-2">
|
<div className="-md:mt-2 flex w-full items-center gap-4">
|
||||||
<span>
|
{assignment &&
|
||||||
Assignees:{" "}
|
uniqBy(assignment.exams, (x) => x.module).map(({module}) => (
|
||||||
{users
|
<div
|
||||||
.filter((u) => assignment?.assignees.includes(u.id))
|
data-tip={capitalize(module)}
|
||||||
.map((u) => `${u.name} (${u.email})`)
|
key={module}
|
||||||
.join(", ")}
|
className={clsx(
|
||||||
</span>
|
"-md:px-4 tooltip flex w-fit items-center gap-2 rounded-xl py-2 text-white md:px-2 xl:px-4",
|
||||||
<span>
|
module === "reading" && "bg-ielts-reading",
|
||||||
Assigner:{" "}
|
module === "listening" && "bg-ielts-listening",
|
||||||
{getUserName(users.find((x) => x.id === assignment?.assigner))}
|
module === "writing" && "bg-ielts-writing",
|
||||||
</span>
|
module === "speaking" && "bg-ielts-speaking",
|
||||||
</div>
|
module === "level" && "bg-ielts-level",
|
||||||
</div>
|
)}>
|
||||||
<div className="flex flex-col gap-2">
|
{module === "reading" && <BsBook className="h-4 w-4" />}
|
||||||
<span className="text-xl font-bold">Average Scores</span>
|
{module === "listening" && <BsHeadphones className="h-4 w-4" />}
|
||||||
<div className="-md:mt-2 flex w-full items-center gap-4">
|
{module === "writing" && <BsPen className="h-4 w-4" />}
|
||||||
{assignment &&
|
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
|
||||||
uniqBy(assignment.exams, (x) => x.module).map(({ module }) => (
|
{module === "level" && <BsClipboard className="h-4 w-4" />}
|
||||||
<div
|
{calculateAverageModuleScore(module) > -1 && (
|
||||||
data-tip={capitalize(module)}
|
<span className="text-sm">{calculateAverageModuleScore(module).toFixed(1)}</span>
|
||||||
key={module}
|
)}
|
||||||
className={clsx(
|
</div>
|
||||||
"-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",
|
</div>
|
||||||
module === "listening" && "bg-ielts-listening",
|
</div>
|
||||||
module === "writing" && "bg-ielts-writing",
|
<div className="flex flex-col gap-2">
|
||||||
module === "speaking" && "bg-ielts-speaking",
|
<span className="text-xl font-bold">
|
||||||
module === "level" && "bg-ielts-level"
|
Results ({assignment?.results.length}/{assignment?.assignees.length})
|
||||||
)}
|
</span>
|
||||||
>
|
<div>
|
||||||
{module === "reading" && <BsBook className="h-4 w-4" />}
|
{assignment && assignment?.results.length > 0 && (
|
||||||
{module === "listening" && (
|
<div className="grid w-full grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3 xl:gap-6">
|
||||||
<BsHeadphones className="h-4 w-4" />
|
{assignment.results.map((r) => customContent(r.stats, r.user, r.type))}
|
||||||
)}
|
</div>
|
||||||
{module === "writing" && <BsPen className="h-4 w-4" />}
|
)}
|
||||||
{module === "speaking" && <BsMegaphone className="h-4 w-4" />}
|
{assignment && assignment?.results.length === 0 && <span className="ml-1 font-semibold">No results yet...</span>}
|
||||||
{module === "level" && <BsClipboard className="h-4 w-4" />}
|
</div>
|
||||||
{calculateAverageModuleScore(module) > -1 && (
|
</div>
|
||||||
<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">
|
<div className="flex gap-4 w-full items-center justify-end">
|
||||||
{assignment &&
|
{assignment && (assignment.results.length === assignment.assignees.length || moment().isAfter(moment(assignment.endDate))) && (
|
||||||
(assignment.results.length === assignment.assignees.length ||
|
<Button variant="outline" color="red" className="w-full max-w-[200px]" onClick={deleteAssignment}>
|
||||||
moment().isAfter(moment(assignment.endDate))) && (
|
Delete
|
||||||
<Button
|
</Button>
|
||||||
variant="outline"
|
)}
|
||||||
color="red"
|
{/** if the assignment is not deemed as active yet, display start */}
|
||||||
className="w-full max-w-[200px]"
|
{shouldRenderStart() && (
|
||||||
onClick={deleteAssignment}
|
<Button variant="outline" color="green" className="w-full max-w-[200px]" onClick={startAssignment}>
|
||||||
>
|
Start
|
||||||
Delete
|
</Button>
|
||||||
</Button>
|
)}
|
||||||
)}
|
<Button onClick={onClose} className="w-full max-w-[200px]">
|
||||||
{/** if the assignment is not deemed as active yet, display start */}
|
Close
|
||||||
{shouldRenderStart() && (
|
</Button>
|
||||||
<Button
|
</div>
|
||||||
variant="outline"
|
</div>
|
||||||
color="green"
|
</Modal>
|
||||||
className="w-full max-w-[200px]"
|
);
|
||||||
onClick={startAssignment}
|
|
||||||
>
|
|
||||||
Start
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
<Button onClick={onClose} className="w-full max-w-[200px]">
|
|
||||||
Close
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</Modal>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -42,6 +42,7 @@ export default function AssignmentsPage({assignments, corporateAssignments, user
|
|||||||
{displayAssignmentView && (
|
{displayAssignmentView && (
|
||||||
<AssignmentView
|
<AssignmentView
|
||||||
isOpen={displayAssignmentView}
|
isOpen={displayAssignmentView}
|
||||||
|
users={users}
|
||||||
onClose={() => {
|
onClose={() => {
|
||||||
setSelectedAssignment(undefined);
|
setSelectedAssignment(undefined);
|
||||||
setIsCreatingAssignment(false);
|
setIsCreatingAssignment(false);
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import client from "@/lib/mongodb";
|
|||||||
import {withIronSessionApiRoute} from "iron-session/next";
|
import {withIronSessionApiRoute} from "iron-session/next";
|
||||||
import {sessionOptions} from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
|
||||||
|
|
||||||
const db = client.db(process.env.MONGODB_DB);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
@@ -25,7 +24,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {id} = req.query;
|
const {id} = req.query;
|
||||||
|
|
||||||
const snapshot = await db.collection("assignments").findOne({ id: id as string });
|
const snapshot = await db.collection("assignments").findOne({id: id as string});
|
||||||
|
|
||||||
if (snapshot) {
|
if (snapshot) {
|
||||||
res.status(200).json({...snapshot, id: snapshot.id});
|
res.status(200).json({...snapshot, id: snapshot.id});
|
||||||
@@ -35,9 +34,7 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {id} = req.query;
|
const {id} = req.query;
|
||||||
|
|
||||||
await db.collection("assignments").deleteOne(
|
await db.collection("assignments").deleteOne({id});
|
||||||
{ id: id as string }
|
|
||||||
);
|
|
||||||
|
|
||||||
res.status(200).json({ok: true});
|
res.status(200).json({ok: true});
|
||||||
}
|
}
|
||||||
@@ -45,10 +42,7 @@ async function DELETE(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
async function PATCH(req: NextApiRequest, res: NextApiResponse) {
|
async function PATCH(req: NextApiRequest, res: NextApiResponse) {
|
||||||
const {id} = req.query;
|
const {id} = req.query;
|
||||||
|
|
||||||
await db.collection("assignments").updateOne(
|
await db.collection("assignments").updateOne({id: id as string}, {$set: {assigner: req.session.user?.id, ...req.body}});
|
||||||
{ id: id as string },
|
|
||||||
{ $set: {assigner: req.session.user?.id, ...req.body} }
|
|
||||||
);
|
|
||||||
|
|
||||||
res.status(200).json({ok: true});
|
res.status(200).json({ok: true});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -128,8 +128,10 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const id = uuidv4();
|
||||||
|
|
||||||
await db.collection("assignments").insertOne({
|
await db.collection("assignments").insertOne({
|
||||||
id: uuidv4(),
|
id,
|
||||||
assigner: req.session.user?.id,
|
assigner: req.session.user?.id,
|
||||||
assignees,
|
assignees,
|
||||||
results: [],
|
results: [],
|
||||||
@@ -138,11 +140,10 @@ async function POST(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
...body,
|
...body,
|
||||||
});
|
});
|
||||||
|
|
||||||
res.status(200).json({ok: true});
|
res.status(200).json({ok: true, id});
|
||||||
|
|
||||||
for (const assigneeID of assignees) {
|
for (const assigneeID of assignees) {
|
||||||
|
const assignee = await db.collection("users").findOne<User>({id: assigneeID});
|
||||||
const assignee = await db.collection("users").findOne<User>({ id: assigneeID });
|
|
||||||
if (!assignee) continue;
|
if (!assignee) continue;
|
||||||
|
|
||||||
const name = body.name;
|
const name = body.name;
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
name: body.name,
|
name: body.name,
|
||||||
admin: body.admin,
|
admin: body.admin,
|
||||||
participants: body.participants,
|
participants: body.participants,
|
||||||
|
entity: body.entity,
|
||||||
});
|
});
|
||||||
res.status(200).json({ok: true, id});
|
res.status(200).json({ok: true, id});
|
||||||
}
|
}
|
||||||
|
|||||||
594
src/pages/assignments/creator/[id].tsx
Normal file
594
src/pages/assignments/creator/[id].tsx
Normal file
@@ -0,0 +1,594 @@
|
|||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import Button from "@/components/Low/Button";
|
||||||
|
import Checkbox from "@/components/Low/Checkbox";
|
||||||
|
import Input from "@/components/Low/Input";
|
||||||
|
import ProgressBar from "@/components/Low/ProgressBar";
|
||||||
|
import Select from "@/components/Low/Select";
|
||||||
|
import useExams from "@/hooks/useExams";
|
||||||
|
import {useListSearch} from "@/hooks/useListSearch";
|
||||||
|
import usePagination from "@/hooks/usePagination";
|
||||||
|
import {Module} from "@/interfaces";
|
||||||
|
import {EntityWithRoles} from "@/interfaces/entity";
|
||||||
|
import {InstructorGender, Variant} from "@/interfaces/exam";
|
||||||
|
import {Assignment} from "@/interfaces/results";
|
||||||
|
import {Group, User} from "@/interfaces/user";
|
||||||
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
import {mapBy, serialize} from "@/utils";
|
||||||
|
import {getAssignment} from "@/utils/assignments.be";
|
||||||
|
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||||
|
import {getGroupsByEntities} from "@/utils/groups.be";
|
||||||
|
import {checkAccess} from "@/utils/permissions";
|
||||||
|
import {calculateAverageLevel} from "@/utils/score";
|
||||||
|
import {getEntitiesUsers} from "@/utils/users.be";
|
||||||
|
import axios from "axios";
|
||||||
|
import clsx from "clsx";
|
||||||
|
import {withIronSessionSsr} from "iron-session/next";
|
||||||
|
import {capitalize} from "lodash";
|
||||||
|
import moment from "moment";
|
||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {generate} from "random-words";
|
||||||
|
import {useEffect, useMemo, useState} from "react";
|
||||||
|
import ReactDatePicker from "react-datepicker";
|
||||||
|
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
|
||||||
|
import {toast} from "react-toastify";
|
||||||
|
|
||||||
|
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 getEntitiesUsers(entityIDS);
|
||||||
|
const entities = await getEntitiesWithRoles(entityIDS);
|
||||||
|
const groups = await getGroupsByEntities(entityIDS);
|
||||||
|
|
||||||
|
return {props: serialize({user, users, entities, assignment, groups})};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
assignment: Assignment;
|
||||||
|
groups: Group[];
|
||||||
|
user: User;
|
||||||
|
users: User[];
|
||||||
|
entities: EntityWithRoles[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const SIZE = 9;
|
||||||
|
|
||||||
|
export default function AssignmentsPage({assignment, user, users, entities, groups}: Props) {
|
||||||
|
const [selectedModules, setSelectedModules] = useState<Module[]>(assignment.exams.map((e) => e.module));
|
||||||
|
const [assignees, setAssignees] = useState<string[]>(assignment.assignees);
|
||||||
|
const [teachers, setTeachers] = useState<string[]>(assignment.teachers || []);
|
||||||
|
const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
|
||||||
|
const [name, setName] = useState(assignment.name);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
|
||||||
|
const [startDate, setStartDate] = useState<Date | null>(moment(assignment.startDate).toDate());
|
||||||
|
const [endDate, setEndDate] = useState<Date | null>(moment(assignment.endDate).toDate());
|
||||||
|
|
||||||
|
const [variant, setVariant] = useState<Variant>("full");
|
||||||
|
const [instructorGender, setInstructorGender] = useState<InstructorGender>(assignment?.instructorGender || "varied");
|
||||||
|
|
||||||
|
const [generateMultiple, setGenerateMultiple] = useState<boolean>(false);
|
||||||
|
const [released, setReleased] = useState<boolean>(assignment.released || false);
|
||||||
|
|
||||||
|
const [autoStart, setAutostart] = useState<boolean>(assignment.autoStart || false);
|
||||||
|
const [autoStartDate, setAutoStartDate] = useState<Date | null>(moment(assignment.autoStartDate).toDate());
|
||||||
|
|
||||||
|
const [useRandomExams, setUseRandomExams] = useState(true);
|
||||||
|
const [examIDs, setExamIDs] = useState<{id: string; module: Module}[]>([]);
|
||||||
|
|
||||||
|
const {exams} = useExams();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const classrooms = useMemo(() => groups.filter((e) => e.entity === entity), [entity, groups]);
|
||||||
|
|
||||||
|
const userStudents = useMemo(() => users.filter((x) => x.type === "student"), [users]);
|
||||||
|
const userTeachers = useMemo(() => users.filter((x) => x.type === "teacher"), [users]);
|
||||||
|
|
||||||
|
const {rows: filteredStudentsRows, renderSearch: renderStudentSearch} = useListSearch([["name"], ["email"]], userStudents);
|
||||||
|
const {rows: filteredTeachersRows, renderSearch: renderTeacherSearch} = useListSearch([["name"], ["email"]], userTeachers);
|
||||||
|
|
||||||
|
const {items: studentRows, renderMinimal: renderStudentPagination} = usePagination(filteredStudentsRows, SIZE);
|
||||||
|
const {items: teacherRows, renderMinimal: renderTeacherPagination} = usePagination(filteredTeachersRows, SIZE);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module)));
|
||||||
|
}, [selectedModules]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setAssignees([]);
|
||||||
|
setTeachers([]);
|
||||||
|
}, [entity]);
|
||||||
|
|
||||||
|
const toggleModule = (module: Module) => {
|
||||||
|
const modules = selectedModules.filter((x) => x !== module);
|
||||||
|
setSelectedModules((prev) => (prev.includes(module) ? modules : [...modules, module]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAssignee = (user: User) => {
|
||||||
|
setAssignees((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleTeacher = (user: User) => {
|
||||||
|
setTeachers((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const createAssignment = () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
(assignment ? axios.patch : axios.post)(`/api/assignments${assignment.id}`, {
|
||||||
|
assignees,
|
||||||
|
name,
|
||||||
|
startDate,
|
||||||
|
examIDs: !useRandomExams ? examIDs : undefined,
|
||||||
|
endDate,
|
||||||
|
selectedModules,
|
||||||
|
generateMultiple,
|
||||||
|
entity,
|
||||||
|
teachers,
|
||||||
|
variant,
|
||||||
|
instructorGender,
|
||||||
|
released,
|
||||||
|
autoStart,
|
||||||
|
autoStartDate,
|
||||||
|
})
|
||||||
|
.then(() => {
|
||||||
|
toast.success(`The assignment "${name}" has been updated successfully!`);
|
||||||
|
router.push(`/assignments/${assignment.id}`);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.log(e);
|
||||||
|
toast.error("Something went wrong, please try again later!");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteAssignment = () => {
|
||||||
|
if (!confirm(`Are you sure you want to delete the "${assignment.name}" assignment?`)) return;
|
||||||
|
console.log("GOT HERE");
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
axios
|
||||||
|
.delete(`/api/assignments/${assignment.id}`)
|
||||||
|
.then(() => {
|
||||||
|
toast.success(`The assignment "${name}" has been deleted successfully!`);
|
||||||
|
router.push("/assignments");
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.log(e);
|
||||||
|
toast.error("Something went wrong, please try again later!");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const startAssignment = () => {
|
||||||
|
if (assignment) {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
axios
|
||||||
|
.post(`/api/assignments/${assignment.id}/start`)
|
||||||
|
.then(() => {
|
||||||
|
toast.success(`The assignment "${name}" has been started successfully!`);
|
||||||
|
router.push(`/assignments/${assignment.id}`);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.log(e);
|
||||||
|
toast.error("Something went wrong, please try again later!");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Layout user={user}>
|
||||||
|
<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">
|
||||||
|
<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 className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label>
|
||||||
|
<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).isSameOrAfter(new Date())}
|
||||||
|
dateFormat="dd/MM/yyyy HH:mm"
|
||||||
|
selected={startDate}
|
||||||
|
showTimeSelect
|
||||||
|
onChange={(date) => setStartDate(date)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">End Date *</label>
|
||||||
|
<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">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label>
|
||||||
|
<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).isSameOrAfter(new Date())}
|
||||||
|
dateFormat="dd/MM/yyyy HH:mm"
|
||||||
|
selected={autoStartDate}
|
||||||
|
showTimeSelect
|
||||||
|
onChange={(date) => setAutoStartDate(date)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedModules.includes("speaking") && (
|
||||||
|
<div className="flex flex-col gap-3 w-full">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor's Gender</label>
|
||||||
|
<Select
|
||||||
|
value={{
|
||||||
|
value: instructorGender,
|
||||||
|
label: capitalize(instructorGender),
|
||||||
|
}}
|
||||||
|
onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)}
|
||||||
|
disabled={!selectedModules.includes("speaking") || !!assignment}
|
||||||
|
options={[
|
||||||
|
{value: "male", label: "Male"},
|
||||||
|
{value: "female", label: "Female"},
|
||||||
|
{value: "varied", label: "Varied"},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedModules.length > 0 && (
|
||||||
|
<div className="flex flex-col gap-3 w-full">
|
||||||
|
<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
|
||||||
|
Random Exams
|
||||||
|
</Checkbox>
|
||||||
|
{!useRandomExams && (
|
||||||
|
<div className="grid md:grid-cols-2 w-full gap-4">
|
||||||
|
{selectedModules.map((module) => (
|
||||||
|
<div key={module} className="flex flex-col gap-3 w-full">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
|
||||||
|
<Select
|
||||||
|
value={{
|
||||||
|
value: examIDs.find((e) => e.module === module)?.id || null,
|
||||||
|
label: examIDs.find((e) => e.module === module)?.id || "",
|
||||||
|
}}
|
||||||
|
onChange={(value) =>
|
||||||
|
value
|
||||||
|
? setExamIDs((prev) => [...prev.filter((x) => x.module !== module), {id: value.value!, module}])
|
||||||
|
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
|
||||||
|
}
|
||||||
|
options={exams
|
||||||
|
.filter((x) => !x.isDiagnostic && x.module === module)
|
||||||
|
.map((x) => ({value: x.id, label: x.id}))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<section className="w-full flex flex-col gap-4">
|
||||||
|
<span className="font-semibold">Assignees ({assignees.length} selected)</span>
|
||||||
|
<div className="grid grid-cols-5 gap-4">
|
||||||
|
{classrooms.map((g) => (
|
||||||
|
<button
|
||||||
|
key={g.id}
|
||||||
|
onClick={() => {
|
||||||
|
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(
|
||||||
|
"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) => assignees.includes(u.id)) &&
|
||||||
|
"!bg-mti-purple-light !text-white",
|
||||||
|
)}>
|
||||||
|
{g.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full flex items-center gap-4">
|
||||||
|
{renderStudentSearch()}
|
||||||
|
{renderStudentPagination()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap -md:justify-center gap-4">
|
||||||
|
{studentRows.map((user) => (
|
||||||
|
<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">
|
||||||
|
{classrooms.map((g) => (
|
||||||
|
<button
|
||||||
|
key={g.id}
|
||||||
|
onClick={() => {
|
||||||
|
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
|
||||||
|
if (groupStudentIds.every((u) => teachers.includes(u))) {
|
||||||
|
setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
|
||||||
|
} else {
|
||||||
|
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>
|
||||||
|
</Layout>
|
||||||
|
);
|
||||||
|
}
|
||||||
537
src/pages/assignments/creator/index.tsx
Normal file
537
src/pages/assignments/creator/index.tsx
Normal file
@@ -0,0 +1,537 @@
|
|||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import Button from "@/components/Low/Button";
|
||||||
|
import Checkbox from "@/components/Low/Checkbox";
|
||||||
|
import Input from "@/components/Low/Input";
|
||||||
|
import ProgressBar from "@/components/Low/ProgressBar";
|
||||||
|
import Select from "@/components/Low/Select";
|
||||||
|
import useExams from "@/hooks/useExams";
|
||||||
|
import {useListSearch} from "@/hooks/useListSearch";
|
||||||
|
import usePagination from "@/hooks/usePagination";
|
||||||
|
import {Module} from "@/interfaces";
|
||||||
|
import {EntityWithRoles} from "@/interfaces/entity";
|
||||||
|
import {InstructorGender, Variant} from "@/interfaces/exam";
|
||||||
|
import {Assignment} from "@/interfaces/results";
|
||||||
|
import {Group, User} from "@/interfaces/user";
|
||||||
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
import {mapBy, serialize} from "@/utils";
|
||||||
|
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||||
|
import {getGroupsByEntities} from "@/utils/groups.be";
|
||||||
|
import {checkAccess} from "@/utils/permissions";
|
||||||
|
import {calculateAverageLevel} from "@/utils/score";
|
||||||
|
import {getEntitiesUsers} from "@/utils/users.be";
|
||||||
|
import axios from "axios";
|
||||||
|
import clsx from "clsx";
|
||||||
|
import {withIronSessionSsr} from "iron-session/next";
|
||||||
|
import {capitalize} from "lodash";
|
||||||
|
import moment from "moment";
|
||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {generate} from "random-words";
|
||||||
|
import {useEffect, useMemo, useState} from "react";
|
||||||
|
import ReactDatePicker from "react-datepicker";
|
||||||
|
import {BsBook, BsCheckCircle, BsClipboard, BsHeadphones, BsMegaphone, BsPen, BsXCircle} from "react-icons/bs";
|
||||||
|
import {toast} from "react-toastify";
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const entityIDS = mapBy(user.entities, "id") || [];
|
||||||
|
|
||||||
|
const users = await getEntitiesUsers(entityIDS);
|
||||||
|
const entities = await getEntitiesWithRoles(entityIDS);
|
||||||
|
const groups = await getGroupsByEntities(entityIDS);
|
||||||
|
|
||||||
|
return {props: serialize({user, users, entities, groups})};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
assignment: Assignment;
|
||||||
|
groups: Group[];
|
||||||
|
user: User;
|
||||||
|
users: User[];
|
||||||
|
entities: EntityWithRoles[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const SIZE = 9;
|
||||||
|
|
||||||
|
export default function AssignmentsPage({user, users, groups, entities}: Props) {
|
||||||
|
const [selectedModules, setSelectedModules] = useState<Module[]>([]);
|
||||||
|
const [assignees, setAssignees] = useState<string[]>([]);
|
||||||
|
const [teachers, setTeachers] = useState<string[]>([...(user.type === "teacher" ? [user.id] : [])]);
|
||||||
|
const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
|
||||||
|
const [name, setName] = useState(
|
||||||
|
generate({
|
||||||
|
minLength: 6,
|
||||||
|
maxLength: 8,
|
||||||
|
min: 2,
|
||||||
|
max: 3,
|
||||||
|
join: " ",
|
||||||
|
formatter: capitalize,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [startDate, setStartDate] = useState<Date | null>(moment().add(1, "hour").toDate());
|
||||||
|
|
||||||
|
const [endDate, setEndDate] = useState<Date | null>(moment().hours(23).minutes(59).add(8, "day").toDate());
|
||||||
|
const [variant, setVariant] = useState<Variant>("full");
|
||||||
|
const [instructorGender, setInstructorGender] = useState<InstructorGender>("varied");
|
||||||
|
|
||||||
|
const [generateMultiple, setGenerateMultiple] = useState<boolean>(false);
|
||||||
|
const [released, setReleased] = useState<boolean>(false);
|
||||||
|
|
||||||
|
const [autoStart, setAutostart] = useState<boolean>(false);
|
||||||
|
const [autoStartDate, setAutoStartDate] = useState<Date | null>(new Date());
|
||||||
|
|
||||||
|
const [useRandomExams, setUseRandomExams] = useState(true);
|
||||||
|
const [examIDs, setExamIDs] = useState<{id: string; module: Module}[]>([]);
|
||||||
|
|
||||||
|
const {exams} = useExams();
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const classrooms = useMemo(() => groups.filter((e) => e.entity === entity), [entity, groups]);
|
||||||
|
|
||||||
|
const userStudents = useMemo(() => users.filter((x) => x.type === "student"), [users]);
|
||||||
|
const userTeachers = useMemo(() => users.filter((x) => x.type === "teacher"), [users]);
|
||||||
|
|
||||||
|
const {rows: filteredStudentsRows, renderSearch: renderStudentSearch} = useListSearch([["name"], ["email"]], userStudents);
|
||||||
|
const {rows: filteredTeachersRows, renderSearch: renderTeacherSearch} = useListSearch([["name"], ["email"]], userTeachers);
|
||||||
|
|
||||||
|
const {items: studentRows, renderMinimal: renderStudentPagination} = usePagination(filteredStudentsRows, SIZE);
|
||||||
|
const {items: teacherRows, renderMinimal: renderTeacherPagination} = usePagination(filteredTeachersRows, SIZE);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setExamIDs((prev) => prev.filter((x) => selectedModules.includes(x.module)));
|
||||||
|
}, [selectedModules]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setAssignees([]);
|
||||||
|
setTeachers([]);
|
||||||
|
}, [entity]);
|
||||||
|
|
||||||
|
const toggleModule = (module: Module) => {
|
||||||
|
const modules = selectedModules.filter((x) => x !== module);
|
||||||
|
setSelectedModules((prev) => (prev.includes(module) ? modules : [...modules, module]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAssignee = (user: User) => {
|
||||||
|
setAssignees((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleTeacher = (user: User) => {
|
||||||
|
setTeachers((prev) => (prev.includes(user.id) ? prev.filter((a) => a !== user.id) : [...prev, user.id]));
|
||||||
|
};
|
||||||
|
|
||||||
|
const createAssignment = () => {
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
axios
|
||||||
|
.post(`/api/assignments`, {
|
||||||
|
assignees,
|
||||||
|
name,
|
||||||
|
startDate,
|
||||||
|
examIDs: !useRandomExams ? examIDs : undefined,
|
||||||
|
endDate,
|
||||||
|
selectedModules,
|
||||||
|
generateMultiple,
|
||||||
|
entity,
|
||||||
|
teachers,
|
||||||
|
variant,
|
||||||
|
instructorGender,
|
||||||
|
released,
|
||||||
|
autoStart,
|
||||||
|
autoStartDate,
|
||||||
|
})
|
||||||
|
.then((result) => {
|
||||||
|
toast.success(`The assignment "${name}" has been created successfully!`);
|
||||||
|
router.push(`/assignments/${result.data.id}`);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.log(e);
|
||||||
|
toast.error("Something went wrong, please try again later!");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Layout user={user}>
|
||||||
|
<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">
|
||||||
|
<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 className="w-full grid -md:grid-cols-1 md:grid-cols-2 gap-8">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Limit Start Date *</label>
|
||||||
|
<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).isSameOrAfter(new Date())}
|
||||||
|
dateFormat="dd/MM/yyyy HH:mm"
|
||||||
|
selected={startDate}
|
||||||
|
showTimeSelect
|
||||||
|
onChange={(date) => setStartDate(date)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">End Date *</label>
|
||||||
|
<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">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Automatic Start Date *</label>
|
||||||
|
<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).isSameOrAfter(new Date())}
|
||||||
|
dateFormat="dd/MM/yyyy HH:mm"
|
||||||
|
selected={autoStartDate}
|
||||||
|
showTimeSelect
|
||||||
|
onChange={(date) => setAutoStartDate(date)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{selectedModules.includes("speaking") && (
|
||||||
|
<div className="flex flex-col gap-3 w-full">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">Speaking Instructor's Gender</label>
|
||||||
|
<Select
|
||||||
|
value={{
|
||||||
|
value: instructorGender,
|
||||||
|
label: capitalize(instructorGender),
|
||||||
|
}}
|
||||||
|
onChange={(value) => (value ? setInstructorGender(value.value as InstructorGender) : null)}
|
||||||
|
disabled={!selectedModules.includes("speaking")}
|
||||||
|
options={[
|
||||||
|
{value: "male", label: "Male"},
|
||||||
|
{value: "female", label: "Female"},
|
||||||
|
{value: "varied", label: "Varied"},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{selectedModules.length > 0 && (
|
||||||
|
<div className="flex flex-col gap-3 w-full">
|
||||||
|
<Checkbox isChecked={useRandomExams} onChange={setUseRandomExams}>
|
||||||
|
Random Exams
|
||||||
|
</Checkbox>
|
||||||
|
{!useRandomExams && (
|
||||||
|
<div className="grid md:grid-cols-2 w-full gap-4">
|
||||||
|
{selectedModules.map((module) => (
|
||||||
|
<div key={module} className="flex flex-col gap-3 w-full">
|
||||||
|
<label className="font-normal text-base text-mti-gray-dim">{capitalize(module)} Exam</label>
|
||||||
|
<Select
|
||||||
|
value={{
|
||||||
|
value: examIDs.find((e) => e.module === module)?.id || null,
|
||||||
|
label: examIDs.find((e) => e.module === module)?.id || "",
|
||||||
|
}}
|
||||||
|
onChange={(value) =>
|
||||||
|
value
|
||||||
|
? setExamIDs((prev) => [...prev.filter((x) => x.module !== module), {id: value.value!, module}])
|
||||||
|
: setExamIDs((prev) => prev.filter((x) => x.module !== module))
|
||||||
|
}
|
||||||
|
options={exams
|
||||||
|
.filter((x) => !x.isDiagnostic && x.module === module)
|
||||||
|
.map((x) => ({value: x.id, label: x.id}))}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<section className="w-full flex flex-col gap-4">
|
||||||
|
<span className="font-semibold">Assignees ({assignees.length} selected)</span>
|
||||||
|
<div className="grid grid-cols-5 gap-4">
|
||||||
|
{classrooms.map((g) => (
|
||||||
|
<button
|
||||||
|
key={g.id}
|
||||||
|
onClick={() => {
|
||||||
|
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(
|
||||||
|
"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) => assignees.includes(u.id)) &&
|
||||||
|
"!bg-mti-purple-light !text-white",
|
||||||
|
)}>
|
||||||
|
{g.name}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="w-full flex items-center gap-4">
|
||||||
|
{renderStudentSearch()}
|
||||||
|
{renderStudentPagination()}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap -md:justify-center gap-4">
|
||||||
|
{studentRows.map((user) => (
|
||||||
|
<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">
|
||||||
|
{classrooms.map((g) => (
|
||||||
|
<button
|
||||||
|
key={g.id}
|
||||||
|
onClick={() => {
|
||||||
|
const groupStudentIds = users.filter((u) => g.participants.includes(u.id)).map((u) => u.id);
|
||||||
|
if (groupStudentIds.every((u) => teachers.includes(u))) {
|
||||||
|
setTeachers((prev) => prev.filter((a) => !groupStudentIds.includes(a)));
|
||||||
|
} else {
|
||||||
|
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
|
||||||
|
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>
|
||||||
|
</Layout>
|
||||||
|
);
|
||||||
|
}
|
||||||
187
src/pages/assignments/index.tsx
Normal file
187
src/pages/assignments/index.tsx
Normal file
@@ -0,0 +1,187 @@
|
|||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import AssignmentCard from "@/dashboards/AssignmentCard";
|
||||||
|
import AssignmentView from "@/dashboards/AssignmentView";
|
||||||
|
import {Assignment} from "@/interfaces/results";
|
||||||
|
import {CorporateUser, Group, User} from "@/interfaces/user";
|
||||||
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
import {getUserCompanyName} from "@/resources/user";
|
||||||
|
import {mapBy, serialize} from "@/utils";
|
||||||
|
import {
|
||||||
|
activeAssignmentFilter,
|
||||||
|
archivedAssignmentFilter,
|
||||||
|
futureAssignmentFilter,
|
||||||
|
pastAssignmentFilter,
|
||||||
|
startHasExpiredAssignmentFilter,
|
||||||
|
} from "@/utils/assignments";
|
||||||
|
import {getEntitiesAssignments} from "@/utils/assignments.be";
|
||||||
|
import {getEntitiesWithRoles} from "@/utils/entities.be";
|
||||||
|
import {getGroupsByEntities} from "@/utils/groups.be";
|
||||||
|
import {checkAccess} from "@/utils/permissions";
|
||||||
|
import {getEntitiesUsers} from "@/utils/users.be";
|
||||||
|
import {withIronSessionSsr} from "iron-session/next";
|
||||||
|
import {groupBy} from "lodash";
|
||||||
|
import Link from "next/link";
|
||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {useMemo, useState} from "react";
|
||||||
|
import {BsChevronLeft, BsPlus} from "react-icons/bs";
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const entityIDS = mapBy(user.entities, "id") || [];
|
||||||
|
|
||||||
|
const users = await getEntitiesUsers(entityIDS);
|
||||||
|
const entities = await getEntitiesWithRoles(entityIDS);
|
||||||
|
const assignments = await getEntitiesAssignments(entityIDS);
|
||||||
|
const groups = await getGroupsByEntities(entityIDS);
|
||||||
|
|
||||||
|
return {props: serialize({user, users, entities, assignments, groups})};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
assignments: Assignment[];
|
||||||
|
corporateAssignments?: ({corporate?: CorporateUser} & Assignment)[];
|
||||||
|
groups: Group[];
|
||||||
|
user: User;
|
||||||
|
users: User[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AssignmentsPage({assignments, corporateAssignments, user, users, groups}: Props) {
|
||||||
|
const [selectedAssignment, setSelectedAssignment] = useState<Assignment>();
|
||||||
|
const [isCreatingAssignment, setIsCreatingAssignment] = useState(false);
|
||||||
|
|
||||||
|
const displayAssignmentView = useMemo(() => !!selectedAssignment && !isCreatingAssignment, [selectedAssignment, isCreatingAssignment]);
|
||||||
|
|
||||||
|
const assignmentsPastExpiredStart = assignments.filter(startHasExpiredAssignmentFilter);
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Layout user={user}>
|
||||||
|
{displayAssignmentView && (
|
||||||
|
<AssignmentView
|
||||||
|
users={users}
|
||||||
|
isOpen={displayAssignmentView}
|
||||||
|
onClose={() => {
|
||||||
|
setSelectedAssignment(undefined);
|
||||||
|
setIsCreatingAssignment(false);
|
||||||
|
}}
|
||||||
|
assignment={selectedAssignment}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<div className="w-full flex justify-between items-center">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<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>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<span className="text-lg font-bold">Active Assignments Status</span>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<span>
|
||||||
|
<b>Total:</b> {assignments.filter(activeAssignmentFilter).reduce((acc, curr) => acc + curr.results.length, 0)}/
|
||||||
|
{assignments.filter(activeAssignmentFilter).reduce((acc, curr) => curr.exams.length + acc, 0)}
|
||||||
|
</span>
|
||||||
|
{Object.keys(groupBy(corporateAssignments, (x) => x.corporate?.id)).map((x) => (
|
||||||
|
<div key={x}>
|
||||||
|
<span className="font-semibold">{getUserCompanyName(users.find((u) => u.id === x)!, users, groups)}: </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.exams.length + acc, 0)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<h2 className="text-2xl font-semibold">Active Assignments ({assignments.filter(activeAssignmentFilter).length})</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{assignments.filter(activeAssignmentFilter).map((a) => (
|
||||||
|
<AssignmentCard {...a} users={users} onClick={() => setSelectedAssignment(a)} key={a.id} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<h2 className="text-2xl font-semibold">Planned Assignments ({assignments.filter(futureAssignmentFilter).length})</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
<Link
|
||||||
|
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">
|
||||||
|
<BsPlus className="text-6xl" />
|
||||||
|
<span className="text-lg">New Assignment</span>
|
||||||
|
</Link>
|
||||||
|
{assignments.filter(futureAssignmentFilter).map((a) => (
|
||||||
|
<AssignmentCard {...a} users={users} onClick={() => router.push(`/assignments/creator/${a.id}`)} key={a.id} />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<h2 className="text-2xl font-semibold">Past Assignments ({assignments.filter(pastAssignmentFilter).length})</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{assignments.filter(pastAssignmentFilter).map((a) => (
|
||||||
|
<AssignmentCard
|
||||||
|
{...a}
|
||||||
|
users={users}
|
||||||
|
onClick={() => setSelectedAssignment(a)}
|
||||||
|
key={a.id}
|
||||||
|
allowDownload
|
||||||
|
allowArchive
|
||||||
|
allowExcelDownload
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<h2 className="text-2xl font-semibold">Assignments start expired ({assignmentsPastExpiredStart.length})</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{assignments.filter(startHasExpiredAssignmentFilter).map((a) => (
|
||||||
|
<AssignmentCard
|
||||||
|
{...a}
|
||||||
|
users={users}
|
||||||
|
onClick={() => setSelectedAssignment(a)}
|
||||||
|
key={a.id}
|
||||||
|
allowDownload
|
||||||
|
allowArchive
|
||||||
|
allowExcelDownload
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
<section className="flex flex-col gap-4">
|
||||||
|
<h2 className="text-2xl font-semibold">Archived Assignments ({assignments.filter(archivedAssignmentFilter).length})</h2>
|
||||||
|
<div className="flex flex-wrap gap-2">
|
||||||
|
{assignments.filter(archivedAssignmentFilter).map((a) => (
|
||||||
|
<AssignmentCard
|
||||||
|
{...a}
|
||||||
|
users={users}
|
||||||
|
onClick={() => setSelectedAssignment(a)}
|
||||||
|
key={a.id}
|
||||||
|
allowDownload
|
||||||
|
allowUnarchive
|
||||||
|
allowExcelDownload
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</Layout>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -165,7 +165,7 @@ export default function Home({user, group, users}: Props) {
|
|||||||
.delete(`/api/groups/${group.id}`)
|
.delete(`/api/groups/${group.id}`)
|
||||||
.then(() => {
|
.then(() => {
|
||||||
toast.success("This group has been successfully deleted!");
|
toast.success("This group has been successfully deleted!");
|
||||||
router.replace("/groups");
|
router.replace("/classrooms");
|
||||||
})
|
})
|
||||||
.catch((e) => {
|
.catch((e) => {
|
||||||
console.error(e);
|
console.error(e);
|
||||||
@@ -195,7 +195,7 @@ export default function Home({user, group, users}: Props) {
|
|||||||
<div className="flex items-end justify-between">
|
<div className="flex items-end justify-between">
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<Link
|
<Link
|
||||||
href="/groups"
|
href="/classrooms"
|
||||||
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||||
<BsChevronLeft />
|
<BsChevronLeft />
|
||||||
</Link>
|
</Link>
|
||||||
202
src/pages/classrooms/create.tsx
Normal file
202
src/pages/classrooms/create.tsx
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
/* eslint-disable @next/next/no-img-element */
|
||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import Input from "@/components/Low/Input";
|
||||||
|
import Select from "@/components/Low/Select";
|
||||||
|
import Tooltip from "@/components/Low/Tooltip";
|
||||||
|
import {useListSearch} from "@/hooks/useListSearch";
|
||||||
|
import usePagination from "@/hooks/usePagination";
|
||||||
|
import {Entity} from "@/interfaces/entity";
|
||||||
|
import {User} from "@/interfaces/user";
|
||||||
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||||
|
import {mapBy, serialize} from "@/utils";
|
||||||
|
import {getEntities} from "@/utils/entities.be";
|
||||||
|
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||||
|
import {getUserName} from "@/utils/users";
|
||||||
|
import {getLinkedUsers} from "@/utils/users.be";
|
||||||
|
import axios from "axios";
|
||||||
|
import clsx from "clsx";
|
||||||
|
import {withIronSessionSsr} from "iron-session/next";
|
||||||
|
import moment from "moment";
|
||||||
|
import Head from "next/head";
|
||||||
|
import Link from "next/link";
|
||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {Divider} from "primereact/divider";
|
||||||
|
import {useState} from "react";
|
||||||
|
import {BsCheck, BsChevronLeft, BsClockFill, BsEnvelopeFill, BsStopwatchFill} from "react-icons/bs";
|
||||||
|
import {toast, ToastContainer} from "react-toastify";
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
||||||
|
const user = req.session.user as User;
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/login",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldRedirectHome(user)) {
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const linkedUsers = await getLinkedUsers(user.id, user.type);
|
||||||
|
const entities = await getEntities(mapBy(user.entities, "id"));
|
||||||
|
|
||||||
|
return {
|
||||||
|
props: serialize({user, entities, users: linkedUsers.users.filter((x) => x.id !== user.id)}),
|
||||||
|
};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
user: User;
|
||||||
|
users: User[];
|
||||||
|
entities: Entity[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function Home({user, users, entities}: Props) {
|
||||||
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
|
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
||||||
|
const [name, setName] = useState("");
|
||||||
|
const [entity, setEntity] = useState<string | undefined>(entities[0]?.id);
|
||||||
|
|
||||||
|
const {rows, renderSearch} = useListSearch<User>([["name"], ["corporateInformation", "companyInformation", "name"]], users);
|
||||||
|
const {items, renderMinimal} = usePagination<User>(rows, 16);
|
||||||
|
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const createGroup = () => {
|
||||||
|
if (!name.trim()) return;
|
||||||
|
if (!entity) return;
|
||||||
|
if (!confirm(`Are you sure you want to create this group with ${selectedUsers.length} participants?`)) return;
|
||||||
|
|
||||||
|
setIsLoading(true);
|
||||||
|
|
||||||
|
axios
|
||||||
|
.post<{id: string}>(`/api/groups`, {name, participants: selectedUsers, admin: user.id, entity})
|
||||||
|
.then((result) => {
|
||||||
|
toast.success("Your group has been created successfully!");
|
||||||
|
router.replace(`/classrooms/${result.data.id}`);
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
toast.error("Something went wrong!");
|
||||||
|
})
|
||||||
|
.finally(() => setIsLoading(false));
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleUser = (u: User) => setSelectedUsers((prev) => (prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>Create Group | 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 />
|
||||||
|
<Layout user={user}>
|
||||||
|
<section className="flex flex-col gap-0">
|
||||||
|
<div className="flex gap-3 justify-between">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Link
|
||||||
|
href="/classrooms"
|
||||||
|
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">Create Classroom</h2>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
onClick={createGroup}
|
||||||
|
disabled={!name.trim() || !entity || isLoading}
|
||||||
|
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
||||||
|
<BsCheck />
|
||||||
|
<span className="text-xs">Create Classroom</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Divider />
|
||||||
|
<div className="grid grid-cols-2 gap-4 place-items-end">
|
||||||
|
<div className="flex flex-col gap-4 w-full">
|
||||||
|
<span className="font-semibold text-xl">Classroom Name:</span>
|
||||||
|
<Input name="name" onChange={setName} type="text" placeholder="Classroom A" />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-4 w-full">
|
||||||
|
<span className="font-semibold text-xl">Entity:</span>
|
||||||
|
<Select
|
||||||
|
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>
|
||||||
|
<Divider />
|
||||||
|
<div className="flex items-center justify-between mb-4">
|
||||||
|
<span className="font-semibold text-xl">Participants ({selectedUsers.length} selected):</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full flex items-center gap-4">
|
||||||
|
{renderSearch()}
|
||||||
|
{renderMinimal()}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
||||||
|
{items.map((u) => (
|
||||||
|
<button
|
||||||
|
onClick={() => toggleUser(u)}
|
||||||
|
disabled={isLoading}
|
||||||
|
key={u.id}
|
||||||
|
className={clsx(
|
||||||
|
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
||||||
|
"hover:border-mti-purple transition ease-in-out duration-300",
|
||||||
|
selectedUsers.includes(u.id) && "border-mti-purple",
|
||||||
|
)}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
||||||
|
<img src={u.profilePicture} alt={u.name} />
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col">
|
||||||
|
<span className="font-semibold">{getUserName(u)}</span>
|
||||||
|
<span className="opacity-80 text-sm">{USER_TYPE_LABELS[u.type]}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-1">
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Tooltip tooltip="E-mail address">
|
||||||
|
<BsEnvelopeFill />
|
||||||
|
</Tooltip>
|
||||||
|
{u.email}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Tooltip tooltip="Expiration Date">
|
||||||
|
<BsStopwatchFill />
|
||||||
|
</Tooltip>
|
||||||
|
{u.subscriptionExpirationDate ? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited"}
|
||||||
|
</span>
|
||||||
|
<span className="flex items-center gap-2">
|
||||||
|
<Tooltip tooltip="Last Login">
|
||||||
|
<BsClockFill />
|
||||||
|
</Tooltip>
|
||||||
|
{u.lastLogin ? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm") : "N/A"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</section>
|
||||||
|
</Layout>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -7,14 +7,14 @@ import Layout from "@/components/High/Layout";
|
|||||||
import {GroupWithUsers, User} from "@/interfaces/user";
|
import {GroupWithUsers, User} from "@/interfaces/user";
|
||||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
||||||
import {getUserName} from "@/utils/users";
|
import {getUserName} from "@/utils/users";
|
||||||
import {convertToUsers, getGroupsForUser} from "@/utils/groups.be";
|
import {convertToUsers, getGroupsForEntities} from "@/utils/groups.be";
|
||||||
import {getSpecificUsers} from "@/utils/users.be";
|
import {getSpecificUsers} from "@/utils/users.be";
|
||||||
import {checkAccess} from "@/utils/permissions";
|
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import {uniq} from "lodash";
|
import {uniq} from "lodash";
|
||||||
import {BsPlus} from "react-icons/bs";
|
import {BsPlus} from "react-icons/bs";
|
||||||
import CardList from "@/components/High/CardList";
|
import CardList from "@/components/High/CardList";
|
||||||
import Separator from "@/components/Low/Separator";
|
import Separator from "@/components/Low/Separator";
|
||||||
|
import {mapBy} from "@/utils";
|
||||||
|
|
||||||
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
||||||
const user = req.session.user;
|
const user = req.session.user;
|
||||||
@@ -37,10 +37,8 @@ export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const groups = await getGroupsForUser(
|
const entityIDS = mapBy(user.entities, "id");
|
||||||
checkAccess(user, ["corporate", "mastercorporate"]) ? user.id : undefined,
|
const groups = await getGroupsForEntities(entityIDS);
|
||||||
checkAccess(user, ["teacher", "student"]) ? user.id : undefined,
|
|
||||||
);
|
|
||||||
|
|
||||||
const users = await getSpecificUsers(uniq(groups.flatMap((g) => [...g.participants.slice(0, 5), g.admin])));
|
const users = await getSpecificUsers(uniq(groups.flatMap((g) => [...g.participants.slice(0, 5), g.admin])));
|
||||||
const groupsWithUsers: GroupWithUsers[] = groups.map((g) => convertToUsers(g, users));
|
const groupsWithUsers: GroupWithUsers[] = groups.map((g) => convertToUsers(g, users));
|
||||||
@@ -67,7 +65,7 @@ interface Props {
|
|||||||
export default function Home({user, groups}: Props) {
|
export default function Home({user, groups}: Props) {
|
||||||
const renderCard = (group: GroupWithUsers) => (
|
const renderCard = (group: GroupWithUsers) => (
|
||||||
<Link
|
<Link
|
||||||
href={`/groups/${group.id}`}
|
href={`/classrooms/${group.id}`}
|
||||||
key={group.id}
|
key={group.id}
|
||||||
className="p-4 border rounded-xl flex flex-col gap-2 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
|
className="p-4 border rounded-xl flex flex-col gap-2 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
|
||||||
<span>
|
<span>
|
||||||
@@ -88,7 +86,7 @@ export default function Home({user, groups}: Props) {
|
|||||||
|
|
||||||
const firstCard = () => (
|
const firstCard = () => (
|
||||||
<Link
|
<Link
|
||||||
href={`/groups/create`}
|
href={`/classrooms/create`}
|
||||||
className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
|
className="p-4 border hover:text-mti-purple rounded-xl flex flex-col items-center justify-center gap-0 hover:border-mti-purple transition ease-in-out duration-300 text-left cursor-pointer">
|
||||||
<BsPlus size={40} />
|
<BsPlus size={40} />
|
||||||
<span className="font-semibold">Create Group</span>
|
<span className="font-semibold">Create Group</span>
|
||||||
@@ -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 {
|
||||||
BsClipboard2Data,
|
BsClipboard2Data,
|
||||||
@@ -78,6 +79,8 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
|
|||||||
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 averageLevelCalculator = (studentStats: Stat[]) => {
|
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||||
const formattedStats = studentStats
|
const formattedStats = studentStats
|
||||||
.map((s) => ({
|
.map((s) => ({
|
||||||
@@ -133,9 +136,27 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
|
|||||||
</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 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={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
Icon={BsPersonFill}
|
||||||
|
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
|
||||||
|
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={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" />
|
||||||
@@ -56,7 +56,7 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!checkAccess(user, ["admin", "developer"]))
|
if (!checkAccess(user, ["developer"]))
|
||||||
return {
|
return {
|
||||||
redirect: {
|
redirect: {
|
||||||
destination: "/dashboard",
|
destination: "/dashboard",
|
||||||
@@ -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,
|
||||||
@@ -80,6 +81,8 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
|
|||||||
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 averageLevelCalculator = (studentStats: Stat[]) => {
|
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||||
const formattedStats = studentStats
|
const formattedStats = studentStats
|
||||||
.map((s) => ({
|
.map((s) => ({
|
||||||
@@ -132,7 +135,7 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
|
|||||||
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
||||||
<IconCard Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" />
|
<IconCard Icon={BsPencilSquare} label="Teachers" value={teachers.length} color="purple" />
|
||||||
<IconCard Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" />
|
<IconCard Icon={BsBank} label="Corporate Accounts" value={corporates.length} color="purple" />
|
||||||
<IconCard Icon={BsPeople} label="Classrooms" value={groups.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={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" />
|
||||||
@@ -17,7 +17,7 @@ import useExamStore from "@/stores/examStore";
|
|||||||
import {mapBy, serialize} from "@/utils";
|
import {mapBy, serialize} from "@/utils";
|
||||||
import {activeAssignmentFilter} from "@/utils/assignments";
|
import {activeAssignmentFilter} from "@/utils/assignments";
|
||||||
import {getAssignmentsByAssignee} from "@/utils/assignments.be";
|
import {getAssignmentsByAssignee} from "@/utils/assignments.be";
|
||||||
import {getEntityWithRoles} from "@/utils/entities.be";
|
import {getEntitiesWithRoles, getEntityWithRoles} from "@/utils/entities.be";
|
||||||
import {getExamsByIds} from "@/utils/exams.be";
|
import {getExamsByIds} from "@/utils/exams.be";
|
||||||
import {getGradingSystemByEntity} from "@/utils/grading.be";
|
import {getGradingSystemByEntity} from "@/utils/grading.be";
|
||||||
import {convertInvitersToUsers, getInvitesByInvitee} from "@/utils/invites.be";
|
import {convertInvitersToUsers, getInvitesByInvitee} from "@/utils/invites.be";
|
||||||
@@ -59,7 +59,7 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!checkAccess(user, ["admin", "developer", "mastercorporate"]))
|
if (!checkAccess(user, ["admin", "developer", "student"]))
|
||||||
return {
|
return {
|
||||||
redirect: {
|
redirect: {
|
||||||
destination: "/dashboard",
|
destination: "/dashboard",
|
||||||
@@ -68,14 +68,13 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const entityIDS = mapBy(user.entities, "id") || [];
|
const entityIDS = mapBy(user.entities, "id") || [];
|
||||||
const entityID = entityIDS.length > 0 ? entityIDS[0] : "";
|
|
||||||
|
|
||||||
const entities = await getEntityWithRoles(entityID);
|
const entities = await getEntitiesWithRoles(entityIDS);
|
||||||
const allAssignments = await getAssignmentsByAssignee(user.id, {archived: false});
|
const allAssignments = await getAssignmentsByAssignee(user.id, {archived: false});
|
||||||
const stats = await getStatsByUser(user.id);
|
const stats = await getStatsByUser(user.id);
|
||||||
const sessions = await getSessionsByUser(user.id, 10);
|
const sessions = await getSessionsByUser(user.id, 10);
|
||||||
const invites = await getInvitesByInvitee(user.id);
|
const invites = await getInvitesByInvitee(user.id);
|
||||||
const grading = await getGradingSystemByEntity(entityID);
|
const grading = await getGradingSystemByEntity(entityIDS[0] || "");
|
||||||
|
|
||||||
const formattedInvites = await Promise.all(invites.map(convertInvitersToUsers));
|
const formattedInvites = await Promise.all(invites.map(convertInvitersToUsers));
|
||||||
const assignments = allAssignments.filter(activeAssignmentFilter);
|
const assignments = allAssignments.filter(activeAssignmentFilter);
|
||||||
@@ -17,21 +17,10 @@ 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 Head from "next/head";
|
import Head from "next/head";
|
||||||
import Link from "next/link";
|
import {useRouter} from "next/router";
|
||||||
import {useMemo} from "react";
|
import {useMemo} from "react";
|
||||||
import {
|
import {BsClipboard2Data, BsEnvelopePaper, BsPaperclip, BsPeople, BsPersonFill} from "react-icons/bs";
|
||||||
BsClipboard2Data,
|
|
||||||
BsClock,
|
|
||||||
BsEnvelopePaper,
|
|
||||||
BsPaperclip,
|
|
||||||
BsPencilSquare,
|
|
||||||
BsPeople,
|
|
||||||
BsPeopleFill,
|
|
||||||
BsPersonFill,
|
|
||||||
BsPersonFillGear,
|
|
||||||
} from "react-icons/bs";
|
|
||||||
import {ToastContainer} from "react-toastify";
|
import {ToastContainer} from "react-toastify";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -76,6 +65,7 @@ export const getServerSideProps = withIronSessionSsr(async ({req, res}) => {
|
|||||||
|
|
||||||
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 router = useRouter();
|
||||||
|
|
||||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||||
const formattedStats = studentStats
|
const formattedStats = studentStats
|
||||||
@@ -133,7 +123,13 @@ export default function Dashboard({user, users, entities, assignments, stats, gr
|
|||||||
)}
|
)}
|
||||||
<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 Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
<IconCard Icon={BsPersonFill} label="Students" value={students.length} color="purple" />
|
||||||
<IconCard Icon={BsPeople} label="Classrooms" value={groups.length} color="purple" />
|
<IconCard
|
||||||
|
onClick={() => router.push("/classrooms")}
|
||||||
|
Icon={BsPeople}
|
||||||
|
label="Classrooms"
|
||||||
|
value={groups.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={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" />
|
<IconCard Icon={BsEnvelopePaper} label="Assignments" value={assignments.filter((a) => !a.archived).length} color="purple" />
|
||||||
@@ -1,186 +0,0 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
|
||||||
import Layout from "@/components/High/Layout";
|
|
||||||
import Input from "@/components/Low/Input";
|
|
||||||
import Tooltip from "@/components/Low/Tooltip";
|
|
||||||
import {useListSearch} from "@/hooks/useListSearch";
|
|
||||||
import usePagination from "@/hooks/usePagination";
|
|
||||||
import {User} from "@/interfaces/user";
|
|
||||||
import {sessionOptions} from "@/lib/session";
|
|
||||||
import {USER_TYPE_LABELS} from "@/resources/user";
|
|
||||||
import {shouldRedirectHome} from "@/utils/navigation.disabled";
|
|
||||||
import {getUserName} from "@/utils/users";
|
|
||||||
import {getLinkedUsers} from "@/utils/users.be";
|
|
||||||
import axios from "axios";
|
|
||||||
import clsx from "clsx";
|
|
||||||
import {withIronSessionSsr} from "iron-session/next";
|
|
||||||
import moment from "moment";
|
|
||||||
import Head from "next/head";
|
|
||||||
import Link from "next/link";
|
|
||||||
import {useRouter} from "next/router";
|
|
||||||
import {Divider} from "primereact/divider";
|
|
||||||
import {useState} from "react";
|
|
||||||
import {BsCheck, BsChevronLeft, BsClockFill, BsEnvelopeFill, BsStopwatchFill} from "react-icons/bs";
|
|
||||||
import {toast, ToastContainer} from "react-toastify";
|
|
||||||
|
|
||||||
export const getServerSideProps = withIronSessionSsr(async ({req}) => {
|
|
||||||
const user = req.session.user as User;
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
return {
|
|
||||||
redirect: {
|
|
||||||
destination: "/login",
|
|
||||||
permanent: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (shouldRedirectHome(user)) {
|
|
||||||
return {
|
|
||||||
redirect: {
|
|
||||||
destination: "/",
|
|
||||||
permanent: false,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const linkedUsers = await getLinkedUsers(user.id, user.type);
|
|
||||||
|
|
||||||
return {
|
|
||||||
props: {user, users: JSON.parse(JSON.stringify(linkedUsers.users.filter((x) => x.id !== user.id)))},
|
|
||||||
};
|
|
||||||
}, sessionOptions);
|
|
||||||
|
|
||||||
interface Props {
|
|
||||||
user: User;
|
|
||||||
users: User[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Home({user, users}: Props) {
|
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
|
||||||
const [selectedUsers, setSelectedUsers] = useState<string[]>([]);
|
|
||||||
const [name, setName] = useState("");
|
|
||||||
|
|
||||||
const {rows, renderSearch} = useListSearch<User>([["name"], ["corporateInformation", "companyInformation", "name"]], users);
|
|
||||||
const {items, renderMinimal} = usePagination<User>(rows, 16);
|
|
||||||
|
|
||||||
const router = useRouter();
|
|
||||||
|
|
||||||
const createGroup = () => {
|
|
||||||
if (!name.trim()) return;
|
|
||||||
if (!confirm(`Are you sure you want to create this group with ${selectedUsers.length} participants?`)) return;
|
|
||||||
|
|
||||||
setIsLoading(true);
|
|
||||||
|
|
||||||
axios
|
|
||||||
.post<{id: string}>(`/api/groups`, {name, participants: selectedUsers, admin: user.id})
|
|
||||||
.then((result) => {
|
|
||||||
toast.success("Your group has been created successfully!");
|
|
||||||
router.replace(`/groups/${result.data.id}`);
|
|
||||||
})
|
|
||||||
.catch((e) => {
|
|
||||||
console.error(e);
|
|
||||||
toast.error("Something went wrong!");
|
|
||||||
})
|
|
||||||
.finally(() => setIsLoading(false));
|
|
||||||
};
|
|
||||||
|
|
||||||
const toggleUser = (u: User) => setSelectedUsers((prev) => (prev.includes(u.id) ? prev.filter((p) => p !== u.id) : [...prev, u.id]));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<Head>
|
|
||||||
<title>Create Group | 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}>
|
|
||||||
<section className="flex flex-col gap-0">
|
|
||||||
<div className="flex gap-3 justify-between">
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<Link
|
|
||||||
href="/groups"
|
|
||||||
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">Create Group</h2>
|
|
||||||
</div>
|
|
||||||
<div className="flex items-center gap-4">
|
|
||||||
<button
|
|
||||||
onClick={createGroup}
|
|
||||||
disabled={!name.trim() || isLoading}
|
|
||||||
className="flex items-center gap-1 px-2 py-2 border rounded-full border-mti-green bg-mti-green-light text-white hover:bg-mti-green-dark disabled:hover:bg-mti-green-light disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer transition ease-in-out duration-300">
|
|
||||||
<BsCheck />
|
|
||||||
<span className="text-xs">Create Group</span>
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Divider />
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<span className="font-semibold text-xl">Group Name:</span>
|
|
||||||
<Input name="name" onChange={setName} type="text" placeholder="Classroom A" />
|
|
||||||
</div>
|
|
||||||
<Divider />
|
|
||||||
<div className="flex items-center justify-between mb-4">
|
|
||||||
<span className="font-semibold text-xl">Participants ({selectedUsers.length} selected):</span>
|
|
||||||
</div>
|
|
||||||
<div className="w-full flex items-center gap-4">
|
|
||||||
{renderSearch()}
|
|
||||||
{renderMinimal()}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="w-full h-full grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
|
|
||||||
{items.map((u) => (
|
|
||||||
<button
|
|
||||||
onClick={() => toggleUser(u)}
|
|
||||||
disabled={isLoading}
|
|
||||||
key={u.id}
|
|
||||||
className={clsx(
|
|
||||||
"p-4 pr-6 h-48 relative border rounded-xl flex flex-col gap-3 justify-between text-left cursor-pointer",
|
|
||||||
"hover:border-mti-purple transition ease-in-out duration-300",
|
|
||||||
selectedUsers.includes(u.id) && "border-mti-purple",
|
|
||||||
)}>
|
|
||||||
<div className="flex items-center gap-2">
|
|
||||||
<div className="min-w-[3rem] min-h-[3rem] w-12 h-12 border flex items-center justify-center overflow-hidden rounded-full">
|
|
||||||
<img src={u.profilePicture} alt={u.name} />
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col">
|
|
||||||
<span className="font-semibold">{getUserName(u)}</span>
|
|
||||||
<span className="opacity-80 text-sm">{USER_TYPE_LABELS[u.type]}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-col gap-1">
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<Tooltip tooltip="E-mail address">
|
|
||||||
<BsEnvelopeFill />
|
|
||||||
</Tooltip>
|
|
||||||
{u.email}
|
|
||||||
</span>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<Tooltip tooltip="Expiration Date">
|
|
||||||
<BsStopwatchFill />
|
|
||||||
</Tooltip>
|
|
||||||
{u.subscriptionExpirationDate ? moment(u.subscriptionExpirationDate).format("DD/MM/YYYY") : "Unlimited"}
|
|
||||||
</span>
|
|
||||||
<span className="flex items-center gap-2">
|
|
||||||
<Tooltip tooltip="Last Login">
|
|
||||||
<BsClockFill />
|
|
||||||
</Tooltip>
|
|
||||||
{u.lastLogin ? moment(u.lastLogin).format("DD/MM/YYYY - HH:mm") : "N/A"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</button>
|
|
||||||
))}
|
|
||||||
</section>
|
|
||||||
</Layout>
|
|
||||||
)}
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
259
src/pages/lists/users.tsx
Normal file
259
src/pages/lists/users.tsx
Normal file
@@ -0,0 +1,259 @@
|
|||||||
|
import Layout from "@/components/High/Layout";
|
||||||
|
import List from "@/components/List";
|
||||||
|
import useUser from "@/hooks/useUser";
|
||||||
|
import useUsers from "@/hooks/useUsers";
|
||||||
|
import {Type, User} from "@/interfaces/user";
|
||||||
|
import {sessionOptions} from "@/lib/session";
|
||||||
|
import useFilterStore from "@/stores/listFilterStore";
|
||||||
|
import {mapBy, serialize} from "@/utils";
|
||||||
|
import {getEntitiesUsers, getEntityUsers} from "@/utils/users.be";
|
||||||
|
import {createColumnHelper} from "@tanstack/react-table";
|
||||||
|
import clsx from "clsx";
|
||||||
|
import {withIronSessionSsr} from "iron-session/next";
|
||||||
|
import Head from "next/head";
|
||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {useEffect, useState} from "react";
|
||||||
|
import {BsArrowLeft, BsCheck, BsChevronLeft} from "react-icons/bs";
|
||||||
|
import {ToastContainer} from "react-toastify";
|
||||||
|
import UserList from "../(admin)/Lists/UserList";
|
||||||
|
import {countries, TCountries} from "countries-list";
|
||||||
|
import countryCodes from "country-codes-list";
|
||||||
|
import {capitalize} from "lodash";
|
||||||
|
import moment from "moment";
|
||||||
|
import {USER_TYPE_LABELS} from "@/resources/user";
|
||||||
|
import {getEntities, getEntitiesWithRoles} from "@/utils/entities.be";
|
||||||
|
import {EntityWithRoles} from "@/interfaces/entity";
|
||||||
|
|
||||||
|
const columnHelper = createColumnHelper<User>();
|
||||||
|
|
||||||
|
const expirationDateColor = (date: Date) => {
|
||||||
|
const momentDate = moment(date);
|
||||||
|
const today = moment(new Date());
|
||||||
|
|
||||||
|
if (today.isAfter(momentDate)) return "!text-mti-red-light font-bold line-through";
|
||||||
|
if (today.add(1, "weeks").isAfter(momentDate)) return "!text-mti-red-light";
|
||||||
|
if (today.add(2, "weeks").isAfter(momentDate)) return "!text-mti-rose-light";
|
||||||
|
if (today.add(1, "months").isAfter(momentDate)) return "!text-mti-orange-light";
|
||||||
|
};
|
||||||
|
|
||||||
|
const SEARCH_FIELDS = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||||
|
|
||||||
|
export const getServerSideProps = withIronSessionSsr(async ({req, res, query}) => {
|
||||||
|
const user = req.session.user as User | undefined;
|
||||||
|
|
||||||
|
if (!user)
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: "/login",
|
||||||
|
permanent: false,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const {type} = query as {type?: Type};
|
||||||
|
const users = await getEntitiesUsers(mapBy(user.entities, "id"));
|
||||||
|
const entities = await getEntitiesWithRoles();
|
||||||
|
|
||||||
|
const filters: ((u: User) => boolean)[] = [];
|
||||||
|
if (type) filters.push((u) => u.type === type);
|
||||||
|
|
||||||
|
return {
|
||||||
|
props: serialize({user, users: filters.reduce((d, f) => d.filter(f), users), entities}),
|
||||||
|
};
|
||||||
|
}, sessionOptions);
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
user: User;
|
||||||
|
users: User[];
|
||||||
|
entities: EntityWithRoles[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function UsersList({user, users, entities}: Props) {
|
||||||
|
const [showDemographicInformation, setShowDemographicInformation] = useState(false);
|
||||||
|
const router = useRouter();
|
||||||
|
|
||||||
|
const defaultColumns = [
|
||||||
|
columnHelper.accessor("name", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Name</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("email", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>E-mail</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("type", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Type</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => USER_TYPE_LABELS[info.getValue()],
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("studentID", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Student ID</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => info.getValue() || "N/A",
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("entities", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Entities</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: ({getValue}) =>
|
||||||
|
getValue()
|
||||||
|
.map((e) => entities.find((x) => x.id === e.id)?.label)
|
||||||
|
.join(", "),
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("subscriptionExpirationDate", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Expiration</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => (
|
||||||
|
<span className={clsx(info.getValue() ? expirationDateColor(moment(info.getValue()).toDate()) : "")}>
|
||||||
|
{!info.getValue() ? "No expiry date" : moment(info.getValue()).format("DD/MM/YYYY")}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("isVerified", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Verified</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => (
|
||||||
|
<div className="flex gap-3 items-center text-mti-gray-dim text-sm self-center">
|
||||||
|
<div
|
||||||
|
className={clsx(
|
||||||
|
"w-6 h-6 rounded-md flex items-center justify-center border border-mti-purple-light bg-white",
|
||||||
|
"transition duration-300 ease-in-out",
|
||||||
|
info.getValue() && "!bg-mti-purple-light ",
|
||||||
|
)}>
|
||||||
|
<BsCheck color="white" className="w-full h-full" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
header: (
|
||||||
|
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||||
|
Switch
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
id: "actions",
|
||||||
|
cell: () => "",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const demographicColumns = [
|
||||||
|
columnHelper.accessor("name", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Name</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: ({row, getValue}) => <div>{getValue()}</div>,
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("demographicInformation.country", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Country</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) =>
|
||||||
|
info.getValue()
|
||||||
|
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${
|
||||||
|
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||||
|
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||||
|
: "N/A",
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("demographicInformation.phone", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Phone</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => info.getValue() || "N/A",
|
||||||
|
enableSorting: true,
|
||||||
|
}),
|
||||||
|
columnHelper.accessor(
|
||||||
|
(x) =>
|
||||||
|
x.type === "corporate" || x.type === "mastercorporate" ? x.demographicInformation?.position : x.demographicInformation?.employment,
|
||||||
|
{
|
||||||
|
id: "employment",
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Employment</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => (info.row.original.type === "corporate" ? info.getValue() : capitalize(info.getValue())) || "N/A",
|
||||||
|
enableSorting: true,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
columnHelper.accessor("lastLogin", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Last Login</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => (!!info.getValue() ? moment(info.getValue()).format("YYYY-MM-DD HH:mm") : "N/A"),
|
||||||
|
}),
|
||||||
|
columnHelper.accessor("demographicInformation.gender", {
|
||||||
|
header: (
|
||||||
|
<button className="flex gap-2 items-center">
|
||||||
|
<span>Gender</span>
|
||||||
|
</button>
|
||||||
|
) as any,
|
||||||
|
cell: (info) => capitalize(info.getValue()) || "N/A",
|
||||||
|
enableSorting: true,
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
header: (
|
||||||
|
<span className="cursor-pointer" onClick={() => setShowDemographicInformation((prev) => !prev)}>
|
||||||
|
Switch
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
id: "actions",
|
||||||
|
cell: () => "",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
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 />
|
||||||
|
|
||||||
|
<Layout user={user} className="!gap-6">
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<button
|
||||||
|
onClick={() => router.back()}
|
||||||
|
className="text-mti-purple hover:text-mti-purple-dark transition ease-in-out duration-300 text-xl">
|
||||||
|
<BsChevronLeft />
|
||||||
|
</button>
|
||||||
|
<h2 className="font-bold text-2xl">User List</h2>
|
||||||
|
</div>
|
||||||
|
<List<User> data={users} searchFields={SEARCH_FIELDS} columns={showDemographicInformation ? demographicColumns : defaultColumns} />
|
||||||
|
</Layout>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -23,6 +23,10 @@ export const getAssignments = async () => {
|
|||||||
return await db.collection("assignments").find<Assignment>({}).toArray();
|
return await db.collection("assignments").find<Assignment>({}).toArray();
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getAssignment = async (id: string) => {
|
||||||
|
return await db.collection("assignments").findOne<Assignment>({id});
|
||||||
|
};
|
||||||
|
|
||||||
export const getAssignmentsByAssignee = async (id: string, filter?: {[key in keyof Partial<Assignment>]: any}) => {
|
export const getAssignmentsByAssignee = async (id: string, filter?: {[key in keyof Partial<Assignment>]: any}) => {
|
||||||
return await db
|
return await db
|
||||||
.collection("assignments")
|
.collection("assignments")
|
||||||
|
|||||||
@@ -84,6 +84,12 @@ export const getAllAssignersByCorporate = async (corporateID: string, type: Type
|
|||||||
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
|
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const getGroupsForEntities = async (ids: string[]) =>
|
||||||
|
await db
|
||||||
|
.collection("groups")
|
||||||
|
.find<Group>({entity: {$in: ids}})
|
||||||
|
.toArray();
|
||||||
|
|
||||||
export const getGroupsForUser = async (admin?: string, participant?: string) => {
|
export const getGroupsForUser = async (admin?: string, participant?: string) => {
|
||||||
if (admin && participant) return await db.collection("groups").find<Group>({admin, participant}).toArray();
|
if (admin && participant) return await db.collection("groups").find<Group>({admin, participant}).toArray();
|
||||||
|
|
||||||
|
|||||||
@@ -44,10 +44,7 @@ export const convertBase64 = (file: File) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const mapBy = <T>(obj: T[], key: keyof T) => {
|
export const mapBy = <T>(obj: T[] | undefined, key: keyof T) => (obj || []).map((i) => i[key]);
|
||||||
if (!obj) return undefined;
|
|
||||||
return obj.map((i) => i[key]);
|
|
||||||
};
|
|
||||||
export const filterBy = <T>(obj: T[], key: keyof T, value: any) => obj.filter((i) => i[key] === value);
|
export const filterBy = <T>(obj: T[], key: keyof T, value: any) => obj.filter((i) => i[key] === value);
|
||||||
|
|
||||||
export const serialize = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
|
export const serialize = <T>(obj: T): T => JSON.parse(JSON.stringify(obj));
|
||||||
|
|||||||
Reference in New Issue
Block a user