Compare commits
7 Commits
feature/tr
...
release/as
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ce97b4dcd | ||
|
|
7bfd000213 | ||
|
|
2a10933206 | ||
|
|
33a46c227b | ||
|
|
85c8f622ee | ||
|
|
b9c097d42c | ||
|
|
192132559b |
@@ -1,546 +1,405 @@
|
||||
/* eslint-disable @next/next/no-img-element */
|
||||
import Modal from "@/components/Modal";
|
||||
import useFilterRecordsByUser from "@/hooks/useFilterRecordsByUser";
|
||||
import useUsers, {
|
||||
userHashStudent,
|
||||
userHashTeacher,
|
||||
userHashCorporate,
|
||||
} from "@/hooks/useUsers";
|
||||
import {
|
||||
CorporateUser,
|
||||
Group,
|
||||
MasterCorporateUser,
|
||||
Stat,
|
||||
User,
|
||||
} from "@/interfaces/user";
|
||||
import useUsers, {userHashStudent, userHashTeacher, userHashCorporate} from "@/hooks/useUsers";
|
||||
import {CorporateUser, Group, MasterCorporateUser, Stat, User} from "@/interfaces/user";
|
||||
import UserList from "@/pages/(admin)/Lists/UserList";
|
||||
import { dateSorter } from "@/utils";
|
||||
import {dateSorter} from "@/utils";
|
||||
import moment from "moment";
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import {useEffect, useMemo, useState} from "react";
|
||||
import {
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClock,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPencilSquare,
|
||||
BsPersonBadge,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsArrowRepeat,
|
||||
BsPlus,
|
||||
BsEnvelopePaper,
|
||||
BsDatabase,
|
||||
BsArrowLeft,
|
||||
BsClipboard2Data,
|
||||
BsClipboard2DataFill,
|
||||
BsClock,
|
||||
BsGlobeCentralSouthAsia,
|
||||
BsPaperclip,
|
||||
BsPerson,
|
||||
BsPersonAdd,
|
||||
BsPersonFill,
|
||||
BsPersonFillGear,
|
||||
BsPersonGear,
|
||||
BsPencilSquare,
|
||||
BsPersonBadge,
|
||||
BsPersonCheck,
|
||||
BsPeople,
|
||||
BsArrowRepeat,
|
||||
BsPlus,
|
||||
BsEnvelopePaper,
|
||||
BsDatabase,
|
||||
} from "react-icons/bs";
|
||||
import UserCard from "@/components/UserCard";
|
||||
import useGroups from "@/hooks/useGroups";
|
||||
import {
|
||||
averageLevelCalculator,
|
||||
calculateAverageLevel,
|
||||
calculateBandScore,
|
||||
} from "@/utils/score";
|
||||
import { MODULE_ARRAY } from "@/utils/moduleUtils";
|
||||
import { Module } from "@/interfaces";
|
||||
import { groupByExam } from "@/utils/stats";
|
||||
import {averageLevelCalculator, calculateAverageLevel, calculateBandScore} from "@/utils/score";
|
||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||
import {Module} from "@/interfaces";
|
||||
import {groupByExam} from "@/utils/stats";
|
||||
import IconCard from "../IconCard";
|
||||
import GroupList from "@/pages/(admin)/Lists/GroupList";
|
||||
import useFilterStore from "@/stores/listFilterStore";
|
||||
import { useRouter } from "next/router";
|
||||
import {useRouter} from "next/router";
|
||||
import useCodes from "@/hooks/useCodes";
|
||||
import { getUserCorporate } from "@/utils/groups";
|
||||
import {getUserCorporate} from "@/utils/groups";
|
||||
import useAssignments from "@/hooks/useAssignments";
|
||||
import { Assignment } from "@/interfaces/results";
|
||||
import {Assignment} from "@/interfaces/results";
|
||||
import AssignmentView from "../AssignmentView";
|
||||
import AssignmentCreator from "../AssignmentCreator";
|
||||
import clsx from "clsx";
|
||||
import AssignmentCard from "../AssignmentCard";
|
||||
import { createColumnHelper } from "@tanstack/react-table";
|
||||
import {createColumnHelper} from "@tanstack/react-table";
|
||||
import Checkbox from "@/components/Low/Checkbox";
|
||||
import List from "@/components/List";
|
||||
import { getUserCompanyName } from "@/resources/user";
|
||||
import {
|
||||
futureAssignmentFilter,
|
||||
pastAssignmentFilter,
|
||||
archivedAssignmentFilter,
|
||||
activeAssignmentFilter,
|
||||
} from "@/utils/assignments";
|
||||
import {getUserCompanyName} from "@/resources/user";
|
||||
import {futureAssignmentFilter, pastAssignmentFilter, archivedAssignmentFilter, activeAssignmentFilter} from "@/utils/assignments";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import AssignmentsPage from "../views/AssignmentsPage";
|
||||
import StudentPerformancePage from "./StudentPerformancePage";
|
||||
import MasterStatistical from "../MasterCorporate/MasterStatistical";
|
||||
import MasterStatisticalPage from "./MasterStatisticalPage";
|
||||
|
||||
interface Props {
|
||||
user: CorporateUser;
|
||||
linkedCorporate?: CorporateUser | MasterCorporateUser;
|
||||
user: CorporateUser;
|
||||
linkedCorporate?: CorporateUser | MasterCorporateUser;
|
||||
}
|
||||
|
||||
const studentHash = {
|
||||
type: "student",
|
||||
orderBy: "registrationDate",
|
||||
size: 25,
|
||||
type: "student",
|
||||
orderBy: "registrationDate",
|
||||
size: 25,
|
||||
};
|
||||
|
||||
const teacherHash = {
|
||||
type: "teacher",
|
||||
orderBy: "registrationDate",
|
||||
size: 25,
|
||||
type: "teacher",
|
||||
orderBy: "registrationDate",
|
||||
size: 25,
|
||||
};
|
||||
|
||||
export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
export default function CorporateDashboard({user, linkedCorporate}: Props) {
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [showModal, setShowModal] = useState(false);
|
||||
|
||||
const { data: stats } = useFilterRecordsByUser<Stat[]>();
|
||||
const { groups } = useGroups({ admin: user.id });
|
||||
const {
|
||||
assignments,
|
||||
isLoading: isAssignmentsLoading,
|
||||
reload: reloadAssignments,
|
||||
} = useAssignments({ corporate: user.id });
|
||||
const { balance } = useUserBalance();
|
||||
const {data: stats} = useFilterRecordsByUser<Stat[]>();
|
||||
const {groups} = useGroups({admin: user.id});
|
||||
const {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id});
|
||||
const {balance} = useUserBalance();
|
||||
|
||||
const {
|
||||
users: students,
|
||||
total: totalStudents,
|
||||
reload: reloadStudents,
|
||||
isLoading: isStudentsLoading,
|
||||
} = useUsers(studentHash);
|
||||
const {
|
||||
users: teachers,
|
||||
total: totalTeachers,
|
||||
reload: reloadTeachers,
|
||||
isLoading: isTeachersLoading,
|
||||
} = useUsers(teacherHash);
|
||||
const {users: students, 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 router = useRouter();
|
||||
const appendUserFilters = useFilterStore((state) => state.appendUserFilter);
|
||||
const router = useRouter();
|
||||
|
||||
const assignmentsGroups = useMemo(
|
||||
() =>
|
||||
groups.filter(
|
||||
(x) => x.admin === user.id || x.participants.includes(user.id)
|
||||
),
|
||||
[groups, user.id]
|
||||
);
|
||||
const assignmentsGroups = useMemo(() => groups.filter((x) => x.admin === user.id || x.participants.includes(user.id)), [groups, user.id]);
|
||||
|
||||
const assignmentsUsers = useMemo(
|
||||
() =>
|
||||
[...teachers, ...students].filter((x) =>
|
||||
!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id)
|
||||
),
|
||||
[groups, teachers, students, selectedUser]
|
||||
);
|
||||
const assignmentsUsers = useMemo(
|
||||
() =>
|
||||
[...teachers, ...students].filter((x) =>
|
||||
!!selectedUser
|
||||
? groups
|
||||
.filter((g) => g.admin === selectedUser.id)
|
||||
.flatMap((g) => g.participants)
|
||||
.includes(x.id) || false
|
||||
: groups.flatMap((g) => g.participants).includes(x.id),
|
||||
),
|
||||
[groups, teachers, students, selectedUser],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||
}, [selectedUser, router.asPath]);
|
||||
useEffect(() => {
|
||||
setShowModal(!!selectedUser && router.asPath === "/#");
|
||||
}, [selectedUser, router.asPath]);
|
||||
|
||||
const getStatsByStudent = (user: User) =>
|
||||
stats.filter((s) => s.user === user.id);
|
||||
const getStatsByStudent = (user: User) => stats.filter((s) => s.user === user.id);
|
||||
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
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"
|
||||
>
|
||||
<img
|
||||
src={displayUser.profilePicture}
|
||||
alt={displayUser.name}
|
||||
className="rounded-full w-10 h-10"
|
||||
/>
|
||||
<div className="flex flex-col gap-1 items-start">
|
||||
<span>{displayUser.name}</span>
|
||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
const UserDisplay = (displayUser: User) => (
|
||||
<div
|
||||
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">
|
||||
<img src={displayUser.profilePicture} alt={displayUser.name} className="rounded-full w-10 h-10" />
|
||||
<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
|
||||
// while still being able to use the corporate user
|
||||
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 = () => {
|
||||
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||
|
||||
const GroupsList = () => {
|
||||
const filter = (x: Group) =>
|
||||
x.admin === user.id || x.participants.includes(user.id);
|
||||
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">Groups ({groups.filter(filter).length})</h2>
|
||||
</div>
|
||||
|
||||
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">
|
||||
Groups ({groups.filter(filter).length})
|
||||
</h2>
|
||||
</div>
|
||||
<GroupList user={user} />
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
<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 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 levels: {[key in Module]: number} = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
|
||||
const levels: { [key in Module]: number } = {
|
||||
reading: 0,
|
||||
listening: 0,
|
||||
writing: 0,
|
||||
speaking: 0,
|
||||
level: 0,
|
||||
};
|
||||
bandScores.forEach((b) => (levels[b.module] += b.level));
|
||||
return calculateAverageLevel(levels);
|
||||
};
|
||||
|
||||
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")
|
||||
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 === "/#teachers")
|
||||
return (
|
||||
<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 === "/#teachers")
|
||||
return (
|
||||
<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 === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
|
||||
|
||||
if (router.asPath === "/#groups") return <GroupsList />;
|
||||
if (router.asPath === "/#studentsPerformance")
|
||||
return <StudentPerformancePage user={user} />;
|
||||
if (router.asPath === "/#assignments")
|
||||
return (
|
||||
<AssignmentsPage
|
||||
assignments={assignments}
|
||||
user={user}
|
||||
groups={assignmentsGroups}
|
||||
reloadAssignments={reloadAssignments}
|
||||
isLoading={isAssignmentsLoading}
|
||||
onBack={() => router.push("/")}
|
||||
/>
|
||||
);
|
||||
|
||||
if (router.asPath === "/#assignments")
|
||||
return (
|
||||
<AssignmentsPage
|
||||
assignments={assignments}
|
||||
user={user}
|
||||
groups={assignmentsGroups}
|
||||
reloadAssignments={reloadAssignments}
|
||||
isLoading={isAssignmentsLoading}
|
||||
onBack={() => router.push("/")}
|
||||
/>
|
||||
);
|
||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />;
|
||||
|
||||
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 (
|
||||
<>
|
||||
<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),
|
||||
});
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
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");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
onViewTeachers={
|
||||
selectedUser.type === "corporate" ||
|
||||
selectedUser.type === "student"
|
||||
? () => {
|
||||
appendUserFilters({
|
||||
id: "view-teachers",
|
||||
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");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
|
||||
router.push("/list/users");
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
user={selectedUser}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
</Modal>
|
||||
<>
|
||||
{!!linkedCorporate && (
|
||||
<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>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/#students")}
|
||||
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>
|
||||
|
||||
<>
|
||||
{!!linkedCorporate && (
|
||||
<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>
|
||||
</div>
|
||||
)}
|
||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||
<IconCard
|
||||
onClick={() => router.push("/#students")}
|
||||
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">
|
||||
<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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
<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>
|
||||
</>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, {useEffect, useMemo, useState} from "react";
|
||||
import {CorporateUser, User} from "@/interfaces/user";
|
||||
import {CorporateUser, StudentUser, User} from "@/interfaces/user";
|
||||
import {BsFileExcel, BsBank, BsPersonFill} from "react-icons/bs";
|
||||
import IconCard from "../IconCard";
|
||||
|
||||
@@ -28,7 +28,7 @@ interface Props {
|
||||
}
|
||||
|
||||
interface TableData {
|
||||
user: string;
|
||||
user: User | undefined;
|
||||
email: string;
|
||||
correct: number;
|
||||
corporate: string;
|
||||
@@ -62,7 +62,7 @@ const MasterStatistical = (props: Props) => {
|
||||
const [startDate, setStartDate] = React.useState<Date | null>(moment("01/01/2023").toDate());
|
||||
const [endDate, setEndDate] = React.useState<Date | null>(moment().endOf("year").toDate());
|
||||
|
||||
const {assignments} = useAssignmentsCorporates({
|
||||
const {assignments, isLoading} = useAssignmentsCorporates({
|
||||
corporates: selectedCorporates,
|
||||
startDate,
|
||||
endDate,
|
||||
@@ -74,11 +74,11 @@ const MasterStatistical = (props: Props) => {
|
||||
() =>
|
||||
assignments.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||
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 userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
||||
const corporate = getUserName(users.find((u) => u.id === a.assigner));
|
||||
const commonData = {
|
||||
user: userData?.name || "N/A",
|
||||
user: userData,
|
||||
email: userData?.email || "N/A",
|
||||
userId: assignee,
|
||||
corporateId: a.corporateId,
|
||||
@@ -86,6 +86,7 @@ const MasterStatistical = (props: Props) => {
|
||||
corporate,
|
||||
assignment: a.name,
|
||||
};
|
||||
|
||||
if (userStats.length === 0) {
|
||||
return {
|
||||
...commonData,
|
||||
@@ -108,8 +109,6 @@ const MasterStatistical = (props: Props) => {
|
||||
[assignments, users],
|
||||
);
|
||||
|
||||
useEffect(() => console.log(assignments), [assignments]);
|
||||
|
||||
const getCorporateScores = (corporateId: string): UserCount => {
|
||||
const corporateAssignmentsUsers = assignments.filter((a) => a.corporateId === corporateId).reduce((acc, a) => acc + a.assignees.length, 0);
|
||||
|
||||
@@ -151,7 +150,7 @@ const MasterStatistical = (props: Props) => {
|
||||
header: "User",
|
||||
id: "user",
|
||||
cell: (info) => {
|
||||
return <span>{info.getValue()}</span>;
|
||||
return <span>{info.getValue()?.name || "N/A"}</span>;
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor("email", {
|
||||
@@ -161,6 +160,13 @@ const MasterStatistical = (props: Props) => {
|
||||
return <span>{info.getValue()}</span>;
|
||||
},
|
||||
}),
|
||||
columnHelper.accessor("user", {
|
||||
header: "Student ID",
|
||||
id: "studentID",
|
||||
cell: (info) => {
|
||||
return <span>{(info.getValue() as StudentUser)?.studentID || "N/A"}</span>;
|
||||
},
|
||||
}),
|
||||
...(displaySelection
|
||||
? [
|
||||
columnHelper.accessor("corporate", {
|
||||
@@ -281,6 +287,7 @@ const MasterStatistical = (props: Props) => {
|
||||
<IconCard
|
||||
Icon={BsBank}
|
||||
label="Consolidate"
|
||||
isLoading={isLoading}
|
||||
value={getConsolidateScoreStr(consolidateScore)}
|
||||
color="purple"
|
||||
onClick={() => {
|
||||
@@ -302,6 +309,7 @@ const MasterStatistical = (props: Props) => {
|
||||
<IconCard
|
||||
key={corporateName}
|
||||
Icon={BsBank}
|
||||
isLoading={isLoading}
|
||||
label={corporateName}
|
||||
value={value}
|
||||
color="purple"
|
||||
@@ -343,7 +351,7 @@ const MasterStatistical = (props: Props) => {
|
||||
</div>
|
||||
{renderSearch()}
|
||||
<div className="flex flex-col gap-3 justify-end">
|
||||
<Button className="max-w-[200px] h-[70px]" variant="outline" onClick={triggerDownload}>
|
||||
<Button className="w-[200px] h-[70px]" variant="outline" isLoading={downloading} onClick={triggerDownload}>
|
||||
Download
|
||||
</Button>
|
||||
</div>
|
||||
@@ -359,7 +367,7 @@ const MasterStatistical = (props: Props) => {
|
||||
{page * SIZE + 1} - {(page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE} /{" "}
|
||||
{filteredRows.length}
|
||||
</span>
|
||||
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= rows.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||
<Button className="w-[200px]" disabled={(page + 1) * SIZE >= filteredRows.length} onClick={() => setPage((prev) => prev + 1)}>
|
||||
Next Page
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
@@ -55,7 +55,7 @@ export default function AssignmentsPage({assignments, corporateAssignments, user
|
||||
<AssignmentCreator
|
||||
assignment={selectedAssignment}
|
||||
groups={groups}
|
||||
users={users}
|
||||
users={[...users, user]}
|
||||
user={user}
|
||||
isCreating={isCreatingAssignment}
|
||||
cancelCreation={() => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {useState, useMemo} from "react";
|
||||
import Input from "@/components/Low/Input";
|
||||
import { search } from "@/utils/search";
|
||||
import {search} from "@/utils/search";
|
||||
|
||||
export function useListSearch<T>(fields: string[][], rows: T[]) {
|
||||
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 updatedRows = useMemo(() => {
|
||||
return search(text, fields, rows);
|
||||
if (text.length > 0) return search(text, fields, rows);
|
||||
return rows;
|
||||
}, [fields, rows, text]);
|
||||
|
||||
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());
|
||||
});
|
||||
|
||||
console.log(params.toString());
|
||||
|
||||
setIsLoading(true);
|
||||
axios
|
||||
.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 usePermissions from "@/hooks/usePermissions";
|
||||
import useUserBalance from "@/hooks/useUserBalance";
|
||||
import usePagination from "@/hooks/usePagination";
|
||||
const columnHelper = createColumnHelper<User>();
|
||||
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
|
||||
|
||||
@@ -62,15 +63,12 @@ export default function UserList({
|
||||
const [sorter, setSorter] = useState<string>();
|
||||
const [displayUsers, setDisplayUsers] = useState<User[]>([]);
|
||||
const [selectedUser, setSelectedUser] = useState<User>();
|
||||
const [page, setPage] = useState(0);
|
||||
|
||||
const userHash = useMemo(
|
||||
() => ({
|
||||
type,
|
||||
size: 16,
|
||||
page,
|
||||
}),
|
||||
[type, page],
|
||||
[type],
|
||||
);
|
||||
|
||||
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||
@@ -102,9 +100,9 @@ export default function UserList({
|
||||
(async () => {
|
||||
if (users && users.length > 0) {
|
||||
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
|
||||
@@ -513,10 +511,14 @@ export default function UserList({
|
||||
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({
|
||||
data: filteredRows,
|
||||
data: items,
|
||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||
getCoreRowModel: getCoreRowModel(),
|
||||
});
|
||||
@@ -632,27 +634,7 @@ export default function UserList({
|
||||
Download List
|
||||
</Button>
|
||||
</div>
|
||||
<div className="w-full flex gap-2 justify-between">
|
||||
<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>
|
||||
{renderPagination()}
|
||||
<table className="rounded-xl bg-mti-purple-ultralight/40 w-full">
|
||||
<thead>
|
||||
{table.getHeaderGroups().map((headerGroup) => (
|
||||
|
||||
@@ -22,7 +22,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
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]);
|
||||
|
||||
res.status(200).json(uniqBy(assignments, "id"));
|
||||
|
||||
@@ -29,7 +29,7 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
||||
try {
|
||||
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);
|
||||
} catch (err: any) {
|
||||
res.status(500).json({error: err.message});
|
||||
|
||||
@@ -1,254 +1,255 @@
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
import { storage } from "@/firebase";
|
||||
import { withIronSessionApiRoute } from "iron-session/next";
|
||||
import { sessionOptions } from "@/lib/session";
|
||||
import { ref, uploadBytes, getDownloadURL } from "firebase/storage";
|
||||
import { AssignmentWithCorporateId } from "@/interfaces/results";
|
||||
import type {NextApiRequest, NextApiResponse} from "next";
|
||||
import {storage} from "@/firebase";
|
||||
import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {ref, uploadBytes, getDownloadURL} from "firebase/storage";
|
||||
import {AssignmentWithCorporateId} from "@/interfaces/results";
|
||||
import moment from "moment-timezone";
|
||||
import ExcelJS from "exceljs";
|
||||
import { getSpecificUsers } from "@/utils/users.be";
|
||||
import { checkAccess } from "@/utils/permissions";
|
||||
import { getAssignmentsForCorporates } from "@/utils/assignments.be";
|
||||
import { search } from "@/utils/search";
|
||||
import { getGradingSystem } from "@/utils/grading.be";
|
||||
import { User } from "@/interfaces/user";
|
||||
import { calculateBandScore, getGradingLabel } from "@/utils/score";
|
||||
import { Module } from "@/interfaces";
|
||||
import {getSpecificUsers} from "@/utils/users.be";
|
||||
import {checkAccess} from "@/utils/permissions";
|
||||
import {getAssignmentsForCorporates} from "@/utils/assignments.be";
|
||||
import {search} from "@/utils/search";
|
||||
import {getGradingSystem} from "@/utils/grading.be";
|
||||
import {StudentUser, User} from "@/interfaces/user";
|
||||
import {calculateBandScore, getGradingLabel} from "@/utils/score";
|
||||
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);
|
||||
|
||||
interface TableData {
|
||||
user: string;
|
||||
email: string;
|
||||
correct: number;
|
||||
corporate: string;
|
||||
submitted: boolean;
|
||||
date: moment.Moment;
|
||||
assignment: string;
|
||||
corporateId: string;
|
||||
score: number;
|
||||
level: string;
|
||||
part1?: string;
|
||||
part2?: string;
|
||||
part3?: string;
|
||||
part4?: string;
|
||||
part5?: string;
|
||||
user: string;
|
||||
studentID: string;
|
||||
passportID: string;
|
||||
exams: string;
|
||||
email: string;
|
||||
correct: number;
|
||||
corporate: string;
|
||||
submitted: boolean;
|
||||
date: moment.Moment;
|
||||
assignment: string;
|
||||
corporateId: string;
|
||||
score: number;
|
||||
level: string;
|
||||
part1?: string;
|
||||
part2?: string;
|
||||
part3?: string;
|
||||
part4?: string;
|
||||
part5?: string;
|
||||
}
|
||||
|
||||
async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
// if (req.method === "GET") return get(req, res);
|
||||
if (req.method === "POST") return await post(req, res);
|
||||
// if (req.method === "GET") return get(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) {
|
||||
// verify if it's a logged user that is trying to export
|
||||
if (req.session.user) {
|
||||
if (
|
||||
!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])
|
||||
) {
|
||||
return res.status(403).json({ error: "Unauthorized" });
|
||||
}
|
||||
const {
|
||||
ids,
|
||||
startDate,
|
||||
endDate,
|
||||
searchText,
|
||||
displaySelection = true,
|
||||
} = req.body as {
|
||||
ids: string[];
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
searchText: string;
|
||||
displaySelection?: boolean;
|
||||
};
|
||||
const startDateParsed = startDate ? new Date(startDate) : undefined;
|
||||
const endDateParsed = endDate ? new Date(endDate) : undefined;
|
||||
const assignments = await getAssignmentsForCorporates(
|
||||
ids,
|
||||
startDateParsed,
|
||||
endDateParsed
|
||||
);
|
||||
// verify if it's a logged user that is trying to export
|
||||
if (req.session.user) {
|
||||
if (!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])) {
|
||||
return res.status(403).json({error: "Unauthorized"});
|
||||
}
|
||||
const {
|
||||
ids,
|
||||
startDate,
|
||||
endDate,
|
||||
searchText,
|
||||
displaySelection = true,
|
||||
} = req.body as {
|
||||
ids: string[];
|
||||
startDate?: string;
|
||||
endDate?: string;
|
||||
searchText: string;
|
||||
displaySelection?: boolean;
|
||||
};
|
||||
const startDateParsed = startDate ? new Date(startDate) : undefined;
|
||||
const endDateParsed = endDate ? new Date(endDate) : undefined;
|
||||
const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
|
||||
|
||||
const assignmentUsers = [
|
||||
...new Set(assignments.flatMap((a) => a.assignees)),
|
||||
];
|
||||
const assigners = [...new Set(assignments.map((a) => a.assigner))];
|
||||
const users = await getSpecificUsers(assignmentUsers);
|
||||
const assignerUsers = await getSpecificUsers(assigners);
|
||||
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]);
|
||||
const assigners = [...new Set(assignments.map((a) => a.assigner))];
|
||||
const users = await getSpecificUsers(assignmentUsers);
|
||||
const assignerUsers = await getSpecificUsers(assigners);
|
||||
const exams = await getSpecificExams(uniq(assignments.flatMap((x) => x.exams.map((x) => x.id))));
|
||||
|
||||
const assignerUsersGradingSystems = await Promise.all(
|
||||
assignerUsers.map(async (user: User) => {
|
||||
const data = await getGradingSystem(user);
|
||||
// in this context I need to override as I'll have to match to the assigner
|
||||
return { ...data, user: user.id };
|
||||
})
|
||||
);
|
||||
const assignerUsersGradingSystems = await Promise.all(
|
||||
assignerUsers.map(async (user: User) => {
|
||||
const data = await getGradingSystem(user);
|
||||
// in this context I need to override as I'll have to match to the assigner
|
||||
return {...data, user: user.id};
|
||||
}),
|
||||
);
|
||||
|
||||
const getGradingSystemHelper = (
|
||||
exams: { id: string; module: Module; assignee: string }[],
|
||||
assigner: string,
|
||||
user: User,
|
||||
correct: number,
|
||||
total: number
|
||||
) => {
|
||||
if (exams.some((e) => e.module === "level")) {
|
||||
const gradingSystem = assignerUsersGradingSystems.find(
|
||||
(gs) => gs.user === assigner
|
||||
);
|
||||
if (gradingSystem) {
|
||||
const bandScore = calculateBandScore(
|
||||
correct,
|
||||
total,
|
||||
"level",
|
||||
user.focus
|
||||
);
|
||||
return {
|
||||
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
|
||||
score: bandScore,
|
||||
};
|
||||
}
|
||||
}
|
||||
const getGradingSystemHelper = (
|
||||
exams: {id: string; module: Module; assignee: string}[],
|
||||
assigner: string,
|
||||
user: User,
|
||||
correct: number,
|
||||
total: number,
|
||||
) => {
|
||||
if (exams.some((e) => e.module === "level")) {
|
||||
const gradingSystem = assignerUsersGradingSystems.find((gs) => gs.user === assigner);
|
||||
if (gradingSystem) {
|
||||
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
|
||||
return {
|
||||
label: getGradingLabel(bandScore, gradingSystem.steps || []),
|
||||
score: bandScore,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { score: -1, label: "N/A" };
|
||||
};
|
||||
return {score: -1, label: "N/A"};
|
||||
};
|
||||
|
||||
const tableResults = assignments
|
||||
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||
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 corporateUser = users.find((u) => u.id === a.assigner);
|
||||
const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
|
||||
const total = userStats.reduce((n, e) => n + e.score.total, 0);
|
||||
const { label: level, score } = getGradingSystemHelper(
|
||||
a.exams,
|
||||
a.assigner,
|
||||
userData!,
|
||||
correct,
|
||||
total
|
||||
);
|
||||
const tableResults = assignments
|
||||
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||
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 corporateUser = users.find((u) => u.id === a.assigner);
|
||||
const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
|
||||
const total = userStats.reduce((n, e) => n + e.score.total, 0);
|
||||
const {label: level, score} = getGradingSystemHelper(a.exams, a.assigner, userData!, correct, total);
|
||||
|
||||
console.log("Level", level);
|
||||
const commonData = {
|
||||
user: userData?.name || "",
|
||||
email: userData?.email || "",
|
||||
userId: assignee,
|
||||
corporateId: a.corporateId,
|
||||
corporate: corporateUser?.name || "",
|
||||
assignment: a.name,
|
||||
level,
|
||||
score,
|
||||
};
|
||||
if (userStats.length === 0) {
|
||||
return {
|
||||
...commonData,
|
||||
correct: 0,
|
||||
submitted: false,
|
||||
// date: moment(),
|
||||
};
|
||||
}
|
||||
const commonData = {
|
||||
user: userData?.name || "",
|
||||
email: userData?.email || "",
|
||||
studentID: (userData as StudentUser)?.studentID || "",
|
||||
passportID: (userData as StudentUser)?.demographicInformation?.passport_id || "",
|
||||
userId: assignee,
|
||||
exams: a.exams.map((x) => x.id).join(", "),
|
||||
corporateId: a.corporateId,
|
||||
corporate: !corporateUser ? "" : getUserName(corporateUser),
|
||||
assignment: a.name,
|
||||
level,
|
||||
score,
|
||||
};
|
||||
if (userStats.length === 0) {
|
||||
return {
|
||||
...commonData,
|
||||
correct: 0,
|
||||
submitted: false,
|
||||
// date: moment(),
|
||||
};
|
||||
}
|
||||
|
||||
const partsData = userStats.every((e) => e.module === "level")
|
||||
? userStats.reduce((acc, e, index) => {
|
||||
return {
|
||||
...acc,
|
||||
[`part${index}`]: `${e.score.correct}/${e.score.total}`,
|
||||
};
|
||||
}, {})
|
||||
: {};
|
||||
let data: {total: number; correct: number}[] = [];
|
||||
if (a.exams.every((x) => x.module === "level")) {
|
||||
const exam = exams.find((x) => x.id === a.exams.find((x) => x.assignee === assignee)?.id) as LevelExam;
|
||||
data = exam.parts.map((x) => {
|
||||
const exerciseIDs = x.exercises.map((x) => x.id);
|
||||
const stats = userStats.filter((x) => exerciseIDs.includes(x.exercise));
|
||||
|
||||
return {
|
||||
...commonData,
|
||||
correct,
|
||||
submitted: true,
|
||||
date: moment.max(userStats.map((e) => moment(e.date))),
|
||||
...partsData,
|
||||
};
|
||||
}) as TableData[];
|
||||
const total = stats.reduce((acc, curr) => acc + curr.score.total, 0);
|
||||
const correct = stats.reduce((acc, curr) => acc + curr.score.correct, 0);
|
||||
|
||||
return [...accmA, ...userResults];
|
||||
}, [])
|
||||
.sort((a, b) => b.score - a.score);
|
||||
return {total, correct};
|
||||
});
|
||||
}
|
||||
|
||||
// Create a new workbook and add a worksheet
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const worksheet = workbook.addWorksheet("Master Statistical");
|
||||
const partsData =
|
||||
data.length > 0 ? data.reduce((acc, e, index) => ({...acc, [`part${index}`]: `${e.correct}/${e.total}`}), {}) : {};
|
||||
|
||||
const headers = [
|
||||
{
|
||||
label: "User",
|
||||
value: (entry: TableData) => entry.user,
|
||||
},
|
||||
{
|
||||
label: "Email",
|
||||
value: (entry: TableData) => entry.email,
|
||||
},
|
||||
...(displaySelection
|
||||
? [
|
||||
{
|
||||
label: "Corporate",
|
||||
value: (entry: TableData) => entry.corporate,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Assignment",
|
||||
value: (entry: TableData) => entry.assignment,
|
||||
},
|
||||
{
|
||||
label: "Submitted",
|
||||
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
|
||||
},
|
||||
{
|
||||
label: "Correct",
|
||||
value: (entry: TableData) => entry.correct,
|
||||
},
|
||||
{
|
||||
label: "Date",
|
||||
value: (entry: TableData) => entry.date?.format("YYYY/MM/DD") || "",
|
||||
},
|
||||
{
|
||||
label: "Level",
|
||||
value: (entry: TableData) => entry.level,
|
||||
},
|
||||
...new Array(5).fill(0).map((_, index) => ({
|
||||
label: `Part ${index + 1}`,
|
||||
value: (entry: TableData) => {
|
||||
const key = `part${index}` as keyof TableData;
|
||||
return entry[key] || "";
|
||||
},
|
||||
})),
|
||||
];
|
||||
return {
|
||||
...commonData,
|
||||
correct,
|
||||
submitted: true,
|
||||
date: moment.max(userStats.map((e) => moment(e.date))),
|
||||
...partsData,
|
||||
};
|
||||
}) as TableData[];
|
||||
|
||||
const filteredSearch = searchText
|
||||
? search(searchText, searchFilters, tableResults)
|
||||
: tableResults;
|
||||
return [...accmA, ...userResults];
|
||||
}, [])
|
||||
.sort((a, b) => b.score - a.score);
|
||||
|
||||
worksheet.addRow(headers.map((h) => h.label));
|
||||
(filteredSearch as TableData[]).forEach((entry) => {
|
||||
worksheet.addRow(headers.map((h) => h.value(entry)));
|
||||
});
|
||||
// Create a new workbook and add a worksheet
|
||||
const workbook = new ExcelJS.Workbook();
|
||||
const worksheet = workbook.addWorksheet("Master Statistical");
|
||||
|
||||
// Convert workbook to Buffer (Node.js) or Blob (Browser)
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
const headers = [
|
||||
{
|
||||
label: "User",
|
||||
value: (entry: TableData) => entry.user,
|
||||
},
|
||||
{
|
||||
label: "Email",
|
||||
value: (entry: TableData) => entry.email,
|
||||
},
|
||||
{
|
||||
label: "Student ID",
|
||||
value: (entry: TableData) => entry.studentID,
|
||||
},
|
||||
{
|
||||
label: "Passport ID",
|
||||
value: (entry: TableData) => entry.passportID,
|
||||
},
|
||||
...(displaySelection
|
||||
? [
|
||||
{
|
||||
label: "Corporate",
|
||||
value: (entry: TableData) => entry.corporate,
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{
|
||||
label: "Assignment",
|
||||
value: (entry: TableData) => entry.assignment,
|
||||
},
|
||||
{
|
||||
label: "Submitted",
|
||||
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
|
||||
},
|
||||
{
|
||||
label: "Score",
|
||||
value: (entry: TableData) => entry.correct,
|
||||
},
|
||||
{
|
||||
label: "Date",
|
||||
value: (entry: TableData) => entry.date?.format("YYYY/MM/DD") || "",
|
||||
},
|
||||
{
|
||||
label: "Level",
|
||||
value: (entry: TableData) => entry.level,
|
||||
},
|
||||
...new Array(5).fill(0).map((_, index) => ({
|
||||
label: `Part ${index + 1}`,
|
||||
value: (entry: TableData) => {
|
||||
const key = `part${index}` as keyof TableData;
|
||||
return entry[key] || "";
|
||||
},
|
||||
})),
|
||||
];
|
||||
|
||||
// generate the file ref for storage
|
||||
const fileName = `${Date.now().toString()}.xlsx`;
|
||||
const refName = `statistical/${fileName}`;
|
||||
const fileRef = ref(storage, refName);
|
||||
// upload the pdf to storage
|
||||
await uploadBytes(fileRef, buffer, {
|
||||
contentType:
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults;
|
||||
|
||||
const url = await getDownloadURL(fileRef);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
}
|
||||
worksheet.addRow(headers.map((h) => h.label));
|
||||
(filteredSearch as TableData[]).forEach((entry) => {
|
||||
worksheet.addRow(headers.map((h) => h.value(entry)));
|
||||
});
|
||||
|
||||
return res.status(401).json({ error: "Unauthorized" });
|
||||
// Convert workbook to Buffer (Node.js) or Blob (Browser)
|
||||
const buffer = await workbook.xlsx.writeBuffer();
|
||||
|
||||
// generate the file ref for storage
|
||||
const fileName = `${Date.now().toString()}.xlsx`;
|
||||
const refName = `statistical/${fileName}`;
|
||||
const fileRef = ref(storage, refName);
|
||||
// upload the pdf to storage
|
||||
await uploadBytes(fileRef, buffer, {
|
||||
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
});
|
||||
|
||||
const url = await getDownloadURL(fileRef);
|
||||
res.status(200).end(url);
|
||||
return;
|
||||
}
|
||||
|
||||
return res.status(401).json({error: "Unauthorized"});
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import {withIronSessionApiRoute} from "iron-session/next";
|
||||
import {sessionOptions} from "@/lib/session";
|
||||
import {getLinkedUsers} from "@/utils/users.be";
|
||||
import {Type} from "@/interfaces/user";
|
||||
import {uniqBy} from "lodash";
|
||||
|
||||
export default withIronSessionApiRoute(handler, sessionOptions);
|
||||
|
||||
@@ -31,5 +32,5 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
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 {Assignment} from "@/interfaces/results";
|
||||
import {getAllAssignersByCorporate} from "@/utils/groups.be";
|
||||
import {Type} from "@/interfaces/user";
|
||||
|
||||
const db = client.db(process.env.MONGODB_DB);
|
||||
|
||||
@@ -36,10 +37,10 @@ export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date,
|
||||
.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(
|
||||
idsList.map(async (id) => {
|
||||
const assigners = await getAllAssignersByCorporate(id);
|
||||
const assigners = await getAllAssignersByCorporate(id, userType);
|
||||
return {
|
||||
corporateId: id,
|
||||
assigners,
|
||||
|
||||
@@ -6,6 +6,28 @@ import {Module} from "@/interfaces";
|
||||
import {getCorporateUser} from "@/resources/user";
|
||||
import {getUserCorporate} from "./groups.be";
|
||||
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 (
|
||||
db: Db,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {app} from "@/firebase";
|
||||
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 moment from "moment";
|
||||
import {getLinkedUsers, getUser} from "./users.be";
|
||||
@@ -71,9 +71,9 @@ export const getUsersGroups = async (ids: string[]) => {
|
||||
.toArray();
|
||||
};
|
||||
|
||||
export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
|
||||
const linkedTeachers = await getLinkedUsers(corporateID, "mastercorporate", "teacher");
|
||||
const linkedCorporates = await getLinkedUsers(corporateID, "mastercorporate", "corporate");
|
||||
export const getAllAssignersByCorporate = async (corporateID: string, type: Type): Promise<string[]> => {
|
||||
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher");
|
||||
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate");
|
||||
|
||||
return [...linkedTeachers.users.map((x) => x.id), ...linkedCorporates.users.map((x) => x.id)];
|
||||
};
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
|
||||
/*fields example = [
|
||||
['id'],
|
||||
['companyInformation', 'companyInformation', 'name']
|
||||
@@ -13,17 +12,17 @@ const getFieldValue = (fields: string[], data: any): string => {
|
||||
};
|
||||
|
||||
export const search = (text: string, fields: string[][], rows: any[]) => {
|
||||
const searchText = text.toLowerCase();
|
||||
return rows.filter((row) => {
|
||||
return fields.some((fieldsKeys) => {
|
||||
const value = getFieldValue(fieldsKeys, row);
|
||||
if (typeof value === "string") {
|
||||
return value.toLowerCase().includes(searchText);
|
||||
}
|
||||
const searchText = text.toLowerCase();
|
||||
return rows.filter((row) => {
|
||||
return fields.some((fieldsKeys) => {
|
||||
const value = getFieldValue(fieldsKeys, row);
|
||||
if (typeof value === "string") {
|
||||
return value.toLowerCase().includes(searchText);
|
||||
}
|
||||
|
||||
if (typeof value === "number") {
|
||||
return (value as Number).toString().includes(searchText);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if (typeof value === "number") {
|
||||
return (value as Number).toString().includes(searchText);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user