Compare commits

..

3 Commits

Author SHA1 Message Date
carlos.mesquita
22209ee1c1 Merged main into feature/training-content 2024-09-09 00:40:36 +00:00
Carlos Mesquita
0e2f53db0a Search on user list with mongo search query 2024-09-09 01:38:11 +01:00
Carlos Mesquita
9177a6b2ac Pagination on UserList 2024-09-09 01:22:13 +01:00
22 changed files with 907 additions and 814 deletions

View File

@@ -1,8 +1,18 @@
/* 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, {userHashStudent, userHashTeacher, userHashCorporate} from "@/hooks/useUsers"; import useUsers, {
import {CorporateUser, Group, MasterCorporateUser, Stat, User} from "@/interfaces/user"; userHashStudent,
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";
@@ -30,7 +40,11 @@ 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 {averageLevelCalculator, calculateAverageLevel, calculateBandScore} from "@/utils/score"; import {
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";
@@ -50,12 +64,16 @@ 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 {futureAssignmentFilter, pastAssignmentFilter, archivedAssignmentFilter, activeAssignmentFilter} from "@/utils/assignments"; import {
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;
@@ -80,16 +98,36 @@ 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 {assignments, isLoading: isAssignmentsLoading, reload: reloadAssignments} = useAssignments({corporate: user.id}); const {
assignments,
isLoading: isAssignmentsLoading,
reload: reloadAssignments,
} = useAssignments({ corporate: user.id });
const { balance } = useUserBalance(); const { balance } = useUserBalance();
const {users: students, total: totalStudents, reload: reloadStudents, isLoading: isStudentsLoading} = useUsers(studentHash); const {
const {users: teachers, total: totalTeachers, reload: reloadTeachers, isLoading: isTeachersLoading} = useUsers(teacherHash); 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 appendUserFilters = useFilterStore((state) => state.appendUserFilter);
const router = useRouter(); 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( const assignmentsUsers = useMemo(
() => () =>
@@ -99,22 +137,28 @@ 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) => stats.filter((s) => s.user === user.id); const getStatsByStudent = (user: User) =>
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>
@@ -122,19 +166,59 @@ 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) => x.admin === user.id || x.participants.includes(user.id); const filter = (x: Group) =>
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">Groups ({groups.filter(filter).length})</h2> <h2 className="text-2xl font-semibold">
Groups ({groups.filter(filter).length})
</h2>
</div> </div>
<GroupList user={user} /> <GroupList user={user} />
@@ -152,7 +236,12 @@ 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(s.score.correct, s.score.total, s.module, s.focus!), level: calculateBandScore(
s.score.correct,
s.score.total,
s.module,
s.focus!
),
})); }));
const levels: { [key in Module]: number } = { const levels: { [key in Module]: number } = {
@@ -176,7 +265,8 @@ 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>
@@ -195,7 +285,8 @@ 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>
@@ -206,7 +297,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
); );
if (router.asPath === "/#groups") return <GroupsList />; if (router.asPath === "/#groups") return <GroupsList />;
if (router.asPath === "/#studentsPerformance") return <StudentPerformancePage user={user} />; if (router.asPath === "/#studentsPerformance")
return <StudentPerformancePage user={user} />;
if (router.asPath === "/#assignments") if (router.asPath === "/#assignments")
return ( return (
@@ -220,7 +312,7 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
/> />
); );
if (router.asPath === "/#statistical") return <MasterStatisticalPage user={user} />; if (router.asPath === "/#statistical") return <MasterStatisticalPage />;
return ( return (
<> <>
@@ -232,11 +324,14 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
loggedInUser={user} loggedInUser={user}
onClose={(shouldReload) => { onClose={(shouldReload) => {
setSelectedUser(undefined); setSelectedUser(undefined);
if (shouldReload && selectedUser!.type === "student") reloadStudents(); if (shouldReload && selectedUser!.type === "student")
if (shouldReload && selectedUser!.type === "teacher") reloadTeachers(); reloadStudents();
if (shouldReload && selectedUser!.type === "teacher")
reloadTeachers();
}} }}
onViewStudents={ onViewStudents={
selectedUser.type === "corporate" || selectedUser.type === "teacher" selectedUser.type === "corporate" ||
selectedUser.type === "teacher"
? () => { ? () => {
appendUserFilters({ appendUserFilters({
id: "view-students", id: "view-students",
@@ -246,7 +341,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
id: "belongs-to-admin", id: "belongs-to-admin",
filter: (x: User) => filter: (x: User) =>
groups groups
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id)) .filter(
(g) =>
g.admin === selectedUser.id ||
g.participants.includes(selectedUser.id)
)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(x.id), .includes(x.id),
}); });
@@ -256,7 +355,8 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
: undefined : undefined
} }
onViewTeachers={ onViewTeachers={
selectedUser.type === "corporate" || selectedUser.type === "student" selectedUser.type === "corporate" ||
selectedUser.type === "student"
? () => { ? () => {
appendUserFilters({ appendUserFilters({
id: "view-teachers", id: "view-teachers",
@@ -266,7 +366,11 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
id: "belongs-to-admin", id: "belongs-to-admin",
filter: (x: User) => filter: (x: User) =>
groups groups
.filter((g) => g.admin === selectedUser.id || g.participants.includes(selectedUser.id)) .filter(
(g) =>
g.admin === selectedUser.id ||
g.participants.includes(selectedUser.id)
)
.flatMap((g) => g.participants) .flatMap((g) => g.participants)
.includes(x.id), .includes(x.id),
}); });
@@ -285,7 +389,11 @@ 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: <b>{linkedCorporate?.corporateInformation?.companyInformation.name || linkedCorporate.name}</b> Linked to:{" "}
<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">
@@ -308,27 +416,47 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
<IconCard <IconCard
Icon={BsClipboard2Data} Icon={BsClipboard2Data}
label="Exams Performed" label="Exams Performed"
value={stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user)).length} value={
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(stats.filter((s) => groups.flatMap((g) => g.participants).includes(s.user))).toFixed(1)} 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" 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}/${user.corporateInformation?.companyInformation?.userAmount || 0}`} value={`${balance}/${
user.corporateInformation?.companyInformation?.userAmount || 0
}`}
color="purple" color="purple"
/> />
<IconCard <IconCard
Icon={BsClock} Icon={BsClock}
label="Expiration Date" label="Expiration Date"
value={user.subscriptionExpirationDate ? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy") : "Unlimited"} value={
user.subscriptionExpirationDate
? moment(user.subscriptionExpirationDate).format("DD/MM/yyyy")
: "Unlimited"
}
color="rose" color="rose"
/> />
<IconCard <IconCard
@@ -339,16 +467,24 @@ export default function CorporateDashboard({user, linkedCorporate}: Props) {
color="purple" color="purple"
onClick={() => router.push("/#studentsPerformance")} onClick={() => router.push("/#studentsPerformance")}
/> />
<IconCard Icon={BsDatabase} label="Master Statistical" color="purple" onClick={() => router.push("/#statistical")} /> <IconCard
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 ? "Loading..." : assignments.filter((a) => !a.archived).length} {isAssignmentsLoading
? "Loading..."
: assignments.filter((a) => !a.archived).length}
</span> </span>
</span> </span>
</button> </button>
@@ -379,7 +515,11 @@ 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((a, b) => calculateAverageLevel(b.levels) - calculateAverageLevel(a.levels)) .sort(
(a, b) =>
calculateAverageLevel(b.levels) -
calculateAverageLevel(a.levels)
)
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />
))} ))}
@@ -391,7 +531,8 @@ 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(a))).length, Object.keys(groupByExam(getStatsByStudent(b))).length -
Object.keys(groupByExam(getStatsByStudent(a))).length
) )
.map((x) => ( .map((x) => (
<UserDisplay key={x.id} {...x} /> <UserDisplay key={x.id} {...x} />

View File

@@ -1,5 +1,5 @@
import React, {useEffect, useMemo, useState} from "react"; import React, {useEffect, useMemo, useState} from "react";
import {CorporateUser, StudentUser, User} from "@/interfaces/user"; import {CorporateUser, 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: User | undefined; user: string;
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, isLoading} = useAssignmentsCorporates({ const {assignments} = 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 userData = users.find((u) => u.id === assignee);
const userStats = a.results.find((r) => r.user === assignee)?.stats || []; const userStats = a.results.find((r) => r.user === assignee)?.stats || [];
const userData = users.find((u) => u.id === assignee);
const corporate = getUserName(users.find((u) => u.id === a.assigner)); const corporate = getUserName(users.find((u) => u.id === a.assigner));
const commonData = { const commonData = {
user: userData, user: userData?.name || "N/A",
email: userData?.email || "N/A", email: userData?.email || "N/A",
userId: assignee, userId: assignee,
corporateId: a.corporateId, corporateId: a.corporateId,
@@ -86,7 +86,6 @@ const MasterStatistical = (props: Props) => {
corporate, corporate,
assignment: a.name, assignment: a.name,
}; };
if (userStats.length === 0) { if (userStats.length === 0) {
return { return {
...commonData, ...commonData,
@@ -109,6 +108,8 @@ 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);
@@ -150,7 +151,7 @@ const MasterStatistical = (props: Props) => {
header: "User", header: "User",
id: "user", id: "user",
cell: (info) => { cell: (info) => {
return <span>{info.getValue()?.name || "N/A"}</span>; return <span>{info.getValue()}</span>;
}, },
}), }),
columnHelper.accessor("email", { columnHelper.accessor("email", {
@@ -160,13 +161,6 @@ 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", {
@@ -287,7 +281,6 @@ 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={() => {
@@ -309,7 +302,6 @@ 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"
@@ -351,7 +343,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="w-[200px] h-[70px]" variant="outline" isLoading={downloading} onClick={triggerDownload}> <Button className="max-w-[200px] h-[70px]" variant="outline" onClick={triggerDownload}>
Download Download
</Button> </Button>
</div> </div>
@@ -367,7 +359,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 >= filteredRows.length} onClick={() => setPage((prev) => prev + 1)}> <Button className="w-[200px]" disabled={(page + 1) * SIZE >= rows.length} onClick={() => setPage((prev) => prev + 1)}>
Next Page Next Page
</Button> </Button>
</div> </div>

View File

@@ -55,7 +55,7 @@ export default function AssignmentsPage({assignments, corporateAssignments, user
<AssignmentCreator <AssignmentCreator
assignment={selectedAssignment} assignment={selectedAssignment}
groups={groups} groups={groups}
users={[...users, user]} users={users}
user={user} user={user}
isCreating={isCreatingAssignment} isCreating={isCreatingAssignment}
cancelCreation={() => { cancelCreation={() => {

View File

@@ -287,9 +287,7 @@ 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>

View File

@@ -8,8 +8,7 @@ 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(() => {
if (text.length > 0) return search(text, fields, rows); return search(text, fields, rows);
return rows;
}, [fields, rows, text]); }, [fields, rows, text]);
return { return {

View File

@@ -1,28 +0,0 @@
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};
}

View File

@@ -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"}) { export default function useUsers(props?: {type?: string; page?: number; size?: number; orderBy?: string; direction?: "asc" | "desc", searchTerm?: string | undefined}) {
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,6 +23,8 @@ 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"}})
@@ -33,7 +35,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]); useEffect(getData, [props?.page, props?.size, props?.type, props?.orderBy, props?.direction, props?.searchTerm]);
return {users, total, isLoading, isError, reload: getData}; return {users, total, isLoading, isError, reload: getData};
} }

View File

@@ -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 usePagination from "@/hooks/usePagination"; import Input from "@/components/Low/Input";
const columnHelper = createColumnHelper<User>(); const columnHelper = createColumnHelper<User>();
const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]]; const searchFields = [["name"], ["email"], ["corporateInformation", "companyInformation", "name"]];
@@ -63,15 +63,11 @@ 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 userHash = useMemo( const { users, total, isLoading, reload } = useUsers({type: type, size: 16, page: page, searchTerm: searchTerm});
() => ({
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]);
@@ -100,9 +96,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([...filteredUsers]); setDisplayUsers([...sortedUsers]);
} }
})(); })();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -141,8 +137,7 @@ 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"} ${ `Are you sure you want to ${user.status === "disabled" ? "enable" : "disable"} ${user.name
user.name
}'s account? This change is usually related to their payment state.`, }'s account? This change is usually related to their payment state.`,
) )
) )
@@ -236,8 +231,7 @@ export default function UserList({
) as any, ) as any,
cell: (info) => cell: (info) =>
info.getValue() info.getValue()
? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${ ? `${countryCodes.findOne("countryCode" as any, info.getValue())?.flag} ${countries[info.getValue() as unknown as keyof TCountries]?.name
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",
}), }),
@@ -511,20 +505,14 @@ 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: items, data: displayUsers,
columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any, columns: (!showDemographicInformation ? defaultColumns : demographicColumns) as any,
getCoreRowModel: getCoreRowModel(), getCoreRowModel: getCoreRowModel(),
}); });
const downloadExcel = () => { const downloadExcel = () => {
const csv = exportListToExcel(filteredRows, users, groups); const csv = exportListToExcel(displayUsers, 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" });
@@ -629,12 +617,32 @@ 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">
{renderSearch()} <Input label="Search" type="text" name="search" onChange={setSearchTerm} placeholder="Enter search text" value={searchTerm} />
<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>
{renderPagination()} <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>
<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) => (

View File

@@ -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, req.session.user!.type); const assigners = await getAllAssignersByCorporate(id);
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"));

View File

@@ -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(req.session.user!.type, idsList, startDateParsed, endDateParsed); const assignments = await getAssignmentsForCorporates(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});

View File

@@ -11,21 +11,14 @@ 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 {StudentUser, User} from "@/interfaces/user"; import { 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;
@@ -47,12 +40,14 @@ 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"], ["assignment"], ["exams"]]; const searchFilters = [["email"], ["user"], ["userId"]];
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 (!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])) { if (
!checkAccess(req.session.user, ["mastercorporate", "corporate", "developer", "admin"])
) {
return res.status(403).json({ error: "Unauthorized" }); return res.status(403).json({ error: "Unauthorized" });
} }
const { const {
@@ -70,20 +65,25 @@ 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(req.session.user.type, ids, startDateParsed, endDateParsed); const assignments = await getAssignmentsForCorporates(
ids,
startDateParsed,
endDateParsed
);
const assignmentUsers = uniq([...assignments.flatMap((x) => x.assignees), ...assignments.flatMap((x) => x.assigner)]); const assignmentUsers = [
...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,14 +91,21 @@ 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((gs) => gs.user === assigner); const gradingSystem = assignerUsersGradingSystems.find(
(gs) => gs.user === assigner
);
if (gradingSystem) { if (gradingSystem) {
const bandScore = calculateBandScore(correct, total, "level", user?.focus || "academic"); const bandScore = calculateBandScore(
correct,
total,
"level",
user.focus
);
return { return {
label: getGradingLabel(bandScore, gradingSystem.steps || []), label: getGradingLabel(bandScore, gradingSystem?.steps || []),
score: bandScore, score: bandScore,
}; };
} }
@@ -110,22 +117,27 @@ 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 = a.results.find((r) => r.user === assignee)?.stats || []; 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 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(a.exams, a.assigner, userData!, correct, total); const { label: level, score } = getGradingSystemHelper(
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 ? "" : getUserName(corporateUser), corporate: corporateUser?.name || "",
assignment: a.name, assignment: a.name,
level, level,
score, score,
@@ -139,22 +151,14 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
}; };
} }
let data: {total: number; correct: number}[] = []; const partsData = userStats.every((e) => e.module === "level")
if (a.exams.every((x) => x.module === "level")) { ? userStats.reduce((acc, e, index) => {
const exam = exams.find((x) => x.id === a.exams.find((x) => x.assignee === assignee)?.id) as LevelExam; return {
data = exam.parts.map((x) => { ...acc,
const exerciseIDs = x.exercises.map((x) => x.id); [`part${index}`]: `${e.score.correct}/${e.score.total}`,
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,
@@ -182,14 +186,6 @@ 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
? [ ? [
{ {
@@ -207,7 +203,7 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
value: (entry: TableData) => (entry.submitted ? "Yes" : "No"), value: (entry: TableData) => (entry.submitted ? "Yes" : "No"),
}, },
{ {
label: "Score", label: "Correct",
value: (entry: TableData) => entry.correct, value: (entry: TableData) => entry.correct,
}, },
{ {
@@ -227,7 +223,9 @@ async function post(req: NextApiRequest, res: NextApiResponse) {
})), })),
]; ];
const filteredSearch = !!searchText ? search(searchText, searchFilters, tableResults) : tableResults; const filteredSearch = searchText
? search(searchText, searchFilters, tableResults)
: tableResults;
worksheet.addRow(headers.map((h) => h.label)); worksheet.addRow(headers.map((h) => h.label));
(filteredSearch as TableData[]).forEach((entry) => { (filteredSearch as TableData[]).forEach((entry) => {
@@ -243,7 +241,8 @@ 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: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", contentType:
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}); });
const url = await getDownloadURL(fileRef); const url = await getDownloadURL(fileRef);

View File

@@ -40,7 +40,6 @@ 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: {
@@ -49,7 +48,6 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
missing: 0, missing: 0,
}, },
isDisabled: false, isDisabled: false,
}
}, },
{upsert: true}, {upsert: true},
); );

View File

@@ -72,9 +72,6 @@ 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);
@@ -120,9 +117,6 @@ 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 = {

View File

@@ -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, id: snapshot.id}); res.status(200).json({...snapshot.data(), id: snapshot.id});
} }

View File

@@ -4,7 +4,6 @@ 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);
@@ -20,7 +19,8 @@ async function handler(req: NextApiRequest, res: NextApiResponse) {
page, page,
orderBy, orderBy,
direction = "desc", direction = "desc",
} = req.query as {size?: string; type?: Type; page?: string; orderBy?: string; direction?: "asc" | "desc"}; searchTerm
} = 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,7 +30,8 @@ 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: uniqBy([...users], "id"), total}); res.status(200).json({users, total});
} }

View File

@@ -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 ? (queryId as string) : req.session.user.id}, {$set: updatedUser}); await db.collection("users").updateOne({id: queryId}, {$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, ...user, id: req.session.user!.id}}); res.status(200).json({user: {...updatedUser, id: req.session.user!.id}});
} }
export const config = { export const config = {

View File

@@ -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]);

View File

@@ -1,7 +1,6 @@
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);
@@ -37,10 +36,10 @@ export const getAssignmentsByAssigners = async (ids: string[], startDate?: Date,
.toArray(); .toArray();
}; };
export const getAssignmentsForCorporates = async (userType: Type, idsList: string[], startDate?: Date, endDate?: Date) => { export const getAssignmentsForCorporates = async (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, userType); const assigners = await getAllAssignersByCorporate(id);
return { return {
corporateId: id, corporateId: id,
assigners, assigners,

View File

@@ -6,28 +6,6 @@ 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,

View File

@@ -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, Type, User} from "@/interfaces/user"; import {CorporateUser, Group, MasterCorporateUser, StudentUser, TeacherUser, 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, type: Type): Promise<string[]> => { export const getAllAssignersByCorporate = async (corporateID: string): Promise<string[]> => {
const linkedTeachers = await getLinkedUsers(corporateID, type, "teacher"); const linkedTeachers = await getLinkedUsers(corporateID, "mastercorporate", "teacher");
const linkedCorporates = await getLinkedUsers(corporateID, type, "corporate"); const linkedCorporates = await getLinkedUsers(corporateID, "mastercorporate", "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)];
}; };

View File

@@ -1,3 +1,4 @@
/*fields example = [ /*fields example = [
['id'], ['id'],
['companyInformation', 'companyInformation', 'name'] ['companyInformation', 'companyInformation', 'name']
@@ -25,4 +26,4 @@ export const search = (text: string, fields: string[][], rows: any[]) => {
} }
}); });
}); });
}; }

View File

@@ -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>({}, { projection: { _id: 0 } }).toArray(); return await db.collection("users").find<User>({}).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: id}, { projection: { _id: 0 } }); const user = await db.collection("users").findOne<User>({ id });
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}}, { projection: { _id: 0 } }) .find<User>({ id: { $in: ids } })
.toArray(); .toArray();
} }
@@ -33,10 +33,21 @@ export async function getLinkedUsers(
size?: number, size?: number,
sort?: string, sort?: string,
direction?: "asc" | "desc", direction?: "asc" | "desc",
searchTerm?: string | undefined,
) { ) {
const filters = { const filters: any = {};
...(!!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