Merged main into bugfix/mongo-migration-bugs
This commit is contained in:
@@ -1,546 +1,405 @@
|
|||||||
/* eslint-disable @next/next/no-img-element */
|
/* eslint-disable @next/next/no-img-element */
|
||||||
import Modal from "@/components/Modal";
|
import Modal from "@/components/Modal";
|
||||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||||
import useUsers, {
|
import useUsers, {userHashStudent, userHashTeacher, userHashCorporate} from "@/hooks/useUsers";
|
||||||
userHashStudent,
|
import {CorporateUser, Group, MasterCorporateUser, Stat, User} from "@/interfaces/user";
|
||||||
userHashTeacher,
|
|
||||||
userHashCorporate,
|
|
||||||
} from "@/hooks/useUsers";
|
|
||||||
import {
|
|
||||||
CorporateUser,
|
|
||||||
Group,
|
|
||||||
MasterCorporateUser,
|
|
||||||
Stat,
|
|
||||||
User,
|
|
||||||
} from "@/interfaces/user";
|
|
||||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||||
import { dateSorter } from "@/utils";
|
import {dateSorter} from "@/utils";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import { useEffect, useMemo, useState } from "react";
|
import {useEffect, useMemo, useState} from "react";
|
||||||
import {
|
import {
|
||||||
BsArrowLeft,
|
BsArrowLeft,
|
||||||
BsClipboard2Data,
|
BsClipboard2Data,
|
||||||
BsClipboard2DataFill,
|
BsClipboard2DataFill,
|
||||||
BsClock,
|
BsClock,
|
||||||
BsGlobeCentralSouthAsia,
|
BsGlobeCentralSouthAsia,
|
||||||
BsPaperclip,
|
BsPaperclip,
|
||||||
BsPerson,
|
BsPerson,
|
||||||
BsPersonAdd,
|
BsPersonAdd,
|
||||||
BsPersonFill,
|
BsPersonFill,
|
||||||
BsPersonFillGear,
|
BsPersonFillGear,
|
||||||
BsPersonGear,
|
BsPersonGear,
|
||||||
BsPencilSquare,
|
BsPencilSquare,
|
||||||
BsPersonBadge,
|
BsPersonBadge,
|
||||||
BsPersonCheck,
|
BsPersonCheck,
|
||||||
BsPeople,
|
BsPeople,
|
||||||
BsArrowRepeat,
|
BsArrowRepeat,
|
||||||
BsPlus,
|
BsPlus,
|
||||||
BsEnvelopePaper,
|
BsEnvelopePaper,
|
||||||
BsDatabase,
|
BsDatabase,
|
||||||
} from "react-icons/bs";
|
} from "react-icons/bs";
|
||||||
import UserCard from "@/components/UserCard";
|
import UserCard from "@/components/UserCard";
|
||||||
import useGroups from "@/hooks/useGroups";
|
import useGroups from "@/hooks/useGroups";
|
||||||
import {
|
import {averageLevelCalculator, calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||||
averageLevelCalculator,
|
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||||
calculateAverageLevel,
|
import {Module} from "@/interfaces";
|
||||||
calculateBandScore,
|
import {groupByExam} from "@/utils/stats";
|
||||||
} from "@/utils/score";
|
|
||||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
|
||||||
import { Module } from "@/interfaces";
|
|
||||||
import { groupByExam } from "@/utils/stats";
|
|
||||||
import IconCard from "../IconCard";
|
import IconCard from "../IconCard";
|
||||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||||
import useFilterStore from "@/stores/listFilterStore";
|
import useFilterStore from "@/stores/listFilterStore";
|
||||||
import { useRouter } from "next/router";
|
import {useRouter} from "next/router";
|
||||||
import useCodes from "@/hooks/useCodes";
|
import useCodes from "@/hooks/useCodes";
|
||||||
import { getUserCorporate } from "@/utils/groups";
|
import {getUserCorporate} from "@/utils/groups";
|
||||||
import useAssignments from "@/hooks/useAssignments";
|
import useAssignments from "@/hooks/useAssignments";
|
||||||
import { Assignment } from "@/interfaces/results";
|
import {Assignment} from "@/interfaces/results";
|
||||||
import AssignmentView from "../AssignmentView";
|
import AssignmentView from "../AssignmentView";
|
||||||
import AssignmentCreator from "../AssignmentCreator";
|
import AssignmentCreator from "../AssignmentCreator";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import AssignmentCard from "../AssignmentCard";
|
import AssignmentCard from "../AssignmentCard";
|
||||||
import { createColumnHelper } from "@tanstack/react-table";
|
import {createColumnHelper} from "@tanstack/react-table";
|
||||||
import Checkbox from "@/components/Low/Checkbox";
|
import Checkbox from "@/components/Low/Checkbox";
|
||||||
import List from "@/components/List";
|
import List from "@/components/List";
|
||||||
import { getUserCompanyName } from "@/resources/user";
|
import {getUserCompanyName} from "@/resources/user";
|
||||||
import {
|
import {futureAssignmentFilter, pastAssignmentFilter, archivedAssignmentFilter, activeAssignmentFilter} from "@/utils/assignments";
|
||||||
futureAssignmentFilter,
|
|
||||||
pastAssignmentFilter,
|
|
||||||
archivedAssignmentFilter,
|
|
||||||
activeAssignmentFilter,
|
|
||||||
} from "@/utils/assignments";
|
|
||||||
import useUserBalance from "@/hooks/useUserBalance";
|
import useUserBalance from "@/hooks/useUserBalance";
|
||||||
import AssignmentsPage from "../views/AssignmentsPage";
|
import AssignmentsPage from "../views/AssignmentsPage";
|
||||||
import StudentPerformancePage from "./StudentPerformancePage";
|
import StudentPerformancePage from "./StudentPerformancePage";
|
||||||
import MasterStatistical from "../MasterCorporate/MasterStatistical";
|
import MasterStatistical from "../MasterCorporate/MasterStatistical";
|
||||||
|
import MasterStatisticalPage from "./MasterStatisticalPage";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
user: CorporateUser;
|
user: CorporateUser;
|
||||||
linkedCorporate?: CorporateUser | MasterCorporateUser;
|
linkedCorporate?: CorporateUser | MasterCorporateUser;
|
||||||
}
|
}
|
||||||
|
|
||||||
const studentHash = {
|
const studentHash = {
|
||||||
type: "student",
|
type: "student",
|
||||||
orderBy: "registrationDate",
|
orderBy: "registrationDate",
|
||||||
size: 25,
|
size: 25,
|
||||||
};
|
};
|
||||||
|
|
||||||
const teacherHash = {
|
const teacherHash = {
|
||||||
type: "teacher",
|
type: "teacher",
|
||||||
orderBy: "registrationDate",
|
orderBy: "registrationDate",
|
||||||
size: 25,
|
size: 25,
|
||||||
};
|
};
|
||||||
|
|
||||||
export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||||
const [selectedUser, setSelectedUser] = useState<User>();
|
const [selectedUser, setSelectedUser] = useState<User>();
|
||||||
const [showModal, setShowModal] = useState(false);
|
const [showModal, setShowModal] = useState(false);
|
||||||
|
|
||||||
const { data: stats } = useFilterRecordsByUser<Stat[]>();
|
const {data: stats} = useFilterRecordsByUser<Stat[]>();
|
||||||
const { groups } = useGroups({ admin: user.id });
|
const {groups} = useGroups({admin: user.id});
|
||||||
const {
|
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
|
||||||
assignments,
|
const {balance} = useUserBalance();
|
||||||
isLoading: isAssignmentsLoading,
|
|
||||||
reload: reloadAssignments,
|
|
||||||
} = useAssignments({ corporate: user.id });
|
|
||||||
const { balance } = useUserBalance();
|
|
||||||
|
|
||||||
const {
|
const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash);
|
||||||
users: students,
|
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash);
|
||||||
total: totalStudents,
|
|
||||||
reload: reloadStudents,
|
|
||||||
isLoading: isStudentsLoading,
|
|
||||||
} = useUsers(studentHash);
|
|
||||||
const {
|
|
||||||
users: teachers,
|
|
||||||
total: totalTeachers,
|
|
||||||
reload: reloadTeachers,
|
|
||||||
isLoading: isTeachersLoading,
|
|
||||||
} = useUsers(teacherHash);
|
|
||||||
|
|
||||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
|
|
||||||
const assignmentsGroups = useMemo(
|
const assignmentsGroups = useMemo(() => groups.filter((x) => x.admin === user.id || x.participants.includes(user.id)), [groups, user.id]);
|
||||||
() =>
|
|
||||||
groups.filter(
|
|
||||||
(x) => x.admin === user.id || x.participants.includes(user.id)
|
|
||||||
),
|
|
||||||
[groups, user.id]
|
|
||||||
);
|
|
||||||
|
|
||||||
const assignmentsUsers = useMemo(
|
const assignmentsUsers = useMemo(
|
||||||
() =>
|
() =>
|
||||||
[...teachers, ...students].filter((x) =>
|
[...teachers, ...students].filter((x) =>
|
||||||
!!selectedUser
|
!!selectedUser
|
||||||
? groups
|
? groups
|
||||||
.filter((g) => g.admin === selectedUser.id)
|
.filter((g) => g.admin === selectedUser.id)
|
||||||
.flatMap((g) => g.participants)
|
.flatMap((g) => g.participants)
|
||||||
.includes(x.id) || false
|
.includes(x.id) || false
|
||||||
: groups.flatMap((g) => g.participants).includes(x.id)
|
: groups.flatMap((g) => g.participants).includes(x.id),
|
||||||
),
|
),
|
||||||
[groups, teachers, students, selectedUser]
|
[groups, teachers, students, selectedUser],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||||
}, [selectedUser, router.asPath]);
|
}, [selectedUser, router.asPath]);
|
||||||
|
|
||||||
const getStatsByStudent = (user: User) =>
|
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||||
stats.filter((s) => s.user === user.id);
|
|
||||||
|
|
||||||
const UserDisplay = (displayUser: User) => (
|
const UserDisplay = (displayUser: User) => (
|
||||||
<div
|
<div
|
||||||
onClick={() => setSelectedUser(displayUser)}
|
onClick={() => setSelectedUser(displayUser)}
|
||||||
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300"
|
className="flex w-full p-4 gap-4 items-center hover:bg-mti-purple-ultralight cursor-pointer transition ease-in-out duration-300">
|
||||||
>
|
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||||
<img
|
<div className="flex flex-col gap-1 items-start">
|
||||||
src={displayUser.profilePicture}
|
<span>{displayUser.name}</span>
|
||||||
alt={displayUser.name}
|
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||||
className="rounded-full w-10 h-10"
|
</div>
|
||||||
/>
|
</div>
|
||||||
<div className="flex flex-col gap-1 items-start">
|
);
|
||||||
<span>{displayUser.name}</span>
|
|
||||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
|
|
||||||
// this workaround will allow us toreuse the master statistical due to master corporate restraints
|
const GroupsList = () => {
|
||||||
// while still being able to use the corporate user
|
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||||
const groupedByNameCorporateIds = useMemo(
|
|
||||||
() => ({
|
|
||||||
[user.corporateInformation?.companyInformation?.name || user.name]: [
|
|
||||||
user.id,
|
|
||||||
],
|
|
||||||
}),
|
|
||||||
[user]
|
|
||||||
);
|
|
||||||
const teachersAndStudents = useMemo(
|
|
||||||
() => [...students, ...teachers],
|
|
||||||
[students, teachers]
|
|
||||||
);
|
|
||||||
const MasterStatisticalPage = () => {
|
|
||||||
return (
|
|
||||||
<>
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<div
|
|
||||||
onClick={() => router.push("/")}
|
|
||||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
|
||||||
>
|
|
||||||
<BsArrowLeft className="text-xl" />
|
|
||||||
<span>Back</span>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-2xl font-semibold">Master Statistical</h2>
|
|
||||||
</div>
|
|
||||||
<MasterStatistical
|
|
||||||
users={teachersAndStudents}
|
|
||||||
corporateUsers={groupedByNameCorporateIds}
|
|
||||||
displaySelection={false}
|
|
||||||
/>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
const GroupsList = () => {
|
return (
|
||||||
const filter = (x: Group) =>
|
<>
|
||||||
x.admin === user.id || x.participants.includes(user.id);
|
<div className="flex flex-col gap-4">
|
||||||
|
<div
|
||||||
|
onClick={() => router.push("/")}
|
||||||
|
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||||
|
<BsArrowLeft className="text-xl" />
|
||||||
|
<span>Back</span>
|
||||||
|
</div>
|
||||||
|
<h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
return (
|
<GroupList user={user} />
|
||||||
<>
|
</>
|
||||||
<div className="flex flex-col gap-4">
|
);
|
||||||
<div
|
};
|
||||||
onClick={() => router.push("/")}
|
|
||||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
|
||||||
>
|
|
||||||
<BsArrowLeft className="text-xl" />
|
|
||||||
<span>Back</span>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-2xl font-semibold">
|
|
||||||
Groups ({groups.filter(filter).length})
|
|
||||||
</h2>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<GroupList user={user} />
|
const averageLevelCalculator = (studentStats: Stat[]) => {
|
||||||
</>
|
const formattedStats = studentStats
|
||||||
);
|
.map((s) => ({
|
||||||
};
|
focus: students.find((u) => u.id === s.user)?.focus,
|
||||||
|
score: s.score,
|
||||||
|
module: s.module,
|
||||||
|
}))
|
||||||
|
.filter((f) => !!f.focus);
|
||||||
|
const bandScores = formattedStats.map((s) => ({
|
||||||
|
module: s.module,
|
||||||
|
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||||
|
}));
|
||||||
|
|
||||||
const averageLevelCalculator = (studentStats: Stat[]) => {
|
const levels: {[key in Module]: number} = {
|
||||||
const formattedStats = studentStats
|
reading: 0,
|
||||||
.map((s) => ({
|
listening: 0,
|
||||||
focus: students.find((u) => u.id === s.user)?.focus,
|
writing: 0,
|
||||||
score: s.score,
|
speaking: 0,
|
||||||
module: s.module,
|
level: 0,
|
||||||
}))
|
};
|
||||||
.filter((f) => !!f.focus);
|
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||||
const bandScores = formattedStats.map((s) => ({
|
|
||||||
module: s.module,
|
|
||||||
level: calculateBandScore(
|
|
||||||
s.score.correct,
|
|
||||||
s.score.total,
|
|
||||||
s.module,
|
|
||||||
s.focus!
|
|
||||||
),
|
|
||||||
}));
|
|
||||||
|
|
||||||
const levels: { [key in Module]: number } = {
|
return calculateAverageLevel(levels);
|
||||||
reading: 0,
|
};
|
||||||
listening: 0,
|
|
||||||
writing: 0,
|
|
||||||
speaking: 0,
|
|
||||||
level: 0,
|
|
||||||
};
|
|
||||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
|
||||||
|
|
||||||
return calculateAverageLevel(levels);
|
if (router.asPath === "/#students")
|
||||||
};
|
return (
|
||||||
|
<UserList
|
||||||
|
user={user}
|
||||||
|
type="student"
|
||||||
|
renderHeader={(total) => (
|
||||||
|
<div className="flex flex-col gap-4">
|
||||||
|
<div
|
||||||
|
onClick={() => router.push("/")}
|
||||||
|
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||||
|
<BsArrowLeft className="text-xl" />
|
||||||
|
<span>Back</span>
|
||||||
|
</div>
|
||||||
|
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
if (router.asPath === "/#students")
|
if (router.asPath === "/#teachers")
|
||||||
return (
|
return (
|
||||||
<UserList
|
<UserList
|
||||||
user={user}
|
user={user}
|
||||||
type="student"
|
type="teacher"
|
||||||
renderHeader={(total) => (
|
renderHeader={(total) => (
|
||||||
<div className="flex flex-col gap-4">
|
<div className="flex flex-col gap-4">
|
||||||
<div
|
<div
|
||||||
onClick={() => router.push("/")}
|
onClick={() => router.push("/")}
|
||||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300">
|
||||||
>
|
<BsArrowLeft className="text-xl" />
|
||||||
<BsArrowLeft className="text-xl" />
|
<span>Back</span>
|
||||||
<span>Back</span>
|
</div>
|
||||||
</div>
|
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
||||||
<h2 className="text-2xl font-semibold">Students ({total})</h2>
|
</div>
|
||||||
</div>
|
)}
|
||||||
)}
|
/>
|
||||||
/>
|
);
|
||||||
);
|
|
||||||
|
|
||||||
if (router.asPath === "/#teachers")
|
if (router.asPath === "/#groups") return <GroupsList />;
|
||||||
return (
|
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
|
||||||
<UserList
|
|
||||||
user={user}
|
|
||||||
type="teacher"
|
|
||||||
renderHeader={(total) => (
|
|
||||||
<div className="flex flex-col gap-4">
|
|
||||||
<div
|
|
||||||
onClick={() => router.push("/")}
|
|
||||||
className="flex gap-2 items-center text-mti-purple-light cursor-pointer hover:text-mti-purple-dark transition ease-in-out duration-300"
|
|
||||||
>
|
|
||||||
<BsArrowLeft className="text-xl" />
|
|
||||||
<span>Back</span>
|
|
||||||
</div>
|
|
||||||
<h2 className="text-2xl font-semibold">Teachers ({total})</h2>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (router.asPath === "/#groups") return <GroupsList />;
|
if (router.asPath === "/#assignments")
|
||||||
if (router.asPath === "/#studentsPerformance")
|
return (
|
||||||
return <StudentPerformancePage user={user} />;
|
<AssignmentsPage
|
||||||
|
assignments={assignments}
|
||||||
|
user={user}
|
||||||
|
groups={assignmentsGroups}
|
||||||
|
reloadAssignments={reloadAssignments}
|
||||||
|
isLoading={isAssignmentsLoading}
|
||||||
|
onBack={() => router.push("/")}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
if (router.asPath === "/#assignments")
|
if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />;
|
||||||
return (
|
|
||||||
<AssignmentsPage
|
|
||||||
assignments={assignments}
|
|
||||||
user={user}
|
|
||||||
groups={assignmentsGroups}
|
|
||||||
reloadAssignments={reloadAssignments}
|
|
||||||
isLoading={isAssignmentsLoading}
|
|
||||||
onBack={() => router.push("/")}
|
|
||||||
/>
|
|
||||||
);
|
|
||||||
|
|
||||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
|
return (
|
||||||
|
<>
|
||||||
|
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
||||||
|
<>
|
||||||
|
{selectedUser && (
|
||||||
|
<div className="w-full flex flex-col gap-8">
|
||||||
|
<UserCard
|
||||||
|
loggedInUser={user}
|
||||||
|
onClose={(shouldReload) => {
|
||||||
|
setSelectedUser(undefined);
|
||||||
|
if (shouldReload && selectedUser!.type === "student") reloadStudents();
|
||||||
|
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
|
||||||
|
}}
|
||||||
|
onViewStudents={
|
||||||
|
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||||
|
? () => {
|
||||||
|
appendUserFilters({
|
||||||
|
id: "view-students",
|
||||||
|
filter: (x: User) => x.type === "student",
|
||||||
|
});
|
||||||
|
appendUserFilters({
|
||||||
|
id: "belongs-to-admin",
|
||||||
|
filter: (x: User) =>
|
||||||
|
groups
|
||||||
|
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||||
|
.flatMap((g) => g.participants)
|
||||||
|
.includes(x.id),
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
router.push("/list/users");
|
||||||
<>
|
}
|
||||||
<Modal isOpen={showModal} onClose={() => setSelectedUser(undefined)}>
|
: undefined
|
||||||
<>
|
}
|
||||||
{selectedUser && (
|
onViewTeachers={
|
||||||
<div className="w-full flex flex-col gap-8">
|
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||||
<UserCard
|
? () => {
|
||||||
loggedInUser={user}
|
appendUserFilters({
|
||||||
onClose={(shouldReload) => {
|
id: "view-teachers",
|
||||||
setSelectedUser(undefined);
|
filter: (x: User) => x.type === "teacher",
|
||||||
if (shouldReload && selectedUser!.type === "student")
|
});
|
||||||
reloadStudents();
|
appendUserFilters({
|
||||||
if (shouldReload && selectedUser!.type === "teacher")
|
id: "belongs-to-admin",
|
||||||
reloadTeachers();
|
filter: (x: User) =>
|
||||||
}}
|
groups
|
||||||
onViewStudents={
|
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||||
selectedUser.type === "corporate" ||
|
.flatMap((g) => g.participants)
|
||||||
selectedUser.type === "teacher"
|
.includes(x.id),
|
||||||
? () => {
|
});
|
||||||
appendUserFilters({
|
|
||||||
id: "view-students",
|
|
||||||
filter: (x: User) => x.type === "student",
|
|
||||||
});
|
|
||||||
appendUserFilters({
|
|
||||||
id: "belongs-to-admin",
|
|
||||||
filter: (x: User) =>
|
|
||||||
groups
|
|
||||||
.filter(
|
|
||||||
(g) =>
|
|
||||||
g.admin === selectedUser.id ||
|
|
||||||
g.participants.includes(selectedUser.id)
|
|
||||||
)
|
|
||||||
.flatMap((g) => g.participants)
|
|
||||||
.includes(x.id),
|
|
||||||
});
|
|
||||||
|
|
||||||
router.push("/list/users");
|
router.push("/list/users");
|
||||||
}
|
}
|
||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onViewTeachers={
|
user={selectedUser}
|
||||||
selectedUser.type === "corporate" ||
|
/>
|
||||||
selectedUser.type === "student"
|
</div>
|
||||||
? () => {
|
)}
|
||||||
appendUserFilters({
|
</>
|
||||||
id: "view-teachers",
|
</Modal>
|
||||||
filter: (x: User) => x.type === "teacher",
|
|
||||||
});
|
|
||||||
appendUserFilters({
|
|
||||||
id: "belongs-to-admin",
|
|
||||||
filter: (x: User) =>
|
|
||||||
groups
|
|
||||||
.filter(
|
|
||||||
(g) =>
|
|
||||||
g.admin === selectedUser.id ||
|
|
||||||
g.participants.includes(selectedUser.id)
|
|
||||||
)
|
|
||||||
.flatMap((g) => g.participants)
|
|
||||||
.includes(x.id),
|
|
||||||
});
|
|
||||||
|
|
||||||
router.push("/list/users");
|
<>
|
||||||
}
|
{!!linkedCorporate && (
|
||||||
: undefined
|
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||||
}
|
Linked to: <b>{linkedCorporate?.corporateInformation?.companyInformation.name || linkedCorporate.name}</b>
|
||||||
user={selectedUser}
|
</div>
|
||||||
/>
|
)}
|
||||||
</div>
|
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||||
)}
|
<IconCard
|
||||||
</>
|
onClick={() => router.push("/#students")}
|
||||||
</Modal>
|
isLoading={isStudentsLoading}
|
||||||
|
Icon={BsPersonFill}
|
||||||
|
label="Students"
|
||||||
|
value={totalStudents}
|
||||||
|
color="purple"
|
||||||
|
/>
|
||||||
|
<IconCard
|
||||||
|
onClick={() => router.push("/#teachers")}
|
||||||
|
isLoading={isTeachersLoading}
|
||||||
|
Icon={BsPencilSquare}
|
||||||
|
label="Teachers"
|
||||||
|
value={totalTeachers}
|
||||||
|
color="purple"
|
||||||
|
/>
|
||||||
|
<IconCard
|
||||||
|
Icon={BsClipboard2Data}
|
||||||
|
label="Exams Performed"
|
||||||
|
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||||
|
color="purple"
|
||||||
|
/>
|
||||||
|
<IconCard
|
||||||
|
Icon={BsPaperclip}
|
||||||
|
isLoading={isStudentsLoading}
|
||||||
|
label="Average Level"
|
||||||
|
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||||
|
color="purple"
|
||||||
|
/>
|
||||||
|
<IconCard onClick={() => router.push("/#groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
|
||||||
|
<IconCard
|
||||||
|
Icon={BsPersonCheck}
|
||||||
|
label="User Balance"
|
||||||
|
value={`${balance}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
|
||||||
|
color="purple"
|
||||||
|
/>
|
||||||
|
<IconCard
|
||||||
|
Icon={BsClock}
|
||||||
|
label="Expiration Date"
|
||||||
|
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
|
||||||
|
color="rose"
|
||||||
|
/>
|
||||||
|
<IconCard
|
||||||
|
Icon={BsPersonFillGear}
|
||||||
|
isLoading={isStudentsLoading}
|
||||||
|
label="Student Performance"
|
||||||
|
value={totalStudents}
|
||||||
|
color="purple"
|
||||||
|
onClick={() => router.push("/#studentsPerformance")}
|
||||||
|
/>
|
||||||
|
<IconCard Icon={BsDatabase} label="Master Statistical" color="purple" onClick={() => router.push("/#statistical")} />
|
||||||
|
<button
|
||||||
|
disabled={isAssignmentsLoading}
|
||||||
|
onClick={() => router.push("/#assignments")}
|
||||||
|
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300">
|
||||||
|
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||||
|
<span className="flex flex-col gap-1 items-center text-xl">
|
||||||
|
<span className="text-lg">Assignments</span>
|
||||||
|
<span className="font-semibold text-mti-purple-light">
|
||||||
|
{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</section>
|
||||||
|
|
||||||
<>
|
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
||||||
{!!linkedCorporate && (
|
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
<span className="p-4">Latest students</span>
|
||||||
Linked to:{" "}
|
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||||
<b>
|
{students
|
||||||
{linkedCorporate?.corporateInformation?.companyInformation.name ||
|
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||||
linkedCorporate.name}
|
.map((x) => (
|
||||||
</b>
|
<UserDisplay key={x.id} {...x} />
|
||||||
</div>
|
))}
|
||||||
)}
|
</div>
|
||||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
</div>
|
||||||
<IconCard
|
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||||
onClick={() => router.push("/#students")}
|
<span className="p-4">Latest teachers</span>
|
||||||
isLoading={isStudentsLoading}
|
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||||
Icon={BsPersonFill}
|
{teachers
|
||||||
label="Students"
|
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
||||||
value={totalStudents}
|
.map((x) => (
|
||||||
color="purple"
|
<UserDisplay key={x.id} {...x} />
|
||||||
/>
|
))}
|
||||||
<IconCard
|
</div>
|
||||||
onClick={() => router.push("/#teachers")}
|
</div>
|
||||||
isLoading={isTeachersLoading}
|
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||||
Icon={BsPencilSquare}
|
<span className="p-4">Highest level students</span>
|
||||||
label="Teachers"
|
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||||
value={totalTeachers}
|
{students
|
||||||
color="purple"
|
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||||
/>
|
.map((x) => (
|
||||||
<IconCard
|
<UserDisplay key={x.id} {...x} />
|
||||||
Icon={BsClipboard2Data}
|
))}
|
||||||
label="Exams Performed"
|
</div>
|
||||||
value={
|
</div>
|
||||||
stats.filter((s) =>
|
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
||||||
groups.flatMap((g) => g.participants).includes(s.user)
|
<span className="p-4">Highest exam count students</span>
|
||||||
).length
|
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||||
}
|
{students
|
||||||
color="purple"
|
.sort(
|
||||||
/>
|
(a, b) =>
|
||||||
<IconCard
|
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||||
Icon={BsPaperclip}
|
)
|
||||||
isLoading={isStudentsLoading}
|
.map((x) => (
|
||||||
label="Average Level"
|
<UserDisplay key={x.id} {...x} />
|
||||||
value={averageLevelCalculator(
|
))}
|
||||||
stats.filter((s) =>
|
</div>
|
||||||
groups.flatMap((g) => g.participants).includes(s.user)
|
</div>
|
||||||
)
|
</section>
|
||||||
).toFixed(1)}
|
</>
|
||||||
color="purple"
|
</>
|
||||||
/>
|
);
|
||||||
<IconCard
|
|
||||||
onClick={() => router.push("/#groups")}
|
|
||||||
Icon={BsPeople}
|
|
||||||
label="Groups"
|
|
||||||
value={groups.length}
|
|
||||||
color="purple"
|
|
||||||
/>
|
|
||||||
<IconCard
|
|
||||||
Icon={BsPersonCheck}
|
|
||||||
label="User Balance"
|
|
||||||
value={`${balance}/${
|
|
||||||
user.corporateInformation?.companyInformation?.userAmount || 0
|
|
||||||
}`}
|
|
||||||
color="purple"
|
|
||||||
/>
|
|
||||||
<IconCard
|
|
||||||
Icon={BsClock}
|
|
||||||
label="Expiration Date"
|
|
||||||
value={
|
|
||||||
user.subscriptionExpirationDate
|
|
||||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
|
||||||
: "Unlimited"
|
|
||||||
}
|
|
||||||
color="rose"
|
|
||||||
/>
|
|
||||||
<IconCard
|
|
||||||
Icon={BsPersonFillGear}
|
|
||||||
isLoading={isStudentsLoading}
|
|
||||||
label="Student Performance"
|
|
||||||
value={totalStudents}
|
|
||||||
color="purple"
|
|
||||||
onClick={() => router.push("/#studentsPerformance")}
|
|
||||||
/>
|
|
||||||
<IconCard
|
|
||||||
Icon={BsDatabase}
|
|
||||||
label="Master Statistical"
|
|
||||||
color="purple"
|
|
||||||
onClick={() => router.push("/#statistical")}
|
|
||||||
/>
|
|
||||||
<button
|
|
||||||
disabled={isAssignmentsLoading}
|
|
||||||
onClick={() => router.push("/#assignments")}
|
|
||||||
className="bg-white col-span-2 rounded-xl shadow p-4 flex flex-col gap-4 items-center w-96 h-52 justify-center cursor-pointer hover:shadow-xl transition ease-in-out duration-300"
|
|
||||||
>
|
|
||||||
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
|
||||||
<span className="flex flex-col gap-1 items-center text-xl">
|
|
||||||
<span className="text-lg">Assignments</span>
|
|
||||||
<span className="font-semibold text-mti-purple-light">
|
|
||||||
{isAssignmentsLoading
|
|
||||||
? "Loading..."
|
|
||||||
: assignments.filter((a) => !a.archived).length}
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="grid grid-cols-1 md:grid-cols-2 gap-4 w-full justify-between">
|
|
||||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
|
||||||
<span className="p-4">Latest students</span>
|
|
||||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
|
||||||
{students
|
|
||||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
|
||||||
.map((x) => (
|
|
||||||
<UserDisplay key={x.id} {...x} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
|
||||||
<span className="p-4">Latest teachers</span>
|
|
||||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
|
||||||
{teachers
|
|
||||||
.sort((a, b) => dateSorter(a, b, "desc", "registrationDate"))
|
|
||||||
.map((x) => (
|
|
||||||
<UserDisplay key={x.id} {...x} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
|
||||||
<span className="p-4">Highest level students</span>
|
|
||||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
|
||||||
{students
|
|
||||||
.sort(
|
|
||||||
(a, b) =>
|
|
||||||
calculateAverageLevel(b.levels) -
|
|
||||||
calculateAverageLevel(a.levels)
|
|
||||||
)
|
|
||||||
.map((x) => (
|
|
||||||
<UserDisplay key={x.id} {...x} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<div className="bg-white shadow flex flex-col rounded-xl w-full">
|
|
||||||
<span className="p-4">Highest exam count students</span>
|
|
||||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
|
||||||
{students
|
|
||||||
.sort(
|
|
||||||
(a, b) =>
|
|
||||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
|
||||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
|
||||||
)
|
|
||||||
.map((x) => (
|
|
||||||
<UserDisplay key={x.id} {...x} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
</>
|
|
||||||
</>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -74,10 +74,8 @@ const MasterStatistical = (props: Props) => {
|
|||||||
() =>
|
() =>
|
||||||
assignments.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
assignments.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||||
const userResults = a.assignees.map((assignee) => {
|
const userResults = a.assignees.map((assignee) => {
|
||||||
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
|
||||||
const userData = users.find((u) => u.id === assignee);
|
const userData = users.find((u) => u.id === assignee);
|
||||||
if (!!userData) console.log(assignee, userData.name);
|
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
||||||
|
|
||||||
const corporate = getUserName(users.find((u) => u.id === a.assigner));
|
const corporate = getUserName(users.find((u) => u.id === a.assigner));
|
||||||
const commonData = {
|
const commonData = {
|
||||||
user: userData,
|
user: userData,
|
||||||
@@ -88,6 +86,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
corporate,
|
corporate,
|
||||||
assignment: a.name,
|
assignment: a.name,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (userStats.length === 0) {
|
if (userStats.length === 0) {
|
||||||
return {
|
return {
|
||||||
...commonData,
|
...commonData,
|
||||||
@@ -110,8 +109,6 @@ const MasterStatistical = (props: Props) => {
|
|||||||
[assignments, users],
|
[assignments, users],
|
||||||
);
|
);
|
||||||
|
|
||||||
useEffect(() => console.log(assignments), [assignments]);
|
|
||||||
|
|
||||||
const getCorporateScores = (corporateId: string): UserCount => {
|
const getCorporateScores = (corporateId: string): UserCount => {
|
||||||
const corporateAssignmentsUsers = assignments.filter((a) => a.corporateId === corporateId).reduce((acc, a) => acc + a.assignees.length, 0);
|
const corporateAssignmentsUsers = assignments.filter((a) => a.corporateId === corporateId).reduce((acc, a) => acc + a.assignees.length, 0);
|
||||||
|
|
||||||
@@ -167,7 +164,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
header: "Student ID",
|
header: "Student ID",
|
||||||
id: "studentID",
|
id: "studentID",
|
||||||
cell: (info) => {
|
cell: (info) => {
|
||||||
return <span>{(info.getValue() as StudentUser).studentID || "N/A"}</span>;
|
return <span>{(info.getValue() as StudentUser)?.studentID || "N/A"}</span>;
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
...(displaySelection
|
...(displaySelection
|
||||||
|
|||||||
@@ -55,7 +55,7 @@ export default function AssignmentsPage({assignments, corporateAssignments, user
|
|||||||
<AssignmentCreator
|
<AssignmentCreator
|
||||||
assignment={selectedAssignment}
|
assignment={selectedAssignment}
|
||||||
groups={groups}
|
groups={groups}
|
||||||
users={users}
|
users={[...users, user]}
|
||||||
user={user}
|
user={user}
|
||||||
isCreating={isCreatingAssignment}
|
isCreating={isCreatingAssignment}
|
||||||
cancelCreation={() => {
|
cancelCreation={() => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {useState, useMemo} from "react";
|
import {useState, useMemo} from "react";
|
||||||
import Input from "@/components/Low/Input";
|
import Input from "@/components/Low/Input";
|
||||||
import { search } from "@/utils/search";
|
import {search} from "@/utils/search";
|
||||||
|
|
||||||
export function useListSearch<T>(fields: string[][], rows: T[]) {
|
export function useListSearch<T>(fields: string[][], rows: T[]) {
|
||||||
const [text, setText] = useState("");
|
const [text, setText] = useState("");
|
||||||
@@ -8,7 +8,8 @@ export function useListSearch<T>(fields: string[][], rows: T[]) {
|
|||||||
const renderSearch = () => <Input label="Search" type="text" name="search" onChange={setText} placeholder="Enter search text" value={text} />;
|
const renderSearch = () => <Input label="Search" type="text" name="search" onChange={setText} placeholder="Enter search text" value={text} />;
|
||||||
|
|
||||||
const updatedRows = useMemo(() => {
|
const updatedRows = useMemo(() => {
|
||||||
return search(text, fields, rows);
|
if (text.length > 0) return search(text, fields, rows);
|
||||||
|
return rows;
|
||||||
}, [fields, rows, text]);
|
}, [fields, rows, text]);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
28
src/hooks/usePagination.tsx
Normal file
28
src/hooks/usePagination.tsx
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
import Button from "@/components/Low/Button";
|
||||||
|
import {useMemo, useState} from "react";
|
||||||
|
|
||||||
|
export default function usePagination<T>(list: T[], size = 25) {
|
||||||
|
const [page, setPage] = useState(0);
|
||||||
|
|
||||||
|
const items = useMemo(() => list.slice(page * size, (page + 1) * size), [page, size, list]);
|
||||||
|
|
||||||
|
const render = () => (
|
||||||
|
<div className="w-full flex gap-2 justify-between items-center">
|
||||||
|
<div className="flex items-center gap-4 w-fit">
|
||||||
|
<Button className="w-[200px] h-fit" disabled={page === 0} onClick={() => setPage((prev) => prev - 1)}>
|
||||||
|
Previous Page
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4 w-fit">
|
||||||
|
<span className="opacity-80">
|
||||||
|
{page * size + 1} - {(page + 1) * size > list.length ? list.length : (page + 1) * size} / {list.length}
|
||||||
|
</span>
|
||||||
|
<Button className="w-[200px]" disabled={(page + 1) * size >= list.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||||
|
Next Page
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return {page, items, setPage, render};
|
||||||
|
}
|
||||||
@@ -23,8 +23,6 @@ export default function useUsers(props?: {type?: string; page?: number; size?: n
|
|||||||
if (props[key as keyof typeof props] !== undefined) params.append(key, props[key as keyof typeof props]!.toString());
|
if (props[key as keyof typeof props] !== undefined) params.append(key, props[key as keyof typeof props]!.toString());
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log(params.toString());
|
|
||||||
|
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
axios
|
axios
|
||||||
.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
|
.get<{users: User[]; total: number}>(`/api/users/list?${params.toString()}`, {headers: {page: "register"}})
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {checkAccess} from "@/utils/permissions";
|
|||||||
import {PermissionType} from "@/interfaces/permissions";
|
import {PermissionType} from "@/interfaces/permissions";
|
||||||
import usePermissions from "@/hooks/usePermissions";
|
import usePermissions from "@/hooks/usePermissions";
|
||||||
import useUserBalance from "@/hooks/useUserBalance";
|
import useUserBalance from "@/hooks/useUserBalance";
|
||||||
|
import usePagination from "@/hooks/usePagination";
|
||||||
const columnHelper = createColumnHelper<User>();
|
const columnHelper = createColumnHelper<User>();
|
||||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||||
|
|
||||||
@@ -62,15 +63,12 @@ export default function UserList({
|
|||||||
const [sorter, setSorter] = useState<string>();
|
const [sorter, setSorter] = useState<string>();
|
||||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||||
const [selectedUser, setSelectedUser] = useState<User>();
|
const [selectedUser, setSelectedUser] = useState<User>();
|
||||||
const [page, setPage] = useState(0);
|
|
||||||
|
|
||||||
const userHash = useMemo(
|
const userHash = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
type,
|
type,
|
||||||
size: 16,
|
|
||||||
page,
|
|
||||||
}),
|
}),
|
||||||
[type, page],
|
[type],
|
||||||
);
|
);
|
||||||
|
|
||||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||||
@@ -102,9 +100,9 @@ export default function UserList({
|
|||||||
(async () => {
|
(async () => {
|
||||||
if (users && users.length > 0) {
|
if (users && users.length > 0) {
|
||||||
const filteredUsers = filters.reduce((d, f) => d.filter(f), users);
|
const filteredUsers = filters.reduce((d, f) => d.filter(f), users);
|
||||||
const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
// const sortedUsers = await asyncSorter<User>(filteredUsers, sortFunction);
|
||||||
|
|
||||||
setDisplayUsers([...sortedUsers]);
|
setDisplayUsers([...filteredUsers]);
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
@@ -513,10 +511,14 @@ export default function UserList({
|
|||||||
return a.id.localeCompare(b.id);
|
return a.id.localeCompare(b.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
const {rows: filteredRows, renderSearch} = useListSearch<User>(searchFields, displayUsers);
|
const {rows: filteredRows, renderSearch, text: searchText} = useListSearch<User>(searchFields, displayUsers);
|
||||||
|
const {items, setPage, render: renderPagination} = usePagination<User>(filteredRows, 16);
|
||||||
|
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
useEffect(() => setPage(0), [searchText]);
|
||||||
|
|
||||||
const table = useReactTable({
|
const table = useReactTable({
|
||||||
data: filteredRows,
|
data: items,
|
||||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
});
|
});
|
||||||
@@ -632,27 +634,7 @@ export default function UserList({
|
|||||||
Download List
|
Download List
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
<div className="w-full flex gap-2 justify-between">
|
{renderPagination()}
|
||||||
<Button
|
|
||||||
isLoading={isLoading}
|
|
||||||
className="w-full max-w-[200px]"
|
|
||||||
disabled={page === 0}
|
|
||||||
onClick={() => setPage((prev) => prev - 1)}>
|
|
||||||
Previous Page
|
|
||||||
</Button>
|
|
||||||
<div className="flex items-center gap-4 w-fit">
|
|
||||||
<span className="opacity-80">
|
|
||||||
{page * userHash.size + 1} - {(page + 1) * userHash.size > total ? total : (page + 1) * userHash.size} / {total}
|
|
||||||
</span>
|
|
||||||
<Button
|
|
||||||
isLoading={isLoading}
|
|
||||||
className="w-[200px]"
|
|
||||||
disabled={(page + 1) * userHash.size >= total}
|
|
||||||
onClick={() => setPage((prev) => prev + 1)}>
|
|
||||||
Next Page
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||||
<thead>
|
<thead>
|
||||||
{table.getHeaderGroups().map((headerGroup) => (
|
{table.getHeaderGroups().map((headerGroup) => (
|
||||||
|
|||||||
@@ -22,7 +22,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 as {id: string};
|
const {id} = req.query as {id: string};
|
||||||
|
|
||||||
const assigners = await getAllAssignersByCorporate(id);
|
const assigners = await getAllAssignersByCorporate(id, req.session.user!.type);
|
||||||
const assignments = await getAssignmentsByAssigners([...assigners, id]);
|
const assignments = await getAssignmentsByAssigners([...assigners, id]);
|
||||||
|
|
||||||
res.status(200).json(uniqBy(assignments, "id"));
|
res.status(200).json(uniqBy(assignments, "id"));
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
try {
|
try {
|
||||||
const idsList = ids.split(",");
|
const idsList = ids.split(",");
|
||||||
|
|
||||||
const assignments = await getAssignmentsForCorporates(idsList, startDateParsed, endDateParsed);
|
const assignments = await getAssignmentsForCorporates(req.session.user!.type, idsList, startDateParsed, endDateParsed);
|
||||||
res.status(200).json(assignments);
|
res.status(200).json(assignments);
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
res.status(500).json({error: err.message});
|
res.status(500).json({error: err.message});
|
||||||
|
|||||||
@@ -14,12 +14,18 @@ import {getGradingSystem} from "@/utils/grading.be";
|
|||||||
import {StudentUser, User} from "@/interfaces/user";
|
import {StudentUser, User} from "@/interfaces/user";
|
||||||
import {calculateBandScore, getGradingLabel} from "@/utils/score";
|
import {calculateBandScore, getGradingLabel} from "@/utils/score";
|
||||||
import {Module} from "@/interfaces";
|
import {Module} from "@/interfaces";
|
||||||
|
import {uniq} from "lodash";
|
||||||
|
import {getUserName} from "@/utils/users";
|
||||||
|
import {LevelExam} from "@/interfaces/exam";
|
||||||
|
import {getSpecificExams} from "@/utils/exams.be";
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
interface TableData {
|
interface TableData {
|
||||||
user: string;
|
user: string;
|
||||||
studentID: string;
|
studentID: string;
|
||||||
|
passportID: string;
|
||||||
|
exams: string;
|
||||||
email: string;
|
email: string;
|
||||||
correct: number;
|
correct: number;
|
||||||
corporate: string;
|
corporate: string;
|
||||||
@@ -41,7 +47,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
if (req.method === "POST") return await post(req, res);
|
if (req.method === "POST") return await post(req, res);
|
||||||
}
|
}
|
||||||
|
|
||||||
const searchFilters = [["email"], ["user"], ["userId"]];
|
const searchFilters = [["email"], ["user"], ["userId"], ["assignment"], ["exams"]];
|
||||||
|
|
||||||
async function post(req: NextApiRequest, res: NextApiResponse) {
|
async function post(req: NextApiRequest, res: NextApiResponse) {
|
||||||
// verify if it's a logged user that is trying to export
|
// verify if it's a logged user that is trying to export
|
||||||
@@ -64,12 +70,13 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
};
|
};
|
||||||
const startDateParsed = startDate ? new Date(startDate) : undefined;
|
const startDateParsed = startDate ? new Date(startDate) : undefined;
|
||||||
const endDateParsed = endDate ? new Date(endDate) : undefined;
|
const endDateParsed = endDate ? new Date(endDate) : undefined;
|
||||||
const assignments = await getAssignmentsForCorporates(ids, startDateParsed, endDateParsed);
|
const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
|
||||||
|
|
||||||
const assignmentUsers = [...new Set(assignments.flatMap((a) => a.assignees))];
|
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]);
|
||||||
const assigners = [...new Set(assignments.map((a) => a.assigner))];
|
const assigners = [...new Set(assignments.map((a) => a.assigner))];
|
||||||
const users = await getSpecificUsers(assignmentUsers);
|
const users = await getSpecificUsers(assignmentUsers);
|
||||||
const assignerUsers = await getSpecificUsers(assigners);
|
const assignerUsers = await getSpecificUsers(assigners);
|
||||||
|
const exams = await getSpecificExams(uniq(assignments.flatMap((x) => x.exams.map((x) => x.id))));
|
||||||
|
|
||||||
const assignerUsersGradingSystems = await Promise.all(
|
const assignerUsersGradingSystems = await Promise.all(
|
||||||
assignerUsers.map(async (user: User) => {
|
assignerUsers.map(async (user: User) => {
|
||||||
@@ -91,7 +98,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
if (gradingSystem) {
|
if (gradingSystem) {
|
||||||
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
|
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
|
||||||
return {
|
return {
|
||||||
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
|
label: getGradingLabel(bandScore, gradingSystem.steps || []),
|
||||||
score: bandScore,
|
score: bandScore,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -113,10 +120,12 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const commonData = {
|
const commonData = {
|
||||||
user: userData?.name || "",
|
user: userData?.name || "",
|
||||||
email: userData?.email || "",
|
email: userData?.email || "",
|
||||||
studentID: (userData as StudentUser).studentID || "",
|
studentID: (userData as StudentUser)?.studentID || "",
|
||||||
|
passportID: (userData as StudentUser)?.demographicInformation?.passport_id || "",
|
||||||
userId: assignee,
|
userId: assignee,
|
||||||
|
exams: a.exams.map((x) => x.id).join(", "),
|
||||||
corporateId: a.corporateId,
|
corporateId: a.corporateId,
|
||||||
corporate: corporateUser?.name || "",
|
corporate: !corporateUser ? "" : getUserName(corporateUser),
|
||||||
assignment: a.name,
|
assignment: a.name,
|
||||||
level,
|
level,
|
||||||
score,
|
score,
|
||||||
@@ -130,14 +139,22 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const partsData = userStats.every((e) => e.module === "level")
|
let data: {total: number; correct: number}[] = [];
|
||||||
? userStats.reduce((acc, e, index) => {
|
if (a.exams.every((x) => x.module === "level")) {
|
||||||
return {
|
const exam = exams.find((x) => x.id === a.exams.find((x) => x.assignee === assignee)?.id) as LevelExam;
|
||||||
...acc,
|
data = exam.parts.map((x) => {
|
||||||
[`part${index}`]: `${e.score.correct}/${e.score.total}`,
|
const exerciseIDs = x.exercises.map((x) => x.id);
|
||||||
};
|
const stats = userStats.filter((x) => exerciseIDs.includes(x.exercise));
|
||||||
}, {})
|
|
||||||
: {};
|
const total = stats.reduce((acc, curr) => acc + curr.score.total, 0);
|
||||||
|
const correct = stats.reduce((acc, curr) => acc + curr.score.correct, 0);
|
||||||
|
|
||||||
|
return {total, correct};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const partsData =
|
||||||
|
data.length > 0 ? data.reduce((acc, e, index) => ({...acc, [`part${index}`]: `${e.correct}/${e.total}`}), {}) : {};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...commonData,
|
...commonData,
|
||||||
@@ -169,6 +186,10 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
label: "Student ID",
|
label: "Student ID",
|
||||||
value: (entry: TableData) => entry.studentID,
|
value: (entry: TableData) => entry.studentID,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: "Passport ID",
|
||||||
|
value: (entry: TableData) => entry.passportID,
|
||||||
|
},
|
||||||
...(displaySelection
|
...(displaySelection
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
@@ -186,7 +207,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
|
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: "Correct",
|
label: "Score",
|
||||||
value: (entry: TableData) => entry.correct,
|
value: (entry: TableData) => entry.correct,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -206,7 +227,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
})),
|
})),
|
||||||
];
|
];
|
||||||
|
|
||||||
const filteredSearch = searchText ? search(searchText, searchFilters, tableResults) : tableResults;
|
const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults;
|
||||||
|
|
||||||
worksheet.addRow(headers.map((h) => h.label));
|
worksheet.addRow(headers.map((h) => h.label));
|
||||||
(filteredSearch as TableData[]).forEach((entry) => {
|
(filteredSearch as TableData[]).forEach((entry) => {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import {withIronSessionApiRoute} from "iron-session/next";
|
|||||||
import {sessionOptions} from "@/lib/session";
|
import {sessionOptions} from "@/lib/session";
|
||||||
import {getLinkedUsers} from "@/utils/users.be";
|
import {getLinkedUsers} from "@/utils/users.be";
|
||||||
import {Type} from "@/interfaces/user";
|
import {Type} from "@/interfaces/user";
|
||||||
|
import {uniqBy} from "lodash";
|
||||||
|
|
||||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||||
|
|
||||||
@@ -31,5 +32,5 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
direction,
|
direction,
|
||||||
);
|
);
|
||||||
|
|
||||||
res.status(200).json({users, total});
|
res.status(200).json({users: uniqBy([...users], "id"), total});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import client from "@/lib/mongodb";
|
import client from "@/lib/mongodb";
|
||||||
import {Assignment} from "@/interfaces/results";
|
import {Assignment} from "@/interfaces/results";
|
||||||
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
||||||
|
import {Type} from "@/interfaces/user";
|
||||||
|
|
||||||
const db = client.db(process.env.MONGODB_DB);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
@@ -36,10 +37,10 @@ export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date,
|
|||||||
.toArray();
|
.toArray();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAssignmentsForCorporates = async (idsList: string[], startDate?: Date, endDate?: Date) => {
|
export const getAssignmentsForCorporates = async (userType: Type, idsList: string[], startDate?: Date, endDate?: Date) => {
|
||||||
const assigners = await Promise.all(
|
const assigners = await Promise.all(
|
||||||
idsList.map(async (id) => {
|
idsList.map(async (id) => {
|
||||||
const assigners = await getAllAssignersByCorporate(id);
|
const assigners = await getAllAssignersByCorporate(id, userType);
|
||||||
return {
|
return {
|
||||||
corporateId: id,
|
corporateId: id,
|
||||||
assigners,
|
assigners,
|
||||||
|
|||||||
@@ -6,6 +6,28 @@ import {Module} from "@/interfaces";
|
|||||||
import {getCorporateUser} from "@/resources/user";
|
import {getCorporateUser} from "@/resources/user";
|
||||||
import {getUserCorporate} from "./groups.be";
|
import {getUserCorporate} from "./groups.be";
|
||||||
import {Db, ObjectId} from "mongodb";
|
import {Db, ObjectId} from "mongodb";
|
||||||
|
import client from "@/lib/mongodb";
|
||||||
|
import {MODULE_ARRAY} from "./moduleUtils";
|
||||||
|
|
||||||
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
|
export async function getSpecificExams(ids: string[]) {
|
||||||
|
if (ids.length === 0) return [];
|
||||||
|
|
||||||
|
const exams: Exam[] = (
|
||||||
|
await Promise.all(
|
||||||
|
MODULE_ARRAY.flatMap(
|
||||||
|
async (module) =>
|
||||||
|
await db
|
||||||
|
.collection(module)
|
||||||
|
.find<Exam>({id: {$in: ids}})
|
||||||
|
.toArray(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
).flat();
|
||||||
|
|
||||||
|
return exams;
|
||||||
|
}
|
||||||
|
|
||||||
export const getExams = async (
|
export const getExams = async (
|
||||||
db: Db,
|
db: Db,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {app} from "@/firebase";
|
import {app} from "@/firebase";
|
||||||
import {Assignment} from "@/interfaces/results";
|
import {Assignment} from "@/interfaces/results";
|
||||||
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, User} from "@/interfaces/user";
|
import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, Type, User} from "@/interfaces/user";
|
||||||
import client from "@/lib/mongodb";
|
import client from "@/lib/mongodb";
|
||||||
import moment from "moment";
|
import moment from "moment";
|
||||||
import {getLinkedUsers, getUser} from "./users.be";
|
import {getLinkedUsers, getUser} from "./users.be";
|
||||||
@@ -71,9 +71,9 @@ export const getUsersGroups = async (ids: string[]) => {
|
|||||||
.toArray();
|
.toArray();
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
export const getAllAssignersByCorporate = async (corporateID: string, type: Type): Promise<string[]> => {
|
||||||
const linkedTeachers = await getLinkedUsers(corporateID, "mastercorporate", "teacher");
|
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
|
||||||
const linkedCorporates = await getLinkedUsers(corporateID, "mastercorporate", "corporate");
|
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
|
||||||
|
|
||||||
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)];
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
|
|
||||||
/*fields example = [
|
/*fields example = [
|
||||||
['id'],
|
['id'],
|
||||||
['companyInformation', 'companyInformation', 'name']
|
['companyInformation', 'companyInformation', 'name']
|
||||||
@@ -13,17 +12,17 @@ const getFieldValue = (fields: string[], data: any): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const search = (text: string, fields: string[][], rows: any[]) => {
|
export const search = (text: string, fields: string[][], rows: any[]) => {
|
||||||
const searchText = text.toLowerCase();
|
const searchText = text.toLowerCase();
|
||||||
return rows.filter((row) => {
|
return rows.filter((row) => {
|
||||||
return fields.some((fieldsKeys) => {
|
return fields.some((fieldsKeys) => {
|
||||||
const value = getFieldValue(fieldsKeys, row);
|
const value = getFieldValue(fieldsKeys, row);
|
||||||
if (typeof value === "string") {
|
if (typeof value === "string") {
|
||||||
return value.toLowerCase().includes(searchText);
|
return value.toLowerCase().includes(searchText);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof value === "number") {
|
if (typeof value === "number") {
|
||||||
return (value as Number).toString().includes(searchText);
|
return (value as Number).toString().includes(searchText);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user