Compare commits
18 Commits
feature/tr
...
bugfix/mon
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3c1c4489f8 | ||
|
|
044ec8d966 | ||
|
|
07c9074d15 | ||
|
|
71bac76c3a | ||
|
|
fb293dc98c | ||
|
|
3ce97b4dcd | ||
|
|
7bfd000213 | ||
|
|
2a10933206 | ||
|
|
33a46c227b | ||
|
|
5153c3d5f1 | ||
|
|
85c8f622ee | ||
|
|
b9c097d42c | ||
|
|
192132559b | ||
|
|
392eac2ef9 | ||
|
|
a073ca1cce | ||
|
|
7e30ca5750 | ||
|
|
2e065eddcb | ||
|
|
4e91b2f1fb |
@@ -1,18 +1,8 @@
|
|||||||
/* 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";
|
||||||
@@ -40,11 +30,7 @@ import {
|
|||||||
} 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,
|
|
||||||
calculateAverageLevel,
|
|
||||||
calculateBandScore,
|
|
||||||
} from "@/utils/score";
|
|
||||||
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
import {MODULE_ARRAY} from "@/utils/moduleUtils";
|
||||||
import {Module} from "@/interfaces";
|
import {Module} from "@/interfaces";
|
||||||
import {groupByExam} from "@/utils/stats";
|
import {groupByExam} from "@/utils/stats";
|
||||||
@@ -64,16 +50,12 @@ 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;
|
||||||
@@ -98,36 +80,16 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
|
|
||||||
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,
|
|
||||||
isLoading: isAssignmentsLoading,
|
|
||||||
reload: reloadAssignments,
|
|
||||||
} = useAssignments({ corporate: user.id });
|
|
||||||
const {balance} = useUserBalance();
|
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(
|
||||||
() =>
|
() =>
|
||||||
@@ -137,28 +99,22 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
.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
|
|
||||||
src={displayUser.profilePicture}
|
|
||||||
alt={displayUser.name}
|
|
||||||
className="rounded-full w-10 h-10"
|
|
||||||
/>
|
|
||||||
<div className="flex flex-col gap-1 items-start">
|
<div className="flex flex-col gap-1 items-start">
|
||||||
<span>{displayUser.name}</span>
|
<span>{displayUser.name}</span>
|
||||||
<span className="text-sm opacity-75">{displayUser.email}</span>
|
<span className="text-sm opacity-75">{displayUser.email}</span>
|
||||||
@@ -166,59 +122,19 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
</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 GroupsList = () => {
|
||||||
const filter = (x: Group) =>
|
const filter = (x: Group) => x.admin === user.id || x.participants.includes(user.id);
|
||||||
x.admin === user.id || x.participants.includes(user.id);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<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">
|
<h2 className="text-2xl font-semibold">Groups ({groups.filter(filter).length})</h2>
|
||||||
Groups ({groups.filter(filter).length})
|
|
||||||
</h2>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<GroupList user={user} />
|
<GroupList user={user} />
|
||||||
@@ -236,12 +152,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
.filter((f) => !!f.focus);
|
.filter((f) => !!f.focus);
|
||||||
const bandScores = formattedStats.map((s) => ({
|
const bandScores = formattedStats.map((s) => ({
|
||||||
module: s.module,
|
module: s.module,
|
||||||
level: calculateBandScore(
|
level: calculateBandScore(s.score.correct, s.score.total, s.module, s.focus!),
|
||||||
s.score.correct,
|
|
||||||
s.score.total,
|
|
||||||
s.module,
|
|
||||||
s.focus!
|
|
||||||
),
|
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const levels: {[key in Module]: number} = {
|
const levels: {[key in Module]: number} = {
|
||||||
@@ -265,8 +176,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
<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>
|
||||||
@@ -285,8 +195,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
<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>
|
||||||
@@ -297,8 +206,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
);
|
);
|
||||||
|
|
||||||
if (router.asPath === "/#groups") return <GroupsList />;
|
if (router.asPath === "/#groups") return <GroupsList />;
|
||||||
if (router.asPath === "/#studentsPerformance")
|
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />;
|
||||||
return <StudentPerformancePage user={user} />;
|
|
||||||
|
|
||||||
if (router.asPath === "/#assignments")
|
if (router.asPath === "/#assignments")
|
||||||
return (
|
return (
|
||||||
@@ -312,7 +220,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
|
|
||||||
if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
|
if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -324,14 +232,11 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
loggedInUser={user}
|
loggedInUser={user}
|
||||||
onClose={(shouldReload) => {
|
onClose={(shouldReload) => {
|
||||||
setSelectedUser(undefined);
|
setSelectedUser(undefined);
|
||||||
if (shouldReload && selectedUser!.type === "student")
|
if (shouldReload && selectedUser!.type === "student") reloadStudents();
|
||||||
reloadStudents();
|
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers();
|
||||||
if (shouldReload && selectedUser!.type === "teacher")
|
|
||||||
reloadTeachers();
|
|
||||||
}}
|
}}
|
||||||
onViewStudents={
|
onViewStudents={
|
||||||
selectedUser.type === "corporate" ||
|
selectedUser.type === "corporate" || selectedUser.type === "teacher"
|
||||||
selectedUser.type === "teacher"
|
|
||||||
? () => {
|
? () => {
|
||||||
appendUserFilters({
|
appendUserFilters({
|
||||||
id: "view-students",
|
id: "view-students",
|
||||||
@@ -341,11 +246,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
id: "belongs-to-admin",
|
id: "belongs-to-admin",
|
||||||
filter: (x: User) =>
|
filter: (x: User) =>
|
||||||
groups
|
groups
|
||||||
.filter(
|
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||||
(g) =>
|
|
||||||
g.admin === selectedUser.id ||
|
|
||||||
g.participants.includes(selectedUser.id)
|
|
||||||
)
|
|
||||||
.flatMap((g) => g.participants)
|
.flatMap((g) => g.participants)
|
||||||
.includes(x.id),
|
.includes(x.id),
|
||||||
});
|
});
|
||||||
@@ -355,8 +256,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
: undefined
|
: undefined
|
||||||
}
|
}
|
||||||
onViewTeachers={
|
onViewTeachers={
|
||||||
selectedUser.type === "corporate" ||
|
selectedUser.type === "corporate" || selectedUser.type === "student"
|
||||||
selectedUser.type === "student"
|
|
||||||
? () => {
|
? () => {
|
||||||
appendUserFilters({
|
appendUserFilters({
|
||||||
id: "view-teachers",
|
id: "view-teachers",
|
||||||
@@ -366,11 +266,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
id: "belongs-to-admin",
|
id: "belongs-to-admin",
|
||||||
filter: (x: User) =>
|
filter: (x: User) =>
|
||||||
groups
|
groups
|
||||||
.filter(
|
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id))
|
||||||
(g) =>
|
|
||||||
g.admin === selectedUser.id ||
|
|
||||||
g.participants.includes(selectedUser.id)
|
|
||||||
)
|
|
||||||
.flatMap((g) => g.participants)
|
.flatMap((g) => g.participants)
|
||||||
.includes(x.id),
|
.includes(x.id),
|
||||||
});
|
});
|
||||||
@@ -389,11 +285,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
<>
|
<>
|
||||||
{!!linkedCorporate && (
|
{!!linkedCorporate && (
|
||||||
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
<div className="absolute top-4 right-4 bg-neutral-200 px-2 rounded-lg py-1">
|
||||||
Linked to:{" "}
|
Linked to: <b>{linkedCorporate?.corporateInformation?.companyInformation.name || linkedCorporate.name}</b>
|
||||||
<b>
|
|
||||||
{linkedCorporate?.corporateInformation?.companyInformation.name ||
|
|
||||||
linkedCorporate.name}
|
|
||||||
</b>
|
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
<section className="grid grid-cols-5 -md:grid-cols-2 gap-4 text-center">
|
||||||
@@ -416,47 +308,27 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
<IconCard
|
<IconCard
|
||||||
Icon={BsClipboard2Data}
|
Icon={BsClipboard2Data}
|
||||||
label="Exams Performed"
|
label="Exams Performed"
|
||||||
value={
|
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length}
|
||||||
stats.filter((s) =>
|
|
||||||
groups.flatMap((g) => g.participants).includes(s.user)
|
|
||||||
).length
|
|
||||||
}
|
|
||||||
color="purple"
|
color="purple"
|
||||||
/>
|
/>
|
||||||
<IconCard
|
<IconCard
|
||||||
Icon={BsPaperclip}
|
Icon={BsPaperclip}
|
||||||
isLoading={isStudentsLoading}
|
isLoading={isStudentsLoading}
|
||||||
label="Average Level"
|
label="Average Level"
|
||||||
value={averageLevelCalculator(
|
value={averageLevelCalculator(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)}
|
||||||
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"
|
color="purple"
|
||||||
/>
|
/>
|
||||||
|
<IconCard onClick={() => router.push("/#groups")} Icon={BsPeople} label="Groups" value={groups.length} color="purple" />
|
||||||
<IconCard
|
<IconCard
|
||||||
Icon={BsPersonCheck}
|
Icon={BsPersonCheck}
|
||||||
label="User Balance"
|
label="User Balance"
|
||||||
value={`${balance}/${
|
value={`${balance}/${user.corporateInformation?.companyInformation?.userAmount || 0}`}
|
||||||
user.corporateInformation?.companyInformation?.userAmount || 0
|
|
||||||
}`}
|
|
||||||
color="purple"
|
color="purple"
|
||||||
/>
|
/>
|
||||||
<IconCard
|
<IconCard
|
||||||
Icon={BsClock}
|
Icon={BsClock}
|
||||||
label="Expiration Date"
|
label="Expiration Date"
|
||||||
value={
|
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"}
|
||||||
user.subscriptionExpirationDate
|
|
||||||
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
|
|
||||||
: "Unlimited"
|
|
||||||
}
|
|
||||||
color="rose"
|
color="rose"
|
||||||
/>
|
/>
|
||||||
<IconCard
|
<IconCard
|
||||||
@@ -467,24 +339,16 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
color="purple"
|
color="purple"
|
||||||
onClick={() => router.push("/#studentsPerformance")}
|
onClick={() => router.push("/#studentsPerformance")}
|
||||||
/>
|
/>
|
||||||
<IconCard
|
<IconCard Icon={BsDatabase} label="Master Statistical" color="purple" onClick={() => router.push("/#statistical")} />
|
||||||
Icon={BsDatabase}
|
|
||||||
label="Master Statistical"
|
|
||||||
color="purple"
|
|
||||||
onClick={() => router.push("/#statistical")}
|
|
||||||
/>
|
|
||||||
<button
|
<button
|
||||||
disabled={isAssignmentsLoading}
|
disabled={isAssignmentsLoading}
|
||||||
onClick={() => router.push("/#assignments")}
|
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"
|
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" />
|
<BsEnvelopePaper className="text-6xl text-mti-purple-light" />
|
||||||
<span className="flex flex-col gap-1 items-center text-xl">
|
<span className="flex flex-col gap-1 items-center text-xl">
|
||||||
<span className="text-lg">Assignments</span>
|
<span className="text-lg">Assignments</span>
|
||||||
<span className="font-semibold text-mti-purple-light">
|
<span className="font-semibold text-mti-purple-light">
|
||||||
{isAssignmentsLoading
|
{isAssignmentsLoading ? "Loading..." : assignments.filter((a) => !a.archived).length}
|
||||||
? "Loading..."
|
|
||||||
: assignments.filter((a) => !a.archived).length}
|
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</button>
|
</button>
|
||||||
@@ -515,11 +379,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
<span className="p-4">Highest level students</span>
|
<span className="p-4">Highest level students</span>
|
||||||
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
<div className="flex flex-col items-start h-96 overflow-scroll scrollbar-hide">
|
||||||
{students
|
{students
|
||||||
.sort(
|
.sort((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels))
|
||||||
(a, b) =>
|
|
||||||
calculateAverageLevel(b.levels) -
|
|
||||||
calculateAverageLevel(a.levels)
|
|
||||||
)
|
|
||||||
.map((x) => (
|
.map((x) => (
|
||||||
<UserDisplay key={x.id} {...x} />
|
<UserDisplay key={x.id} {...x} />
|
||||||
))}
|
))}
|
||||||
@@ -531,8 +391,7 @@ export default function CorporateDashboard({ user, linkedCorporate }: Props) {
|
|||||||
{students
|
{students
|
||||||
.sort(
|
.sort(
|
||||||
(a, b) =>
|
(a, b) =>
|
||||||
Object.keys(groupByExam(getStatsByStudent(b))).length -
|
Object.keys(groupByExam(getStatsByStudent(b))).length - Object.keys(groupByExam(getStatsByStudent(a))).length,
|
||||||
Object.keys(groupByExam(getStatsByStudent(a))).length
|
|
||||||
)
|
)
|
||||||
.map((x) => (
|
.map((x) => (
|
||||||
<UserDisplay key={x.id} {...x} />
|
<UserDisplay key={x.id} {...x} />
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import React, {useEffect, useMemo, useState} from "react";
|
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 {BsFileExcel, BsBank, BsPersonFill} from "react-icons/bs";
|
||||||
import IconCard from "../IconCard";
|
import IconCard from "../IconCard";
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ interface Props {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface TableData {
|
interface TableData {
|
||||||
user: string;
|
user: User | undefined;
|
||||||
email: string;
|
email: string;
|
||||||
correct: number;
|
correct: number;
|
||||||
corporate: string;
|
corporate: string;
|
||||||
@@ -62,7 +62,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
const [startDate, setStartDate] = React.useState<Date | null>(moment("01/01/2023").toDate());
|
const [startDate, setStartDate] = React.useState<Date | null>(moment("01/01/2023").toDate());
|
||||||
const [endDate, setEndDate] = React.useState<Date | null>(moment().endOf("year").toDate());
|
const [endDate, setEndDate] = React.useState<Date | null>(moment().endOf("year").toDate());
|
||||||
|
|
||||||
const {assignments} = useAssignmentsCorporates({
|
const {assignments, isLoading} = useAssignmentsCorporates({
|
||||||
corporates: selectedCorporates,
|
corporates: selectedCorporates,
|
||||||
startDate,
|
startDate,
|
||||||
endDate,
|
endDate,
|
||||||
@@ -74,11 +74,11 @@ 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);
|
||||||
|
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?.name || "N/A",
|
user: userData,
|
||||||
email: userData?.email || "N/A",
|
email: userData?.email || "N/A",
|
||||||
userId: assignee,
|
userId: assignee,
|
||||||
corporateId: a.corporateId,
|
corporateId: a.corporateId,
|
||||||
@@ -86,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,
|
||||||
@@ -108,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);
|
||||||
|
|
||||||
@@ -151,7 +150,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
header: "User",
|
header: "User",
|
||||||
id: "user",
|
id: "user",
|
||||||
cell: (info) => {
|
cell: (info) => {
|
||||||
return <span>{info.getValue()}</span>;
|
return <span>{info.getValue()?.name || "N/A"}</span>;
|
||||||
},
|
},
|
||||||
}),
|
}),
|
||||||
columnHelper.accessor("email", {
|
columnHelper.accessor("email", {
|
||||||
@@ -161,6 +160,13 @@ const MasterStatistical = (props: Props) => {
|
|||||||
return <span>{info.getValue()}</span>;
|
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
|
...(displaySelection
|
||||||
? [
|
? [
|
||||||
columnHelper.accessor("corporate", {
|
columnHelper.accessor("corporate", {
|
||||||
@@ -281,6 +287,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
<IconCard
|
<IconCard
|
||||||
Icon={BsBank}
|
Icon={BsBank}
|
||||||
label="Consolidate"
|
label="Consolidate"
|
||||||
|
isLoading={isLoading}
|
||||||
value={getConsolidateScoreStr(consolidateScore)}
|
value={getConsolidateScoreStr(consolidateScore)}
|
||||||
color="purple"
|
color="purple"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
@@ -302,6 +309,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
<IconCard
|
<IconCard
|
||||||
key={corporateName}
|
key={corporateName}
|
||||||
Icon={BsBank}
|
Icon={BsBank}
|
||||||
|
isLoading={isLoading}
|
||||||
label={corporateName}
|
label={corporateName}
|
||||||
value={value}
|
value={value}
|
||||||
color="purple"
|
color="purple"
|
||||||
@@ -343,7 +351,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
</div>
|
</div>
|
||||||
{renderSearch()}
|
{renderSearch()}
|
||||||
<div className="flex flex-col gap-3 justify-end">
|
<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
|
Download
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
@@ -359,7 +367,7 @@ const MasterStatistical = (props: Props) => {
|
|||||||
{page * SIZE + 1} - {(page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE} /{" "}
|
{page * SIZE + 1} - {(page + 1) * SIZE > filteredRows.length ? filteredRows.length : (page + 1) * SIZE} /{" "}
|
||||||
{filteredRows.length}
|
{filteredRows.length}
|
||||||
</span>
|
</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
|
Next Page
|
||||||
</Button>
|
</Button>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -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={() => {
|
||||||
|
|||||||
@@ -287,7 +287,9 @@ export default function Finish({user, scores, modules, information, solutions, i
|
|||||||
<div className="flex w-fit cursor-pointer flex-col items-center gap-1">
|
<div className="flex w-fit cursor-pointer flex-col items-center gap-1">
|
||||||
<button
|
<button
|
||||||
onClick={() => window.location.reload()}
|
onClick={() => window.location.reload()}
|
||||||
disabled={user.type === "admin"}
|
// disabled={user.type === "admin"}
|
||||||
|
// TODO: temporarily disabled
|
||||||
|
disabled
|
||||||
className="bg-mti-purple-light hover:bg-mti-purple flex h-11 w-11 items-center justify-center rounded-full transition duration-300 ease-in-out">
|
className="bg-mti-purple-light hover:bg-mti-purple flex h-11 w-11 items-center justify-center rounded-full transition duration-300 ease-in-out">
|
||||||
<BsArrowCounterclockwise className="h-7 w-7 text-white" />
|
<BsArrowCounterclockwise className="h-7 w-7 text-white" />
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -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};
|
||||||
|
}
|
||||||
@@ -9,7 +9,7 @@ export const userHashStudent = {type: "student"} as {type: Type};
|
|||||||
export const userHashTeacher = {type: "teacher"} as {type: Type};
|
export const userHashTeacher = {type: "teacher"} as {type: Type};
|
||||||
export const userHashCorporate = {type: "corporate"} as {type: Type};
|
export const userHashCorporate = {type: "corporate"} as {type: Type};
|
||||||
|
|
||||||
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc", searchTerm?: string | undefined}) {
|
export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc"}) {
|
||||||
const [users, setUsers] = useState<User[]>([]);
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
@@ -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"}})
|
||||||
@@ -35,7 +33,7 @@ export default function useUsers(props?: {type?: string; page?: number; size?: n
|
|||||||
.finally(() => setIsLoading(false));
|
.finally(() => setIsLoading(false));
|
||||||
};
|
};
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction, props?.searchTerm]);
|
useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction]);
|
||||||
|
|
||||||
return {users, total, isLoading, isError, reload: getData};
|
return {users, total, isLoading, isError, reload: getData};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,7 +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 Input from "@/components/Low/Input";
|
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"]];
|
||||||
|
|
||||||
@@ -63,11 +63,15 @@ 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 [searchTerm, setSearchTerm] = useState<string | undefined>(undefined);
|
|
||||||
|
|
||||||
const { users, total, isLoading, reload } = useUsers({type: type, size: 16, page: page, searchTerm: searchTerm});
|
const userHash = useMemo(
|
||||||
|
() => ({
|
||||||
|
type,
|
||||||
|
}),
|
||||||
|
[type],
|
||||||
|
);
|
||||||
|
|
||||||
|
const {users, total, isLoading, reload} = useUsers(userHash);
|
||||||
const {users: corporates} = useUsers(corporatesHash);
|
const {users: corporates} = useUsers(corporatesHash);
|
||||||
|
|
||||||
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
const totalUsers = useMemo(() => [...users, ...corporates], [users, corporates]);
|
||||||
@@ -96,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
|
||||||
@@ -137,7 +141,8 @@ export default function UserList({
|
|||||||
const toggleDisableAccount = (user: User) => {
|
const toggleDisableAccount = (user: User) => {
|
||||||
if (
|
if (
|
||||||
!confirm(
|
!confirm(
|
||||||
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${user.name
|
`Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${
|
||||||
|
user.name
|
||||||
}'s account? This change is usually related to their payment state.`,
|
}'s account? This change is usually related to their payment state.`,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -231,7 +236,8 @@ export default function UserList({
|
|||||||
) as any,
|
) as any,
|
||||||
cell: (info) =>
|
cell: (info) =>
|
||||||
info.getValue()
|
info.getValue()
|
||||||
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
|
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${
|
||||||
|
countries[info.getValue() as unknown as keyof TCountries]?.name
|
||||||
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
} (+${countryCodes.findOne("countryCode" as any, info.getValue())?.countryCallingCode})`
|
||||||
: "N/A",
|
: "N/A",
|
||||||
}),
|
}),
|
||||||
@@ -505,14 +511,20 @@ export default function UserList({
|
|||||||
return a.id.localeCompare(b.id);
|
return a.id.localeCompare(b.id);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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: displayUsers,
|
data: items,
|
||||||
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
|
||||||
getCoreRowModel: getCoreRowModel(),
|
getCoreRowModel: getCoreRowModel(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const downloadExcel = () => {
|
const downloadExcel = () => {
|
||||||
const csv = exportListToExcel(displayUsers, users, groups);
|
const csv = exportListToExcel(filteredRows, users, groups);
|
||||||
|
|
||||||
const element = document.createElement("a");
|
const element = document.createElement("a");
|
||||||
const file = new Blob([csv], {type: "text/csv"});
|
const file = new Blob([csv], {type: "text/csv"});
|
||||||
@@ -617,32 +629,12 @@ export default function UserList({
|
|||||||
</Modal>
|
</Modal>
|
||||||
<div className="w-full flex flex-col gap-2">
|
<div className="w-full flex flex-col gap-2">
|
||||||
<div className="w-full flex gap-2 items-end">
|
<div className="w-full flex gap-2 items-end">
|
||||||
<Input label="Search" type="text" name="search" onChange={setSearchTerm} placeholder="Enter search text" value={searchTerm} />
|
{renderSearch()}
|
||||||
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
<Button className="w-full max-w-[200px] mb-1" variant="outline" onClick={downloadExcel}>
|
||||||
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});
|
||||||
|
|||||||
@@ -11,14 +11,21 @@ import { checkAccess } from "@/utils/permissions";
|
|||||||
import {getAssignmentsForCorporates} from "@/utils/assignments.be";
|
import {getAssignmentsForCorporates} from "@/utils/assignments.be";
|
||||||
import {search} from "@/utils/search";
|
import {search} from "@/utils/search";
|
||||||
import {getGradingSystem} from "@/utils/grading.be";
|
import {getGradingSystem} from "@/utils/grading.be";
|
||||||
import { 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;
|
||||||
|
passportID: string;
|
||||||
|
exams: string;
|
||||||
email: string;
|
email: string;
|
||||||
correct: number;
|
correct: number;
|
||||||
corporate: string;
|
corporate: string;
|
||||||
@@ -40,14 +47,12 @@ 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
|
||||||
if (req.session.user) {
|
if (req.session.user) {
|
||||||
if (
|
if (!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])) {
|
||||||
!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])
|
|
||||||
) {
|
|
||||||
return res.status(403).json({error: "Unauthorized"});
|
return res.status(403).json({error: "Unauthorized"});
|
||||||
}
|
}
|
||||||
const {
|
const {
|
||||||
@@ -65,25 +70,20 @@ 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(
|
const assignments = await getAssignmentsForCorporates(req.session.user.type, ids, startDateParsed, endDateParsed);
|
||||||
ids,
|
|
||||||
startDateParsed,
|
|
||||||
endDateParsed
|
|
||||||
);
|
|
||||||
|
|
||||||
const assignmentUsers = [
|
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]);
|
||||||
...new Set(assignments.flatMap((a) => a.assignees)),
|
|
||||||
];
|
|
||||||
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) => {
|
||||||
const data = await getGradingSystem(user);
|
const data = await getGradingSystem(user);
|
||||||
// in this context I need to override as I'll have to match to the assigner
|
// in this context I need to override as I'll have to match to the assigner
|
||||||
return {...data, user: user.id};
|
return {...data, user: user.id};
|
||||||
})
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
const getGradingSystemHelper = (
|
const getGradingSystemHelper = (
|
||||||
@@ -91,21 +91,14 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
assigner: string,
|
assigner: string,
|
||||||
user: User,
|
user: User,
|
||||||
correct: number,
|
correct: number,
|
||||||
total: number
|
total: number,
|
||||||
) => {
|
) => {
|
||||||
if (exams.some((e) => e.module === "level")) {
|
if (exams.some((e) => e.module === "level")) {
|
||||||
const gradingSystem = assignerUsersGradingSystems.find(
|
const gradingSystem = assignerUsersGradingSystems.find((gs) => gs.user === assigner);
|
||||||
(gs) => gs.user === assigner
|
|
||||||
);
|
|
||||||
if (gradingSystem) {
|
if (gradingSystem) {
|
||||||
const bandScore = calculateBandScore(
|
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic");
|
||||||
correct,
|
|
||||||
total,
|
|
||||||
"level",
|
|
||||||
user.focus
|
|
||||||
);
|
|
||||||
return {
|
return {
|
||||||
label: getGradingLabel(bandScore, gradingSystem?.steps || []),
|
label: getGradingLabel(bandScore, gradingSystem.steps || []),
|
||||||
score: bandScore,
|
score: bandScore,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -117,27 +110,22 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const tableResults = assignments
|
const tableResults = assignments
|
||||||
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
.reduce((accmA: TableData[], a: AssignmentWithCorporateId) => {
|
||||||
const userResults = a.assignees.map((assignee) => {
|
const userResults = a.assignees.map((assignee) => {
|
||||||
const userStats =
|
const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
|
||||||
a.results.find((r) => r.user === assignee)?.stats || [];
|
|
||||||
const userData = users.find((u) => u.id === assignee);
|
const userData = users.find((u) => u.id === assignee);
|
||||||
const corporateUser = users.find((u) => u.id === a.assigner);
|
const corporateUser = users.find((u) => u.id === a.assigner);
|
||||||
const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
|
const correct = userStats.reduce((n, e) => n + e.score.correct, 0);
|
||||||
const total = userStats.reduce((n, e) => n + e.score.total, 0);
|
const total = userStats.reduce((n, e) => n + e.score.total, 0);
|
||||||
const { label: level, score } = getGradingSystemHelper(
|
const {label: level, score} = getGradingSystemHelper(a.exams, a.assigner, userData!, correct, total);
|
||||||
a.exams,
|
|
||||||
a.assigner,
|
|
||||||
userData!,
|
|
||||||
correct,
|
|
||||||
total
|
|
||||||
);
|
|
||||||
|
|
||||||
console.log("Level", level);
|
|
||||||
const commonData = {
|
const commonData = {
|
||||||
user: userData?.name || "",
|
user: userData?.name || "",
|
||||||
email: userData?.email || "",
|
email: userData?.email || "",
|
||||||
|
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,
|
||||||
@@ -151,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,
|
||||||
@@ -186,6 +182,14 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
label: "Email",
|
label: "Email",
|
||||||
value: (entry: TableData) => entry.email,
|
value: (entry: TableData) => entry.email,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
label: "Student ID",
|
||||||
|
value: (entry: TableData) => entry.studentID,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Passport ID",
|
||||||
|
value: (entry: TableData) => entry.passportID,
|
||||||
|
},
|
||||||
...(displaySelection
|
...(displaySelection
|
||||||
? [
|
? [
|
||||||
{
|
{
|
||||||
@@ -203,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,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -223,9 +227,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
})),
|
})),
|
||||||
];
|
];
|
||||||
|
|
||||||
const filteredSearch = searchText
|
const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults;
|
||||||
? 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) => {
|
||||||
@@ -241,8 +243,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const fileRef = ref(storage, refName);
|
const fileRef = ref(storage, refName);
|
||||||
// upload the pdf to storage
|
// upload the pdf to storage
|
||||||
await uploadBytes(fileRef, buffer, {
|
await uploadBytes(fileRef, buffer, {
|
||||||
contentType:
|
contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const url = await getDownloadURL(fileRef);
|
const url = await getDownloadURL(fileRef);
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
await db.collection("stats").updateOne(
|
await db.collection("stats").updateOne(
|
||||||
{ id: (req.body as Body).id },
|
{ id: (req.body as Body).id },
|
||||||
{
|
{
|
||||||
|
$set: {
|
||||||
id: (req.body as Body).id,
|
id: (req.body as Body).id,
|
||||||
solutions,
|
solutions,
|
||||||
score: {
|
score: {
|
||||||
@@ -48,6 +49,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
missing: 0,
|
missing: 0,
|
||||||
},
|
},
|
||||||
isDisabled: false,
|
isDisabled: false,
|
||||||
|
}
|
||||||
},
|
},
|
||||||
{ upsert: true },
|
{ upsert: true },
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -72,6 +72,9 @@ async function registerIndividual(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
...(passport_id ? {demographicInformation: {passport_id}} : {}),
|
||||||
registrationDate: new Date().toISOString(),
|
registrationDate: new Date().toISOString(),
|
||||||
status: code ? "active" : "paymentDue",
|
status: code ? "active" : "paymentDue",
|
||||||
|
// apparently there's an issue with the verification email system
|
||||||
|
// therefore we will skip this requirement for now
|
||||||
|
isVerified: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
await db.collection("users").insertOne(user);
|
await db.collection("users").insertOne(user);
|
||||||
@@ -117,6 +120,9 @@ async function registerCorporate(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
subscriptionExpirationDate: req.body.subscriptionExpirationDate || null,
|
subscriptionExpirationDate: req.body.subscriptionExpirationDate || null,
|
||||||
status: "paymentDue",
|
status: "paymentDue",
|
||||||
registrationDate: new Date().toISOString(),
|
registrationDate: new Date().toISOString(),
|
||||||
|
// apparently there's an issue with the verification email system
|
||||||
|
// therefore we will skip this requirement for now
|
||||||
|
isVerified: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
const defaultTeachersGroup: Group = {
|
const defaultTeachersGroup: Group = {
|
||||||
|
|||||||
@@ -16,5 +16,5 @@ async function GET(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
const snapshot = await db.collection("stats").findOne({ id: id as string});
|
const snapshot = await db.collection("stats").findOne({ id: id as string});
|
||||||
if (!snapshot) return res.status(404).json({id: id as string});
|
if (!snapshot) return res.status(404).json({id: id as string});
|
||||||
|
|
||||||
res.status(200).json({...snapshot.data(), id: snapshot.id});
|
res.status(200).json({...snapshot, id: snapshot.id});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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);
|
||||||
|
|
||||||
@@ -19,8 +20,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
page,
|
page,
|
||||||
orderBy,
|
orderBy,
|
||||||
direction = "desc",
|
direction = "desc",
|
||||||
searchTerm
|
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"};
|
||||||
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"; searchTerm?: string | undefined};
|
|
||||||
|
|
||||||
const {users, total} = await getLinkedUsers(
|
const {users, total} = await getLinkedUsers(
|
||||||
req.session.user?.id,
|
req.session.user?.id,
|
||||||
@@ -30,8 +30,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
size !== undefined ? parseInt(size) : undefined,
|
size !== undefined ? parseInt(size) : undefined,
|
||||||
orderBy,
|
orderBy,
|
||||||
direction,
|
direction,
|
||||||
searchTerm
|
|
||||||
);
|
);
|
||||||
|
|
||||||
res.status(200).json({users, total});
|
res.status(200).json({users: uniqBy([...users], "id"), total});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -158,7 +158,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
delete updatedUser.password;
|
delete updatedUser.password;
|
||||||
delete updatedUser.newPassword;
|
delete updatedUser.newPassword;
|
||||||
|
|
||||||
await db.collection("users").updateOne({id: queryId}, {$set: updatedUser});
|
await db.collection("users").updateOne({id: queryId ? (queryId as string) : req.session.user.id}, {$set: updatedUser});
|
||||||
|
|
||||||
if (!queryId) {
|
if (!queryId) {
|
||||||
req.session.user = updatedUser ? {...updatedUser, id: req.session.user.id} : null;
|
req.session.user = updatedUser ? {...updatedUser, id: req.session.user.id} : null;
|
||||||
@@ -169,7 +169,7 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
|
|||||||
await managePaymentRecords({...updatedUser, id: req.session.user!.id}, queryId);
|
await managePaymentRecords({...updatedUser, id: req.session.user!.id}, queryId);
|
||||||
}
|
}
|
||||||
|
|
||||||
res.status(200).json({user: {...updatedUser, id: req.session.user!.id}});
|
res.status(200).json({user: {...updatedUser, ...user, id: req.session.user!.id}});
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export default function Home({user: propsUser, linkedCorporate}: Props) {
|
|||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (user) {
|
if (user) {
|
||||||
// setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
|
setShowDemographicInput(!user.demographicInformation || !user.demographicInformation.country || !user.demographicInformation.phone);
|
||||||
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
setShowDiagnostics(user.isFirstLogin && user.type === "student");
|
||||||
}
|
}
|
||||||
}, [user]);
|
}, [user]);
|
||||||
|
|||||||
@@ -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']
|
||||||
@@ -26,4 +25,4 @@ export const search = (text: string, fields: string[][], rows: any[]) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
};
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ import client from "@/lib/mongodb";
|
|||||||
const db = client.db(process.env.MONGODB_DB);
|
const db = client.db(process.env.MONGODB_DB);
|
||||||
|
|
||||||
export async function getUsers() {
|
export async function getUsers() {
|
||||||
return await db.collection("users").find<User>({}).toArray();
|
return await db.collection("users").find<User>({}, { projection: { _id: 0 } }).toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getUser(id: string): Promise<User | undefined> {
|
export async function getUser(id: string): Promise<User | undefined> {
|
||||||
const user = await db.collection("users").findOne<User>({ id });
|
const user = await db.collection("users").findOne<User>({id: id}, { projection: { _id: 0 } });
|
||||||
return !!user ? user : undefined;
|
return !!user ? user : undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -21,7 +21,7 @@ export async function getSpecificUsers(ids: string[]) {
|
|||||||
|
|
||||||
return await db
|
return await db
|
||||||
.collection("users")
|
.collection("users")
|
||||||
.find<User>({ id: { $in: ids } })
|
.find<User>({id: {$in: ids}}, { projection: { _id: 0 } })
|
||||||
.toArray();
|
.toArray();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -33,21 +33,10 @@ export async function getLinkedUsers(
|
|||||||
size?: number,
|
size?: number,
|
||||||
sort?: string,
|
sort?: string,
|
||||||
direction?: "asc" | "desc",
|
direction?: "asc" | "desc",
|
||||||
searchTerm?: string | undefined,
|
|
||||||
) {
|
) {
|
||||||
const filters: any = {};
|
const filters = {
|
||||||
|
...(!!type ? {type} : {}),
|
||||||
if (type) {
|
};
|
||||||
filters.type = type;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (searchTerm) {
|
|
||||||
filters.$or = [
|
|
||||||
{ name: { $regex: searchTerm, $options: 'i' } },
|
|
||||||
{ email: { $regex: searchTerm, $options: 'i' } },
|
|
||||||
{ company: { $regex: searchTerm, $options: 'i' } },
|
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!userID || userType === "admin" || userType === "developer") {
|
if (!userID || userType === "admin" || userType === "developer") {
|
||||||
const users = await db
|
const users = await db
|
||||||
|
|||||||
Reference in New Issue
Block a user